diff --git a/CHANGELOG.md b/CHANGELOG.md
index 93a19fc243..1a0dd92cba 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,23 @@
## [Unreleased]
+## [1.0.3b7] - 2026-11-17
+
+### 新增
+- 托管专家可选会话模式,并能使用连接器、知识库、专家回调和已启用的插件
+- 云服务器页的地域筛选改为按大区分组的下拉面板
+
+### 变更
+- 工具调用上限只拦截连续的相同调用
+- 云服务器页侧栏折叠、字号和未授权提示与对话页对齐
+
+### 修复
+- Docker 部署时仍可将宿主机目录挂进 Docker 专家
+- Telegram 回复本机器人时保留引用;记忆列表不再被过期响应覆盖
+- PostgreSQL 清理孤儿 checkpoint 时只统计,不再误删其他智能体的对话
+- 带路径的 MCP OAuth 按规范发现授权信息
+- 窄屏下 Word / PDF 左侧可以滚到;新手引导遮罩铺满窗口
+
## [1.0.3b6] - 2026-11-15
### 新增
diff --git a/README.md b/README.md
index a00f12febb..b09fe64747 100644
--- a/README.md
+++ b/README.md
@@ -15,7 +15,7 @@
-
+
diff --git a/README_CN.md b/README_CN.md
index 3dc81548c3..06fedae361 100644
--- a/README_CN.md
+++ b/README_CN.md
@@ -15,7 +15,7 @@
-
+
diff --git a/dashboard/src/api/modules/acp.ts b/dashboard/src/api/modules/acp.ts
index 120fbcd778..46914df02c 100644
--- a/dashboard/src/api/modules/acp.ts
+++ b/dashboard/src/api/modules/acp.ts
@@ -46,6 +46,53 @@ export interface AcpHostRequest {
env: Record;
}
+export interface AcpSessionMode {
+ id: string;
+ name_zh: string;
+ name_en: string;
+ hint_zh: string;
+ hint_en: string;
+}
+
+export function acpSessionModeText(
+ mode: AcpSessionMode,
+ language: string,
+ field: "name" | "hint",
+): string {
+ const zh = language.toLowerCase().startsWith("zh");
+ return zh ? mode[`${field}_zh`] : mode[`${field}_en`];
+}
+
+/** Same ids the harness treats as unattended. */
+export function isUnattendedSessionMode(modeId: string): boolean {
+ const folded = modeId.toLowerCase();
+ return (
+ folded.includes("yolo") ||
+ folded.includes("bypass") ||
+ folded.includes("full-access") ||
+ folded.includes("fullaccess") ||
+ folded.includes("auto-accept") ||
+ folded.includes("autoaccept") ||
+ folded.includes("unrestricted") ||
+ folded.includes("danger")
+ );
+}
+
+export function catalogOffersUnattendedMode(modes: { id: string }[]): boolean {
+ return modes.some((mode) => isUnattendedSessionMode(mode.id));
+}
+
+/** Approval stored with a managed expert. A published unattended mode wins. */
+export function permissionForSessionMode(
+ modes: { id: string }[],
+ sessionMode: string,
+ yoloSwitch: boolean,
+): "ask" | "yolo" {
+ if (isUnattendedSessionMode(sessionMode)) return "yolo";
+ if (catalogOffersUnattendedMode(modes)) return "ask";
+ return yoloSwitch ? "yolo" : "ask";
+}
+
export const acpApi = {
/** Global runner definitions (shared by all agents for the current user). */
getGlobalRunners: (agentId?: string | null) =>
@@ -63,6 +110,11 @@ export const acpApi = {
headers: optionalAgentHeaders(agentId),
}),
+ sessionModes: (runner: string) =>
+ request<{ runner: string; modes: AcpSessionMode[] }>(
+ `/acp/session-modes?runner=${encodeURIComponent(runner)}`,
+ ),
+
getRunner: (runnerName: string) =>
request(`/acp/${encodeURIComponent(runnerName)}`),
diff --git a/dashboard/src/api/modules/managedAgents.ts b/dashboard/src/api/modules/managedAgents.ts
index c37370bf99..ad332f7e2e 100644
--- a/dashboard/src/api/modules/managedAgents.ts
+++ b/dashboard/src/api/modules/managedAgents.ts
@@ -42,6 +42,10 @@ export interface ManagedAgentCreate {
group_ids?: string[];
quick_prompts?: ManagedQuickPrompt[];
file_overrides?: ManagedWorkspaceFile[];
+ skill_package_ids?: string[];
+ knowledge_base_ids?: string[];
+ mcp_servers?: string[];
+ permission_mode?: "ask" | "yolo";
}
export const managedAgentsApi = {
diff --git a/dashboard/src/api/modules/octopThreads.ts b/dashboard/src/api/modules/octopThreads.ts
index 7f5d39ff0b..e942170073 100644
--- a/dashboard/src/api/modules/octopThreads.ts
+++ b/dashboard/src/api/modules/octopThreads.ts
@@ -57,6 +57,7 @@ export interface OctopThread {
reasoning_mode?: "auto" | "enabled" | "disabled" | null;
reasoning_effort?: string | null;
conversation_mode?: "ask" | "plan" | "craft" | null;
+ session_mode?: string | null;
pending_plan_path?: string | null;
hitl_policy?: HitlSessionPolicy | null;
/** Legacy path list (compat). Prefer ``artifact_refs`` when present. */
@@ -92,6 +93,7 @@ export interface OctopThreadHistory {
reasoning_mode?: "auto" | "enabled" | "disabled" | null;
reasoning_effort?: string | null;
conversation_mode?: "ask" | "plan" | "craft" | null;
+ session_mode?: string | null;
pending_plan_path?: string | null;
hitl_policy?: HitlSessionPolicy | null;
has_more?: boolean;
@@ -126,6 +128,7 @@ export interface OctopThreadPatch {
reasoning_mode?: "auto" | "enabled" | "disabled" | null;
reasoning_effort?: string | null;
conversation_mode?: "ask" | "plan" | "craft" | null;
+ session_mode?: string | null;
hitl_policy?: HitlSessionPolicy | null;
}
@@ -251,6 +254,7 @@ export const octopThreadsApi = {
reasoning_mode?: "auto" | "enabled" | "disabled" | null;
reasoning_effort?: string | null;
conversation_mode?: "ask" | "plan" | "craft" | null;
+ session_mode?: string | null;
pending_plan_path?: string | null;
hitl_policy?: HitlSessionPolicy | null;
}>(
diff --git a/dashboard/src/api/modules/teams.ts b/dashboard/src/api/modules/teams.ts
index 99533a7398..9158adef65 100644
--- a/dashboard/src/api/modules/teams.ts
+++ b/dashboard/src/api/modules/teams.ts
@@ -9,6 +9,8 @@ export interface TeamMemberSummary {
state?: string;
is_shared?: boolean;
user_id?: number | null;
+ kind?: string | null;
+ managed_runner?: string | null;
}
export interface TeamRecord {
diff --git a/dashboard/src/components/AgentProfileDrawer.tsx b/dashboard/src/components/AgentProfileDrawer.tsx
index 6146382c4c..9671b1c64e 100644
--- a/dashboard/src/components/AgentProfileDrawer.tsx
+++ b/dashboard/src/components/AgentProfileDrawer.tsx
@@ -13,6 +13,7 @@ import { request } from "../api/request";
import { withFromWorkspace } from "../utils/fromWorkspace";
import type { OctopAgent } from "../context/AgentContext";
import { useAgent } from "../context/AgentContext";
+import { useCurrentUser } from "../hooks/useCurrentUser";
import { isAgentChatReady } from "../utils/agentError";
import { isTeamAgent } from "../utils/teamAgent";
import {
@@ -26,6 +27,8 @@ import {
ExpertIcon,
metaForFile,
} from "../pages/Experts/components/iconForName";
+import { ManagedAvatarMark } from "../pages/Experts/components/ManagedAvatarMark";
+import { incomingShareProps, SharedAvatarMark } from "./SharedResourceBadge";
import { fetchConfigMdFiles } from "../pages/Experts/components/expertFileGroups";
import { useSkillDisplayName } from "../pages/Agent/Skills/skillDisplayNames";
import { DEFAULT_SKILL_EMOJI } from "../pages/Agent/Skills/skillMarkdown";
@@ -114,6 +117,7 @@ export default function AgentProfileDrawer({
}: AgentProfileDrawerProps) {
const { t } = useTranslation();
const { agents } = useAgent();
+ const viewerId = useCurrentUser()?.id;
const skillDisplayName = useSkillDisplayName();
const [loading, setLoading] = useState(false);
const [filesLoading, setFilesLoading] = useState(false);
@@ -145,6 +149,12 @@ export default function AgentProfileDrawer({
icon_name: found.icon_name ?? member.icon_name,
icon_url: found.icon_url ?? member.icon_url,
state: found.state || member.state,
+ kind: found.kind || member.kind,
+ managed_runner:
+ (found.kind === "managed" &&
+ typeof found.config?.managed_runner === "string"
+ ? found.config.managed_runner
+ : null) || member.managed_runner,
};
}),
[teamMembers, agents],
@@ -409,23 +419,39 @@ export default function AgentProfileDrawer({
visibleTeamMembers.map((member) => {
const accent = member.color || "#0d9488";
const stateKey = member.state || "unknown";
+ const memberAgent = agents.find(
+ (item) => item.agent_id === member.agent_id,
+ );
+ const shareSource =
+ memberAgent ??
+ (member.user_id != null && viewerId != null
+ ? {
+ is_shared: member.is_shared,
+ is_owner: Number(member.user_id) === Number(viewerId),
+ user_id: member.user_id,
+ }
+ : null);
return (
-
-
+
+
+
+
+
+
+
}
title={member.name}
trailing={
diff --git a/dashboard/src/components/AgentSelector.test.tsx b/dashboard/src/components/AgentSelector.test.tsx
index 6e43d87cdc..c945a16b22 100644
--- a/dashboard/src/components/AgentSelector.test.tsx
+++ b/dashboard/src/components/AgentSelector.test.tsx
@@ -122,6 +122,24 @@ describe("AgentSelector groups", () => {
expect(screen.queryByRole("combobox")).not.toBeInTheDocument();
});
+ it("hides managed experts when the page does not use them", () => {
+ const hosted = fakeAgent({
+ agent_id: "hosted",
+ name: "托管写手",
+ kind: "managed",
+ });
+ state.agents = [writer, hosted];
+ state.activeAgentId = "hosted";
+ render( );
+ const chips = within(screen.getByTestId("agent-selector-chips"));
+ expect(chips.getByText("写手")).toBeInTheDocument();
+ expect(chips.queryByText("托管写手")).not.toBeInTheDocument();
+ expect(
+ screen.getByText("当前是托管专家「托管写手」,此页请选择其他专家"),
+ ).toBeInTheDocument();
+ expect(setActiveAgent).not.toHaveBeenCalled();
+ });
+
it("keeps a hidden team selection and asks the user to pick an expert", () => {
state.activeAgentId = "crew";
render( );
diff --git a/dashboard/src/components/AgentSelector.tsx b/dashboard/src/components/AgentSelector.tsx
index e6412415ce..e87d1e4122 100644
--- a/dashboard/src/components/AgentSelector.tsx
+++ b/dashboard/src/components/AgentSelector.tsx
@@ -16,6 +16,11 @@ import {
} from "../utils/agentSelector";
import { isTeamAgent } from "../utils/teamAgent";
import { ExpertIcon } from "../pages/Experts/components/iconForName";
+import {
+ ManagedAvatarMark,
+ managedRunnerId,
+} from "../pages/Experts/components/ManagedAvatarMark";
+import { incomingShareProps, SharedAvatarMark } from "./SharedResourceBadge";
import RemoteExpertHint from "../pages/Chat/components/RemoteExpertHint";
import styles from "./AgentSelector.module.less";
@@ -30,6 +35,8 @@ interface AgentSelectorProps {
* expert-only.
*/
showTeams?: boolean;
+ /** Tools / plugins / MBTI pages do not list managed experts. */
+ hideManaged?: boolean;
/**
* 受控模式:只改这个面板自己的专家,不写入全局当前 Agent。
* 传入 onChange 即生效。
@@ -57,13 +64,17 @@ function AgentIcon({
}) {
const photo = Boolean(agent.icon_url?.trim());
return (
-
-
-
+
+
+
+
+
+
+
);
}
@@ -168,6 +179,7 @@ export default function AgentSelector({
variant = "auto",
showLabel = true,
showTeams = false,
+ hideManaged = false,
value,
onChange,
}: AgentSelectorProps) {
@@ -179,7 +191,13 @@ export default function AgentSelector({
if (onChange) onChange(id);
else setActiveAgent(id);
};
- const soloSelectable = useMemo(() => ownedSoloExperts(agents), [agents]);
+ const soloSelectable = useMemo(
+ () =>
+ ownedSoloExperts(agents).filter(
+ (agent) => !hideManaged || agent.kind !== "managed",
+ ),
+ [agents, hideManaged],
+ );
const allTeams = useMemo(() => ownedTeamAgents(agents), [agents]);
const teamSelectable = useMemo(
() => (showTeams ? allTeams : []),
@@ -222,6 +240,9 @@ export default function AgentSelector({
const activeIsHiddenTeam = Boolean(
activeAgent && isTeamAgent(activeAgent) && !showTeams,
);
+ const activeIsHiddenManaged = Boolean(
+ hideManaged && activeAgent?.kind === "managed",
+ );
const useBar = variant !== "select";
const currentId =
chosenId ?? (controlled ? undefined : selectable[0]?.agent_id);
@@ -274,7 +295,13 @@ export default function AgentSelector({
);
}
- if (selectable.length === 0 && allTeams.length === 0) return null;
+ if (
+ selectable.length === 0 &&
+ allTeams.length === 0 &&
+ !activeIsHiddenManaged
+ ) {
+ return null;
+ }
const disconnectedLabel = t("agentSelector.disconnected");
const selectOptions: DefaultOptionType[] = showGroupLabels
@@ -292,6 +319,11 @@ export default function AgentSelector({
name: activeAgent?.name ?? "",
defaultValue: "当前是团队「{{name}}」,此页请选择专家",
})
+ : activeIsHiddenManaged
+ ? t("agentSelector.managedNeedsExpert", {
+ name: activeAgent?.name ?? "",
+ defaultValue: "当前是托管专家「{{name}}」,此页请选择其他专家",
+ })
: soloSelectable.length === 0 && allTeams.length > 0
? t("agentSelector.expertsRequired", "此页需要专家")
: null;
diff --git a/dashboard/src/components/DocumentPreviewCore.module.less b/dashboard/src/components/DocumentPreviewCore.module.less
index 973f85e3b4..0385c3a655 100644
--- a/dashboard/src/components/DocumentPreviewCore.module.less
+++ b/dashboard/src/components/DocumentPreviewCore.module.less
@@ -55,6 +55,22 @@
overscroll-behavior: contain;
}
+/*
+ * docx-preview centres pages with `align-items: center` on its flex wrapper.
+ * A page wider than the preview (phones, the chat side panel) then overflows
+ * to both sides, and the left overflow can never be scrolled into view.
+ * Start-align and centre with auto margins instead: they centre while the page
+ * fits and fall back to 0 once it overflows, so the extra width scrolls right.
+ */
+.docxWrap :global(.docx-doc-wrapper) {
+ align-items: flex-start;
+}
+
+.docxWrap :global(.docx-doc-wrapper > section.docx-doc) {
+ margin-left: auto;
+ margin-right: auto;
+}
+
.pptxWrap {
flex: 1;
min-height: 0;
diff --git a/dashboard/src/components/DocumentPreviewCore.narrowLayout.test.ts b/dashboard/src/components/DocumentPreviewCore.narrowLayout.test.ts
new file mode 100644
index 0000000000..d96542f435
--- /dev/null
+++ b/dashboard/src/components/DocumentPreviewCore.narrowLayout.test.ts
@@ -0,0 +1,105 @@
+import { readFileSync } from "node:fs";
+import { resolve } from "node:path";
+import { renderAsync } from "docx-preview";
+import JSZip from "jszip";
+import { describe, expect, it, vi } from "vitest";
+
+import { DOCX_RENDER_OPTIONS } from "./DocumentPreviewCore";
+
+// pdf.js needs DOMMatrix, which jsdom lacks; the Word path never touches it.
+vi.mock("react-pdf", () => ({
+ Document: () => null,
+ Page: () => null,
+ pdfjs: { GlobalWorkerOptions: { workerSrc: "" } },
+}));
+
+const W = "http://schemas.openxmlformats.org/wordprocessingml/2006/main";
+
+/** Smallest Word file docx-preview accepts: one paragraph on an A4 page. */
+async function a4Docx(): Promise {
+ const zip = new JSZip();
+ zip.file(
+ "[Content_Types].xml",
+ '' +
+ ' ' +
+ ' ' +
+ ' ' +
+ " ",
+ );
+ zip.file(
+ "_rels/.rels",
+ '' +
+ ' ' +
+ " ",
+ );
+ zip.file(
+ "word/document.xml",
+ `` +
+ "Left edge " +
+ ' ' +
+ " ",
+ );
+ return zip.generateAsync({ type: "arraybuffer" });
+}
+
+/** Body of the first rule whose selector is exactly ``selector``. */
+function ruleBody(css: string, selector: string): string {
+ const escaped = selector.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+ const match = css.match(new RegExp(`(?:^|\\n)${escaped}\\s*\\{([^}]*)\\}`));
+ if (!match) throw new Error(`missing rule: ${selector}`);
+ return match[1];
+}
+
+// A page wider than the preview must overflow to the right (scrollable), not
+// to both sides: centring the flex item puts its left part out of reach
+// (#1262). Auto margins keep pages centred whenever they fit.
+describe("document previews on narrow screens", () => {
+ it("keeps the left edge of Word pages reachable", () => {
+ const css = readFileSync(
+ resolve(__dirname, "DocumentPreviewCore.module.less"),
+ "utf8",
+ );
+ expect(ruleBody(css, ".docxWrap :global(.docx-doc-wrapper)")).toMatch(
+ /align-items:\s*flex-start/,
+ );
+ const page = ruleBody(
+ css,
+ ".docxWrap :global(.docx-doc-wrapper > section.docx-doc)",
+ );
+ expect(page).toMatch(/margin-left:\s*auto/);
+ expect(page).toMatch(/margin-right:\s*auto/);
+ });
+
+ it("targets the wrapper and pages docx-preview actually renders", async () => {
+ const host = document.createElement("div");
+ await renderAsync(await a4Docx(), host, undefined, DOCX_RENDER_OPTIONS);
+
+ // Pages keep their real paper width (A4 = 595.3pt ≈ 794px), wider than a phone.
+ const page = host.querySelector(
+ ".docx-doc-wrapper > section.docx-doc",
+ );
+ expect(page).not.toBeNull();
+ expect(page!.style.width).toBe("595.3pt");
+
+ // docx-preview's own stylesheet is what centres (and so clips) the page.
+ const injected = Array.from(host.querySelectorAll("style"))
+ .map((style) => style.textContent ?? "")
+ .join("\n");
+ expect(injected).toMatch(
+ /\.docx-doc-wrapper\s*\{[^}]*align-items:\s*center/,
+ );
+ });
+
+ it("keeps the left edge of zoomed-in PDF pages reachable", () => {
+ const css = readFileSync(
+ resolve(__dirname, "PdfDocumentPreview.module.less"),
+ "utf8",
+ );
+ const doc = ruleBody(css, ".pdfDocument");
+ expect(doc).toMatch(/align-items:\s*flex-start/);
+ expect(doc).not.toMatch(/align-items:\s*center/);
+ const slot = ruleBody(css, ".pdfPageSlot");
+ expect(slot).toMatch(/margin-left:\s*auto/);
+ expect(slot).toMatch(/margin-right:\s*auto/);
+ });
+});
diff --git a/dashboard/src/components/DocumentPreviewCore.tsx b/dashboard/src/components/DocumentPreviewCore.tsx
index 30359ef903..8d144ce754 100644
--- a/dashboard/src/components/DocumentPreviewCore.tsx
+++ b/dashboard/src/components/DocumentPreviewCore.tsx
@@ -138,6 +138,16 @@ async function extractXlsxMediaDataUrls(
return items;
}
+/** docx-preview options; the narrow-layout CSS targets the DOM they produce. */
+export const DOCX_RENDER_OPTIONS = {
+ className: "docx-doc",
+ inWrapper: true,
+ breakPages: true,
+ ignoreWidth: false,
+ ignoreHeight: false,
+ useBase64URL: true,
+};
+
/** Absolute lengths beyond this (≈ 27″) are treated as corrupt DOCX metrics. */
const DOCX_MAX_LENGTH_PT = 2000;
@@ -441,14 +451,12 @@ export default function DocumentPreviewCore({
}
const { renderAsync } = await import("docx-preview");
if (containerRef.current && !cancelled) {
- await renderAsync(buf, containerRef.current, undefined, {
- className: "docx-doc",
- inWrapper: true,
- breakPages: true,
- ignoreWidth: false,
- ignoreHeight: false,
- useBase64URL: true,
- });
+ await renderAsync(
+ buf,
+ containerRef.current,
+ undefined,
+ DOCX_RENDER_OPTIONS,
+ );
if (!cancelled && containerRef.current) {
neutralizeDocxPreviewChrome(containerRef.current);
sanitizeDocxPreviewLayout(containerRef.current);
diff --git a/dashboard/src/components/OnboardingGuide/OnboardingGuide.module.less b/dashboard/src/components/OnboardingGuide/OnboardingGuide.module.less
index f807dfa5df..a231468ec7 100644
--- a/dashboard/src/components/OnboardingGuide/OnboardingGuide.module.less
+++ b/dashboard/src/components/OnboardingGuide/OnboardingGuide.module.less
@@ -52,8 +52,9 @@
box-shadow: 0 0 0 0
color-mix(in srgb, var(--fn-color-brand) 45%, transparent);
}
+ // Stays inside the tour's 6px spotlight gap, so the mask never clips it.
70% {
- box-shadow: 0 0 0 10px
+ box-shadow: 0 0 0 5px
color-mix(in srgb, var(--fn-color-brand) 0%, transparent);
}
100% {
@@ -112,6 +113,7 @@
font-size: 14px;
line-height: 22px;
color: var(--fn-text-secondary);
+ text-wrap: pretty;
animation: fadeUp 0.45s @ease-out 0.14s both;
}
@@ -227,9 +229,12 @@
/* ---------- tour card ---------- */
-.tour {
+/* rootClassName also lands on the mask, so size only the card. */
+.tour:global(.octop-tour) {
width: min(360px, calc(100vw - 32px));
+}
+.tour {
:global(.octop-tour-content) {
width: 100%;
}
@@ -340,6 +345,8 @@
> :first-child {
margin-right: auto;
+ // Line the "Skip" text up with the card content, not its button padding.
+ margin-left: -7px;
}
}
diff --git a/dashboard/src/components/OnboardingGuide/OnboardingGuide.tsx b/dashboard/src/components/OnboardingGuide/OnboardingGuide.tsx
index 0e72d97958..d3cb7fbf69 100644
--- a/dashboard/src/components/OnboardingGuide/OnboardingGuide.tsx
+++ b/dashboard/src/components/OnboardingGuide/OnboardingGuide.tsx
@@ -6,7 +6,7 @@ import {
type CSSProperties,
type ComponentType,
} from "react";
-import { Button, Modal, Tour, type TourStepProps } from "antd";
+import { Button, Modal, Tour, theme, type TourStepProps } from "antd";
import {
ArrowLeft,
ArrowRight,
@@ -59,6 +59,20 @@ function navTarget(step: OnboardingStep): HTMLElement | null {
return document.querySelector(`[data-nav-key="${step.navKey}"]`);
}
+/**
+ * Side placement for a step's card. antd shifts an overflowing card back
+ * into view flush with the window edge, so align it to the top or bottom of
+ * targets near those edges instead.
+ */
+function sidePlacement(step: OnboardingStep): TourStepProps["placement"] {
+ const rect = navTarget(step)?.getBoundingClientRect();
+ if (!rect) return "right";
+ const middle = rect.top + rect.height / 2;
+ if (middle < window.innerHeight / 3) return "rightTop";
+ if (middle > (window.innerHeight * 2) / 3) return "rightBottom";
+ return "right";
+}
+
/**
* Welcome guide: an intro card, a spotlight tour that opens each page and
* highlights its sidebar entry, then a short wrap-up.
@@ -73,10 +87,13 @@ export default function OnboardingGuide({
const { t } = useTranslation();
const navigate = useNavigate();
const isMobile = useIsMobile();
+ const { token } = theme.useToken();
const user = useCurrentUser();
const steps = useMemo(() => buildOnboardingSteps(user), [user]);
const [phase, setPhase] = useState("intro");
const [current, setCurrent] = useState(0);
+ // True once the wrap-up modal has finished opening.
+ const [doneSettled, setDoneSettled] = useState(false);
useEffect(() => {
if (!open) return;
@@ -137,7 +154,7 @@ export default function OnboardingGuide({
return {
// Mobile keeps the nav in a closed drawer, so the card stays centered.
target: isMobile ? null : () => navTarget(s) as HTMLElement,
- placement: isMobile ? "center" : "right",
+ placement: isMobile ? "center" : sidePlacement(s),
title: (
@@ -176,6 +193,9 @@ export default function OnboardingGuide({
width={isMobile ? "calc(100vw - 32px)" : 560}
centered
destroyOnHidden
+ // The tour mask appears at once; fading this one out over it would
+ // briefly double the dim.
+ maskTransitionName={phase === "tour" ? "" : undefined}
className={styles.modal}
>
@@ -230,6 +250,9 @@ export default function OnboardingGuide({
steps={tourSteps}
rootClassName={styles.tour}
disabledInteraction
+ // Same dim as the intro and wrap-up modals, so switching between them
+ // does not flicker (Tour's own mask is a fixed 50% black).
+ mask={{ color: token.colorBgMask }}
gap={{ offset: 6, radius: 10 }}
indicatorsRender={(cur, total) => (
@@ -279,6 +302,10 @@ export default function OnboardingGuide({
width={isMobile ? "calc(100vw - 32px)" : 440}
centered
destroyOnHidden
+ // The tour mask goes at once; fading this one in would flash the
+ // page. Closing still fades.
+ maskTransitionName={doneSettled ? undefined : ""}
+ afterOpenChange={setDoneSettled}
className={styles.modal}
>
diff --git a/dashboard/src/components/PdfDocumentPreview.module.less b/dashboard/src/components/PdfDocumentPreview.module.less
index f47c136a01..30b5ce8255 100644
--- a/dashboard/src/components/PdfDocumentPreview.module.less
+++ b/dashboard/src/components/PdfDocumentPreview.module.less
@@ -193,16 +193,22 @@
overscroll-behavior: contain;
}
+/*
+ * Start-align and centre each page with auto margins: `align-items: center`
+ * would push a zoomed-in page past the left edge, where it can't be scrolled.
+ */
.pdfDocument {
display: flex;
flex-direction: column;
- align-items: center;
+ align-items: flex-start;
gap: 12px;
}
.pdfPageSlot {
position: relative;
flex: 0 0 auto;
+ margin-left: auto;
+ margin-right: auto;
overflow: hidden;
box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
background: #fff;
diff --git a/dashboard/src/components/SharedResourceBadge/SharedResourceBadge.module.less b/dashboard/src/components/SharedResourceBadge/SharedResourceBadge.module.less
index 7ecba4b5f0..9dcfac40df 100644
--- a/dashboard/src/components/SharedResourceBadge/SharedResourceBadge.module.less
+++ b/dashboard/src/components/SharedResourceBadge/SharedResourceBadge.module.less
@@ -41,6 +41,12 @@
line-height: 0;
}
+/* Sit above a managed-runner mark so both stay visible on the right edge. */
+.avatarHost:has([data-managed-avatar-mark]) > .avatarMark {
+ bottom: max(38%, 11px);
+ z-index: 2;
+}
+
.avatarMark {
position: absolute;
right: -8%;
diff --git a/dashboard/src/components/SharedResourceBadge/index.tsx b/dashboard/src/components/SharedResourceBadge/index.tsx
index 3414d64aed..544f23c906 100644
--- a/dashboard/src/components/SharedResourceBadge/index.tsx
+++ b/dashboard/src/components/SharedResourceBadge/index.tsx
@@ -3,6 +3,10 @@ import { Share2 } from "lucide-react";
import { Tooltip } from "antd";
import { useTranslation } from "react-i18next";
import cx from "classnames";
+import {
+ isSharedExpertViewer,
+ type SharedExpertAccess,
+} from "../../utils/sharedExpert";
import styles from "./SharedResourceBadge.module.less";
type Props = {
@@ -45,6 +49,18 @@ export function SharedResourceBadge({
);
}
+/** Props for the incoming-share pip. Owners who shared outward get no avatar mark. */
+export function incomingShareProps(
+ agent?: (SharedExpertAccess & { owner_username?: string | null }) | null,
+): { shared: boolean; owned: boolean; ownerName?: string | null } {
+ const incoming = Boolean(agent && isSharedExpertViewer(agent));
+ return {
+ shared: incoming,
+ owned: !incoming,
+ ownerName: agent?.owner_username,
+ };
+}
+
/** Avatar with a pip when the resource was shared to the current user. */
export function SharedAvatarMark({
shared,
diff --git a/dashboard/src/hooks/useAcpSessionModes.ts b/dashboard/src/hooks/useAcpSessionModes.ts
new file mode 100644
index 0000000000..f62c982faa
--- /dev/null
+++ b/dashboard/src/hooks/useAcpSessionModes.ts
@@ -0,0 +1,31 @@
+import { useEffect, useState } from "react";
+import { acpApi, type AcpSessionMode } from "../api/modules/acp";
+
+/** Modes the selected underlying agent documents. Empty when it has no catalog. */
+export function useAcpSessionModes(
+ runner: string | null | undefined,
+): AcpSessionMode[] {
+ const [modes, setModes] = useState
([]);
+
+ useEffect(() => {
+ const name = (runner ?? "").trim();
+ if (!name) {
+ setModes([]);
+ return;
+ }
+ let cancelled = false;
+ acpApi
+ .sessionModes(name)
+ .then((data) => {
+ if (!cancelled) setModes(data.modes ?? []);
+ })
+ .catch(() => {
+ if (!cancelled) setModes([]);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [runner]);
+
+ return modes;
+}
diff --git a/dashboard/src/hooks/useDashboardPushToast.tsx b/dashboard/src/hooks/useDashboardPushToast.tsx
index eca8e5b0ce..7008a115c6 100644
--- a/dashboard/src/hooks/useDashboardPushToast.tsx
+++ b/dashboard/src/hooks/useDashboardPushToast.tsx
@@ -5,8 +5,16 @@ import { useTranslation } from "react-i18next";
import { useNavigate } from "react-router-dom";
import { buildDashboardNotifyWsUrl } from "../api/modules/wsNotifications";
import { getAuthToken } from "../api/request";
-import { useAgent } from "../context/AgentContext";
+import { useAgent, type OctopAgent } from "../context/AgentContext";
import { ExpertIcon } from "../pages/Experts/components/iconForName";
+import {
+ ManagedAvatarMark,
+ managedRunnerId,
+} from "../pages/Experts/components/ManagedAvatarMark";
+import {
+ incomingShareProps,
+ SharedAvatarMark,
+} from "../components/SharedResourceBadge";
import {
emitSessionEvent,
invalidateHistory,
@@ -61,20 +69,24 @@ function systemNotifyOptions(
};
}
-function PushToastIcon({
- iconUrl,
- iconName,
-}: {
- iconUrl?: string | null;
- iconName?: string | null;
-}) {
+function PushToastIcon({ agent }: { agent?: OctopAgent }) {
+ const icon =
+ agent?.icon_url || agent?.icon_name ? (
+
+ ) : (
+
+ );
return (
- {iconUrl || iconName ? (
-
- ) : (
-
- )}
+
+
+ {icon}
+
+
);
}
@@ -149,10 +161,7 @@ export function useDashboardPushToast(): void {
},
message: (
-
+
{pushTitle(parsed)}
),
diff --git a/dashboard/src/layouts/PageShell.tsx b/dashboard/src/layouts/PageShell.tsx
index e06a5381f7..95d0313d1a 100644
--- a/dashboard/src/layouts/PageShell.tsx
+++ b/dashboard/src/layouts/PageShell.tsx
@@ -39,6 +39,8 @@ interface PageShellProps {
agentScoped?: boolean;
/** Include team hosts in the agent picker (memory / channels). */
showTeams?: boolean;
+ /** Omit managed experts from the agent picker (tools / plugins / MBTI). */
+ hideManaged?: boolean;
/** When true, the content area does not scroll; children fill remaining height. */
fill?: boolean;
children: React.ReactNode;
@@ -96,6 +98,7 @@ function PageShell({
pathTabs,
agentScoped,
showTeams,
+ hideManaged,
fill,
children,
}: PageShellProps) {
@@ -179,7 +182,7 @@ function PageShell({
{agentScoped && (
)}
diff --git a/dashboard/src/locales/en.json b/dashboard/src/locales/en.json
index e4ecedf234..7346f3dbc1 100644
--- a/dashboard/src/locales/en.json
+++ b/dashboard/src/locales/en.json
@@ -199,7 +199,7 @@
"SKILL_PACKAGE_NOT_FOUND": "Skill package not found.",
"SKILL_PACKAGE_NAME_TAKEN": "Skill package {{name}} already exists.",
"SKILL_PACKAGE_BACKEND_UNSUPPORTED": "Skill packages currently support only “Full local environment (filesystem + shell)” or “Local filesystem (no shell commands)”, with storage root / (POSIX) or the agent workspace root (Windows default).",
- "ACP_BACKEND_UNSUPPORTED": "This agent has a sandbox enabled, so external runners can’t be enabled or edited here. The outbound acp_runner tool toggle is unaffected; connecting via IDE / octop acp is also unaffected.",
+ "ACP_BACKEND_UNSUPPORTED": "This agent has a sandbox enabled, so external agents can’t be enabled or edited here. External agent collaboration for this expert is unaffected; connecting via IDE / octop acp is also unaffected.",
"PUBLISHED_EXPERT_SLUG_TAKEN": "Published expert slug {{slug}} already exists.",
"PUBLISHED_EXPERT_ALREADY_EXISTS": "This agent is already published as “{{name}}”. Refresh the published template instead.",
"OIDC_BAD_REQUEST": "Invalid OIDC request: {{detail}}",
@@ -283,7 +283,7 @@
"tasks": "Automation",
"connectors": "Connectors",
"bridge": "Cloud collab",
- "acp": "ACP Collaboration",
+ "acp": "Agent collaboration",
"agents": "Agents",
"providers": "Providers",
"models": "Model Configuration",
@@ -1171,6 +1171,7 @@
"defaultModeHint": "Ask / Plan / Craft mode for new conversations; Craft is the full-execution mode. Existing conversations are unaffected.",
"skillPackagesLabel": "Optional Skill Packages",
"skillPackagesHint": "Mount packages at create time (local storage with root /).",
+ "managedSkillPackagesHint": "Selected packages are linked into this agent's skill directory. If two packages share a skill name, the first one is kept.",
"skillPackagesUnsupportedHint": "This sandbox cannot mount skill-package directories directly. You can still use Copy skills to create independent workspace copies.",
"skillPackagesClearFailed": "Backend settings saved, but clearing mounted skill packages failed",
"skillPackagesPlaceholder": "Select skill packages",
@@ -1239,8 +1240,8 @@
"backendRootDirPlaceholder": "Browse and select a directory",
"backendRootDirDesc": "Defaults to the filesystem root (`/` on POSIX, the home drive on Windows). You may also browse and pick another directory.",
"backendRootDirDescContainer": "Running in a container: defaults to the filesystem root `/` (the container is already the isolation boundary). You may still browse and pick another directory.",
- "backendRootDirJailHint": "Saving to a non-root directory enables a sandbox and confines the AI filesystem to that folder. External ACP runners can’t be used with this setup; connecting via IDE / octop acp is unaffected.",
- "backendRootDirPathLimitHint": "Saving to a non-root directory limits the AI’s file access to that folder, but this host provides no OS-level sandbox — the AI process still runs with the service account’s own permissions. External ACP runners can’t be used with this setup; connecting via IDE / octop acp is unaffected.",
+ "backendRootDirJailHint": "Saving to a non-root directory enables a sandbox and confines the AI filesystem to that folder. External agents can’t be used with this setup; connecting via IDE / octop acp is unaffected.",
+ "backendRootDirPathLimitHint": "Saving to a non-root directory limits the AI’s file access to that folder, but this host provides no OS-level sandbox — the AI process still runs with the service account’s own permissions. External agents can’t be used with this setup; connecting via IDE / octop acp is unaffected.",
"backendRootDirImmutableHint": "Cannot be changed after creation.",
"workspaceDir": "Workspace directory",
"workspaceDirDesc": "Filled with this expert's server default directory. You can choose another one.",
@@ -1269,7 +1270,7 @@
"backendAllowedEmpty": "Allowed: {{types}}. No storage connection of those types exists yet. Create one under Storage backends first.",
"backendPathMappings": "Path Mappings (optional)",
"addPathMapping": "Add path mapping",
- "advancedOptions": "Advanced options",
+ "advancedOptions": "Runtime parameters",
"temperature": "Temperature",
"temperatureTooltip": "Sampling temperature — higher values produce more varied output",
"topP": "Top P",
@@ -1344,20 +1345,24 @@
"managed": {
"create": "Create",
"createTitle": "New managed expert",
+ "editTitle": "Edit managed expert",
"badge": "Managed",
"name": "Name",
"nameRequired": "Enter a name",
"runner": "Managed agent",
- "manageAcp": "Manage ACP",
+ "manageAcp": "Manage agent collaboration",
"runnerRequired": "Choose a managed agent",
- "noRunners": "Enable a runner on the ACP page first.",
+ "noRunners": "Enable an agent on the Agent collaboration page first.",
"runnerSearch": "Search managed agents",
"runnerSearchEmpty": "No matching managed agents",
"workspaceRequired": "Choose a working directory",
"description": "Description",
- "loadFailed": "Could not load ACP runners",
+ "loadFailed": "Could not load external agents",
"templateFailed": "Could not load the default prompts. Built-in files are still copied on create.",
- "createFailed": "Could not create the managed expert"
+ "createFailed": "Could not create the managed expert",
+ "yolo": "YOLO",
+ "yoloHint": "New chats skip approval. The underlying agent runs actions directly, including file edits and commands. A chat can still switch back to asking every time.",
+ "sessionModeHint": "Modes come from the managed agent. New chats start here, and a chat can still switch."
}
},
"subagents": {
@@ -1450,6 +1455,7 @@
"insufficient_balance": "The model provider rejected this request due to insufficient balance or quota. Top up or upgrade the plan for this API key, then try again.",
"context_length": "This conversation is too long for the model's context window. Start a new chat, or shorten the history and try again.",
"recursion_limit": "The agent hit its max iteration / recursion limit before finishing. Open Configuration and raise Max Iterations, then try again.",
+ "tool_call_repeat": "\"{{tool}}\" was called {{count}} times in a row with the same arguments and reached the limit of {{limit}}, so this turn stopped. Try a different approach, or open Configuration, raise Repeated calls in a row, and reload the expert.",
"timeout_network": "Connecting to the model timed out or the network failed. Check your network and retry. If you use a proxy or self-hosted endpoint, confirm it is reachable.",
"provider_unavailable": "The model provider is temporarily unavailable. Retry later, or switch to another model.",
"invalid_request": "This endpoint may reject the live-token field. Turn off “Show live token count in chat” and retry. If it still fails, check whether the model supports tool calling.",
@@ -1468,7 +1474,7 @@
"manageToast": "This is a peer expert. Manage skills, models, knowledge bases, and related settings on the peer Octop.",
"editBanner": "You are editing a peer expert. Changes are saved on the peer Octop.",
"editSkillPackages": "Skill packages stay on this instance and cannot be installed onto a peer expert. That tab is hidden.",
- "editTools": "ACP runners execute on the peer. Plugin icons that are local files on the peer may not preview here.",
+ "editTools": "External agents run on the peer. Plugin icons that are local files on the peer may not preview here.",
"editPlugins": "You can toggle plugins already installed on the peer. Install, uninstall, and marketplace stay on the peer Octop.",
"editChannels": "QR login and bot-creator flows run on the peer machine, not this browser.",
"editTasks": "Tasks use the peer timezone. Model and connector options come from the peer; install new connectors there.",
@@ -1480,7 +1486,7 @@
"reconnect": "Reconnect",
"openBridge": "View connection",
"peerOnlyTitle": "This page stays on this instance",
- "peerOnlyAcp": "ACP runners listed here belong to this Octop. Pick a local expert to toggle its ACP tool, or open the peer expert’s Tools tab to manage the peer.",
+ "peerOnlyAcp": "External agents listed here belong to this Octop. Open the peer expert’s Tools tab to toggle external agent collaboration.",
"peerOnlyBrowser": "This page controls the browser on this host. For a peer expert, open the browser dock in chat instead."
},
"pushToast": {
@@ -1613,6 +1619,13 @@
"executeUtterance": "Execute {{path}}",
"keepEditing": "Keep editing"
},
+ "managedApproval": {
+ "picker": "Approval mode",
+ "ask": "Ask every time",
+ "askHint": "Confirm each action from the underlying agent before it runs.",
+ "yolo": "YOLO",
+ "yoloHint": "Skip approval. The underlying agent runs actions directly, including file edits and commands."
+ },
"errorOccurred": "An error occurred",
"imageLoadFailed": "Image failed to load",
"mediaLoadFailed": "Unable to load media",
@@ -2067,7 +2080,7 @@
"ask_agent": "Ask expert",
"call_agent": "Call expert",
"call_deferred_tool": "Call on demand",
- "acp_runner": "ACP external agent",
+ "acp_runner": "External agent collaboration",
"external-agent": "Managed agent",
"browser_use": "Use browser",
"browser_control": "Browser control",
@@ -2089,6 +2102,7 @@
"toolSettings": {
"title": "Tool settings",
"hint": "Turn off built-in tools you do not want the model to call. Required system tools cannot be disabled.",
+ "hintManaged": "Only tools Octop can attach are listed. Files, shell, and web tools belong to the external agent. A switch stays off until memory is enabled, a knowledge base is selected, or another expert can be called.",
"hintPlugin": "Turn off plugin tools you do not want the model to call. Unloaded plugins must be enabled under Plugins first.",
"empty": "No tools available",
"emptyPlugin": "No plugin tools yet. Enable plugins for this agent on the Plugins tab first.",
@@ -2104,7 +2118,7 @@
"pluginToolCount": "{{count}} tools",
"tabs": {
"builtin": "Built-in tools",
- "acp": "ACP Collaboration tools",
+ "acp": "Agent collaboration",
"plugin": "Plugin tools"
},
"categories": {
@@ -4236,10 +4250,10 @@
"noActiveAgent": "Select an agent first",
"retryDelayBelowInitial": "Maximum delay must be at least the initial delay",
"toolCallLimit": {
- "enabled": "Limit tool calls per turn",
- "enabledTooltip": "Cap how many times tools can be called in one user turn. The turn ends when the cap is reached. Turn this off for no cap. Saving reloads this expert.",
- "runLimit": "Tool calls per turn",
- "runLimitTooltip": "Maximum tool calls in one user turn. Empty uses 40.",
+ "enabled": "Limit repeated tool calls",
+ "enabledTooltip": "Count a streak of the same tool called with the same arguments. A different tool or different arguments starts the count over. The turn ends when the streak reaches the limit. Turn this off for no cap. Saving reloads this expert.",
+ "runLimit": "Repeated calls in a row",
+ "runLimitTooltip": "How many times the same tool may be called in a row with the same arguments. Other tools and other arguments are not counted. Empty uses 40.",
"runLimitPlaceholder": "40"
},
"modelRetry": {
@@ -4413,6 +4427,7 @@
},
"upload": {
"tooltip": "Upload files or a folder. You can also drop them on the input.",
+ "action": "Upload",
"files": "Files",
"folder": "Folder",
"dropHint": "Drop files or a folder to upload",
@@ -6244,6 +6259,7 @@
"remoteKindGroup": "{{name}}·{{kind}}",
"more": "More",
"teamNeedsExpert": "\"{{name}}\" is a team. Choose an expert for this page.",
+ "managedNeedsExpert": "\"{{name}}\" is a managed expert. Choose another expert for this page.",
"expertsRequired": "This page needs an expert"
},
"login": {
@@ -7304,11 +7320,11 @@
"pickAgent": "Select an Agent first"
},
"acp": {
- "description": "Connect external ACP-compatible coding agents. Runner settings are shared across all your agents; enable the acp_runner tool per agent below.",
- "globalRunnersHint": "Runner configuration below applies to all agents for your account.",
- "toolEnabledHint": "The acp_runner tool is enabled per agent — switch the agent above to configure the current one.",
- "toolEnabled": "Enable outbound delegation (acp_runner)",
- "outboundBlockedHint": "This agent has a sandbox enabled, so external runners can’t be enabled or edited here. The outbound acp_runner tool toggle is unaffected; connecting via IDE / octop acp is also unaffected.",
+ "description": "Connect external ACP-compatible coding agents. Agent settings are shared across all your experts; enable external agent collaboration for the current expert below.",
+ "globalRunnersHint": "The agent configuration below applies to every expert on this account.",
+ "toolEnabledHint": "The external agent collaboration tool is enabled per expert. Switch the expert above to configure the current one.",
+ "toolEnabled": "Enable external agent collaboration for this expert",
+ "outboundBlockedHint": "This expert has a sandbox enabled, so external agents can’t be enabled or edited here. External agent collaboration for this expert is unaffected; connecting via IDE / octop acp is also unaffected.",
"outboundBlockedTooltip": "Unavailable to enable or edit in sandbox",
"runnerUnavailable": "Unavailable",
"builtin": "Built-in",
@@ -7327,16 +7343,16 @@
"intro_kimi_code": "Moonshot Kimi Code CLI — run kimi acp after kimi login.",
"intro_cursor_cli": "Cursor CLI agent — run agent acp after agent login or set CURSOR_API_KEY.",
"intro_pi": "Pi coding agent via pi-acp bridge (npx -y pi-acp).",
- "intro_custom": "Custom runner: {{command}}",
+ "intro_custom": "Custom agent: {{command}}",
"runnerNeedsConfig": "Enabled — configure command",
"clickCardToConfigure": "Click the card to set the launch command first",
- "create": "Add runner",
- "createTitle": "Add ACP runner",
- "editTitle": "Edit runner",
- "runnerKey": "Runner ID",
- "runnerKeyRequired": "Runner ID is required",
+ "create": "Add agent",
+ "createTitle": "Add external agent",
+ "editTitle": "Edit agent",
+ "runnerKey": "Agent ID",
+ "runnerKeyRequired": "Agent ID is required",
"runnerKeyInvalid": "Use letters, numbers, underscore or hyphen only",
- "runnerKeyExists": "This runner ID is already in use. Open that card to edit it. A custom runner can be deleted from its editor.",
+ "runnerKeyExists": "This agent ID is already in use. Open that card to edit it. A custom agent can be deleted from its editor.",
"command": "Command",
"commandRequired": "Command is required",
"args": "Arguments",
@@ -7347,7 +7363,7 @@
"askHint": "Sends who are you? over ACP and shows the reply above the buttons.",
"askResult": "Reply to who are you?",
"askFailed": "The probe did not return a reply",
- "trusted": "Trusted runner",
+ "trusted": "Trusted agent",
"toolParseMode": "Tool parse mode",
"stdioBufferLimit": "Stdio buffer limit (bytes)",
"notSet": "Not set",
@@ -7356,13 +7372,13 @@
"saveNeedsInstall": "Not saved: {{status}}",
"saveNeedsInstallDetail": "Not saved: {{status}}. {{detail}}",
"configFailed": "Failed to save ACP config",
- "createSuccess": "Runner created",
+ "createSuccess": "Agent created",
"deleteTitle": "Delete {{name}}?",
- "deleteConfirm": "This custom runner will be removed.",
- "deleteSuccess": "Runner deleted",
- "docsHint": "Install an ACP-compatible agent locally (opencode, codebuddy --acp, etc.) before enabling a runner.",
+ "deleteConfirm": "This custom agent will be removed.",
+ "deleteSuccess": "Agent deleted",
+ "docsHint": "Install an ACP-compatible agent locally (opencode, codebuddy --acp, etc.) before enabling it.",
"chatPermissionTitle": "External agent permission required",
- "runnerReenabled": "This runner was disabled. It has been updated and turned back on.",
+ "runnerReenabled": "This agent was disabled. It has been updated and turned back on.",
"installOnHost": "Install on the machine that runs Octop",
"host": {
"title": "Host probe",
@@ -7411,7 +7427,7 @@
}
},
"advanced": "Advanced",
- "disableKeepsRunner": "Turning a runner off keeps its settings. The ID stays reserved. Delete a custom runner from this editor to free the ID."
+ "disableKeepsRunner": "Turning an agent off keeps its settings. The ID stays reserved. Delete a custom agent from this editor to free the ID."
},
"plugins": {
"loadError": "Failed to load plugins",
@@ -7569,8 +7585,8 @@
"subtitle": "Connect docs, cloud storage, and email, then use them in chat as needed"
},
"acp": {
- "title": "ACP Collaboration",
- "subtitle": "Configure external coding-agent runners and enable them per expert"
+ "title": "Agent collaboration",
+ "subtitle": "Configure external agents and enable collaboration on this expert"
},
"skills": {
"title": "Skills",
@@ -7906,6 +7922,14 @@
"notAuthorized": "Not authorized",
"remaining": "Remaining",
"regionPlaceholder": "Regions (all by default)",
+ "regionAll": "All regions",
+ "regionRecent": "Recently used",
+ "regionAllAreas": "All areas",
+ "regionOtherArea": "Other areas",
+ "regionOthers": "Others ({{count}})",
+ "regionSelectedMulti": "{{name}} +{{count}}",
+ "regionSelectedTotal": "{{count}} selected",
+ "regionClear": "Clear filter",
"refresh": "Refresh",
"renew": "Renew",
"manageAuth": "Manage",
diff --git a/dashboard/src/locales/zh.json b/dashboard/src/locales/zh.json
index bdd15364a7..d003cf6df2 100644
--- a/dashboard/src/locales/zh.json
+++ b/dashboard/src/locales/zh.json
@@ -199,7 +199,7 @@
"SKILL_PACKAGE_NOT_FOUND": "未找到技能包。",
"SKILL_PACKAGE_NAME_TAKEN": "技能包 {{name}} 已存在。",
"SKILL_PACKAGE_BACKEND_UNSUPPORTED": "技能包目前仅支持「本地完整环境(文件系统+指令执行)」或「本地文件系统(不能执行指令)」,且存储根目录须为 /(POSIX)或专家的工作区根目录(Windows 默认)。",
- "ACP_BACKEND_UNSUPPORTED": "当前专家已启用沙箱环境,不可启用或编辑外部 Runner。启用向外委托(acp_runner)不受影响;通过 IDE / octop acp 接入也不受影响。",
+ "ACP_BACKEND_UNSUPPORTED": "当前专家已启用沙箱环境,不可启用或编辑外部智能体。在当前专家中启用外部智能体协作不受影响;通过 IDE / octop acp 接入也不受影响。",
"PUBLISHED_EXPERT_SLUG_TAKEN": "已存在发布专家 slug:{{slug}}。",
"PUBLISHED_EXPERT_ALREADY_EXISTS": "该专家已发布为「{{name}}」,请改为刷新已发布模板。",
"OIDC_BAD_REQUEST": "OIDC 请求无效:{{detail}}",
@@ -283,7 +283,7 @@
"tasks": "自动化",
"connectors": "连接器",
"bridge": "云端协同",
- "acp": "ACP 协作",
+ "acp": "智能体协作",
"agents": "专家",
"providers": "供应商",
"models": "模型配置",
@@ -1171,6 +1171,7 @@
"defaultModeHint": "新建对话时使用的 Ask / Plan / Craft 模式;Craft 为完整执行模式。已有对话不受影响。",
"skillPackagesLabel": "可选技能包",
"skillPackagesHint": "创建时挂载选中的技能包(需本地存储,且根目录为 /)。",
+ "managedSkillPackagesHint": "选中的技能包会放进这个智能体的技能目录。同名技能以先选中的包为准。",
"skillPackagesUnsupportedHint": "当前沙箱无法直接挂载技能包目录,但仍可使用“复制技能”在工作区创建独立副本。",
"skillPackagesClearFailed": "已保存后端设置,但清除已挂载技能包失败",
"skillPackagesPlaceholder": "选择技能包",
@@ -1240,8 +1241,8 @@
"backendRootDirPlaceholder": "浏览并选择目录",
"backendRootDirDesc": "默认使用文件系统的根目录(POSIX 为 `/`,Windows 为所在盘符)。也可浏览并选择其他目录。",
"backendRootDirDescContainer": "当前运行在容器环境中,默认使用文件系统根目录 `/`(容器本身已是隔离边界)。也可浏览并选择其他目录。",
- "backendRootDirJailHint": "保存至非根目录时,会启用沙箱环境并将 AI 文件系统限制在该目录内。此配置下无法调用外部 ACP Runner;通过 IDE / octop acp 接入不受影响。",
- "backendRootDirPathLimitHint": "保存至非根目录时,会将 AI 的文件访问限制在该目录内;但当前系统未提供操作系统级沙箱,AI 进程仍以服务账号自身的权限运行。此配置下无法调用外部 ACP Runner;通过 IDE / octop acp 接入不受影响。",
+ "backendRootDirJailHint": "保存至非根目录时,会启用沙箱环境并将 AI 文件系统限制在该目录内。此配置下无法调用外部智能体;通过 IDE / octop acp 接入不受影响。",
+ "backendRootDirPathLimitHint": "保存至非根目录时,会将 AI 的文件访问限制在该目录内;但当前系统未提供操作系统级沙箱,AI 进程仍以服务账号自身的权限运行。此配置下无法调用外部智能体;通过 IDE / octop acp 接入不受影响。",
"backendRootDirImmutableHint": "创建后不可更改。",
"workspaceDir": "工作区目录",
"workspaceDirDesc": "已填入系统为这位专家分配的默认目录,也可以改成其他目录。",
@@ -1289,7 +1290,7 @@
},
"backendPathMappings": "路径映射(可选)",
"addPathMapping": "添加路径映射",
- "advancedOptions": "高级选项",
+ "advancedOptions": "运行参数",
"temperature": "温度 (temperature)",
"temperatureTooltip": "采样温度,越高输出越随机",
"topP": "Top P",
@@ -1344,20 +1345,24 @@
"managed": {
"create": "创建",
"createTitle": "新建托管专家",
+ "editTitle": "编辑托管专家",
"badge": "托管",
"name": "名称",
"nameRequired": "请填写名称",
"runner": "托管智能体",
- "manageAcp": "管理 ACP",
+ "manageAcp": "管理智能体协作",
"runnerRequired": "请选择一个托管智能体",
- "noRunners": "请先在 ACP 页面启用一个 Runner。",
+ "noRunners": "请先在智能体协作页面启用一个智能体。",
"runnerSearch": "搜索托管智能体",
"runnerSearchEmpty": "没有匹配的托管智能体",
"workspaceRequired": "请选择工作目录",
"description": "描述",
- "loadFailed": "无法加载 ACP Runner",
+ "loadFailed": "无法加载外部智能体",
"templateFailed": "默认提示词加载失败,创建时仍会写入内置内容",
- "createFailed": "创建托管专家失败"
+ "createFailed": "创建托管专家失败",
+ "yolo": "YOLO",
+ "yoloHint": "新会话默认不审批。底层智能体会直接执行,包括改文件和运行命令。对话里仍可改回每次审批。",
+ "sessionModeHint": "按当前托管智能体提供的模式。新对话默认用这里的选择,单个对话里还可以改。"
}
},
"subagents": {
@@ -1450,6 +1455,7 @@
"insufficient_balance": "模型服务返回余额或额度不足。请为该 API Key 对应的账户充值或升级套餐后再试。",
"context_length": "对话上下文过长,超出模型限制。请新开会话,或精简历史后再试。",
"recursion_limit": "智能体已达到最大迭代次数(递归上限),任务尚未完成。请前往「运行配置」调高「最大迭代次数」后重试。",
+ "tool_call_repeat": "工具「{{tool}}」带着相同参数已连续调用 {{count}} 次,达到上限 {{limit}},本轮已停止。请换一种做法,或前往「运行配置」调高「连续相同调用上限」,保存后重新加载该专家。",
"timeout_network": "连接模型服务超时或网络异常。请检查网络后重试;若使用代理或自建服务,请确认其可达。",
"provider_unavailable": "模型服务暂时不可用。请稍后重试,或切换其他模型。",
"invalid_request": "该接口可能不接受用量字段。可关闭「聊天里显示实时 Token」后重试;若仍失败,请确认模型是否支持工具调用。",
@@ -1468,7 +1474,7 @@
"manageToast": "当前是对端专家,技能 / 模型 / 知识库等请在对端 Octop 上管理",
"editBanner": "正在编辑对端专家,改动会保存到对端 Octop。",
"editSkillPackages": "技能包属于本机用户资源,无法安装到对端专家,该页签已隐藏。",
- "editTools": "ACP 运行器在对端执行。插件图标若是对端本地文件,这里可能无法预览。",
+ "editTools": "外部智能体在对端执行。插件图标若是对端本地文件,这里可能无法预览。",
"editPlugins": "此处只能开关对端已安装的插件;安装、卸载和市场请在对端进行。",
"editChannels": "扫码登录和机器人创建会在对端机器上执行,而不是这台浏览器。",
"editTasks": "任务按对端时区运行。模型与连接器选项来自对端,新增连接器请在对端安装。",
@@ -1480,7 +1486,7 @@
"reconnect": "去重连",
"openBridge": "查看连接",
"peerOnlyTitle": "此页只管理本机",
- "peerOnlyAcp": "这里的 ACP 运行器属于本机 Octop。要开关对端专家的 ACP 工具,请打开该专家的「工具」页签。",
+ "peerOnlyAcp": "这里的外部智能体属于本机 Octop。要开关对端专家的外部智能体协作工具,请打开该专家的「工具」页签。",
"peerOnlyBrowser": "此页控制本机浏览器。对端专家请在聊天侧栏打开浏览器面板。"
},
"pushToast": {
@@ -1613,6 +1619,13 @@
"executeUtterance": "请按 {{path}} 执行",
"keepEditing": "继续改计划"
},
+ "managedApproval": {
+ "picker": "审批模式",
+ "ask": "每次审批",
+ "askHint": "底层智能体每次执行操作前都需要确认。",
+ "yolo": "YOLO",
+ "yoloHint": "不需要审批。底层智能体会直接执行,包括改文件和运行命令。"
+ },
"errorOccurred": "出现错误",
"imageLoadFailed": "图片加载失败",
"mediaLoadFailed": "无法加载媒体",
@@ -2067,7 +2080,7 @@
"ask_agent": "咨询专家",
"call_agent": "调用专家",
"call_deferred_tool": "按需调用",
- "acp_runner": "ACP 外部专家",
+ "acp_runner": "外部智能体协作",
"external-agent": "托管智能体",
"browser_use": "使用浏览器",
"browser_control": "浏览器控制",
@@ -2089,6 +2102,7 @@
"toolSettings": {
"title": "工具设置",
"hint": "关闭后模型将无法调用该内置工具。系统必需工具不可关闭。",
+ "hintManaged": "这里只列出 Octop 能挂上的工具。文件、命令和网页由外部智能体自己提供。记忆未开启、没有知识库或没有其他专家时,对应开关不可用。",
"hintPlugin": "关闭后模型将无法调用该插件工具。未挂载的插件需先在「插件管理」中启用。",
"empty": "暂无工具",
"emptyPlugin": "暂无插件工具。请先在「插件」页为当前智能体启用插件。",
@@ -2104,7 +2118,7 @@
"pluginToolCount": "{{count}} 个工具",
"tabs": {
"builtin": "内置工具",
- "acp": "ACP 协作工具",
+ "acp": "智能体协作",
"plugin": "插件工具"
},
"categories": {
@@ -4236,10 +4250,10 @@
"noActiveAgent": "请先选择一个专家",
"retryDelayBelowInitial": "最大间隔不能小于初始间隔",
"toolCallLimit": {
- "enabled": "限制单轮工具调用",
- "enabledTooltip": "限制一次用户请求里工具被调用的总次数。达到上限后结束本轮。关闭后不限制。保存后重新加载该专家。",
- "runLimit": "单轮工具调用上限",
- "runLimitTooltip": "一次用户请求里最多调用多少次工具。留空为 40。",
+ "enabled": "限制连续相同工具调用",
+ "enabledTooltip": "同一个工具带着相同参数连续调用时计数。换成别的工具或参数后重新计数。达到上限后结束本轮。关闭后不限制。保存后重新加载该专家。",
+ "runLimit": "连续相同调用上限",
+ "runLimitTooltip": "同一个工具、同一组参数最多连续调用多少次。不同工具或不同参数不累计。留空为 40。",
"runLimitPlaceholder": "40"
},
"modelRetry": {
@@ -4413,6 +4427,7 @@
},
"upload": {
"tooltip": "上传文件或文件夹。也可拖到输入框。",
+ "action": "上传",
"files": "文件",
"folder": "文件夹",
"dropHint": "松开以上传文件或文件夹",
@@ -6244,6 +6259,7 @@
"remoteKindGroup": "{{name}}·{{kind}}",
"more": "更多",
"teamNeedsExpert": "当前是团队「{{name}}」,此页请选择专家",
+ "managedNeedsExpert": "当前是托管专家「{{name}}」,此页请选择其他专家",
"expertsRequired": "此页需要专家"
},
"login": {
@@ -7304,11 +7320,11 @@
"pickAgent": "请先选择一个专家"
},
"acp": {
- "description": "连接支持 ACP 协议的外部编程专家。Runner 配置对该账号下所有专家共享;可在下方按专家单独开启 acp_runner 工具。",
- "globalRunnersHint": "以下 Runner 配置对该账号下所有专家生效。",
- "toolEnabledHint": "acp_runner 工具需按专家单独开启,切换上方专家后为当前专家配置。",
- "toolEnabled": "启用向外委托(acp_runner)",
- "outboundBlockedHint": "当前专家已启用沙箱环境,不可启用或编辑外部 Runner。启用向外委托(acp_runner)不受影响;通过 IDE / octop acp 接入也不受影响。",
+ "description": "连接支持 ACP 协议的外部编程智能体。智能体配置对该账号下所有专家共享;可在下方为当前专家启用外部智能体协作。",
+ "globalRunnersHint": "以下智能体配置对该账号下所有专家生效。",
+ "toolEnabledHint": "外部智能体协作工具需按专家单独开启,切换上方专家后为当前专家配置。",
+ "toolEnabled": "在当前专家中启用外部智能体协作",
+ "outboundBlockedHint": "当前专家已启用沙箱环境,不可启用或编辑外部智能体。在当前专家中启用外部智能体协作不受影响;通过 IDE / octop acp 接入也不受影响。",
"outboundBlockedTooltip": "沙箱环境下不可启用或编辑",
"runnerUnavailable": "不可用",
"builtin": "内置",
@@ -7327,16 +7343,16 @@
"intro_kimi_code": "月之暗面 Kimi Code CLI,先 kimi 登录后使用 kimi acp 启动。",
"intro_cursor_cli": "Cursor CLI agent,先 agent login 或设置 CURSOR_API_KEY 后使用 agent acp 启动。",
"intro_pi": "Pi 编程专家,通过 pi-acp 桥接(npx -y pi-acp)接入 ACP。",
- "intro_custom": "自定义 Runner:{{command}}",
+ "intro_custom": "自定义智能体:{{command}}",
"runnerNeedsConfig": "已启用,待配置命令",
"clickCardToConfigure": "请先点击卡片配置启动命令",
- "create": "添加 Runner",
- "createTitle": "添加 ACP Runner",
- "editTitle": "编辑 Runner",
- "runnerKey": "Runner ID",
- "runnerKeyRequired": "请填写 Runner ID",
+ "create": "添加智能体",
+ "createTitle": "添加外部智能体",
+ "editTitle": "编辑智能体",
+ "runnerKey": "智能体 ID",
+ "runnerKeyRequired": "请填写智能体 ID",
"runnerKeyInvalid": "仅允许字母、数字、下划线和连字符",
- "runnerKeyExists": "该 Runner ID 已被占用。请打开对应卡片编辑;自定义 Runner 可在编辑里删除。",
+ "runnerKeyExists": "该智能体 ID 已被占用。请打开对应卡片编辑;自定义智能体可在编辑里删除。",
"command": "启动命令",
"commandRequired": "请填写启动命令",
"args": "参数",
@@ -7347,7 +7363,7 @@
"askHint": "向 ACP 发送 who are you?,回复显示在按钮上方。",
"askResult": "who are you? 的回复",
"askFailed": "探测没有得到回复",
- "trusted": "受信任 Runner",
+ "trusted": "受信任智能体",
"toolParseMode": "工具解析模式",
"stdioBufferLimit": "Stdio 缓冲上限(字节)",
"notSet": "未设置",
@@ -7356,13 +7372,13 @@
"configFailed": "保存 ACP 配置失败",
"saveNeedsInstall": "未保存:{{status}}",
"saveNeedsInstallDetail": "未保存:{{status}}。{{detail}}",
- "createSuccess": "Runner 已创建",
+ "createSuccess": "智能体已创建",
"deleteTitle": "删除 {{name}}?",
- "deleteConfirm": "将移除此自定义 Runner。",
- "deleteSuccess": "Runner 已删除",
- "docsHint": "请先在本地安装并配置好 ACP 专家(如 opencode、codebuddy --acp)后再启用 Runner。",
+ "deleteConfirm": "将移除此自定义智能体。",
+ "deleteSuccess": "智能体已删除",
+ "docsHint": "请先在本地安装并配置好外部智能体(如 opencode、codebuddy --acp)后再启用。",
"chatPermissionTitle": "外部专家需要权限确认",
- "runnerReenabled": "该 Runner 之前是关闭状态,已按本次填写更新并重新启用。",
+ "runnerReenabled": "该智能体之前是关闭状态,已按本次填写更新并重新启用。",
"installOnHost": "在运行 Octop 的机器上安装",
"host": {
"title": "本机探测",
@@ -7411,7 +7427,7 @@
}
},
"advanced": "高级设置",
- "disableKeepsRunner": "卡片上的开关只是关闭,配置仍保留,ID 也不会释放。要腾出 ID,请在此删除自定义 Runner。"
+ "disableKeepsRunner": "卡片上的开关只是关闭,配置仍保留,ID 也不会释放。要腾出 ID,请在此删除自定义智能体。"
},
"plugins": {
"loadError": "加载插件失败",
@@ -7569,8 +7585,8 @@
"subtitle": "连接文档、网盘与邮箱,并在对话中按需使用"
},
"acp": {
- "title": "ACP 协作",
- "subtitle": "配置外部编程专家 Runner,并按专家开启协作"
+ "title": "智能体协作",
+ "subtitle": "配置外部智能体,并在当前专家中开启协作"
},
"skills": {
"title": "技能",
@@ -7906,6 +7922,14 @@
"notAuthorized": "未授权",
"remaining": "剩余",
"regionPlaceholder": "选择地域(默认全部)",
+ "regionAll": "全部地域",
+ "regionRecent": "最近访问",
+ "regionAllAreas": "全部地区",
+ "regionOtherArea": "其他地区",
+ "regionOthers": "其它地域({{count}})",
+ "regionSelectedMulti": "{{name}} 等 {{count}} 个",
+ "regionSelectedTotal": "已选 {{count}} 个地域",
+ "regionClear": "清空筛选",
"refresh": "刷新",
"renew": "续期",
"manageAuth": "管理授权",
diff --git a/dashboard/src/pages/Agent/Memory/AtomsList.tsx b/dashboard/src/pages/Agent/Memory/AtomsList.tsx
index bf65ba8d97..fed415e7e5 100644
--- a/dashboard/src/pages/Agent/Memory/AtomsList.tsx
+++ b/dashboard/src/pages/Agent/Memory/AtomsList.tsx
@@ -5,7 +5,13 @@
* star importance, percentage confidence, relative timestamps, and no raw metadata IDs.
*/
-import { useCallback, useEffect, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
import {
Button,
Progress,
@@ -33,6 +39,7 @@ import MemoryPipelineEmpty from "./shared/MemoryPipelineEmpty";
import { confirmDeprecateAtom } from "./shared/deprecateAtom";
import { confirmEditAtom } from "./shared/editAtom";
import CreateAtomModal from "./shared/createAtom";
+import { useMemoryRequestGate } from "./shared/useMemoryRequestGate";
const PAGE_SIZE = 20;
@@ -69,8 +76,30 @@ export default function AtomsList({ agentId }: Props) {
const [hoveredId, setHoveredId] = useState(null);
const [entities, setEntities] = useState([]);
const [createOpen, setCreateOpen] = useState(false);
+ const listGate = useMemoryRequestGate(
+ JSON.stringify([agentId, page, kind, importance]),
+ );
+ const entityGate = useMemoryRequestGate(agentId);
+ const actionModal = useRef<{ destroy: () => void } | null>(null);
+
+ useLayoutEffect(() => {
+ setItems([]);
+ setTotal(0);
+ setPage(1);
+ setLoading(Boolean(agentId));
+ setSelected(null);
+ setHoveredId(null);
+ setEntities([]);
+ setCreateOpen(false);
+ return () => {
+ actionModal.current?.destroy();
+ actionModal.current = null;
+ };
+ }, [agentId]);
const load = useCallback(async () => {
+ const isCurrent = listGate.begin();
+ if (!isCurrent) return;
setLoading(true);
const body: ListAtomsBody = {
offset: (page - 1) * PAGE_SIZE,
@@ -80,44 +109,66 @@ export default function AtomsList({ agentId }: Props) {
if (importance) body.importance_min = importance;
try {
const r = await memoryDashboardApi.listAtoms(agentId, body);
+ if (!isCurrent()) return;
setItems(r.items);
setTotal(r.total);
+ } catch (error) {
+ if (isCurrent()) throw error;
} finally {
- setLoading(false);
+ if (isCurrent()) setLoading(false);
}
- }, [agentId, page, kind, importance]);
+ }, [agentId, page, kind, importance, listGate]);
+ const reload = useRef(load);
+ useLayoutEffect(() => {
+ reload.current = load;
+ }, [load]);
+
+ const loadEntities = useCallback(
+ async (clearOnError: boolean) => {
+ const isCurrent = entityGate.begin();
+ if (!isCurrent) return;
+ try {
+ const r = await memoryDashboardApi.listEntities(agentId, {
+ limit: 200,
+ order_by: "atom_count",
+ order: "desc",
+ });
+ if (isCurrent()) setEntities(r.items);
+ } catch {
+ if (isCurrent() && clearOnError) setEntities([]);
+ }
+ },
+ [agentId, entityGate],
+ );
useEffect(() => {
if (!agentId) return;
void load();
- void memoryDashboardApi
- .listEntities(agentId, {
- limit: 200,
- order_by: "atom_count",
- order: "desc",
- })
- .then((r) => setEntities(r.items))
- .catch(() => setEntities([]));
- }, [agentId, load]);
+ void loadEntities(true);
+ }, [agentId, load, loadEntities]);
const handleDeprecate = (atom: AtomItem) => {
- confirmDeprecateAtom({
+ actionModal.current = confirmDeprecateAtom({
agentId,
atom,
+ isActive: entityGate.isActive,
onSuccess: () => {
+ if (!entityGate.isActive()) return;
setSelected(null);
- void load();
+ void reload.current();
},
});
};
const handleEdit = (atom: AtomItem) => {
- confirmEditAtom({
+ actionModal.current = confirmEditAtom({
agentId,
atom,
+ isActive: entityGate.isActive,
onSuccess: (next) => {
+ if (!entityGate.isActive()) return;
setSelected(next);
- void load();
+ void reload.current();
},
});
};
@@ -316,17 +367,14 @@ export default function AtomsList({ agentId }: Props) {
open={createOpen}
agentId={agentId}
entities={entities}
- onClose={() => setCreateOpen(false)}
+ isActive={entityGate.isActive}
+ onClose={() => {
+ if (entityGate.isActive()) setCreateOpen(false);
+ }}
onSuccess={() => {
- void load();
- void memoryDashboardApi
- .listEntities(agentId, {
- limit: 200,
- order_by: "atom_count",
- order: "desc",
- })
- .then((r) => setEntities(r.items))
- .catch(() => undefined);
+ if (!entityGate.isActive()) return;
+ void reload.current();
+ void loadEntities(false);
}}
/>
>
diff --git a/dashboard/src/pages/Agent/Memory/CandidatesReview.tsx b/dashboard/src/pages/Agent/Memory/CandidatesReview.tsx
index 08c4d8a880..21a79c7726 100644
--- a/dashboard/src/pages/Agent/Memory/CandidatesReview.tsx
+++ b/dashboard/src/pages/Agent/Memory/CandidatesReview.tsx
@@ -19,7 +19,13 @@
* - the candidate diff view (vs existing atoms) — covered elsewhere.
*/
-import { useCallback, useEffect, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useRef,
+ useState,
+} from "react";
import {
Alert,
Button,
@@ -48,6 +54,7 @@ import {
type ListCandidatesBody,
} from "../../../api/modules/memoryDashboard";
import { useIsMobile } from "../../../hooks/useIsMobile";
+import { useMemoryRequestGate } from "./shared/useMemoryRequestGate";
import styles from "./CandidatesReview.module.less";
const PAGE_SIZE = 20;
@@ -92,8 +99,26 @@ export default function CandidatesReview({ agentId }: Props) {
// per-row pending state so the spinning button is local, not global
const [busyId, setBusyId] = useState(null);
+ const listGate = useMemoryRequestGate(
+ JSON.stringify([agentId, page, status, kind]),
+ );
+ const agentGate = useMemoryRequestGate(agentId);
+
+ useLayoutEffect(() => {
+ setItems([]);
+ setTotal(0);
+ setPage(1);
+ setLoading(Boolean(agentId));
+ setSelected(null);
+ setRejectTarget(null);
+ setRejectReason("");
+ setRejecting(false);
+ setBusyId(null);
+ }, [agentId]);
const load = useCallback(async () => {
+ const isCurrent = listGate.begin();
+ if (!isCurrent) return;
setLoading(true);
const body: ListCandidatesBody = {
offset: (page - 1) * PAGE_SIZE,
@@ -103,17 +128,22 @@ export default function CandidatesReview({ agentId }: Props) {
if (kind) body.candidate_type = kind;
try {
const r = await memoryDashboardApi.listCandidates(agentId, body);
+ if (!isCurrent()) return;
setItems(r.items);
setTotal(r.total);
} catch (e) {
- message.error((e as Error).message ?? "load failed");
+ if (isCurrent()) message.error((e as Error).message ?? "load failed");
} finally {
- setLoading(false);
+ if (isCurrent()) setLoading(false);
}
// ``t`` is intentionally NOT a dependency — the i18n hook returns
// a fresh ``t`` ref on every render, which would re-fire the load
// effect on every keystroke / hover.
- }, [agentId, page, status, kind]);
+ }, [agentId, page, status, kind, listGate]);
+ const reload = useRef(load);
+ useLayoutEffect(() => {
+ reload.current = load;
+ }, [load]);
useEffect(() => {
if (!agentId) return;
@@ -121,9 +151,11 @@ export default function CandidatesReview({ agentId }: Props) {
}, [agentId, load]);
const handlePromote = async (c: CandidateItem) => {
+ if (!agentGate.isActive()) return;
setBusyId(c.id);
try {
const r = await memoryDashboardApi.promoteCandidate(agentId, c.id);
+ if (!agentGate.isActive()) return;
const detail =
r.merged > 0
? `与现有记忆合并 ${r.merged} 条`
@@ -133,29 +165,32 @@ export default function CandidatesReview({ agentId }: Props) {
message.success(
t("memory.candidates.promoteOk", "已采纳") + ` · ${detail}`,
);
- void load();
+ void reload.current();
} catch (e) {
- message.error((e as Error).message ?? "操作失败");
+ if (agentGate.isActive())
+ message.error((e as Error).message ?? "操作失败");
} finally {
- setBusyId(null);
+ if (agentGate.isActive()) setBusyId(null);
}
};
const handleReject = async () => {
- if (!rejectTarget) return;
+ if (!rejectTarget || !agentGate.isActive()) return;
setRejecting(true);
try {
await memoryDashboardApi.rejectCandidate(agentId, rejectTarget.id, {
reason: rejectReason.trim() || undefined,
});
+ if (!agentGate.isActive()) return;
message.success(t("memory.candidates.rejectOk", "已忽略"));
setRejectTarget(null);
setRejectReason("");
- void load();
+ void reload.current();
} catch (e) {
- message.error((e as Error).message ?? "操作失败");
+ if (agentGate.isActive())
+ message.error((e as Error).message ?? "操作失败");
} finally {
- setRejecting(false);
+ if (agentGate.isActive()) setRejecting(false);
}
};
diff --git a/dashboard/src/pages/Agent/Memory/ConversationRecords.tsx b/dashboard/src/pages/Agent/Memory/ConversationRecords.tsx
index 1aa821969b..c5f43a0439 100644
--- a/dashboard/src/pages/Agent/Memory/ConversationRecords.tsx
+++ b/dashboard/src/pages/Agent/Memory/ConversationRecords.tsx
@@ -37,6 +37,7 @@ import {
} from "../../../utils/messageParser";
import { useIsMobile } from "../../../hooks/useIsMobile";
import { useServerTimezone } from "../../../hooks/useServerTimezone";
+import { useMemoryRequestGate } from "./shared/useMemoryRequestGate";
import {
confirmDeleteConversation,
deleteConversation,
@@ -174,20 +175,28 @@ export default function ConversationRecords({
const [deletingId, setDeletingId] = useState(null);
const [cardPage, setCardPage] = useState(1);
const [cardPageSize, setCardPageSize] = useState(THREAD_LIST_PAGE_SIZE);
+ const listGate = useMemoryRequestGate(agentId);
+ const deleteModal = useRef | null>(null);
const loadThreads = useCallback(async () => {
+ const isCurrent = listGate.begin();
+ if (!isCurrent) return;
setListLoading(true);
try {
const list = await octopThreadsApi.list(agentId, 100);
+ if (!isCurrent()) return;
list.sort((a, b) => b.last_active - a.last_active);
setThreads(list);
} catch {
+ if (!isCurrent()) return;
setThreads([]);
message.error(t("memory.loadFailed"));
} finally {
- setListLoading(false);
+ if (isCurrent()) setListLoading(false);
}
- }, [agentId, t]);
+ }, [agentId, t, listGate]);
const resetHistoryState = useCallback(() => {
setMessages([]);
@@ -197,13 +206,25 @@ export default function ConversationRecords({
scrollHeightBeforePrependRef.current = null;
}, []);
- useEffect(() => {
+ useLayoutEffect(() => {
+ setThreads([]);
+ setListLoading(Boolean(agentId));
setSelectedThread(null);
setDrawerOpen(false);
resetHistoryState();
+ setHistoryLoading(false);
+ setDeletingId(null);
setCardPage(1);
+ return () => {
+ deleteModal.current?.destroy();
+ deleteModal.current = null;
+ };
+ }, [agentId, resetHistoryState]);
+
+ useEffect(() => {
+ if (!agentId) return;
void loadThreads();
- }, [agentId, loadThreads, resetHistoryState]);
+ }, [agentId, loadThreads]);
const fetchThreadHistory = useCallback(
async (threadId: string, offset: number) => {
@@ -302,7 +323,10 @@ export default function ConversationRecords({
const confirmDelete = useCallback(
(thread: OctopThread) => {
- confirmDeleteConversation(t, async (compact) => {
+ if (!listGate.isActive()) return;
+ deleteModal.current?.destroy();
+ deleteModal.current = confirmDeleteConversation(t, async (compact) => {
+ if (!listGate.isActive()) return;
setDeletingId(thread.thread_id);
try {
const deleted = await deleteConversation(
@@ -310,7 +334,9 @@ export default function ConversationRecords({
thread.thread_id,
compact,
t,
+ listGate.isActive,
);
+ if (!listGate.isActive()) return;
if (deleted !== true) return deleted;
if (selectedThread?.thread_id === thread.thread_id) {
closeDrawer();
@@ -319,11 +345,11 @@ export default function ConversationRecords({
prev.filter((row) => row.thread_id !== thread.thread_id),
);
} finally {
- setDeletingId(null);
+ if (listGate.isActive()) setDeletingId(null);
}
});
},
- [agentId, closeDrawer, selectedThread?.thread_id, t],
+ [agentId, closeDrawer, selectedThread?.thread_id, t, listGate],
);
const roleLabel = (role: string) => {
@@ -523,7 +549,12 @@ export default function ConversationRecords({
scroll={{ x: 980 }}
locale={{ emptyText: t("memory.noConversations") }}
pagination={{
- defaultPageSize: THREAD_LIST_PAGE_SIZE,
+ current: cardPage,
+ pageSize: cardPageSize,
+ onChange: (page, size) => {
+ setCardPage(size !== cardPageSize ? 1 : page);
+ setCardPageSize(size);
+ },
showSizeChanger: true,
pageSizeOptions: THREAD_LIST_PAGE_SIZE_OPTIONS.map(String),
showTotal: threadPaginationTotal,
diff --git a/dashboard/src/pages/Agent/Memory/EpisodesList.tsx b/dashboard/src/pages/Agent/Memory/EpisodesList.tsx
index ef95478b7e..776a2e143e 100644
--- a/dashboard/src/pages/Agent/Memory/EpisodesList.tsx
+++ b/dashboard/src/pages/Agent/Memory/EpisodesList.tsx
@@ -6,7 +6,13 @@
* compact intensity bar while hiding raw IDs.
*/
-import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useState,
+} from "react";
import {
Card,
Drawer,
@@ -24,6 +30,7 @@ import {
type EpisodeItem,
} from "../../../api/modules/memoryDashboard";
import { useServerTimezone } from "../../../hooks/useServerTimezone";
+import { useMemoryRequestGate } from "./shared/useMemoryRequestGate";
import {
calendarDaysAgo,
formatServerHourMinute,
@@ -45,20 +52,34 @@ export default function EpisodesList({ agentId }: Props) {
const [page, setPage] = useState(1);
const [loading, setLoading] = useState(true);
const [selected, setSelected] = useState(null);
+ const listGate = useMemoryRequestGate(JSON.stringify([agentId, page]));
+
+ useLayoutEffect(() => {
+ setItems([]);
+ setTotal(0);
+ setPage(1);
+ setLoading(Boolean(agentId));
+ setSelected(null);
+ }, [agentId]);
const load = useCallback(async () => {
+ const isCurrent = listGate.begin();
+ if (!isCurrent) return;
setLoading(true);
try {
const r = await memoryDashboardApi.listEpisodes(agentId, {
offset: (page - 1) * PAGE_SIZE,
limit: PAGE_SIZE,
});
+ if (!isCurrent()) return;
setItems(r.items);
setTotal(r.total);
+ } catch (error) {
+ if (isCurrent()) throw error;
} finally {
- setLoading(false);
+ if (isCurrent()) setLoading(false);
}
- }, [agentId, page]);
+ }, [agentId, page, listGate]);
useEffect(() => {
if (!agentId) return;
diff --git a/dashboard/src/pages/Agent/Memory/JournalList.tsx b/dashboard/src/pages/Agent/Memory/JournalList.tsx
index 80b535189c..ad0d1d689e 100644
--- a/dashboard/src/pages/Agent/Memory/JournalList.tsx
+++ b/dashboard/src/pages/Agent/Memory/JournalList.tsx
@@ -6,7 +6,13 @@
* while key events such as promote/reject/deprecate remain standalone.
*/
-import { useCallback, useEffect, useMemo, useState } from "react";
+import {
+ useCallback,
+ useEffect,
+ useLayoutEffect,
+ useMemo,
+ useState,
+} from "react";
import { Card, Empty, Pagination, Select, Skeleton, Space, Tag } from "antd";
import { ChevronDown, ChevronRight } from "lucide-react";
@@ -17,6 +23,7 @@ import {
type ListJournalBody,
} from "../../../api/modules/memoryDashboard";
import { useServerTimezone } from "../../../hooks/useServerTimezone";
+import { useMemoryRequestGate } from "./shared/useMemoryRequestGate";
import {
calendarDaysAgo,
formatServerHourMinute,
@@ -81,8 +88,21 @@ export default function JournalList({ agentId }: Props) {
const [loading, setLoading] = useState(true);
const [action, setAction] = useState("");
const [expanded, setExpanded] = useState>({});
+ const listGate = useMemoryRequestGate(
+ JSON.stringify([agentId, page, action]),
+ );
+
+ useLayoutEffect(() => {
+ setItems([]);
+ setTotal(0);
+ setPage(1);
+ setLoading(Boolean(agentId));
+ setExpanded({});
+ }, [agentId]);
const load = useCallback(async () => {
+ const isCurrent = listGate.begin();
+ if (!isCurrent) return;
setLoading(true);
const body: ListJournalBody = {
offset: (page - 1) * PAGE_SIZE,
@@ -91,12 +111,15 @@ export default function JournalList({ agentId }: Props) {
if (action) body.action = action;
try {
const r = await memoryDashboardApi.listJournal(agentId, body);
+ if (!isCurrent()) return;
setItems(r.items);
setTotal(r.total);
+ } catch (error) {
+ if (isCurrent()) throw error;
} finally {
- setLoading(false);
+ if (isCurrent()) setLoading(false);
}
- }, [agentId, page, action]);
+ }, [agentId, page, action, listGate]);
useEffect(() => {
if (!agentId) return;
diff --git a/dashboard/src/pages/Agent/Memory/MemoryActions.test.tsx b/dashboard/src/pages/Agent/Memory/MemoryActions.test.tsx
new file mode 100644
index 0000000000..ccbf6791cc
--- /dev/null
+++ b/dashboard/src/pages/Agent/Memory/MemoryActions.test.tsx
@@ -0,0 +1,334 @@
+import {
+ act,
+ cleanup,
+ fireEvent,
+ render,
+ screen,
+ waitFor,
+} from "@testing-library/react";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Modal, type ModalFuncProps } from "antd";
+import { makeAtom, makeEntity } from "../../../test/memoryFixtures";
+
+const mocks = vi.hoisted(() => ({
+ atoms: vi.fn(),
+ entities: vi.fn(),
+ replace: vi.fn(),
+ deprecate: vi.fn(),
+ create: vi.fn(),
+ threads: vi.fn(),
+ history: vi.fn(),
+ remove: vi.fn(),
+ error: vi.fn(),
+ success: vi.fn(),
+ loading: vi.fn(),
+ closeLoading: vi.fn(),
+ mobile: false,
+ t: (key: string, fallback?: unknown) =>
+ typeof fallback === "string" ? fallback : key,
+}));
+
+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: mocks.t }) }));
+vi.mock("../../../i18n", () => ({ default: { t: mocks.t } }));
+vi.mock("../../../utils/antdMessage", () => ({
+ message: {
+ error: mocks.error,
+ success: mocks.success,
+ loading: mocks.loading,
+ },
+}));
+vi.mock("../../../hooks/useIsMobile", () => ({
+ useIsMobile: () => mocks.mobile,
+}));
+vi.mock("../../../hooks/useServerTimezone", () => ({
+ useServerTimezone: () => "UTC",
+}));
+vi.mock("../../../api/modules/memoryDashboard", () => ({
+ memoryDashboardApi: {
+ listAtoms: mocks.atoms,
+ listEntities: mocks.entities,
+ replaceAtom: mocks.replace,
+ deprecateAtom: mocks.deprecate,
+ createAtom: mocks.create,
+ },
+ isAtomDeprecated: () => false,
+}));
+vi.mock("../../../api/modules/octopThreads", () => ({
+ CHAT_HISTORY_PAGE_SIZE: 50,
+ octopThreadsApi: {
+ list: mocks.threads,
+ history: mocks.history,
+ delete: mocks.remove,
+ },
+}));
+vi.mock("./shared/LineageStrip", () => ({ default: () => null }));
+vi.mock("./shared/MemoryPipelineEmpty", () => ({ default: () => null }));
+vi.mock("../../../components/Markdown/LazyMarkdown", () => ({
+ default: () => null,
+}));
+
+// Keep the mutation helpers and conversation confirmation real: replacing them
+// with callback-only mocks hides stale toasts and dialogs mounted outside the list.
+import AtomsList from "./AtomsList";
+import ConversationRecords from "./ConversationRecords";
+
+let restoreConfirm: (() => void) | undefined;
+const originalWidth = window.innerWidth;
+
+function deferred() {
+ let resolve!: (value: unknown) => void;
+ let reject!: (reason: Error) => void;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ for (const mutation of [
+ mocks.replace,
+ mocks.deprecate,
+ mocks.create,
+ mocks.remove,
+ ]) {
+ mutation.mockReset();
+ }
+ mocks.mobile = false;
+ mocks.atoms.mockResolvedValue({
+ items: [makeAtom({ assertion: "visible atom" })],
+ total: 1,
+ });
+ mocks.entities.mockResolvedValue({ items: [], total: 0 });
+ mocks.threads.mockResolvedValue([
+ {
+ thread_id: "same-id",
+ title: "visible conversation",
+ channel_type: "web",
+ created_at: 1,
+ last_active: 2,
+ },
+ ]);
+ mocks.history.mockResolvedValue({ messages: [], has_more: false });
+ mocks.loading.mockReturnValue(mocks.closeLoading);
+});
+
+afterEach(async () => {
+ cleanup();
+ restoreConfirm?.();
+ restoreConfirm = undefined;
+ window.innerWidth = originalWidth;
+ act(() => Modal.destroyAll());
+ await waitFor(() =>
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+});
+
+async function openAtomAction(action: "edit" | "deprecate") {
+ let confirmProps: ModalFuncProps | undefined;
+ const destroy = vi.fn();
+ const spy = vi.spyOn(Modal, "confirm").mockImplementation((props) => {
+ confirmProps = props;
+ return { destroy, update: vi.fn() };
+ });
+ restoreConfirm = () => spy.mockRestore();
+ const view = render( );
+ fireEvent.click(await screen.findByText("visible atom"));
+ fireEvent.click(
+ await screen.findByRole("button", {
+ name: action === "edit" ? "编辑这条记忆" : "弃用这条记忆",
+ }),
+ );
+ expect(confirmProps).toBeDefined();
+ return { ...view, confirm: () => confirmProps!.onOk?.(), destroy };
+}
+
+describe.each(["edit", "deprecate"] as const)(
+ "%s with the real helper",
+ (action) => {
+ const mutation = action === "edit" ? mocks.replace : mocks.deprecate;
+
+ it.each([
+ ["switch", "resolve"],
+ ["switch", "reject"],
+ ["revisit", "resolve"],
+ ["revisit", "reject"],
+ ["unmount", "resolve"],
+ ["unmount", "reject"],
+ ])("ignores obsolete feedback after %s and %s", async (change, outcome) => {
+ const pending = deferred();
+ mutation.mockReturnValueOnce(pending.promise);
+ const { rerender, unmount, confirm, destroy } = await openAtomAction(
+ action,
+ );
+ const completion = Promise.resolve(confirm());
+ expect(mutation).toHaveBeenCalledOnce();
+ if (change === "unmount") unmount();
+ else {
+ await act(async () => rerender( ));
+ if (change === "revisit")
+ await act(async () => rerender( ));
+ }
+ expect(destroy).toHaveBeenCalledOnce();
+ const calls = mocks.atoms.mock.calls.length;
+ await act(async () => {
+ if (outcome === "resolve") pending.resolve({ atom: makeAtom() });
+ else pending.reject(new Error("old operation failed"));
+ await completion;
+ });
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.error).not.toHaveBeenCalled();
+ expect(mocks.atoms).toHaveBeenCalledTimes(calls);
+ });
+
+ it.each(["resolve", "reject"])(
+ "preserves current %s feedback",
+ async (outcome) => {
+ const error = new Error("current failure");
+ if (outcome === "resolve")
+ mutation.mockResolvedValue({ atom: makeAtom() });
+ else mutation.mockRejectedValue(error);
+ const { confirm } = await openAtomAction(action);
+ const calls = mocks.atoms.mock.calls.length;
+ await act(async () => {
+ if (outcome === "resolve") await confirm();
+ else await expect(confirm()).rejects.toThrow(error);
+ });
+ if (outcome === "resolve") {
+ expect(mocks.success).toHaveBeenCalledOnce();
+ expect(mocks.atoms).toHaveBeenCalledTimes(calls + 1);
+ } else {
+ expect(mocks.error).toHaveBeenCalledOnce();
+ expect(mocks.atoms).toHaveBeenCalledTimes(calls);
+ }
+ },
+ );
+ },
+);
+
+describe("create atom", () => {
+ it.each(["resolve", "reject"])(
+ "ignores an old %s without closing the new form",
+ async (outcome) => {
+ const pending = deferred();
+ mocks.create.mockReturnValueOnce(pending.promise);
+ const { rerender } = render( );
+ await screen.findByText("visible atom");
+ fireEvent.click(screen.getByRole("button", { name: "新建记忆" }));
+ fireEvent.change(await screen.findByLabelText("主题名称"), {
+ target: { value: "old topic" },
+ });
+ fireEvent.change(screen.getByLabelText("记忆内容"), {
+ target: { value: "old assertion" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: /保\s*存/ }));
+ await waitFor(() => expect(mocks.create).toHaveBeenCalledOnce());
+ await act(async () => rerender( ));
+ await waitFor(() =>
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+ fireEvent.click(screen.getByRole("button", { name: "新建记忆" }));
+ await screen.findByRole("dialog");
+ const calls = mocks.atoms.mock.calls.length;
+ await act(async () => {
+ if (outcome === "resolve")
+ pending.resolve({
+ atom: makeAtom(),
+ entity: makeEntity(),
+ created_entity: true,
+ });
+ else pending.reject(new Error("old create failed"));
+ });
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.error).not.toHaveBeenCalled();
+ expect(mocks.atoms).toHaveBeenCalledTimes(calls);
+ },
+ );
+});
+
+describe.each([false, true])("conversation deletion (mobile: %s)", (mobile) => {
+ async function openDelete() {
+ mocks.mobile = mobile;
+ window.innerWidth = mobile ? 390 : 1200;
+ const view = render( );
+ await screen.findByText("visible conversation");
+ fireEvent.click(screen.getByRole("button", { name: "common.delete" }));
+ await screen.findByRole("dialog");
+ return view;
+ }
+
+ it.each(["switch", "unmount"])(
+ "destroys the confirmation on %s",
+ async (change) => {
+ const { rerender, unmount } = await openDelete();
+ if (change === "unmount") unmount();
+ else await act(async () => rerender( ));
+ await waitFor(() =>
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+ expect(mocks.remove).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(["resolve", "reject"])(
+ "ignores stale delete %s after A/B/A",
+ async (outcome) => {
+ const pending = deferred();
+ mocks.remove.mockReturnValueOnce(pending.promise);
+ const { rerender } = await openDelete();
+ fireEvent.click(
+ screen.getByRole("button", { name: "chat.deleteSessionOnly" }),
+ );
+ await waitFor(() =>
+ expect(mocks.remove).toHaveBeenCalledWith("A", "same-id", false),
+ );
+ await act(async () => rerender( ));
+ await act(async () => rerender( ));
+ await act(async () => {
+ if (outcome === "resolve") pending.resolve({ compacted: false });
+ else pending.reject(new Error("old delete failed"));
+ });
+ expect(screen.getByText("visible conversation")).toBeInTheDocument();
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.error).not.toHaveBeenCalled();
+ },
+ );
+
+ it("keeps a current 409 confirmation open and allows retry with compact", async () => {
+ mocks.remove.mockRejectedValueOnce(
+ new Error(
+ `Request failed: 409 Conflict - ${JSON.stringify({
+ error: { code: "THREAD_TURN_ACTIVE", message: "Reply in progress" },
+ })}`,
+ ),
+ );
+ await openDelete();
+ fireEvent.click(
+ screen.getByRole("button", { name: "chat.deleteSessionOnly" }),
+ );
+ await waitFor(() =>
+ expect(mocks.error).toHaveBeenCalledWith("apiErrors.THREAD_TURN_ACTIVE"),
+ );
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ expect(screen.getByText("visible conversation")).toBeInTheDocument();
+ mocks.remove.mockResolvedValueOnce({ compacted: true });
+ fireEvent.click(
+ screen.getByRole("button", { name: "chat.deleteSessionAndCompact" }),
+ );
+ await waitFor(() =>
+ expect(mocks.remove).toHaveBeenLastCalledWith("A", "same-id", true),
+ );
+ await waitFor(() =>
+ expect(
+ screen.queryByText("visible conversation"),
+ ).not.toBeInTheDocument(),
+ );
+ await waitFor(() =>
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument(),
+ );
+ expect(mocks.success).toHaveBeenCalledWith("chat.deleteSessionCompacted");
+ expect(mocks.closeLoading).toHaveBeenCalledOnce();
+ });
+});
diff --git a/dashboard/src/pages/Agent/Memory/MemoryLists.race.test.tsx b/dashboard/src/pages/Agent/Memory/MemoryLists.race.test.tsx
new file mode 100644
index 0000000000..02719c6f63
--- /dev/null
+++ b/dashboard/src/pages/Agent/Memory/MemoryLists.race.test.tsx
@@ -0,0 +1,784 @@
+import {
+ StrictMode,
+ useState,
+ type ComponentType,
+ type ReactNode,
+} from "react";
+import { act, fireEvent, render, screen } from "@testing-library/react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import {
+ makeAtom,
+ makeCandidate,
+ makeEntity,
+ makeEpisode,
+ makeJournal,
+} from "../../../test/memoryFixtures";
+
+const mocks = vi.hoisted(() => ({
+ atoms: vi.fn(),
+ raw: vi.fn(),
+ episodes: vi.fn(),
+ journal: vi.fn(),
+ candidates: vi.fn(),
+ entities: vi.fn(),
+ threads: vi.fn(),
+ history: vi.fn(),
+ removeThread: vi.fn(),
+ promote: vi.fn(),
+ reject: vi.fn(),
+ edit: vi.fn(),
+ deprecate: vi.fn(),
+ destroyAction: vi.fn(),
+ confirmDelete: vi.fn(),
+ error: vi.fn(),
+ success: vi.fn(),
+ createProps: null as null | {
+ onSuccess: () => void;
+ onClose: () => void;
+ entities: { canonical_name: string }[];
+ open: boolean;
+ },
+ t: (key: string, fallback?: unknown) =>
+ typeof fallback === "string" ? fallback : key,
+}));
+
+vi.mock("react-i18next", () => ({ useTranslation: () => ({ t: mocks.t }) }));
+vi.mock("../../../hooks/useIsMobile", () => ({ useIsMobile: () => false }));
+vi.mock("../../../hooks/useServerTimezone", () => ({
+ useServerTimezone: () => "UTC",
+}));
+vi.mock("../../../utils/antdMessage", () => ({
+ message: { error: mocks.error, success: mocks.success },
+}));
+vi.mock("../../../utils/antdModal", () => ({
+ modal: { confirm: mocks.confirmDelete },
+}));
+vi.mock("../../../api/modules/memoryDashboard", () => ({
+ memoryDashboardApi: {
+ listAtoms: mocks.atoms,
+ listRawEvents: mocks.raw,
+ listEpisodes: mocks.episodes,
+ listJournal: mocks.journal,
+ listCandidates: mocks.candidates,
+ listEntities: mocks.entities,
+ promoteCandidate: mocks.promote,
+ rejectCandidate: mocks.reject,
+ },
+ isAtomDeprecated: () => false,
+}));
+vi.mock("../../../api/modules/octopThreads", () => ({
+ CHAT_HISTORY_PAGE_SIZE: 50,
+ octopThreadsApi: {
+ list: mocks.threads,
+ history: mocks.history,
+ delete: mocks.removeThread,
+ },
+}));
+vi.mock("./shared/LineageStrip", () => ({ default: () => null }));
+vi.mock("./shared/MemoryPipelineEmpty", () => ({ default: () => null }));
+vi.mock("../../../components/Markdown/LazyMarkdown", () => ({
+ default: () => null,
+}));
+vi.mock("./shared/editAtom", () => ({ confirmEditAtom: mocks.edit }));
+vi.mock("./shared/deprecateAtom", () => ({
+ confirmDeprecateAtom: mocks.deprecate,
+}));
+vi.mock("./shared/createAtom", () => ({
+ default: (props: NonNullable) => {
+ mocks.createProps = props;
+ return (
+
+ {props.entities.map((entity) => entity.canonical_name).join(",")}
+
+ );
+ },
+}));
+
+// Keep the real list components and their event handlers. Lightweight display
+// controls expose loading/count state without Antd animation or portal timing.
+vi.mock("antd", async (importOriginal) => {
+ const actual = await importOriginal();
+ const Pagination = ({
+ total,
+ current = 1,
+ onChange,
+ }: {
+ total: number;
+ current?: number;
+ onChange?: (page: number) => void;
+ }) => (
+
+ {total}
+ {current}
+ {[2, 3].map((page) => (
+ onChange?.(page)}>
+ page {page}
+
+ ))}
+
+ );
+ return {
+ ...actual,
+ Skeleton: () =>
,
+ Pagination,
+ Select: ({
+ value,
+ onChange,
+ options,
+ }: {
+ value: string;
+ onChange: (value: string) => void;
+ options: { value: string; label: string }[];
+ }) => (
+ onChange(event.target.value)}>
+ {options.map((option) => (
+
+ {option.label}
+
+ ))}
+
+ ),
+ Drawer: ({ open, children }: { open: boolean; children: ReactNode }) =>
+ open ? : null,
+ Modal: ({
+ open,
+ children,
+ onOk,
+ confirmLoading,
+ }: {
+ open: boolean;
+ children: ReactNode;
+ onOk: () => void;
+ confirmLoading: boolean;
+ }) =>
+ open ? (
+
+ {children}
+ confirm reject
+
+ ) : null,
+ Popconfirm: ({
+ children,
+ onConfirm,
+ disabled,
+ }: {
+ children: ReactNode;
+ onConfirm: () => void;
+ disabled?: boolean;
+ }) => (
+
+ {children}
+
+ confirm action
+
+
+ ),
+ Table: function Table({
+ dataSource,
+ loading,
+ columns,
+ pagination,
+ }: {
+ dataSource: { thread_id: string; title: string }[];
+ loading: boolean;
+ columns: {
+ key?: string;
+ render?: (
+ value: undefined,
+ row: { thread_id: string; title: string },
+ ) => ReactNode;
+ }[];
+ pagination: {
+ current?: number;
+ onChange?: (page: number, size: number) => void;
+ pageSize?: number;
+ };
+ }) {
+ const [page, setPage] = useState(1);
+ return (
+
+ {loading &&
}
+
{
+ setPage(page);
+ pagination.onChange?.(page, pagination.pageSize ?? 20);
+ }}
+ />
+ {dataSource.map((row) => (
+
+ {row.title}
+ {columns
+ .find((column) => column.key === "actions")
+ ?.render?.(undefined, row)}
+
+ ))}
+
+ );
+ },
+ };
+});
+
+import AtomsList from "./AtomsList";
+import RawEventsList from "./RawEventsList";
+import EpisodesList from "./EpisodesList";
+import JournalList from "./JournalList";
+import CandidatesReview from "./CandidatesReview";
+import ConversationRecords from "./ConversationRecords";
+
+function deferred() {
+ let resolve!: (value: unknown) => void;
+ let reject!: (reason: Error) => void;
+ const promise = new Promise((res, rej) => {
+ resolve = res;
+ reject = rej;
+ });
+ return { promise, resolve, reject };
+}
+
+const cases = [
+ {
+ name: "atoms",
+ View: AtomsList,
+ api: mocks.atoms,
+ pageSize: 20,
+ item: (label: string) => makeAtom({ id: label, assertion: label }),
+ filters: ["Fact", "Task"],
+ },
+ {
+ name: "raw",
+ View: RawEventsList,
+ api: mocks.raw,
+ pageSize: 20,
+ item: (label: string) => ({
+ id: label,
+ content: label,
+ event_type: "user_message",
+ timestamp: "2026-09-01T00:00:00Z",
+ }),
+ filters: ["user_message", "assistant_message"],
+ },
+ {
+ name: "episodes",
+ View: EpisodesList,
+ api: mocks.episodes,
+ pageSize: 20,
+ item: (label: string) => makeEpisode({ id: label, summary: label }),
+ },
+ {
+ name: "journal",
+ View: JournalList,
+ api: mocks.journal,
+ pageSize: 30,
+ item: (label: string) => makeJournal({ id: label, target_summary: label }),
+ filters: ["promote", "reject"],
+ },
+ {
+ name: "candidates",
+ View: CandidatesReview,
+ api: mocks.candidates,
+ pageSize: 20,
+ item: (label: string) => makeCandidate({ id: label, title: label }),
+ filters: ["pending", "promoted"],
+ },
+ {
+ name: "threads",
+ View: ConversationRecords,
+ api: mocks.threads,
+ item: (label: string) => ({
+ thread_id: label,
+ title: label,
+ channel_type: "web",
+ created_at: 1,
+ last_active: 2,
+ }),
+ },
+];
+
+function response(testCase: (typeof cases)[number], label: string, total = 1) {
+ const items = [testCase.item(label)];
+ return testCase.name === "threads"
+ ? Array.from({ length: total }, (_, index) =>
+ testCase.item(index ? `${label}-${index}` : label),
+ )
+ : { items, total, has_more: total > 1 };
+}
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.promote.mockReset();
+ mocks.reject.mockReset();
+ mocks.removeThread.mockReset();
+ for (const testCase of cases) testCase.api.mockReset();
+ mocks.entities
+ .mockReset()
+ .mockResolvedValue({ items: [], total: 0, has_more: false });
+ mocks.history.mockResolvedValue({ messages: [], has_more: false });
+ mocks.createProps = null;
+ mocks.edit.mockReturnValue({ destroy: mocks.destroyAction });
+ mocks.deprecate.mockReturnValue({ destroy: mocks.destroyAction });
+ mocks.confirmDelete.mockReturnValue({ destroy: mocks.destroyAction });
+});
+
+describe.each(cases)("$name list request ownership", (testCase) => {
+ const View: ComponentType<{ agentId: string }> = testCase.View;
+
+ it("keeps B's rows and count when A completes last", async () => {
+ const old = deferred();
+ const current = deferred();
+ testCase.api
+ .mockReturnValueOnce(old.promise)
+ .mockReturnValueOnce(current.promise);
+ const { rerender } = render( );
+ rerender( );
+ await act(async () =>
+ current.resolve(response(testCase, "current-row", 2)),
+ );
+ await act(async () => old.resolve(response(testCase, "obsolete-row", 3)));
+ expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument();
+ expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument();
+ expect(screen.getByTestId("total")).toHaveTextContent(/^2$/);
+ });
+
+ it.each(["resolve", "reject"] as const)(
+ "ignores obsolete %s while B is pending",
+ async (outcome) => {
+ const old = deferred();
+ const current = deferred();
+ testCase.api
+ .mockReturnValueOnce(old.promise)
+ .mockReturnValueOnce(current.promise);
+ const { rerender } = render( );
+ rerender( );
+ await act(async () => {
+ if (outcome === "resolve")
+ old.resolve(response(testCase, "obsolete-row"));
+ else old.reject(new Error("obsolete failure"));
+ });
+ expect(screen.getByTestId("loading")).toBeInTheDocument();
+ expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument();
+ expect(mocks.error).not.toHaveBeenCalled();
+ await act(async () => current.resolve(response(testCase, "current-row")));
+ expect(screen.queryByTestId("loading")).not.toBeInTheDocument();
+ },
+ );
+
+ it("does not clear B's successful result when A fails later", async () => {
+ const old = deferred();
+ testCase.api
+ .mockReturnValueOnce(old.promise)
+ .mockResolvedValueOnce(response(testCase, "current-row"));
+ const { rerender } = render( );
+ await act(async () => rerender( ));
+ await act(async () => old.reject(new Error("obsolete failure")));
+ expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument();
+ expect(mocks.error).not.toHaveBeenCalled();
+ });
+
+ it("clears previously loaded rows and count before B responds", async () => {
+ testCase.api.mockResolvedValueOnce(response(testCase, "obsolete-row", 2));
+ const { rerender } = render( );
+ await act(async () => {});
+ expect(screen.getByText(/^「?obsolete-row」?$/)).toBeInTheDocument();
+ testCase.api.mockReturnValue(new Promise(() => {}));
+ rerender( );
+ expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument();
+ expect(screen.getByTestId("total")).toHaveTextContent(/^0$/);
+ expect(screen.getByTestId("loading")).toBeInTheDocument();
+ await act(async () => {});
+ });
+
+ it("distinguishes two visits to A separated by B", async () => {
+ const old = deferred();
+ testCase.api
+ .mockReturnValueOnce(old.promise)
+ .mockResolvedValue(response(testCase, "current-row"));
+ const { rerender } = render( );
+ await act(async () => rerender( ));
+ await act(async () => rerender( ));
+ await act(async () => old.resolve(response(testCase, "obsolete-row")));
+ expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument();
+ expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument();
+ });
+
+ it("ignores a failure after unmount", async () => {
+ const pending = deferred();
+ testCase.api.mockReturnValue(pending.promise);
+ const { unmount } = render( );
+ unmount();
+ await act(async () => pending.reject(new Error("unmounted failure")));
+ expect(mocks.error).not.toHaveBeenCalled();
+ });
+
+ it("survives StrictMode effect cleanup and replay", async () => {
+ const old = deferred();
+ testCase.api
+ .mockReturnValueOnce(old.promise)
+ .mockResolvedValue(response(testCase, "current-row"));
+ render(
+
+
+ ,
+ );
+ await act(async () => {});
+ await act(async () => old.resolve(response(testCase, "obsolete-row")));
+ expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument();
+ expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument();
+ });
+});
+
+describe.each(cases.filter((testCase) => testCase.pageSize))(
+ "$name pagination",
+ (testCase) => {
+ it("keeps the latest page when responses arrive out of order, and resets the page for a new agent", async () => {
+ const View = testCase.View;
+ testCase.api.mockResolvedValueOnce(
+ response(testCase, "initial-row", 200),
+ );
+ const { rerender } = render( );
+ await act(async () => {});
+ const old = deferred();
+ const current = deferred();
+ testCase.api
+ .mockReturnValueOnce(old.promise)
+ .mockReturnValueOnce(current.promise);
+ fireEvent.click(screen.getByText("page 2"));
+ fireEvent.click(screen.getByText("page 3"));
+ await act(async () =>
+ current.resolve(response(testCase, "current-row", 200)),
+ );
+ await act(async () =>
+ old.resolve(response(testCase, "obsolete-row", 100)),
+ );
+ expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument();
+ expect(screen.getByTestId("page")).toHaveTextContent(/^3$/);
+ expect(screen.getByTestId("total")).toHaveTextContent(/^200$/);
+ testCase.api.mockResolvedValue(response(testCase, "new-agent-row"));
+ await act(async () => rerender( ));
+ expect(screen.getByTestId("page")).toHaveTextContent(/^1$/);
+ expect(testCase.api).toHaveBeenLastCalledWith(
+ "B",
+ expect.objectContaining({ offset: 0 }),
+ );
+ });
+ },
+);
+
+describe.each(cases.filter((testCase) => testCase.filters))(
+ "$name filters",
+ (testCase) => {
+ it("keeps the latest filter result and preserves the filter on agent change", async () => {
+ const View = testCase.View;
+ testCase.api.mockResolvedValueOnce(response(testCase, "initial-row"));
+ const { rerender } = render( );
+ await act(async () => {});
+ const old = deferred();
+ const current = deferred();
+ testCase.api
+ .mockReturnValueOnce(old.promise)
+ .mockReturnValueOnce(current.promise);
+ const select = screen.getAllByRole("combobox")[0];
+ fireEvent.change(select, { target: { value: testCase.filters![0] } });
+ fireEvent.change(select, { target: { value: testCase.filters![1] } });
+ await act(async () => current.resolve(response(testCase, "current-row")));
+ await act(async () => old.resolve(response(testCase, "obsolete-row")));
+ expect(screen.getByText(/^「?current-row」?$/)).toBeInTheDocument();
+ expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument();
+ testCase.api.mockResolvedValue(response(testCase, "new-agent-row"));
+ await act(async () => rerender( ));
+ expect(screen.getAllByRole("combobox")[0]).toHaveValue(
+ testCase.filters![1],
+ );
+ });
+ },
+);
+
+describe.each(
+ cases.filter((testCase) =>
+ ["raw", "episodes", "candidates"].includes(testCase.name),
+ ),
+)("$name selection", (testCase) => {
+ it("closes the old detail on agent change", async () => {
+ const View = testCase.View;
+ testCase.api.mockResolvedValue(response(testCase, "visible-row"));
+ const { rerender } = render( );
+ await act(async () => {});
+ fireEvent.click(screen.getByText("visible-row"));
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ testCase.api.mockReturnValue(new Promise(() => {}));
+ rerender( );
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+});
+
+describe.each(
+ cases.filter((testCase) => ["candidates", "threads"].includes(testCase.name)),
+)("$name current errors", (testCase) => {
+ it("still reports the current failure and does not accept an older success", async () => {
+ const View = testCase.View;
+ const old = deferred();
+ testCase.api
+ .mockReturnValueOnce(old.promise)
+ .mockRejectedValueOnce(new Error("current failure"));
+ const { rerender } = render( );
+ await act(async () => rerender( ));
+ expect(mocks.error).toHaveBeenCalledTimes(1);
+ expect(screen.queryByTestId("loading")).not.toBeInTheDocument();
+ await act(async () => old.resolve(response(testCase, "obsolete-row")));
+ expect(screen.queryByText(/obsolete-row/)).not.toBeInTheDocument();
+ expect(screen.getByTestId("total")).toHaveTextContent(/^0$/);
+ });
+});
+
+describe("Atoms related requests and callbacks", () => {
+ it.each(["resolve", "reject"] as const)(
+ "ignores obsolete entity %s without invalidating the atom request",
+ async (outcome) => {
+ const old = deferred();
+ const currentAtoms = deferred();
+ mocks.atoms
+ .mockReturnValueOnce(new Promise(() => {}))
+ .mockReturnValueOnce(currentAtoms.promise);
+ mocks.entities.mockReturnValueOnce(old.promise).mockResolvedValueOnce({
+ items: [makeEntity({ canonical_name: "B entity" })],
+ });
+ const { rerender } = render( );
+ await act(async () => rerender( ));
+ await act(async () => {
+ if (outcome === "resolve")
+ old.resolve({ items: [makeEntity({ canonical_name: "A entity" })] });
+ else old.reject(new Error("old entities"));
+ currentAtoms.resolve({
+ items: [makeAtom({ assertion: "B atom" })],
+ total: 1,
+ });
+ });
+ expect(screen.getByTestId("entities")).toHaveTextContent(/^B entity$/);
+ expect(screen.getByText("B atom")).toBeInTheDocument();
+ },
+ );
+
+ it("gates repeated creation refreshes for both atoms and entities", async () => {
+ mocks.atoms.mockResolvedValue({ items: [], total: 0 });
+ render( );
+ await act(async () => {});
+ const oldAtoms = deferred();
+ const oldEntities = deferred();
+ mocks.atoms.mockReturnValueOnce(oldAtoms.promise).mockResolvedValueOnce({
+ items: [makeAtom({ assertion: "new atom" })],
+ total: 1,
+ });
+ mocks.entities
+ .mockReturnValueOnce(oldEntities.promise)
+ .mockResolvedValueOnce({
+ items: [makeEntity({ canonical_name: "new entity" })],
+ });
+ await act(async () => {
+ mocks.createProps!.onSuccess();
+ mocks.createProps!.onSuccess();
+ });
+ await act(async () => {
+ oldAtoms.resolve({
+ items: [makeAtom({ assertion: "old atom" })],
+ total: 1,
+ });
+ oldEntities.resolve({
+ items: [makeEntity({ canonical_name: "old entity" })],
+ });
+ });
+ expect(screen.getByText("new atom")).toBeInTheDocument();
+ expect(screen.getByTestId("entities")).toHaveTextContent(/^new entity$/);
+ });
+
+ it("clears the selected atom and create modal, and ignores callbacks from a prior A visit", async () => {
+ mocks.atoms.mockResolvedValue({
+ items: [makeAtom({ assertion: "visible atom" })],
+ total: 1,
+ });
+ const { rerender } = render( );
+ await act(async () => {});
+ fireEvent.click(screen.getByText("visible atom"));
+ fireEvent.click(screen.getByRole("button", { name: "编辑这条记忆" }));
+ const editSuccess = mocks.edit.mock.calls[0][0].onSuccess;
+ const oldCreateSuccess = mocks.createProps!.onSuccess;
+ const oldCreateClose = mocks.createProps!.onClose;
+ fireEvent.click(screen.getByRole("button", { name: "新建记忆" }));
+ expect(mocks.createProps!.open).toBe(true);
+ await act(async () => rerender( ));
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(mocks.createProps!.open).toBe(false);
+ expect(mocks.destroyAction).toHaveBeenCalledOnce();
+ fireEvent.click(screen.getByRole("button", { name: "新建记忆" }));
+ act(() => oldCreateClose());
+ expect(mocks.createProps!.open).toBe(true);
+ await act(async () => rerender( ));
+ const atomCalls = mocks.atoms.mock.calls.length;
+ const entityCalls = mocks.entities.mock.calls.length;
+ await act(async () => {
+ editSuccess(makeAtom({ assertion: "obsolete edit" }));
+ oldCreateSuccess();
+ });
+ expect(mocks.atoms).toHaveBeenCalledTimes(atomCalls);
+ expect(mocks.entities).toHaveBeenCalledTimes(entityCalls);
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it("destroys the deprecation confirmation when the list unmounts", async () => {
+ mocks.atoms.mockResolvedValue({
+ items: [makeAtom({ assertion: "visible atom" })],
+ total: 1,
+ });
+ const { unmount } = render( );
+ await act(async () => {});
+ fireEvent.click(screen.getByText("visible atom"));
+ fireEvent.click(screen.getByRole("button", { name: "弃用这条记忆" }));
+ expect(mocks.deprecate).toHaveBeenCalledOnce();
+ unmount();
+ expect(mocks.destroyAction).toHaveBeenCalledOnce();
+ });
+
+ it("refreshes the current filter when an edit started under the previous filter completes", async () => {
+ mocks.atoms.mockResolvedValue({
+ items: [makeAtom({ assertion: "visible atom" })],
+ total: 1,
+ });
+ render( );
+ await act(async () => {});
+ fireEvent.click(screen.getByText("visible atom"));
+ fireEvent.click(screen.getByRole("button", { name: "编辑这条记忆" }));
+ const editSuccess = mocks.edit.mock.calls[0][0].onSuccess;
+ await act(async () =>
+ fireEvent.change(screen.getAllByRole("combobox")[0], {
+ target: { value: "Fact" },
+ }),
+ );
+ const calls = mocks.atoms.mock.calls.length;
+ await act(async () => editSuccess(makeAtom()));
+ expect(mocks.atoms).toHaveBeenCalledTimes(calls + 1);
+ expect(mocks.atoms).toHaveBeenLastCalledWith(
+ "A",
+ expect.objectContaining({ candidate_type: "Fact" }),
+ );
+ });
+});
+
+describe("Candidate action completion", () => {
+ it.each(["resolve", "reject"] as const)(
+ "ignores obsolete promote %s after A/B/A",
+ async (outcome) => {
+ const pending = deferred();
+ mocks.promote.mockReturnValue(pending.promise);
+ mocks.candidates.mockResolvedValue({
+ items: [makeCandidate()],
+ total: 1,
+ });
+ const { rerender } = render( );
+ await act(async () => {});
+ fireEvent.click(screen.getByText("confirm action"));
+ await act(async () => rerender( ));
+ await act(async () => rerender( ));
+ const calls = mocks.candidates.mock.calls.length;
+ await act(async () => {
+ if (outcome === "resolve")
+ pending.resolve({ merged: 0, promoted: 1, needs_review: 0 });
+ else pending.reject(new Error("old promote"));
+ });
+ expect(mocks.candidates).toHaveBeenCalledTimes(calls);
+ expect(mocks.success).not.toHaveBeenCalled();
+ expect(mocks.error).not.toHaveBeenCalled();
+ },
+ );
+
+ it("does not let A's rejection close B's pending rejection modal", async () => {
+ const old = deferred();
+ const current = deferred();
+ mocks.reject
+ .mockReturnValueOnce(old.promise)
+ .mockReturnValueOnce(current.promise);
+ mocks.candidates.mockResolvedValue({ items: [makeCandidate()], total: 1 });
+ const { rerender } = render( );
+ await act(async () => {});
+ fireEvent.click(screen.getByRole("button", { name: /忽\s*略/ }));
+ fireEvent.click(screen.getByText("confirm reject"));
+ await act(async () => rerender( ));
+ expect(screen.queryByTestId("reject-modal")).not.toBeInTheDocument();
+ fireEvent.click(screen.getByRole("button", { name: /忽\s*略/ }));
+ fireEvent.click(screen.getByText("confirm reject"));
+ const calls = mocks.candidates.mock.calls.length;
+ await act(async () => old.resolve({}));
+ expect(screen.getByTestId("reject-modal")).toHaveAttribute(
+ "data-loading",
+ "true",
+ );
+ expect(mocks.candidates).toHaveBeenCalledTimes(calls);
+ expect(mocks.success).not.toHaveBeenCalled();
+ await act(async () => current.resolve({}));
+ expect(screen.queryByTestId("reject-modal")).not.toBeInTheDocument();
+ expect(mocks.candidates).toHaveBeenLastCalledWith("B", expect.anything());
+ });
+
+ it("finishes an in-agent rejection and refreshes the latest filter", async () => {
+ const pending = deferred();
+ mocks.reject.mockReturnValue(pending.promise);
+ mocks.candidates.mockResolvedValue({ items: [makeCandidate()], total: 1 });
+ render( );
+ await act(async () => {});
+ fireEvent.click(screen.getByRole("button", { name: /忽\s*略/ }));
+ fireEvent.click(screen.getByText("confirm reject"));
+ await act(async () =>
+ fireEvent.change(screen.getAllByRole("combobox")[0], {
+ target: { value: "promoted" },
+ }),
+ );
+ const calls = mocks.candidates.mock.calls.length;
+ await act(async () => pending.resolve({}));
+ expect(screen.queryByTestId("reject-modal")).not.toBeInTheDocument();
+ expect(mocks.candidates).toHaveBeenCalledTimes(calls + 1);
+ expect(mocks.candidates).toHaveBeenLastCalledWith(
+ "A",
+ expect.objectContaining({ status: "promoted" }),
+ );
+ });
+});
+
+describe("Conversation list actions", () => {
+ it("clears the selection and desktop page on agent change; ignores the old delete", async () => {
+ const pending = deferred();
+ mocks.removeThread.mockReturnValue(pending.promise);
+ mocks.threads.mockResolvedValue([
+ {
+ thread_id: "same-id",
+ title: "visible thread",
+ channel_type: "web",
+ created_at: 1,
+ last_active: 2,
+ },
+ ]);
+ const { rerender } = render( );
+ await act(async () => {});
+ await act(async () =>
+ fireEvent.click(screen.getByRole("button", { name: "common.view" })),
+ );
+ expect(screen.getByRole("dialog")).toBeInTheDocument();
+ fireEvent.click(screen.getByText("page 2"));
+ expect(screen.getByTestId("page")).toHaveTextContent(/^2$/);
+ fireEvent.click(screen.getByRole("button", { name: "common.delete" }));
+ render(<>{mocks.confirmDelete.mock.calls[0][0].footer}>);
+ await act(async () =>
+ fireEvent.click(
+ screen.getByRole("button", { name: "chat.deleteSessionOnly" }),
+ ),
+ );
+ await act(async () => rerender( ));
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ expect(screen.getByTestId("page")).toHaveTextContent(/^1$/);
+ await act(async () => pending.resolve({}));
+ expect(screen.getByText("visible thread")).toBeInTheDocument();
+ expect(mocks.success).not.toHaveBeenCalled();
+ });
+});
diff --git a/dashboard/src/pages/Agent/Memory/MemoryPanel.tsx b/dashboard/src/pages/Agent/Memory/MemoryPanel.tsx
index d07ac38d48..b513f04e5a 100644
--- a/dashboard/src/pages/Agent/Memory/MemoryPanel.tsx
+++ b/dashboard/src/pages/Agent/Memory/MemoryPanel.tsx
@@ -35,6 +35,7 @@ import MemorySettings from "./MemorySettings";
import StrongMemory from "./StrongMemory";
import memoryDashboardApi from "../../../api/modules/memoryDashboard";
+import { useAgent } from "../../../context/AgentContext";
import styles from "./index.module.less";
type MemoryTab =
@@ -136,11 +137,24 @@ export interface MemoryPanelProps {
fill?: boolean;
}
+/** Memory tabs. Managed experts use the same pages; memory stays off until enabled. */
+export function memoryTabsForKind(
+ kind: string | null | undefined,
+): readonly TabDef[] {
+ void kind;
+ return TABS;
+}
+
export default function MemoryPanel({
agentId,
fill = true,
}: MemoryPanelProps) {
const { t } = useTranslation();
+ const { agents } = useAgent();
+ const agentKind = agents.find((agent) => agent.agent_id === agentId)?.kind;
+ const tabs = useMemo(() => memoryTabsForKind(agentKind), [agentKind]);
+ const conversationsOnly =
+ tabs.length === 1 && tabs[0]?.key === "conversations";
const [activeTab, setActiveTab] = useState("overview");
const [libraryView, setLibraryView] = useState("tree");
@@ -151,7 +165,7 @@ export default function MemoryPanel({
const [expandKey, setExpandKey] = useState(0);
useEffect(() => {
- if (!agentId) {
+ if (!agentId || conversationsOnly) {
setPendingCount(0);
return;
}
@@ -167,7 +181,7 @@ export default function MemoryPanel({
return () => {
cancelled = true;
};
- }, [agentId, activeTab]);
+ }, [agentId, activeTab, conversationsOnly]);
const tabItems = useMemo(() => {
if (!agentId) return [];
@@ -224,7 +238,7 @@ export default function MemoryPanel({
);
- return TABS.map((tab) => {
+ return tabs.map((tab) => {
const showBadge = tab.showPendingBadge && pendingCount > 0;
const label = (
@@ -310,7 +324,7 @@ export default function MemoryPanel({
return { key: tab.key, label, children };
});
- }, [agentId, expandEntityId, expandKey, libraryView, pendingCount, t]);
+ }, [agentId, expandEntityId, expandKey, libraryView, pendingCount, t, tabs]);
if (!agentId) {
return (
@@ -325,7 +339,7 @@ export default function MemoryPanel({
setActiveTab(k as MemoryTab)}
destroyOnHidden
items={tabItems}
diff --git a/dashboard/src/pages/Agent/Memory/RawEventsList.tsx b/dashboard/src/pages/Agent/Memory/RawEventsList.tsx
index 18411a9d1a..bf06848133 100644
--- a/dashboard/src/pages/Agent/Memory/RawEventsList.tsx
+++ b/dashboard/src/pages/Agent/Memory/RawEventsList.tsx
@@ -8,7 +8,7 @@
* pipeline card hint on the Overview tab.
*/
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useLayoutEffect, useState } from "react";
import { Input, Select, Space, Tag, Typography } from "antd";
import { useTranslation } from "react-i18next";
import type { TFunction } from "i18next";
@@ -20,6 +20,7 @@ import {
} from "../../../api/modules/memoryDashboard";
import MemoryLayerView from "./shared/MemoryLayerView";
import MemoryPipelineEmpty from "./shared/MemoryPipelineEmpty";
+import { useMemoryRequestGate } from "./shared/useMemoryRequestGate";
import { useServerTimezone } from "../../../hooks/useServerTimezone";
import { formatServerIsoDateTime } from "../../../utils/formatMessageTime";
@@ -78,8 +79,21 @@ export default function RawEventsList({ agentId }: Props) {
const [eventType, setEventType] = useState("");
const [query, setQuery] = useState("");
const [selected, setSelected] = useState(null);
+ const listGate = useMemoryRequestGate(
+ JSON.stringify([agentId, page, eventType, query]),
+ );
+
+ useLayoutEffect(() => {
+ setItems([]);
+ setTotal(0);
+ setPage(1);
+ setLoading(Boolean(agentId));
+ setSelected(null);
+ }, [agentId]);
const load = useCallback(async () => {
+ const isCurrent = listGate.begin();
+ if (!isCurrent) return;
setLoading(true);
const body: ListRawEventsBody = {
offset: (page - 1) * PAGE_SIZE,
@@ -89,12 +103,15 @@ export default function RawEventsList({ agentId }: Props) {
if (query.trim()) body.query = query.trim();
try {
const r = await memoryDashboardApi.listRawEvents(agentId, body);
+ if (!isCurrent()) return;
setItems(r.items);
setTotal(r.total);
+ } catch (error) {
+ if (isCurrent()) throw error;
} finally {
- setLoading(false);
+ if (isCurrent()) setLoading(false);
}
- }, [agentId, page, eventType, query]);
+ }, [agentId, page, eventType, query, listGate]);
useEffect(() => {
if (!agentId) return;
diff --git a/dashboard/src/pages/Agent/Memory/memoryTabsForKind.test.ts b/dashboard/src/pages/Agent/Memory/memoryTabsForKind.test.ts
new file mode 100644
index 0000000000..c3c17c2c06
--- /dev/null
+++ b/dashboard/src/pages/Agent/Memory/memoryTabsForKind.test.ts
@@ -0,0 +1,18 @@
+import { describe, expect, it } from "vitest";
+import { memoryTabsForKind } from "./MemoryPanel";
+
+describe("memoryTabsForKind", () => {
+ it("keeps the full memory dashboard for a managed expert", () => {
+ const keys = memoryTabsForKind("managed").map((tab) => tab.key);
+ expect(keys).toContain("settings");
+ expect(keys).toContain("conversations");
+ expect(keys.length).toBeGreaterThan(1);
+ });
+
+ it("keeps the full memory dashboard for other experts", () => {
+ const keys = memoryTabsForKind("expert").map((tab) => tab.key);
+ expect(keys).toContain("overview");
+ expect(keys).toContain("conversations");
+ expect(keys.length).toBeGreaterThan(1);
+ });
+});
diff --git a/dashboard/src/pages/Agent/Memory/shared/createAtom.tsx b/dashboard/src/pages/Agent/Memory/shared/createAtom.tsx
index 533f87546d..0aafbaf242 100644
--- a/dashboard/src/pages/Agent/Memory/shared/createAtom.tsx
+++ b/dashboard/src/pages/Agent/Memory/shared/createAtom.tsx
@@ -36,6 +36,7 @@ interface Props {
/** When set, lock the form to this existing topic. */
presetEntityId?: string;
onClose: () => void;
+ isActive?: () => boolean;
onSuccess?: (
atom: AtomItem,
entity: EntityItem,
@@ -50,6 +51,7 @@ export default function CreateAtomModal({
presetEntityId,
onClose,
onSuccess,
+ isActive = () => true,
}: Props) {
const { t } = useTranslation();
const [form] = Form.useForm();
@@ -85,7 +87,9 @@ export default function CreateAtomModal({
cancelText={t("common.cancel", "取消")}
destroyOnHidden
onOk={async () => {
+ if (!isActive()) return;
const values = await form.validateFields();
+ if (!isActive()) return;
const assertion = String(values.assertion || "").trim();
try {
const body =
@@ -102,10 +106,12 @@ export default function CreateAtomModal({
kind: values.kind as AtomKind,
};
const r = await memoryDashboardApi.createAtom(agentId, body);
+ if (!isActive()) return;
message.success(t("memory.create.success", "记忆已添加"));
onSuccess?.(r.atom, r.entity, r.created_entity);
onClose();
} catch (e) {
+ if (!isActive()) return;
message.error(
t("memory.create.failed", {
message: (e as Error).message ?? e,
diff --git a/dashboard/src/pages/Agent/Memory/shared/deprecateAtom.tsx b/dashboard/src/pages/Agent/Memory/shared/deprecateAtom.tsx
index 6fecc9ab5a..51a279d35b 100644
--- a/dashboard/src/pages/Agent/Memory/shared/deprecateAtom.tsx
+++ b/dashboard/src/pages/Agent/Memory/shared/deprecateAtom.tsx
@@ -18,14 +18,16 @@ export function confirmDeprecateAtom({
agentId,
atom,
onSuccess,
+ isActive = () => true,
}: {
agentId: string;
atom: AtomItem;
/** Callback after successful deprecation, usually to close drawer and refresh list. */
onSuccess?: () => void;
+ isActive?: () => boolean;
}) {
let reason = "";
- modal.confirm({
+ return modal.confirm({
title: i18n.t("memory.deprecate.title"),
content: (
@@ -45,13 +47,16 @@ export function confirmDeprecateAtom({
okType: "danger",
cancelText: i18n.t("common.cancel"),
onOk: async () => {
+ if (!isActive()) return;
try {
await memoryDashboardApi.deprecateAtom(agentId, atom.id, {
reason: reason || undefined,
});
+ if (!isActive()) return;
message.success(i18n.t("memory.deprecate.success"));
onSuccess?.();
} catch (e) {
+ if (!isActive()) return;
message.error(
i18n.t("memory.deprecate.failed", {
message: (e as Error).message ?? e,
diff --git a/dashboard/src/pages/Agent/Memory/shared/editAtom.tsx b/dashboard/src/pages/Agent/Memory/shared/editAtom.tsx
index 730098c630..0c7a3acb9a 100644
--- a/dashboard/src/pages/Agent/Memory/shared/editAtom.tsx
+++ b/dashboard/src/pages/Agent/Memory/shared/editAtom.tsx
@@ -14,13 +14,15 @@ export function confirmEditAtom({
agentId,
atom,
onSuccess,
+ isActive = () => true,
}: {
agentId: string;
atom: AtomItem;
onSuccess?: (next: AtomItem) => void;
+ isActive?: () => boolean;
}) {
let assertion = atom.assertion;
- Modal.confirm({
+ return Modal.confirm({
title: i18n.t("memory.edit.title"),
width: 520,
content: (
@@ -40,6 +42,7 @@ export function confirmEditAtom({
okText: i18n.t("memory.edit.ok"),
cancelText: i18n.t("common.cancel"),
onOk: async () => {
+ if (!isActive()) return;
const text = assertion.trim();
if (!text) {
message.error(i18n.t("memory.edit.empty"));
@@ -49,9 +52,11 @@ export function confirmEditAtom({
const r = await memoryDashboardApi.replaceAtom(agentId, atom.id, {
assertion: text,
});
+ if (!isActive()) return;
message.success(i18n.t("memory.edit.success"));
onSuccess?.(r.atom);
} catch (e) {
+ if (!isActive()) return;
message.error(
i18n.t("memory.edit.failed", {
message: (e as Error).message ?? e,
diff --git a/dashboard/src/pages/Agent/Memory/shared/useMemoryRequestGate.ts b/dashboard/src/pages/Agent/Memory/shared/useMemoryRequestGate.ts
new file mode 100644
index 0000000000..e15633b9d8
--- /dev/null
+++ b/dashboard/src/pages/Agent/Memory/shared/useMemoryRequestGate.ts
@@ -0,0 +1,31 @@
+import { useLayoutEffect, useMemo } from "react";
+import { createDetailRequestGate } from "../../../../utils/detailRequestGate";
+
+/** Own requests by a committed memory view, including repeated visits to it. */
+export function useMemoryRequestGate(scopeKey: string) {
+ const scope = useMemo(
+ () => ({ scopeKey, active: false, gate: createDetailRequestGate() }),
+ [scopeKey],
+ );
+
+ useLayoutEffect(() => {
+ scope.active = true;
+ return () => {
+ scope.active = false;
+ scope.gate.begin();
+ };
+ }, [scope]);
+
+ return useMemo(
+ () => ({
+ isActive: () => scope.active,
+ begin: () => {
+ // An old mutation callback must not start a new request for its view.
+ if (!scope.active) return null;
+ const requestId = scope.gate.begin();
+ return () => scope.active && scope.gate.isCurrent(requestId);
+ },
+ }),
+ [scope],
+ );
+}
diff --git a/dashboard/src/pages/Agent/Personalization/index.tsx b/dashboard/src/pages/Agent/Personalization/index.tsx
index acdbeb5584..425901149a 100644
--- a/dashboard/src/pages/Agent/Personalization/index.tsx
+++ b/dashboard/src/pages/Agent/Personalization/index.tsx
@@ -102,17 +102,31 @@ export default function PersonalizationPage() {
`personalization.tabs.${activeTab}`,
)}`;
const showTeams = activeTab === "memory" || activeTab === "channels";
+ const hideManaged = activeTab === "mbti";
const expertOnlyBlocked = isTeamAgent(activeAgent) && !showTeams;
+ const managedAgent = activeAgent?.kind === "managed";
const teamNeedsExpert = t("agentSelector.teamNeedsExpert", {
name: activeAgent?.name ?? "",
defaultValue: "当前是团队「{{name}}」,此页请选择专家",
});
+ const managedNeedsExpert = t("agentSelector.managedNeedsExpert", {
+ name: activeAgent?.name ?? "",
+ defaultValue: "当前是托管专家「{{name}}」,此页请选择其他专家",
+ });
const expertOnly = (node: ReactNode) =>
expertOnlyBlocked ? (
) : (
node
);
+ const withoutManaged = (node: ReactNode) =>
+ expertOnlyBlocked ? (
+
+ ) : managedAgent ? (
+
+ ) : (
+ node
+ );
return (
@@ -165,7 +180,7 @@ export default function PersonalizationPage() {
>
{expertOnly(
-
+
,
)}
@@ -215,21 +230,21 @@ export default function PersonalizationPage() {
style={{ display: activeTab === "mbti" ? "flex" : "none" }}
aria-hidden={activeTab !== "mbti"}
>
- {!activeAgentId || expertOnlyBlocked ? (
+ {!activeAgentId ? (
) : (
-
-
-
+ withoutManaged(
+
+
+
,
+ )
)}
)}
diff --git a/dashboard/src/pages/Agent/Tools/ToolsPanel.tsx b/dashboard/src/pages/Agent/Tools/ToolsPanel.tsx
index e8965ecf45..c2bf654487 100644
--- a/dashboard/src/pages/Agent/Tools/ToolsPanel.tsx
+++ b/dashboard/src/pages/Agent/Tools/ToolsPanel.tsx
@@ -86,6 +86,8 @@ interface ToolsPanelProps {
agentId: string | null;
/** Which tool source to show. Defaults to built-in. */
source?: "builtin" | "plugin";
+ /** Managed experts only list tools Octop can attach. */
+ managed?: boolean;
}
/**
@@ -94,6 +96,7 @@ interface ToolsPanelProps {
export default function ToolsPanel({
agentId,
source = "builtin",
+ managed = false,
}: ToolsPanelProps) {
const { t } = useTranslation();
const [loading, setLoading] = useState(false);
@@ -472,7 +475,9 @@ export default function ToolsPanel({
return (
-
{t("toolSettings.hint")}
+
+ {t(managed ? "toolSettings.hintManaged" : "toolSettings.hint")}
+
{builtinGroups.map((group) => (
diff --git a/dashboard/src/pages/Agent/Tools/ToolsTabs.tsx b/dashboard/src/pages/Agent/Tools/ToolsTabs.tsx
index c323b5403a..44bd3c0b17 100644
--- a/dashboard/src/pages/Agent/Tools/ToolsTabs.tsx
+++ b/dashboard/src/pages/Agent/Tools/ToolsTabs.tsx
@@ -25,11 +25,16 @@ const TOOL_TABS: TabBarItem[] = [
interface ToolsTabsProps {
agentId: string | null;
+ /** Managed experts only list tools Octop can attach, plus plugin tools. */
+ managed?: boolean;
}
-export default function ToolsTabs({ agentId }: ToolsTabsProps) {
+export default function ToolsTabs({
+ agentId,
+ managed = false,
+}: ToolsTabsProps) {
const user = useCurrentUser();
- const canAcp = canAccessKeys(user, "admin");
+ const canAcp = canAccessKeys(user, "admin") && !managed;
const [activeTab, setActiveTab] = useState("builtin");
const tabs = useMemo(
@@ -50,7 +55,7 @@ export default function ToolsTabs({ agentId }: ToolsTabsProps) {
)}
>
{resolvedTab === "builtin" ? (
-
+
) : resolvedTab === "plugin" ? (
) : (
diff --git a/dashboard/src/pages/Chat/components/ChatInput.tsx b/dashboard/src/pages/Chat/components/ChatInput.tsx
index c8fa024de1..bf167e6c8f 100644
--- a/dashboard/src/pages/Chat/components/ChatInput.tsx
+++ b/dashboard/src/pages/Chat/components/ChatInput.tsx
@@ -21,6 +21,7 @@ import { useSlashCommands } from "../../../hooks/useSlashCommands";
import SlashCommandMenu from "./SlashCommandMenu";
import { textAssistApi } from "../../../api/modules/textAssist";
import type { ChatAttachment } from "../hooks/useChat";
+import type { AcpSessionMode } from "../../../api/modules/acp";
import type { ResolvedModel } from "../../../api/types";
import type { KnowledgeBase } from "../../../api/modules/knowledgeBases";
import type { SkillSpec } from "../../Agent/Skills/useSkills";
@@ -112,6 +113,9 @@ interface ChatInputProps {
) => void;
conversationMode?: "ask" | "plan" | "craft";
onConversationModeChange?: (mode: "ask" | "plan" | "craft") => void;
+ sessionModes?: AcpSessionMode[];
+ sessionMode?: string;
+ onSessionModeChange?: (modeId: string) => void;
hitlPolicy?: HitlSessionPolicy;
onHitlPolicyChange?: (policy: HitlSessionPolicy) => void;
/** Shared conversation: model, reasoning, mode, and approval stay with the owner. */
@@ -178,6 +182,9 @@ const ChatInput = forwardRef(
onReasoningChange,
conversationMode = "craft",
onConversationModeChange,
+ sessionModes,
+ sessionMode,
+ onSessionModeChange,
hitlPolicy,
onHitlPolicyChange,
lockThreadSettings = false,
@@ -504,7 +511,7 @@ const ChatInput = forwardRef(
locale: i18n.language,
availableSkills,
availableConnectors,
- availableExperts: managed ? [] : availableExperts,
+ availableExperts,
availableSubagents,
agentId,
selectedConnectors,
@@ -515,6 +522,7 @@ const ChatInput = forwardRef(
isStreaming,
onSubmitRef: submitRef,
enterToSend: !isMobile,
+ slashMenuEnabled: !managed,
});
const skillTokenRefs = useMemo(
@@ -1034,6 +1042,9 @@ const ChatInput = forwardRef(
onReasoningChange={onReasoningChange}
conversationMode={conversationMode}
onConversationModeChange={onConversationModeChange}
+ sessionModes={sessionModes}
+ sessionMode={sessionMode}
+ onSessionModeChange={onSessionModeChange}
hitlPolicy={hitlPolicy}
onHitlPolicyChange={onHitlPolicyChange}
lockThreadSettings={lockThreadSettings}
@@ -1046,11 +1057,9 @@ const ChatInput = forwardRef(
onKnowledgeBaseIdsChange={onKnowledgeBaseIdsChange}
availableSkills={availableSkills}
onInsertSkillCommand={insertSkillCommand}
- availableExperts={
- managed
- ? []
- : availableExperts.filter((a) => a.agent_id !== agentId)
- }
+ availableExperts={availableExperts.filter(
+ (a) => a.agent_id !== agentId,
+ )}
onInsertExpertMention={insertExpertMention}
availableSubagents={availableSubagents}
onInsertSubagentMention={insertSubagentMention}
diff --git a/dashboard/src/pages/Chat/components/ChatInputActionsRow.test.tsx b/dashboard/src/pages/Chat/components/ChatInputActionsRow.test.tsx
index eae61eca9e..6c40d918b6 100644
--- a/dashboard/src/pages/Chat/components/ChatInputActionsRow.test.tsx
+++ b/dashboard/src/pages/Chat/components/ChatInputActionsRow.test.tsx
@@ -89,6 +89,137 @@ describe("ChatInputActionsRow plus menu", () => {
);
expect(screen.queryByTestId("context-window-ring")).not.toBeInTheDocument();
+ expect(screen.getByTestId("managed-approval-picker")).toBeInTheDocument();
+ expect(screen.queryByTestId("hitl-policy-picker")).not.toBeInTheDocument();
+ });
+
+ it("keeps approval when the managed agent has no unattended mode", () => {
+ render(
+
+ undefined}
+ sessionModes={[
+ {
+ id: "build",
+ name_zh: "构建",
+ name_en: "Build",
+ hint_zh: "",
+ hint_en: "",
+ },
+ {
+ id: "plan",
+ name_zh: "规划",
+ name_en: "Plan",
+ hint_zh: "",
+ hint_en: "",
+ },
+ ]}
+ />
+ ,
+ );
+
+ expect(screen.getByTestId("managed-approval-picker")).toBeInTheDocument();
+ expect(
+ screen.getByLabelText("chat.conversationMode.picker"),
+ ).toBeInTheDocument();
+ });
+
+ it("hides approval when a session mode already skips it", () => {
+ render(
+
+ undefined}
+ sessionModes={[
+ {
+ id: "default",
+ name_zh: "默认",
+ name_en: "Default",
+ hint_zh: "",
+ hint_en: "",
+ },
+ {
+ id: "bypassPermissions",
+ name_zh: "YOLO",
+ name_en: "YOLO",
+ hint_zh: "",
+ hint_en: "",
+ },
+ ]}
+ />
+ ,
+ );
+
+ expect(
+ screen.queryByTestId("managed-approval-picker"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("keeps connector and knowledge pickers for a managed expert", () => {
+ render(
+
+ undefined}
+ availableKnowledgeBases={[
+ {
+ id: "kb1",
+ owner_user_id: 1,
+ name: "手册",
+ description: "",
+ default_open: false,
+ shared: false,
+ icon_name: "book",
+ embedding_model: "",
+ embedding_dim: 0,
+ doc_count: 0,
+ max_documents: 1,
+ created_at: 0,
+ updated_at: 0,
+ },
+ ]}
+ selectedKnowledgeBaseIds={[]}
+ onKnowledgeBaseIdsChange={() => undefined}
+ />
+ ,
+ );
+
+ expect(screen.getByLabelText("connectors.chatPicker")).toBeInTheDocument();
+ expect(screen.getByLabelText("chat.knowledgePicker")).toBeInTheDocument();
+ expect(screen.queryByLabelText("Model")).not.toBeInTheDocument();
+ });
+
+ it("keeps the expert picker for a managed expert", () => {
+ render(
+
+ undefined}
+ />
+ ,
+ );
+
+ expect(screen.getByLabelText("chat.expertPicker")).toBeInTheDocument();
});
it("folds shortcut, upload, and polish into the plus menu when the composer is narrow", async () => {
diff --git a/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx b/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx
index d214b3fdef..9ab0202429 100644
--- a/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx
+++ b/dashboard/src/pages/Chat/components/ChatInputActionsRow.tsx
@@ -32,6 +32,11 @@ import {
import { Tooltip, Popover } from "antd";
import cx from "classnames";
import { message } from "@/utils/antdMessage";
+import {
+ catalogOffersUnattendedMode,
+ type AcpSessionMode,
+} from "../../../api/modules/acp";
+import { acpSessionModeText } from "../../../api/modules/acp";
import type { ResolvedModel } from "../../../api/types";
import type { KnowledgeBase } from "../../../api/modules/knowledgeBases";
import type { SkillSpec } from "../../Agent/Skills/useSkills";
@@ -53,6 +58,8 @@ import {
conversationModeIcon,
} from "./ConversationModePicker";
import HitlPolicyPicker from "./HitlPolicyPicker";
+import { SessionModeMenu, sessionModeIcon } from "./SessionModeMenu";
+import ManagedApprovalPicker from "./ManagedApprovalPicker";
import SlashCommandMenu from "./SlashCommandMenu";
import type { SlashMenuGroup } from "../../../utils/slashCategories";
import type { SlashMenuItem } from "../hooks/useSlashMentionInput";
@@ -160,6 +167,9 @@ interface ChatInputActionsRowProps {
) => void;
conversationMode?: "ask" | "plan" | "craft";
onConversationModeChange?: (mode: "ask" | "plan" | "craft") => void;
+ sessionModes?: AcpSessionMode[];
+ sessionMode?: string;
+ onSessionModeChange?: (modeId: string) => void;
hitlPolicy?: HitlSessionPolicy;
onHitlPolicyChange?: (policy: HitlSessionPolicy) => void;
lockThreadSettings?: boolean;
@@ -182,7 +192,7 @@ interface ChatInputActionsRowProps {
slashPickerGroups: SlashMenuGroup[] | null;
slashMenuItems: SlashMenuItem[];
onSlashShortcutSelect: (command: string) => void;
- /** Hide mode, model, connectors, knowledge, experts, and shortcuts. */
+ /** Hide mode, model, and shortcuts. Experts, subagents, connectors, and knowledge stay. */
managed?: boolean;
onFileSelect: () => void;
onFolderSelect: () => void;
@@ -226,6 +236,9 @@ export default function ChatInputActionsRow({
onReasoningChange,
conversationMode = "craft",
onConversationModeChange,
+ sessionModes,
+ sessionMode = "",
+ onSessionModeChange,
hitlPolicy,
onHitlPolicyChange,
lockThreadSettings = false,
@@ -253,7 +266,7 @@ export default function ChatInputActionsRow({
onCancel,
onSubmit,
}: ChatInputActionsRowProps) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const settingsLockedHint = lockThreadSettings
? t("chat.threadSettingsOwnerOnly", "只有会话创建人可以改模型和审批设置")
: undefined;
@@ -359,22 +372,21 @@ export default function ChatInputActionsRow({
!managed &&
Boolean(availableModels && availableModels.length > 0 && onModelChange);
const allowWriteTools = conversationMode === "craft";
- const showConnectorPicker =
- !managed &&
- Boolean(allowWriteTools && availableConnectors && onConnectorsChange);
- const showKnowledgePicker =
- !managed && Boolean(availableKnowledgeBases && onKnowledgeBaseIdsChange);
+ const showConnectorPicker = Boolean(
+ allowWriteTools && availableConnectors && onConnectorsChange,
+ );
+ const showKnowledgePicker = Boolean(
+ availableKnowledgeBases && onKnowledgeBaseIdsChange,
+ );
const showSkillPicker = Boolean(
allowWriteTools && availableSkills && onInsertSkillCommand,
);
- const showExpertPicker =
- !managed &&
- Boolean(
- allowWriteTools &&
- availableExperts &&
- onInsertExpertMention &&
- availableExperts.length > 0,
- );
+ const showExpertPicker = Boolean(
+ allowWriteTools &&
+ availableExperts &&
+ onInsertExpertMention &&
+ availableExperts.length > 0,
+ );
const showSubagentPicker = Boolean(
allowWriteTools &&
availableSubagents &&
@@ -396,7 +408,13 @@ export default function ChatInputActionsRow({
[availableSkills, skillDisplayName],
);
const activeSkillSlugs = parseSkillSlugsInText(text, skillTokenRefs);
- const showModePicker = !managed && Boolean(onConversationModeChange);
+ const showManagedModes =
+ managed && (sessionModes?.length ?? 0) > 0 && Boolean(onSessionModeChange);
+ const showModePicker =
+ showManagedModes || (!managed && Boolean(onConversationModeChange));
+ const activeSessionMode = sessionModes?.find(
+ (mode) => mode.id === sessionMode,
+ );
const polishDisabled =
!text.trim() || polishing || isStreaming || disabled || !agentId;
const overflowKeys = (
@@ -460,7 +478,7 @@ export default function ChatInputActionsRow({
expert: t("chat.expertPicker"),
subagent: t("chat.subagentPicker"),
shortcut: t("shortcut.title", "快捷指令"),
- upload: t("upload.tooltip", "Upload"),
+ upload: t("upload.action", "Upload"),
};
const reasoningModel = availableModels?.find(
@@ -765,7 +783,9 @@ export default function ChatInputActionsRow({
);
- const ModeIcon = conversationModeIcon(conversationMode);
+ const ModeIcon = showManagedModes
+ ? sessionModeIcon(sessionMode)
+ : conversationModeIcon(conversationMode);
const renderPlusMenu = () => (
@@ -788,7 +808,11 @@ export default function ChatInputActionsRow({
- {t(`chat.conversationMode.${conversationMode}`)}
+ {showManagedModes
+ ? activeSessionMode
+ ? acpSessionModeText(activeSessionMode, i18n.language, "name")
+ : sessionMode
+ : t(`chat.conversationMode.${conversationMode}`)}
@@ -951,7 +975,7 @@ export default function ChatInputActionsRow({
>
- {t("upload.tooltip", "Upload")}
+ {t("upload.action", "Upload")}
@@ -1074,7 +1098,17 @@ export default function ChatInputActionsRow({
const renderPickerBody = (key: CompactPickerKey) => {
switch (key) {
case "mode":
- return (
+ return showManagedModes ? (
+ {
+ onSessionModeChange?.(modeId);
+ closePlusMenu();
+ }}
+ />
+ ) : (
{
@@ -1277,14 +1311,24 @@ export default function ChatInputActionsRow({
)}
- {onHitlPolicyChange && (
+ {onHitlPolicyChange &&
+ managed &&
+ !catalogOffersUnattendedMode(sessionModes ?? []) ? (
+
+ ) : null}
+ {onHitlPolicyChange && !managed ? (
- )}
+ ) : null}
{!useCompactControls && !managed && (
);
- return
{avatar} ;
+ return (
+
+ {avatar}
+
+ );
}
diff --git a/dashboard/src/pages/Chat/components/ExpertPickerPopover.tsx b/dashboard/src/pages/Chat/components/ExpertPickerPopover.tsx
index 43d8a846bc..6f40b62994 100644
--- a/dashboard/src/pages/Chat/components/ExpertPickerPopover.tsx
+++ b/dashboard/src/pages/Chat/components/ExpertPickerPopover.tsx
@@ -8,6 +8,7 @@ import SearchablePickerPanel, {
} from "../../../components/ChatPicker/SearchablePickerPanel";
import { message } from "@/utils/antdMessage";
import ExpertAgentAvatar, { type ChatAgentOption } from "./ExpertAgentAvatar";
+import { incomingShareProps } from "../../../components/SharedResourceBadge";
import RemoteExpertHint from "./RemoteExpertHint";
import { SharedResourceBadge } from "../../../components/SharedResourceBadge";
import { groupExpertsByConnection } from "../../../utils/remoteExpert";
@@ -164,6 +165,7 @@ export default function ExpertPickerPopover({
size={32}
iconSize={18}
managedRunner={agent.managed_runner}
+ {...incomingShareProps(agent)}
/>
{agent.name}
diff --git a/dashboard/src/pages/Chat/components/GeneratingIndicator.tsx b/dashboard/src/pages/Chat/components/GeneratingIndicator.tsx
index 71fd7ebf6f..2444c4bfd7 100644
--- a/dashboard/src/pages/Chat/components/GeneratingIndicator.tsx
+++ b/dashboard/src/pages/Chat/components/GeneratingIndicator.tsx
@@ -4,6 +4,7 @@ import { useAgent } from "../../../context/AgentContext";
import { isTeamAgent, isTeamHostSpeaker } from "../../../utils/teamAgent";
import { rewritePeerSpeakerId } from "../../../utils/remoteExpert";
import { managedRunnerId } from "../../Experts/components/ManagedAvatarMark";
+import { incomingShareProps } from "../../../components/SharedResourceBadge";
import { ExpertMessageAvatar } from "./MessageSender";
import styles from "../index.module.less";
@@ -62,6 +63,7 @@ function GeneratingAvatar({ agentId }: { agentId?: string | null }) {
tooltip={avatarTooltip}
profileAgentId={avatarProfileId}
managedRunner={managedRunnerId(expert)}
+ {...incomingShareProps(expert)}
/>
);
diff --git a/dashboard/src/pages/Chat/components/ManagedApprovalPicker.tsx b/dashboard/src/pages/Chat/components/ManagedApprovalPicker.tsx
new file mode 100644
index 0000000000..640062b5a5
--- /dev/null
+++ b/dashboard/src/pages/Chat/components/ManagedApprovalPicker.tsx
@@ -0,0 +1,97 @@
+import { useState } from "react";
+import { useTranslation } from "react-i18next";
+import { ShieldAlert, ShieldOff } from "lucide-react";
+import { Popover, Tooltip } from "antd";
+import cx from "classnames";
+import type { HitlSessionPolicy } from "../utils/hitlSessionPolicy";
+import styles from "../index.module.less";
+
+interface ManagedApprovalPickerProps {
+ policy: HitlSessionPolicy;
+ onChange: (policy: HitlSessionPolicy) => void;
+ disabled?: boolean;
+ disabledHint?: string;
+}
+
+/** Approval switch for a chat whose replies come from an external agent. */
+export default function ManagedApprovalPicker({
+ policy,
+ onChange,
+ disabled = false,
+ disabledHint,
+}: ManagedApprovalPickerProps) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const yolo = policy.mode === "allow_all";
+ const triggerLabel = yolo
+ ? t("chat.managedApproval.yolo")
+ : t("chat.managedApproval.ask");
+
+ const choose = (next: HitlSessionPolicy) => {
+ onChange(next);
+ setOpen(false);
+ };
+
+ return (
+
+ choose({ mode: "ask" })}
+ >
+
+
+ {t("chat.managedApproval.ask")}
+
+
+ {t("chat.managedApproval.askHint")}
+
+
+ choose({ mode: "allow_all" })}
+ >
+
+
+ {t("chat.managedApproval.yolo")}
+
+
+ {t("chat.managedApproval.yoloHint")}
+
+
+
+ }
+ >
+
+
+ {yolo ? : }
+
+
+
+ );
+}
diff --git a/dashboard/src/pages/Chat/components/MentionPickerMenu.tsx b/dashboard/src/pages/Chat/components/MentionPickerMenu.tsx
index 15cc64eeed..ff88cb015d 100644
--- a/dashboard/src/pages/Chat/components/MentionPickerMenu.tsx
+++ b/dashboard/src/pages/Chat/components/MentionPickerMenu.tsx
@@ -11,6 +11,7 @@ import {
type WorkspaceMentionHint,
} from "../utils/fileMention";
import ExpertAgentAvatar from "./ExpertAgentAvatar";
+import { incomingShareProps } from "../../../components/SharedResourceBadge";
import styles from "../index.module.less";
export type MentionAgentOption = ChatAgentOption;
@@ -205,6 +206,7 @@ export default function MentionPickerMenu({
size={20}
iconSize={11}
managedRunner={agent?.managed_runner}
+ {...incomingShareProps(agent)}
/>
);
}
diff --git a/dashboard/src/pages/Chat/components/MessageBubble.tsx b/dashboard/src/pages/Chat/components/MessageBubble.tsx
index 74ad0020c3..9baf677386 100644
--- a/dashboard/src/pages/Chat/components/MessageBubble.tsx
+++ b/dashboard/src/pages/Chat/components/MessageBubble.tsx
@@ -40,6 +40,7 @@ import { prepareSpeechText } from "../../../utils/plainTextForSpeech";
import {
chatStreamErrorAction,
formatChatStreamError,
+ isChatStreamError,
} from "../../../utils/chatStreamError";
import { MessageFileCard } from "./MessageFileCard";
import AskQuestionCard from "./AskQuestionCard";
@@ -49,6 +50,7 @@ import {
} from "./ConnectorAuthAction";
import HitlApprovalCard from "./HitlApprovalCard";
import { managedRunnerId } from "../../Experts/components/ManagedAvatarMark";
+import { incomingShareProps } from "../../../components/SharedResourceBadge";
import MessageSender, { ExpertMessageAvatar } from "./MessageSender";
import { useCurrentUser } from "../../../hooks/useCurrentUser";
import { useAgent } from "../../../context/AgentContext";
@@ -746,7 +748,9 @@ function MessageBubble({
isUser && !isEditing && hasUserComposerTags(message.composerContext);
const isStreaming = message.status === "streaming";
const hasToolData = !!message.toolData;
- const isError = message.status === "error";
+ const isError =
+ message.status === "error" ||
+ (!isUser && !hasToolData && isChatStreamError(textContent));
const errorSource = isError
? message.errorInfo?.message?.trim() || textContent
: textContent;
@@ -848,6 +852,7 @@ function MessageBubble({
tooltip={avatarTooltip}
profileAgentId={avatarProfileId}
managedRunner={managedRunnerId(expert)}
+ {...incomingShareProps(expert)}
/>
) : null;
diff --git a/dashboard/src/pages/Chat/components/MessageSender.tsx b/dashboard/src/pages/Chat/components/MessageSender.tsx
index 2cbbee1d32..abf0439849 100644
--- a/dashboard/src/pages/Chat/components/MessageSender.tsx
+++ b/dashboard/src/pages/Chat/components/MessageSender.tsx
@@ -36,6 +36,9 @@ interface ExpertMessageAvatarProps {
profileAgentId?: string | null;
/** ACP runner shown at the avatar's bottom-right. */
managedRunner?: string | null;
+ shared?: boolean;
+ owned?: boolean;
+ ownerName?: string | null;
}
export function ExpertMessageAvatar({
@@ -46,6 +49,9 @@ export function ExpertMessageAvatar({
tooltip,
profileAgentId,
managedRunner,
+ shared,
+ owned,
+ ownerName,
}: ExpertMessageAvatarProps) {
const { t } = useTranslation();
const profile = useChatAgentProfile();
@@ -58,6 +64,9 @@ export function ExpertMessageAvatar({
color={color}
size={MESSAGE_AVATAR_SIZE}
managedRunner={managedRunner}
+ shared={shared}
+ owned={owned}
+ ownerName={ownerName}
/>
);
diff --git a/dashboard/src/pages/Chat/components/SessionModeMenu.tsx b/dashboard/src/pages/Chat/components/SessionModeMenu.tsx
new file mode 100644
index 0000000000..d7b0962074
--- /dev/null
+++ b/dashboard/src/pages/Chat/components/SessionModeMenu.tsx
@@ -0,0 +1,70 @@
+import {
+ Hammer,
+ ListTodo,
+ MessageCircleQuestion,
+ ShieldOff,
+ type LucideIcon,
+} from "lucide-react";
+import cx from "classnames";
+import {
+ acpSessionModeText,
+ isUnattendedSessionMode,
+ type AcpSessionMode,
+} from "../../../api/modules/acp";
+import styles from "../index.module.less";
+
+export function sessionModeIcon(modeId: string): LucideIcon {
+ const folded = modeId.toLowerCase();
+ if (isUnattendedSessionMode(modeId)) {
+ return ShieldOff;
+ }
+ if (folded.includes("plan")) return ListTodo;
+ if (
+ folded.includes("read-only") ||
+ folded.includes("readonly") ||
+ folded === "default" ||
+ folded.includes("ask")
+ ) {
+ return MessageCircleQuestion;
+ }
+ return Hammer;
+}
+
+export function SessionModeMenu({
+ modes,
+ modeId,
+ language,
+ onChange,
+}: {
+ modes: AcpSessionMode[];
+ modeId: string;
+ language: string;
+ onChange: (modeId: string) => void;
+}) {
+ return (
+
+ {modes.map((mode) => {
+ const Icon = sessionModeIcon(mode.id);
+ return (
+ onChange(mode.id)}
+ >
+
+
+ {acpSessionModeText(mode, language, "name")}
+
+
+ {acpSessionModeText(mode, language, "hint")}
+
+
+ );
+ })}
+
+ );
+}
diff --git a/dashboard/src/pages/Chat/components/TurnProcessBlocks.tsx b/dashboard/src/pages/Chat/components/TurnProcessBlocks.tsx
index dd5118e1f3..ff25dc07fd 100644
--- a/dashboard/src/pages/Chat/components/TurnProcessBlocks.tsx
+++ b/dashboard/src/pages/Chat/components/TurnProcessBlocks.tsx
@@ -7,6 +7,7 @@ import { useToolRendererVersion } from "../../../plugins/toolRenderers";
import AssistantProcessSummary from "./AssistantProcessSummary";
import { ToolDetailsInline } from "./MessageBubble";
import { managedRunnerId } from "../../Experts/components/ManagedAvatarMark";
+import { incomingShareProps } from "../../../components/SharedResourceBadge";
import { ExpertMessageAvatar } from "./MessageSender";
import { useAgent } from "../../../context/AgentContext";
import { isTeamAgent, isTeamHostSpeaker } from "../../../utils/teamAgent";
@@ -90,6 +91,7 @@ export function TurnProcessBlocks({
tooltip={avatarTooltip}
profileAgentId={avatarProfileId}
managedRunner={managedRunnerId(expert)}
+ {...incomingShareProps(expert)}
/>
) : null}
diff --git a/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx b/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx
index 63a1dfed40..053f68f501 100644
--- a/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx
+++ b/dashboard/src/pages/Chat/components/UserMessageComposerTags.tsx
@@ -7,6 +7,7 @@ import { useSkillDisplayName } from "../../Agent/Skills/skillDisplayNames";
import type { KnowledgeBase } from "../../../api/modules/knowledgeBases";
import type { ChatAgentOption } from "./ExpertAgentAvatar";
import ExpertAgentAvatar from "./ExpertAgentAvatar";
+import { incomingShareProps } from "../../../components/SharedResourceBadge";
import { ConnectorLogo } from "../../Agent/Connectors/connectorDefs";
import { knowledgeIconForName } from "../../KnowledgeBases/knowledgeIcons";
import ContextChip, { type ContextChipVariant } from "./ContextChip";
@@ -114,6 +115,7 @@ export default function UserMessageComposerTags({
iconSize={9}
muted
managedRunner={agent?.managed_runner}
+ {...incomingShareProps(agent)}
/>
),
label: agent?.name || id,
diff --git a/dashboard/src/pages/Chat/hooks/chatStore.ts b/dashboard/src/pages/Chat/hooks/chatStore.ts
index c95479d9ec..7829997c09 100644
--- a/dashboard/src/pages/Chat/hooks/chatStore.ts
+++ b/dashboard/src/pages/Chat/hooks/chatStore.ts
@@ -3186,6 +3186,7 @@ async function sendTurnWebSocket(
conversationMode?: "ask" | "plan" | "craft" | null,
hitlPolicy?: { mode: string; tools?: string[] } | null,
clientMessageId?: string | null,
+ sessionMode?: string | null,
): Promise {
const state = getOrCreate(sessionId);
const resolvedThreadId = (threadId || sessionId).trim();
@@ -3269,6 +3270,7 @@ async function sendTurnWebSocket(
if (reasoningMode) payload.reasoning_mode = reasoningMode;
if (reasoningEffort) payload.reasoning_effort = reasoningEffort;
if (conversationMode) payload.conversation_mode = conversationMode;
+ if (sessionMode) payload.session_mode = sessionMode;
if (hitlPolicy) payload.hitl_policy = hitlPolicy;
ws.send(JSON.stringify(payload));
};
@@ -3501,6 +3503,7 @@ export async function sendTurn(
conversationMode?: "ask" | "plan" | "craft" | null,
hitlPolicy?: { mode: string; tools?: string[] } | null,
clientMessageId?: string | null,
+ sessionMode?: string | null,
): Promise {
const state = getOrCreate(sessionId);
rememberRoomAgent(state, agentId);
@@ -3607,6 +3610,7 @@ export async function sendTurn(
conversationMode,
hitlPolicy,
clientMessageId,
+ sessionMode,
);
if (!wsOk) {
state.messages = [
diff --git a/dashboard/src/pages/Chat/hooks/toolDisplayNames.test.ts b/dashboard/src/pages/Chat/hooks/toolDisplayNames.test.ts
index 02d8a5a108..08f9a1c078 100644
--- a/dashboard/src/pages/Chat/hooks/toolDisplayNames.test.ts
+++ b/dashboard/src/pages/Chat/hooks/toolDisplayNames.test.ts
@@ -11,6 +11,16 @@ describe("preferToolName", () => {
expect(preferToolName("Web Search", "unknown")).toBe("Web Search");
});
+ it("keeps write_file when a later ACP title reuses the call", () => {
+ expect(
+ preferToolName(
+ "Write /home/wally/GWN3MS/random_7f3a9c.txt",
+ "write_file",
+ ),
+ ).toBe("write_file");
+ expect(preferToolName("edit_file", "Write notes.md")).toBe("edit_file");
+ });
+
it("treats only a blank or unknown name as a placeholder", () => {
expect(isPlaceholderToolName("unknown")).toBe(true);
expect(isPlaceholderToolName("Web Search")).toBe(false);
diff --git a/dashboard/src/pages/Chat/hooks/toolDisplayNames.ts b/dashboard/src/pages/Chat/hooks/toolDisplayNames.ts
index e3fc3c9120..d4939d812f 100644
--- a/dashboard/src/pages/Chat/hooks/toolDisplayNames.ts
+++ b/dashboard/src/pages/Chat/hooks/toolDisplayNames.ts
@@ -4,6 +4,7 @@
*/
import { useTranslation } from "react-i18next";
+import { isFileToolName } from "../constants";
/** Names the harness invents when an ACP update did not include a title. */
export function isPlaceholderToolName(name?: string): boolean {
@@ -11,14 +12,20 @@ export function isPlaceholderToolName(name?: string): boolean {
return !text || text === "unknown";
}
-/** Keep a real tool name. A later ``unknown`` update must not replace it. */
+/** Keep a real tool name. A later ``unknown`` update must not replace it.
+
+ACP file edits are stored as ``write_file`` / ``edit_file`` and then again
+under the agent title (``Write /path``). The file card only recognizes the
+native name, so that title must not replace it.
+*/
export function preferToolName(
incoming?: string,
current?: string,
): string | undefined {
const next = incoming?.trim();
- if (!isPlaceholderToolName(next)) return next;
const prev = current?.trim();
+ if (isFileToolName(prev) && !isFileToolName(next)) return prev;
+ if (!isPlaceholderToolName(next)) return next;
return prev || next;
}
diff --git a/dashboard/src/pages/Chat/hooks/useChat.ts b/dashboard/src/pages/Chat/hooks/useChat.ts
index 875e649783..a4e97a176f 100644
--- a/dashboard/src/pages/Chat/hooks/useChat.ts
+++ b/dashboard/src/pages/Chat/hooks/useChat.ts
@@ -34,6 +34,7 @@ import {
import { injectPendingHitlMessage } from "../../../utils/injectPendingHitlMessage";
import {
mergeHistoryWithLocalTail,
+ preserveLocalComposerContext,
preferLocalTranscript,
restoreUnpersistedTurn,
serverCaughtUp,
@@ -542,12 +543,22 @@ function convertCallEntries(entries: CallEntry[]): ChatMessage[] {
current.toolData?.name,
existing.toolData?.name,
);
- if (name && name !== existing.toolData?.name) {
+ const existingArgs = existing.toolData?.arguments?.trim() ?? "";
+ const incomingArgs = current.toolData?.arguments?.trim() ?? "";
+ const argumentsJson =
+ !existingArgs || existingArgs === "{}"
+ ? incomingArgs || existing.toolData?.arguments
+ : existing.toolData?.arguments;
+ if (
+ (name && name !== existing.toolData?.name) ||
+ argumentsJson !== existing.toolData?.arguments
+ ) {
merged[existingIdx] = {
...existing,
toolData: {
...existing.toolData,
- name,
+ name: name || existing.toolData?.name,
+ arguments: argumentsJson,
displayName: isPlaceholderToolName(current.toolData?.name)
? existing.toolData?.displayName
: current.toolData?.displayName ||
@@ -828,6 +839,7 @@ async function loadThreadHistory(
syncSessionArtifacts,
syncSessionConversationMode,
syncSessionHitlPolicy,
+ syncSessionMode,
} = await import("./useSessions");
const limit = params.limit ?? CHAT_HISTORY_PAGE_SIZE;
const offset = params.offset ?? 0;
@@ -851,6 +863,7 @@ async function loadThreadHistory(
history.pending_plan_path,
);
syncSessionHitlPolicy(threadId, history.hitl_policy);
+ syncSessionMode(threadId, history.session_mode);
chatStore.setPendingPlanPath(threadId, history.pending_plan_path);
}
const messages = injectPendingHitlMessage(
@@ -1025,6 +1038,7 @@ export function useChat(
reasoningEffort?: string | null,
conversationMode?: "ask" | "plan" | "craft" | null,
hitlPolicy?: HitlSessionPolicy | null,
+ sessionMode?: string | null,
) => {
const key = storeKey || stableSessionId;
@@ -1070,6 +1084,7 @@ export function useChat(
conversationMode,
hitlPolicy,
userMsg.id,
+ sessionMode,
);
},
[currentUser, stableSessionId],
@@ -1170,10 +1185,13 @@ export function useChat(
retainedHistoryPrefix(loaded.messages, current.messages).length > 0;
chatStore.setHistoryPage(
key,
- mergeHistoryWithLocalTail(
- loaded.messages,
+ preserveLocalComposerContext(
+ mergeHistoryWithLocalTail(
+ loaded.messages,
+ local,
+ current.isStreaming,
+ ),
local,
- current.isStreaming,
),
{
hasMore: keptOlder ? current.historyHasMore : loaded.hasMore,
@@ -1339,7 +1357,10 @@ export function useChat(
retainedHistoryPrefix(latest, current.messages).length > 0;
chatStore.setHistoryPage(
key,
- mergeHistoryWithLocalTail(latest, local, current.isStreaming),
+ preserveLocalComposerContext(
+ mergeHistoryWithLocalTail(latest, local, current.isStreaming),
+ local,
+ ),
{
hasMore: keptOlder ? current.historyHasMore : hasMore,
nextOffset: keptOlder ? current.historyNextOffset : nextOffset,
diff --git a/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts b/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts
index e3f2c2ce16..754ab21296 100644
--- a/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts
+++ b/dashboard/src/pages/Chat/hooks/useChatComposerResources.ts
@@ -12,6 +12,8 @@ import type { ResolvedModel } from "../../../api/types";
import { CONNECTORS_CHANGED_EVENT } from "../../Agent/Connectors/customMcpUtils";
import { useCurrentUser } from "../../../hooks/useCurrentUser";
import { useAgent } from "../../../context/AgentContext";
+import { useAcpSessionModes } from "../../../hooks/useAcpSessionModes";
+import { isUnattendedSessionMode } from "../../../api/modules/acp";
import { activeModelToRef } from "./useChatContextWindow";
import {
hasSavedConnectors,
@@ -31,6 +33,7 @@ import {
isPendingThread,
syncSessionConversationMode,
syncSessionHitlPolicy,
+ syncSessionMode,
} from "./useSessions";
import { isTeamAgent } from "../../../utils/teamAgent";
import * as chatStore from "./chatStore";
@@ -69,6 +72,7 @@ export function useChatComposerResources(
stickyReasoningEffort?: string | null,
stickyConversationMode?: ConversationMode | null,
stickyHitlPolicy?: HitlSessionPolicy | null,
+ stickySessionMode?: string | null,
persistThreadSettings = true,
) {
const user = useCurrentUser();
@@ -78,6 +82,19 @@ export function useChatComposerResources(
const expertDefaultMode = parseConversationMode(
expert?.config?.conversation_mode,
);
+ const expertYolo =
+ expert?.kind === "managed" &&
+ expert.config?.managed_permission_mode === "yolo";
+ const managedRunner =
+ expert?.kind === "managed" &&
+ typeof expert.config?.managed_runner === "string"
+ ? expert.config.managed_runner
+ : "";
+ const sessionModes = useAcpSessionModes(managedRunner);
+ const pinnedSessionMode =
+ typeof expert?.config?.managed_session_mode === "string"
+ ? expert.config.managed_session_mode.trim()
+ : "";
const teamHost = isTeamAgent(expert);
const bridgeConnectionId =
expert?.bridge && expert.bridge_connection_id
@@ -140,6 +157,7 @@ export function useChatComposerResources(
const [hitlPolicy, setHitlPolicy] = useState(
DEFAULT_HITL_SESSION_POLICY,
);
+ const [sessionMode, setSessionMode] = useState("");
const [conversationOverrides, setConversationOverrides] = useState<
Record<
string,
@@ -230,10 +248,36 @@ export function useChatComposerResources(
useEffect(() => {
setHitlPolicy(
isNewSession
- ? DEFAULT_HITL_SESSION_POLICY
+ ? expertYolo
+ ? { mode: "allow_all" }
+ : DEFAULT_HITL_SESSION_POLICY
: parseHitlSessionPolicy(stickyHitlPolicy),
);
- }, [isNewSession, stickyHitlPolicy, activeThreadId]);
+ }, [isNewSession, stickyHitlPolicy, activeThreadId, expertYolo]);
+
+ const expertSessionMode =
+ pinnedSessionMode ||
+ (expertYolo
+ ? sessionModes.find((mode) => isUnattendedSessionMode(mode.id))?.id ?? ""
+ : "") ||
+ sessionModes[0]?.id ||
+ "";
+
+ useEffect(() => {
+ if (expert?.kind !== "managed") {
+ setSessionMode("");
+ return;
+ }
+ const sticky =
+ !isNewSession && stickySessionMode ? stickySessionMode.trim() : "";
+ setSessionMode(sticky || expertSessionMode);
+ }, [
+ expert?.kind,
+ isNewSession,
+ stickySessionMode,
+ activeThreadId,
+ expertSessionMode,
+ ]);
useEffect(() => {
if (agentsLoading) return;
@@ -670,6 +714,28 @@ export function useChatComposerResources(
[activeThreadId, persistThreadSettings, resolvedAgentId],
);
+ const handleSessionModeChange = useCallback(
+ (modeId: string) => {
+ const next = modeId.trim();
+ if (!next) return;
+ setSessionMode(next);
+ if (activeThreadId) {
+ syncSessionMode(activeThreadId, next);
+ }
+ if (
+ persistThreadSettings &&
+ resolvedAgentId &&
+ activeThreadId &&
+ !isPendingThread(activeThreadId)
+ ) {
+ void octopThreadsApi.patch(resolvedAgentId, activeThreadId, {
+ session_mode: next,
+ });
+ }
+ },
+ [activeThreadId, persistThreadSettings, resolvedAgentId],
+ );
+
return {
selectedModel,
setSelectedModel: handleModelChange,
@@ -680,6 +746,9 @@ export function useChatComposerResources(
handleConversationModeChange,
hitlPolicy,
handleHitlPolicyChange,
+ sessionModes,
+ sessionMode,
+ handleSessionModeChange,
selectedConnectors,
selectedKnowledgeBaseIds,
chatConnectors,
diff --git a/dashboard/src/pages/Chat/hooks/useChatSend.ts b/dashboard/src/pages/Chat/hooks/useChatSend.ts
index 5ebccbec27..ae485e0c23 100644
--- a/dashboard/src/pages/Chat/hooks/useChatSend.ts
+++ b/dashboard/src/pages/Chat/hooks/useChatSend.ts
@@ -29,6 +29,7 @@ interface UseChatSendParams {
reasoningMode: "auto" | "enabled" | "disabled";
reasoningEffort: string | null;
conversationMode?: "ask" | "plan" | "craft";
+ sessionMode?: string;
hitlPolicy?: HitlSessionPolicy;
defaultModel?: string | null;
sendMessage: (
@@ -46,6 +47,7 @@ interface UseChatSendParams {
reasoningEffort?: string | null,
conversationMode?: "ask" | "plan" | "craft" | null,
hitlPolicy?: HitlSessionPolicy | null,
+ sessionMode?: string | null,
) => void;
createSession: () => { session: Session; resolvedId: Promise };
/** Called when auto-recording starts successfully from a pending message. */
@@ -79,6 +81,7 @@ export function useChatSend({
reasoningMode,
reasoningEffort,
conversationMode = "craft",
+ sessionMode,
hitlPolicy,
defaultModel,
sendMessage,
@@ -155,6 +158,7 @@ export function useChatSend({
composerContext?.reasoningEffort ?? reasoningEffort,
mode,
policy,
+ sessionMode,
);
};
@@ -210,6 +214,7 @@ export function useChatSend({
mode,
policy,
userMsg.id,
+ sessionMode,
);
navigate(`/chat/${agent}/${tid}`, { replace: true });
});
@@ -228,6 +233,7 @@ export function useChatSend({
reasoningMode,
reasoningEffort,
conversationMode,
+ sessionMode,
hitlPolicy,
defaultModel,
t,
diff --git a/dashboard/src/pages/Chat/hooks/useSessions.ts b/dashboard/src/pages/Chat/hooks/useSessions.ts
index 1804af4d4b..495a2a4d93 100644
--- a/dashboard/src/pages/Chat/hooks/useSessions.ts
+++ b/dashboard/src/pages/Chat/hooks/useSessions.ts
@@ -25,6 +25,7 @@ export interface Session {
reasoningMode?: "auto" | "enabled" | "disabled" | null;
reasoningEffort?: string | null;
conversationMode?: "ask" | "plan" | "craft" | null;
+ sessionMode?: string | null;
pendingPlanPath?: string | null;
hitlPolicy?: HitlSessionPolicy | null;
artifacts?: ThreadArtifact[];
@@ -52,6 +53,7 @@ export function toSession(row: {
reasoning_mode?: "auto" | "enabled" | "disabled" | null;
reasoning_effort?: string | null;
conversation_mode?: "ask" | "plan" | "craft" | null;
+ session_mode?: string | null;
pending_plan_path?: string | null;
hitl_policy?: HitlSessionPolicy | null;
artifacts?: Array | null;
@@ -85,6 +87,7 @@ export function toSession(row: {
reasoningMode: row.reasoning_mode ?? null,
reasoningEffort: row.reasoning_effort ?? null,
conversationMode: row.conversation_mode ?? null,
+ sessionMode: row.session_mode ?? null,
pendingPlanPath: row.pending_plan_path ?? null,
hitlPolicy: row.hitl_policy
? parseHitlSessionPolicy(row.hitl_policy)
@@ -179,6 +182,23 @@ export function syncSessionHitlPolicy(
});
}
+/** Patch the managed agent's session mode for one thread. */
+export function syncSessionMode(
+ threadId: string,
+ mode: string | null | undefined,
+) {
+ if (!threadId) return;
+ const nextMode = mode?.trim() || null;
+ setModuleSessions((prev) => {
+ const idx = prev.findIndex((s) => s.id === threadId);
+ if (idx < 0) return prev;
+ if ((prev[idx].sessionMode ?? null) === nextMode) return prev;
+ const next = [...prev];
+ next[idx] = { ...prev[idx], sessionMode: nextMode };
+ return next;
+ });
+}
+
/** Patch conversation-mode fields for one thread in the module session store. */
export function syncSessionConversationMode(
threadId: string,
diff --git a/dashboard/src/pages/Chat/hooks/useSlashMentionInput.test.ts b/dashboard/src/pages/Chat/hooks/useSlashMentionInput.test.ts
index df0699047a..80974f3d37 100644
--- a/dashboard/src/pages/Chat/hooks/useSlashMentionInput.test.ts
+++ b/dashboard/src/pages/Chat/hooks/useSlashMentionInput.test.ts
@@ -78,6 +78,35 @@ describe("useSlashMentionInput skills", () => {
});
});
+describe("useSlashMentionInput managed composer", () => {
+ it("does not open the shortcut menu when slash shortcuts are disabled", () => {
+ const { result } = renderHook(() =>
+ useSlashMentionInput({
+ text: "",
+ setText: vi.fn(),
+ textareaRef: { current: null },
+ slashCommands: [stopCommand],
+ labelFor: (spec) => spec.label_en,
+ locale: "en",
+ availableExperts: [],
+ selectedConnectors: [],
+ onSend: vi.fn(),
+ onNewChat: vi.fn(),
+ onCancel: vi.fn(),
+ isStreaming: false,
+ onSubmitRef: { current: vi.fn() },
+ slashMenuEnabled: false,
+ }),
+ );
+
+ act(() => {
+ result.current.handleTextChange("/st");
+ });
+
+ expect(result.current.slashMenuOpen).toBe(false);
+ });
+});
+
describe("useSlashMentionInput workspace files", () => {
it("keeps empty @ as a hint-only file section and inserts the workspace path", () => {
const setText = vi.fn();
diff --git a/dashboard/src/pages/Chat/hooks/useSlashMentionInput.ts b/dashboard/src/pages/Chat/hooks/useSlashMentionInput.ts
index fdee4e8c7c..2c21394c9e 100644
--- a/dashboard/src/pages/Chat/hooks/useSlashMentionInput.ts
+++ b/dashboard/src/pages/Chat/hooks/useSlashMentionInput.ts
@@ -66,6 +66,8 @@ interface UseSlashMentionInputParams {
onSubmitRef: React.MutableRefObject<() => void>;
/** When false, Enter inserts a newline; send only via button (mobile). */
enterToSend?: boolean;
+ /** Managed experts keep typed slash text, but do not open the shortcut menu. */
+ slashMenuEnabled?: boolean;
}
export function useSlashMentionInput({
@@ -88,6 +90,7 @@ export function useSlashMentionInput({
isStreaming: _isStreaming,
onSubmitRef,
enterToSend = true,
+ slashMenuEnabled = true,
}: UseSlashMentionInputParams) {
const skillDisplayName = useSkillDisplayName();
const skillTokenRefs = useMemo(
@@ -364,8 +367,12 @@ export function useSlashMentionInput({
(val: string) => {
setText(val);
if (isSlashNamePrefix(val)) {
- setSlashMenuOpen(true);
- setSlashMenuIndex(0);
+ if (slashMenuEnabled) {
+ setSlashMenuOpen(true);
+ setSlashMenuIndex(0);
+ } else {
+ setSlashMenuOpen(false);
+ }
setMentionMenuOpen(false);
} else {
setSlashMenuOpen(false);
@@ -392,9 +399,14 @@ export function useSlashMentionInput({
mentionAgents.length,
availableSubagents.length,
agentId,
+ slashMenuEnabled,
],
);
+ useEffect(() => {
+ if (!slashMenuEnabled) setSlashMenuOpen(false);
+ }, [slashMenuEnabled]);
+
const handleKeyDown = useCallback(
(e: KeyboardEvent) => {
if (e.nativeEvent.isComposing || e.keyCode === 229) return;
diff --git a/dashboard/src/pages/Chat/index.tsx b/dashboard/src/pages/Chat/index.tsx
index 081d0f8190..36ba3c3102 100644
--- a/dashboard/src/pages/Chat/index.tsx
+++ b/dashboard/src/pages/Chat/index.tsx
@@ -597,6 +597,9 @@ function ChatPageInner() {
handleConversationModeChange,
hitlPolicy,
handleHitlPolicyChange,
+ sessionModes,
+ sessionMode,
+ handleSessionModeChange,
handleConnectorsChange,
handleKnowledgeBaseIdsChange,
} = useChatComposerResources(
@@ -607,6 +610,7 @@ function ChatPageInner() {
composerSession?.reasoningEffort,
composerSession?.conversationMode,
composerSession?.hitlPolicy,
+ composerSession?.sessionMode,
composerSession?.owned !== false,
);
@@ -742,6 +746,7 @@ function ChatPageInner() {
reasoningMode,
reasoningEffort,
conversationMode,
+ sessionMode,
hitlPolicy,
defaultModel: activeAgent?.default_model ?? null,
sendMessage,
@@ -1671,11 +1676,7 @@ function ChatPageInner() {
onOpenBrowser={
hasBrowserTool ? openBrowserTab : undefined
}
- onEditFile={
- !sharedExpertViewer && panelFilePaths.length > 0
- ? openFileList
- : undefined
- }
+ onEditFile={sharedExpertViewer ? undefined : openFileList}
/>
>
@@ -1974,9 +1975,14 @@ function ChatPageInner() {
onReasoningChange={handleReasoningChange}
conversationMode={conversationMode}
onConversationModeChange={handleConversationModeChange}
+ sessionModes={sessionModes}
+ sessionMode={sessionMode}
+ onSessionModeChange={handleSessionModeChange}
hitlPolicy={hitlPolicy}
onHitlPolicyChange={
- hitlEnabled ? handleComposerHitlPolicyChange : undefined
+ hitlEnabled || isManagedChat
+ ? handleComposerHitlPolicyChange
+ : undefined
}
lockThreadSettings={composerSession?.owned === false}
availableConnectors={isTeamChat ? undefined : chatConnectors}
diff --git a/dashboard/src/pages/Chat/utils/deleteConversation.tsx b/dashboard/src/pages/Chat/utils/deleteConversation.tsx
index 3e3a5f1eed..f2498913c5 100644
--- a/dashboard/src/pages/Chat/utils/deleteConversation.tsx
+++ b/dashboard/src/pages/Chat/utils/deleteConversation.tsx
@@ -34,17 +34,20 @@ export async function deleteConversation(
threadId: string,
compact: boolean,
t: TFunction,
+ isActive: () => boolean = () => true,
): Promise {
+ if (!isActive()) return false;
const closeLoading = compact
? antMessage.loading(t("chat.deleteSessionCompacting"), 0)
: undefined;
try {
const result = await octopThreadsApi.delete(agentId, threadId, compact);
if (typeof closeLoading === "function") closeLoading();
- antMessage.success(deleteResultText(t, compact, result));
+ if (isActive()) antMessage.success(deleteResultText(t, compact, result));
return true;
} catch (error) {
if (typeof closeLoading === "function") closeLoading();
+ if (!isActive()) return false;
if (parseApiError(error)?.code === "THREAD_TURN_ACTIVE") {
antMessage.error(t("apiErrors.THREAD_TURN_ACTIVE"));
return null;
@@ -68,7 +71,7 @@ export function confirmDeleteConversation(
| DeleteConversationResult
| void
| Promise,
-): void {
+): ReturnType {
const mobile =
typeof window !== "undefined" && window.innerWidth < MOBILE_BREAKPOINT;
let inflight = false;
@@ -133,4 +136,5 @@ export function confirmDeleteConversation(
),
});
handle.destroy = opened.destroy;
+ return opened;
}
diff --git a/dashboard/src/pages/Chat/utils/mergeHistoryTail.ts b/dashboard/src/pages/Chat/utils/mergeHistoryTail.ts
index 027539de19..cdcf513874 100644
--- a/dashboard/src/pages/Chat/utils/mergeHistoryTail.ts
+++ b/dashboard/src/pages/Chat/utils/mergeHistoryTail.ts
@@ -182,6 +182,45 @@ export function retainedHistoryPrefix(
: [];
}
+/** Keep chips the live bubble already showed when the stored row omitted them. */
+export function preserveLocalComposerContext(
+ loaded: ChatMessage[],
+ local: ChatMessage[],
+): ChatMessage[] {
+ const byId = new Map();
+ for (const message of local) {
+ if (message.role === "user" && message.composerContext) {
+ byId.set(message.id, message.composerContext);
+ }
+ }
+ if (byId.size === 0) return loaded;
+ return loaded.map((message) => {
+ if (message.role !== "user") return message;
+ const previous = byId.get(message.id);
+ if (!previous) return message;
+ const server = message.composerContext;
+ if (!server) return { ...message, composerContext: previous };
+ return {
+ ...message,
+ composerContext: {
+ skills: server.skills?.length ? server.skills : previous.skills,
+ connectors: server.connectors?.length
+ ? server.connectors
+ : previous.connectors,
+ knowledgeBaseIds: server.knowledgeBaseIds?.length
+ ? server.knowledgeBaseIds
+ : previous.knowledgeBaseIds,
+ targetAgents: server.targetAgents?.length
+ ? server.targetAgents
+ : previous.targetAgents,
+ model: server.model || previous.model,
+ reasoningMode: server.reasoningMode || previous.reasoningMode,
+ reasoningEffort: server.reasoningEffort || previous.reasoningEffort,
+ },
+ };
+ });
+}
+
/**
* Apply a server history page without dropping a turn the user just sent.
*
diff --git a/dashboard/src/pages/Control/CloudHosts/components/CloudOverviewBoard.module.less b/dashboard/src/pages/Control/CloudHosts/components/CloudOverviewBoard.module.less
index a635c31d5f..403fbdd5e9 100644
--- a/dashboard/src/pages/Control/CloudHosts/components/CloudOverviewBoard.module.less
+++ b/dashboard/src/pages/Control/CloudHosts/components/CloudOverviewBoard.module.less
@@ -22,7 +22,7 @@
align-items: center;
min-height: 34px;
padding: 7px 12px;
- font-size: 11px;
+ font-size: 12px;
color: #55708f;
background: linear-gradient(100deg, #f4f9ff, #f8fbff 52%, #f5f8fd);
border: 1px solid #dfe9f7;
@@ -75,7 +75,7 @@
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
- font-size: 11px;
+ font-size: 12px;
color: #788190;
}
@@ -118,14 +118,14 @@
gap: 6px;
align-items: center;
margin-top: 9px;
- font-size: 11px;
+ font-size: 12px;
color: #9aa2af;
white-space: nowrap;
}
.miniTag {
padding: 1px 5px;
- font-size: 11px;
+ font-size: 12px;
color: #29a17d;
background: #eef8f3;
border-radius: 4px;
@@ -203,7 +203,7 @@
.panelSub {
margin: 3px 0 0;
- font-size: 11px;
+ font-size: 12px;
color: #9aa2af;
}
@@ -214,7 +214,7 @@
.count {
padding: 1px 5px;
font-family: var(--sc-mono);
- font-size: 11px;
+ font-size: 12px;
color: #a0a8b4;
border: 1px solid #e9ecf0;
border-radius: 4px;
@@ -232,7 +232,7 @@
.segmented button {
padding: 4px 10px;
- font-size: 11px;
+ font-size: 12px;
line-height: 1.3;
color: #8a92a0;
white-space: nowrap;
@@ -278,7 +278,7 @@
align-items: center;
justify-content: space-between;
margin-bottom: 8px;
- font-size: 11px;
+ font-size: 12px;
color: #677182;
}
@@ -298,7 +298,7 @@
.regionTotal {
font-family: var(--sc-mono);
- font-size: 11px;
+ font-size: 12px;
color: #a7aeba;
white-space: nowrap;
}
@@ -319,7 +319,7 @@
min-width: 0;
padding: 0;
font-family: var(--sc-mono);
- font-size: 11px;
+ font-size: 12px;
cursor: pointer;
border: 1px solid transparent;
border-radius: 4px;
@@ -374,7 +374,7 @@
gap: 11px;
align-items: center;
padding: 10px 16px;
- font-size: 11px;
+ font-size: 12px;
color: #8b94a2;
border-top: 1px solid #f0f2f5;
}
@@ -435,7 +435,7 @@
.trendEmpty {
padding: 28px 0;
- font-size: 11px;
+ font-size: 12px;
color: var(--fn-text-quaternary);
text-align: center;
}
@@ -444,7 +444,7 @@
display: flex;
gap: 13px;
padding: 0 16px 6px;
- font-size: 11px;
+ font-size: 12px;
color: #8590a0;
}
@@ -493,7 +493,7 @@
grid-template-columns: 96px minmax(0, 1fr) 42px;
gap: 8px;
align-items: center;
- font-size: 11px;
+ font-size: 12px;
color: #8a94a3;
}
@@ -515,7 +515,7 @@
.resourceName i {
font-style: normal;
- font-size: 10px;
+ font-size: 12px;
color: #b0b8c4;
}
@@ -536,7 +536,7 @@
.resourceNumber {
font-family: var(--sc-mono);
- font-size: 11px;
+ font-size: 12px;
color: #9099a7;
text-align: right;
}
@@ -552,7 +552,7 @@
.alertCount {
padding: 2px 6px;
- font-size: 11px;
+ font-size: 12px;
font-weight: 600;
color: #c64756;
background: #fdefef;
@@ -567,7 +567,7 @@
.table {
width: 100%;
min-width: 560px;
- font-size: 12px;
+ font-size: 13px;
text-align: left;
border-collapse: collapse;
}
@@ -575,7 +575,7 @@
.table th {
height: 28px;
padding: 0 10px;
- font-size: 11px;
+ font-size: 12px;
font-weight: 400;
color: #a0a8b5;
background: #fafbfc;
@@ -605,7 +605,7 @@
align-items: center;
padding: 0;
font-family: var(--sc-mono);
- font-size: 12px;
+ font-size: 13px;
color: #4e5a6e;
cursor: pointer;
background: none;
@@ -628,7 +628,7 @@
}
.cellMain {
- font-size: 12px;
+ font-size: 13px;
font-weight: 500;
color: #657083;
}
@@ -636,13 +636,13 @@
.cellSub {
margin-top: 1px;
font-family: var(--sc-mono);
- font-size: 11px;
+ font-size: 12px;
color: #adb4bf;
}
.metricNumber {
font-family: var(--sc-mono);
- font-size: 12px;
+ font-size: 13px;
color: #7a8495;
}
@@ -668,7 +668,7 @@
.softBadge {
padding: 3px 6px;
- font-size: 11px;
+ font-size: 12px;
font-weight: 500;
color: #7a8290;
background: #f5f6f8;
@@ -731,13 +731,13 @@
display: flex;
gap: 5px;
justify-content: space-between;
- font-size: 12px;
+ font-size: 13px;
color: #747f90;
}
.eventTime {
font-family: var(--sc-mono);
- font-size: 11px;
+ font-size: 12px;
color: #a7afbb;
white-space: nowrap;
}
@@ -745,7 +745,7 @@
.eventDesc {
margin-top: 1px;
font-family: var(--sc-mono);
- font-size: 11px;
+ font-size: 12px;
color: #a4acb8;
}
@@ -758,7 +758,7 @@
gap: 10px;
align-items: center;
padding: 0 2px 2px;
- font-size: 11px;
+ font-size: 12px;
color: #a1a9b6;
}
@@ -783,7 +783,7 @@
gap: 7px;
min-height: 80px;
padding: 20px;
- font-size: 11px;
+ font-size: 12px;
color: #a0a8b4;
grid-column: 1 / -1;
}
@@ -862,7 +862,7 @@
.summaryBand {
flex-wrap: wrap;
- font-size: 11px;
+ font-size: 12px;
}
.bandTime {
diff --git a/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.module.less b/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.module.less
new file mode 100644
index 0000000000..bd38c9f43b
--- /dev/null
+++ b/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.module.less
@@ -0,0 +1,246 @@
+/* 地域选择器:触发器沿用工具栏输入框的尺寸,弹层参考腾讯云控制台的
+ 「最近访问 + 全部地区」双段式布局。 */
+
+.trigger {
+ display: inline-flex;
+ flex: 0 0 auto;
+ gap: 6px;
+ align-items: center;
+ min-width: 240px;
+ max-width: 360px;
+ height: 32px;
+ padding: 0 10px;
+ font-size: 14px;
+ color: var(--fn-text-primary);
+ cursor: pointer;
+ background: var(--fn-bg-primary);
+ border: 1px solid var(--fn-border-secondary);
+ border-radius: 8px;
+ transition:
+ border-color 0.15s ease,
+ box-shadow 0.15s ease;
+}
+
+.trigger:hover:not(:disabled) {
+ border-color: var(--fn-color-brand);
+}
+
+.trigger:focus-visible {
+ outline: 2px solid var(--fn-color-brand);
+ outline-offset: 1px;
+}
+
+.triggerDisabled {
+ cursor: not-allowed;
+ opacity: 0.55;
+}
+
+.triggerMain {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 2px;
+ min-width: 0;
+ font-weight: 500;
+}
+
+.triggerLabel {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* 选中地域的节点总数:与地名同色,只有后面那个红点强调"有节点" */
+.triggerCount {
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: inherit;
+}
+
+.triggerDot {
+ flex: 0 0 auto;
+ align-self: flex-start;
+ width: 4px;
+ height: 4px;
+ margin: 3px 0 0 2px;
+ background: var(--fn-color-danger);
+ border-radius: 50%;
+}
+
+.triggerRest {
+ flex: 0 0 auto;
+ font-size: 13px;
+ color: var(--fn-text-tertiary);
+ white-space: nowrap;
+}
+
+.triggerRest::before {
+ padding-right: 6px;
+ color: var(--fn-border-secondary);
+ content: "|";
+}
+
+.caret {
+ flex: 0 0 auto;
+ margin-left: auto;
+ color: var(--fn-text-tertiary);
+ transition: transform 0.15s ease;
+}
+
+.caretOpen {
+ transform: rotate(180deg);
+}
+
+.popover {
+ /* 弹层自己控内边距,antd 默认的 12px 会把两段式布局压扁 */
+}
+
+.popover :global(.ant-popover-inner) {
+ padding: 0;
+ border-radius: 12px;
+ box-shadow: 0 14px 38px
+ color-mix(in srgb, var(--fn-text-primary) 16%, transparent);
+}
+
+.body {
+ box-sizing: border-box;
+ width: min(1060px, calc(100vw - 32px));
+ max-height: min(76vh, 680px);
+ padding: 16px 24px 20px;
+ overflow: auto;
+}
+
+.section {
+ padding-bottom: 16px;
+}
+
+.sectionTitle {
+ margin-bottom: 16px;
+ font-size: 14px;
+ font-weight: 600;
+ color: var(--fn-text-primary);
+}
+
+/* 最近访问与下面的大区共用同一套列宽,视觉上对齐到同一栅格 */
+.recentRow {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(128px, 1fr));
+ column-gap: 24px;
+ row-gap: 8px;
+}
+
+/* 报纸式多栏流:大区块按列往下排,短列表不会独占一整行留白。
+ 列宽取 128px 保证最长地名(7 个汉字)不截断。 */
+.areas {
+ column-width: 128px;
+ column-gap: 24px;
+ column-fill: balance;
+}
+
+.area {
+ margin-bottom: 18px;
+ break-inside: avoid;
+ page-break-inside: avoid;
+}
+
+/* 层级对比是"清晰"的关键:地域名用主色,大区标题刻意压浅,
+ 跟控制台一样靠颜色深浅区分两级,而不是靠字号。 */
+.areaTitle {
+ margin-bottom: 14px;
+ font-size: 12px;
+ font-weight: 400;
+ color: var(--fn-text-tertiary);
+}
+
+.areaItems {
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+}
+
+.item {
+ display: inline-flex;
+ align-self: flex-start;
+ align-items: baseline;
+ max-width: 100%;
+ padding: 5px 10px;
+ font-size: 14px;
+ line-height: 22px;
+ color: var(--fn-text-primary);
+ text-align: left;
+ cursor: pointer;
+ background: transparent;
+ border: 0;
+ border-radius: 6px;
+ transition:
+ background 0.12s ease,
+ color 0.12s ease;
+}
+
+.item:hover {
+ color: var(--fn-text-primary);
+ background: var(--fn-bg-hover);
+}
+
+.item:focus-visible {
+ outline: 2px solid var(--fn-color-brand);
+ outline-offset: -2px;
+}
+
+.itemActive {
+ font-weight: 500;
+ color: var(--fn-text-primary);
+ background: var(--fn-bg-selected, var(--fn-bg-hover));
+}
+
+.itemName {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+/* 地域下的节点数:与地名同色(继承父级),红点只用来标记"这个地域有节点" */
+.itemCount {
+ margin-left: 3px;
+ font-size: 11px;
+ font-variant-numeric: tabular-nums;
+ color: inherit;
+}
+
+.itemDot {
+ flex: 0 0 auto;
+ align-self: flex-start;
+ width: 4px;
+ height: 4px;
+ margin: 6px 0 0 3px;
+ background: var(--fn-color-danger);
+ border-radius: 50%;
+}
+
+.footer {
+ display: flex;
+ gap: 8px;
+ align-items: center;
+ justify-content: space-between;
+ padding: 8px 6px 2px;
+ margin-top: 6px;
+ border-top: 1px solid var(--fn-border-primary);
+}
+
+.footerText {
+ font-size: 12px;
+ color: var(--fn-text-tertiary);
+}
+
+.clearBtn {
+ padding: 2px 6px;
+ font-size: 12px;
+ color: var(--fn-text-brand);
+ cursor: pointer;
+ background: transparent;
+ border: 0;
+ border-radius: 4px;
+}
+
+.clearBtn:hover {
+ background: var(--fn-bg-hover);
+}
diff --git a/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.tsx b/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.tsx
new file mode 100644
index 0000000000..f12764d03d
--- /dev/null
+++ b/dashboard/src/pages/Control/CloudHosts/components/RegionPicker.tsx
@@ -0,0 +1,286 @@
+import { useCallback, useMemo, useState } from "react";
+import { Popover } from "antd";
+import cx from "classnames";
+import { ChevronDown } from "lucide-react";
+import { useTranslation } from "react-i18next";
+import styles from "./RegionPicker.module.less";
+
+export type CloudRegion = { id: string; name: string };
+
+interface RegionPickerProps {
+ regions: CloudRegion[];
+ /** 每个地域的节点数(`region` → 实例数量)。 */
+ counts: Record;
+ /** 已选地域 id,空数组表示"全部地域"。 */
+ value: string[];
+ onChange: (next: string[]) => void;
+ disabled?: boolean;
+}
+
+interface RegionItem {
+ id: string;
+ short: string;
+ area: string;
+ count: number;
+}
+
+const RECENT_KEY = "octop:cloud:recent-regions";
+const RECENT_MAX = 6;
+
+/** 大区排序:与腾讯云控制台地域选择器一致,未命中的排在末尾。 */
+const AREA_ORDER = [
+ "华南地区",
+ "华东地区",
+ "华北地区",
+ "华中地区",
+ "西南地区",
+ "西北地区",
+ "东北地区",
+ "港澳台地区",
+ "亚太东南",
+ "亚太东北",
+ "亚太南部",
+ "欧洲地区",
+ "北美地区",
+ "南美地区",
+ "中东地区",
+ "非洲地区",
+];
+
+/** "华南地区(广州 OPEN)" → { area: "华南地区", short: "广州 OPEN" } */
+function parseRegionName(
+ name: string,
+ id: string,
+): { area: string; short: string } {
+ const match = /^\s*(.+?)\s*[((](.+?)[))]\s*$/.exec(name ?? "");
+ if (match) {
+ return { area: match[1].trim(), short: match[2].trim() };
+ }
+ return { area: "", short: (name || id).trim() };
+}
+
+function readRecent(): string[] {
+ try {
+ const raw = window.localStorage.getItem(RECENT_KEY);
+ if (!raw) return [];
+ const parsed = JSON.parse(raw);
+ return Array.isArray(parsed)
+ ? parsed.filter((item): item is string => typeof item === "string")
+ : [];
+ } catch {
+ return [];
+ }
+}
+
+function writeRecent(ids: string[]) {
+ try {
+ window.localStorage.setItem(RECENT_KEY, JSON.stringify(ids));
+ } catch {
+ // 隐私模式 / 配额满:只是便利功能,失败不影响筛选
+ }
+}
+
+export default function RegionPicker({
+ regions,
+ counts,
+ value,
+ onChange,
+ disabled = false,
+}: RegionPickerProps) {
+ const { t } = useTranslation();
+ const [open, setOpen] = useState(false);
+ const [recent, setRecent] = useState(readRecent);
+
+ const items = useMemo(
+ () =>
+ regions.map((region) => {
+ const { area, short } = parseRegionName(region.name, region.id);
+ return { id: region.id, short, area, count: counts[region.id] ?? 0 };
+ }),
+ [regions, counts],
+ );
+
+ const groups = useMemo(() => {
+ const map = new Map();
+ for (const item of items) {
+ const bucket = map.get(item.area);
+ if (bucket) bucket.push(item);
+ else map.set(item.area, [item]);
+ }
+ return [...map.entries()]
+ .map(([area, list]) => ({
+ area,
+ label: area || t("cloud.regionOtherArea", "其他地区"),
+ items: list,
+ }))
+ .sort((a, b) => {
+ const ia = AREA_ORDER.indexOf(a.area);
+ const ib = AREA_ORDER.indexOf(b.area);
+ return (
+ (ia < 0 ? AREA_ORDER.length : ia) - (ib < 0 ? AREA_ORDER.length : ib)
+ );
+ });
+ }, [items, t]);
+
+ const recentItems = useMemo(
+ () =>
+ recent
+ .map((id) => items.find((item) => item.id === id))
+ .filter((item): item is RegionItem => Boolean(item))
+ .slice(0, RECENT_MAX),
+ [recent, items],
+ );
+
+ const selected = useMemo(
+ () => items.filter((item) => value.includes(item.id)),
+ [items, value],
+ );
+ const totalCount = useMemo(
+ () => items.reduce((sum, item) => sum + item.count, 0),
+ [items],
+ );
+ const selectedCount = selected.reduce((sum, item) => sum + item.count, 0);
+ const restCount = Math.max(0, totalCount - selectedCount);
+
+ const toggle = useCallback(
+ (id: string) => {
+ const next = value.includes(id)
+ ? value.filter((item) => item !== id)
+ : [...value, id];
+ onChange(next);
+ setRecent((prev) => {
+ const merged = [id, ...prev.filter((item) => item !== id)].slice(
+ 0,
+ RECENT_MAX,
+ );
+ writeRecent(merged);
+ return merged;
+ });
+ },
+ [onChange, value],
+ );
+
+ const triggerLabel =
+ selected.length === 0
+ ? t("cloud.regionAll", "全部地域")
+ : selected.length === 1
+ ? selected[0].short
+ : t("cloud.regionSelectedMulti", {
+ name: selected[0].short,
+ count: selected.length,
+ defaultValue: "{{name}} 等 {{count}} 个",
+ });
+
+ const renderItem = (item: RegionItem, extraClass?: string) => {
+ const active = value.includes(item.id);
+ return (
+ toggle(item.id)}
+ >
+ {item.short}
+ {item.count > 0 ? (
+ <>
+ {item.count}
+
+ >
+ ) : null}
+
+ );
+ };
+
+ const body = (
+
+ {recentItems.length > 0 ? (
+
+
+ {t("cloud.regionRecent", "最近访问")}
+
+
+ {recentItems.map((item) => renderItem(item, styles.recentItem))}
+
+
+ ) : null}
+
+
+
+ {t("cloud.regionAllAreas", "全部地区")}
+
+
+ {groups.map((group) => (
+
+
{group.label}
+
+ {group.items.map((item) => renderItem(item))}
+
+
+ ))}
+
+
+
+ {value.length > 0 ? (
+
+
+ {t("cloud.regionSelectedTotal", {
+ count: value.length,
+ defaultValue: "已选 {{count}} 个地域",
+ })}
+
+ onChange([])}
+ >
+ {t("cloud.regionClear", "清空筛选")}
+
+
+ ) : null}
+
+ );
+
+ return (
+ setOpen(disabled ? false : next)}
+ overlayClassName={styles.popover}
+ content={body}
+ arrow={false}
+ >
+
+
+ {triggerLabel}
+ {selected.length > 0 && selectedCount > 0 ? (
+ <>
+ {selectedCount}
+
+ >
+ ) : null}
+
+ {selected.length > 0 && restCount > 0 ? (
+
+ {t("cloud.regionOthers", {
+ count: restCount,
+ defaultValue: "其它地域({{count}})",
+ })}
+
+ ) : null}
+
+
+
+ );
+}
diff --git a/dashboard/src/pages/Control/CloudHosts/index.module.less b/dashboard/src/pages/Control/CloudHosts/index.module.less
index 7370eedd3b..5cdd1957e1 100644
--- a/dashboard/src/pages/Control/CloudHosts/index.module.less
+++ b/dashboard/src/pages/Control/CloudHosts/index.module.less
@@ -84,7 +84,7 @@
align-items: center;
padding: 3px 10px;
font-family: var(--sc-mono);
- font-size: 11px;
+ font-size: 12px;
font-variant-numeric: tabular-nums;
color: inherit;
cursor: pointer;
@@ -167,7 +167,7 @@
.overviewLabel {
font-family: var(--sc-mono);
- font-size: 11px;
+ font-size: 12px;
letter-spacing: 0.08em;
text-transform: uppercase;
opacity: 0.5;
@@ -182,11 +182,13 @@
}
.overviewHint {
- font-size: 11px;
+ font-size: 12px;
opacity: 0.45;
}
.sidebar {
+ /* RailEdgeControl 绝对定位的锚点:折叠手柄骑在右侧分隔线上 */
+ position: relative;
display: flex;
flex: 0 0 196px;
flex-direction: column;
@@ -201,31 +203,8 @@
flex: 0 0 auto;
gap: 4px;
align-items: center;
- font-size: 11px;
- color: var(--fn-text-quaternary);
-}
-
-.railBtn {
- display: inline-flex;
- flex: 0 0 auto;
- align-items: center;
- justify-content: center;
- width: 24px;
- height: 24px;
- padding: 0;
+ font-size: 12px;
color: var(--fn-text-quaternary);
- cursor: pointer;
- background: transparent;
- border: 0;
- border-radius: 6px;
- transition:
- background 0.12s ease,
- color 0.12s ease;
-}
-
-.railBtn:hover {
- color: var(--fn-text-primary);
- background: var(--fn-bg-secondary);
}
.sidebarHead {
@@ -234,20 +213,18 @@
align-items: center;
}
+/* 标签统一走 12px 常规字体,不再用 mono + 全大写 + 低透明度的终端风,
+ 否则和页面其它文案放在一起显得忽大忽小、忽轻忽重。 */
.sidebarTitle {
flex: 1;
- font-family: var(--sc-mono);
- font-size: 10px;
- letter-spacing: 0.1em;
- text-transform: uppercase;
- opacity: 0.45;
+ font-size: 12px;
+ color: var(--fn-text-tertiary);
}
.sidebarCount {
- font-family: var(--sc-mono);
- font-size: 11px;
+ font-size: 12px;
font-variant-numeric: tabular-nums;
- opacity: 0.55;
+ color: var(--fn-text-tertiary);
}
.nodeList {
@@ -348,7 +325,7 @@
.nodeName {
overflow: hidden;
- font-size: 12.5px;
+ font-size: 13px;
font-weight: 500;
text-overflow: ellipsis;
white-space: nowrap;
@@ -357,16 +334,16 @@
.nodeMeta {
overflow: hidden;
font-family: var(--sc-mono);
- font-size: 10.5px;
- opacity: 0.45;
+ font-size: 12px;
+ color: var(--fn-text-tertiary);
text-overflow: ellipsis;
white-space: nowrap;
}
.nodeEmpty {
padding: 16px 4px;
- font-size: 11px;
- opacity: 0.45;
+ font-size: 12px;
+ color: var(--fn-text-tertiary);
text-align: center;
}
@@ -405,7 +382,7 @@
.miniValue {
font-family: var(--sc-mono);
- font-size: 11px;
+ font-size: 12px;
font-variant-numeric: tabular-nums;
opacity: 0.7;
}
@@ -461,6 +438,8 @@
}
.stage {
+ /* 折叠态下 RailEdgeControl 以此为锚点,手柄停在内容区左边缘 */
+ position: relative;
display: flex;
flex: 1;
flex-direction: row;
@@ -469,6 +448,19 @@
min-height: 0;
}
+/* 折叠态:左侧没有独立面板可以挂边线,手柄整体内移几个像素,
+ 避免被 Workbench 面板的 overflow: hidden 裁掉一半。 */
+.railEdgeClosed {
+ left: 4px !important;
+ right: auto !important;
+
+ /* 面板收起后这是唯一的展开入口,常驻可见,不等 hover */
+ > button {
+ opacity: 1;
+ pointer-events: auto;
+ }
+}
+
.main {
display: flex;
flex: 1;
@@ -609,11 +601,8 @@
}
.kpiLabel {
- font-family: var(--sc-mono);
- font-size: 10px;
- letter-spacing: 0.14em;
- text-transform: uppercase;
- opacity: 0.5;
+ font-size: 12px;
+ color: var(--fn-text-tertiary);
}
.kpiValue {
@@ -636,11 +625,9 @@
}
.blockTitle {
- font-family: var(--sc-mono);
- font-size: 10px;
- letter-spacing: 0.14em;
- text-transform: uppercase;
- opacity: 0.5;
+ font-size: 13px;
+ font-weight: 600;
+ color: var(--fn-text-primary);
}
.mono {
@@ -652,17 +639,14 @@
/* ---- Terminal-flavoured table ---- */
.page :global(.octop-table) {
- font-size: 12.5px;
+ font-size: 13px;
}
.page :global(.octop-table-thead > tr > th) {
- font-family: var(--sc-mono);
- font-size: 10px;
+ font-size: 12px;
font-weight: 500;
- letter-spacing: 0.1em;
- text-transform: uppercase;
+ color: var(--fn-text-tertiary);
background: transparent !important;
- opacity: 0.6;
}
.page :global(.octop-table-tbody > tr > td) {
@@ -671,8 +655,6 @@
.page :global(.octop-tag) {
margin: 0;
- font-family: var(--sc-mono);
- font-size: 10px;
- letter-spacing: 0.06em;
+ font-size: 12px;
border-radius: 3px;
}
diff --git a/dashboard/src/pages/Control/CloudHosts/index.tsx b/dashboard/src/pages/Control/CloudHosts/index.tsx
index 37233de220..a717ce852e 100644
--- a/dashboard/src/pages/Control/CloudHosts/index.tsx
+++ b/dashboard/src/pages/Control/CloudHosts/index.tsx
@@ -8,7 +8,6 @@ import {
Modal,
Popconfirm,
Segmented,
- Select,
Space,
Spin,
Table,
@@ -21,8 +20,6 @@ import {
Info,
KeyRound,
LogIn,
- PanelLeftClose,
- PanelLeftOpen,
PauseCircle,
PlayCircle,
RefreshCw,
@@ -32,6 +29,7 @@ import {
} from "lucide-react";
import { request } from "../../../api/request";
import { OctopEmptyMascot } from "../../../components/EmptyState";
+import RailEdgeControl from "../../../components/RailEdgeControl";
import StreamSetupGuide from "../../../components/StreamSetupGuide/StreamSetupGuide";
import { useCvmOpsExpert } from "../../../hooks/useCvmOpsExpert";
import { ALERT_MIN, WARN_MIN, levelTone } from "./theme";
@@ -47,6 +45,7 @@ import CloudOverviewBoard, {
type BoardInstance,
type TrendPoint,
} from "./components/CloudOverviewBoard";
+import RegionPicker from "./components/RegionPicker";
import styles from "./index.module.less";
type CloudStatus = {
@@ -187,8 +186,10 @@ function CredentialBadge({
onExpire();
}, [remaining, expiresAt, status?.authorized, onExpire]);
+ // 未授权时不再渲染「未授权」标签:空状态引导里已有完整说明,
+ // 工具栏再挂一个灰 Tag 只会干扰视线。
if (!status?.authorized) {
- return {t("cloud.notAuthorized")} ;
+ return null;
}
const critical = remaining <= 60;
@@ -747,6 +748,15 @@ export default function CloudHostsPage({
);
}, [instances, keyword]);
+ // 每个地域的节点数:地域选择器要在名字后带上这个数字
+ const regionCounts = useMemo(() => {
+ const out: Record = {};
+ for (const row of instances) {
+ out[row.region] = (out[row.region] ?? 0) + 1;
+ }
+ return out;
+ }, [instances]);
+
// KPI 跟随搜索范围,避免"顶部写 486、左侧只剩 2 台"的口径不一致
const runningCount = filteredInstances.filter(
(row) => row.state === "RUNNING",
@@ -893,17 +903,11 @@ export default function CloudHostsPage({
onExpire={handleExpire}
onRenew={() => void refreshCredential()}
/>
- ({
- value: region.id,
- label: `${region.name} (${region.id})`,
- }))}
- onChange={(value) => setSelectedRegions(value)}
+ onChange={setSelectedRegions}
disabled={!authorized}
/>
{revalidating ? (
@@ -1076,32 +1080,27 @@ export default function CloudHostsPage({
)}
+
) : null}
+ {sidebarOpen ? null : (
+
+ )}
@@ -516,6 +520,7 @@ export const AgentCard = memo(function AgentCard({
setSkillCatalogOpen(true)}
onSubagents={openSubagentCatalog}
onTools={() => setToolSettingsOpen(true)}
@@ -577,6 +582,7 @@ export const AgentCard = memo(function AgentCard({
/>
setToolSettingsOpen(false)}
/>
diff --git a/dashboard/src/pages/Experts/components/AgentExpertsTable.tsx b/dashboard/src/pages/Experts/components/AgentExpertsTable.tsx
index a3ef6de48e..a3c32d29fb 100644
--- a/dashboard/src/pages/Experts/components/AgentExpertsTable.tsx
+++ b/dashboard/src/pages/Experts/components/AgentExpertsTable.tsx
@@ -50,7 +50,11 @@ import { apiErrorMessage } from "../../../utils/apiError";
import styles from "../index.module.less";
import RemoteExpertHint from "../../Chat/components/RemoteExpertHint";
import { expertDeleteConfirm } from "../../../utils/remoteExpert";
-import { SharedResourceBadge } from "../../../components/SharedResourceBadge";
+import {
+ incomingShareProps,
+ SharedAvatarMark,
+ SharedResourceBadge,
+} from "../../../components/SharedResourceBadge";
import {
canManageExpert,
canReadAgentRuntimeStatus,
@@ -311,28 +315,30 @@ export default function AgentExpertsTable({
fixed: isMobile ? undefined : "left",
render: (name: string, row) => (
-
-
+
-
-
-
+
+
+
+
+
{name}
(
- openMbtiCatalog(row.agent_id)
- : undefined
- }
- />
- ),
+ render: (value: string | null, row) =>
+ row.kind === "managed" ? (
+ "—"
+ ) : (
+ openMbtiCatalog(row.agent_id)
+ : undefined
+ }
+ />
+ ),
},
{
title: t("experts.table.actions", "操作"),
@@ -536,6 +545,7 @@ export default function AgentExpertsTable({
)}
setSkillCatalogAgentId(row.agent_id)}
onSubagents={() => openSubagentCatalog(row.agent_id)}
onTools={() => setToolSettingsAgentId(row.agent_id)}
@@ -606,6 +616,10 @@ export default function AgentExpertsTable({
/>
row.agent_id === toolSettingsAgentId)?.kind ===
+ "managed"
+ }
open={toolSettingsAgentId !== null}
onClose={() => setToolSettingsAgentId(null)}
/>
diff --git a/dashboard/src/pages/Experts/components/AgentMoreActions.tsx b/dashboard/src/pages/Experts/components/AgentMoreActions.tsx
index a25accd707..48a29a3e87 100644
--- a/dashboard/src/pages/Experts/components/AgentMoreActions.tsx
+++ b/dashboard/src/pages/Experts/components/AgentMoreActions.tsx
@@ -21,6 +21,8 @@ interface AgentMoreActionsProps {
onMbti: () => void;
onMemory: () => void;
onChannels: () => void;
+ /** Managed experts omit MBTI. Tools and plugins stay. */
+ managed?: boolean;
}
/** Overflow menu for expert catalog actions (skills / subagents / …). */
@@ -33,6 +35,7 @@ export default function AgentMoreActions({
onMbti,
onMemory,
onChannels,
+ managed = false,
}: AgentMoreActionsProps) {
const { t } = useTranslation();
@@ -61,12 +64,16 @@ export default function AgentMoreActions({
label: t("experts.pluginsBtn"),
onClick: onPlugins,
},
- {
- key: "mbti",
- icon: ,
- label: t("experts.mbtiBtn"),
- onClick: onMbti,
- },
+ ...(managed
+ ? []
+ : [
+ {
+ key: "mbti",
+ icon: ,
+ label: t("experts.mbtiBtn"),
+ onClick: onMbti,
+ },
+ ]),
{
key: "memory",
icon: ,
diff --git a/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx b/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx
index 8285d8064b..30ab6aa6c6 100644
--- a/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx
+++ b/dashboard/src/pages/Experts/components/CreateFromExpertDrawer.tsx
@@ -694,6 +694,8 @@ export default function CreateFromExpertDrawer({
width={600}
onClose={onClose}
destroyOnHidden
+ className={styles.expertDrawer}
+ rootClassName={styles.expertDrawerRoot}
footer={
@@ -828,6 +830,36 @@ export default function CreateFromExpertDrawer({
onRemovePathMapping={removePathMapping}
onUpdatePathMapping={updatePathMapping}
/>
+
+ ({
+ value: mode,
+ label: t(`chat.conversationMode.${mode}`),
+ }))}
+ />
+
+
+
+ ((opt?.label as string) ?? "")
+ .toLowerCase()
+ .includes(input.toLowerCase())
+ }
+ />
+
+
+ ({
+ value: pack.id,
+ label: pack.name,
+ }))}
+ placeholder={t("experts.skillPackagesPlaceholder")}
+ />
+
+
-
- ({
- value: mode,
- label: t(`chat.conversationMode.${mode}`),
- }))}
- />
-
-
-
-
- ((opt?.label as string) ?? "")
- .toLowerCase()
- .includes(input.toLowerCase())
- }
- />
-
-
- ({
- value: pack.id,
- label: pack.name,
- }))}
- placeholder={t("experts.skillPackagesPlaceholder")}
- />
-
-
-
;
}
@@ -156,6 +169,10 @@ interface EditFormValues extends AgentRuntimeFormValues {
enable_trajectory?: boolean;
knowledge_base_ids?: string[];
mcp_servers?: string[];
+ skill_package_ids?: string[];
+ runner?: string;
+ permission_mode?: boolean;
+ session_mode?: string;
}
interface EditAgentDrawerProps {
@@ -233,12 +250,27 @@ function EditAgentDrawerBody({
onSaveReady,
onSavingChange,
}: EditAgentDrawerBodyProps) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const { modal, message } = App.useApp();
const { refresh } = useAgent();
const skillDisplayName = useSkillDisplayName();
const [workspaceDrawerOpen, setWorkspaceDrawerOpen] = useState(false);
const [form] = Form.useForm();
+ const watchedRunner = Form.useWatch("runner", form);
+ const sessionModes = useAcpSessionModes(
+ agent.kind === "managed" ? watchedRunner : "",
+ );
+
+ useEffect(() => {
+ if (agent.kind !== "managed" || sessionModes.length === 0) return;
+ const current = String(form.getFieldValue("session_mode") ?? "");
+ if (sessionModes.some((mode) => mode.id === current)) return;
+ const yolo = form.getFieldValue("permission_mode") === true;
+ const preferred = yolo
+ ? sessionModes.find((mode) => isUnattendedSessionMode(mode.id))
+ : undefined;
+ form.setFieldValue("session_mode", (preferred ?? sessionModes[0]).id);
+ }, [agent.kind, form, sessionModes]);
const [workspaceFiles, setWorkspaceFiles] = useState([]);
const [agentSkills, setAgentSkills] = useState([]);
const [agentSubagents, setAgentSubagents] = useState([]);
@@ -247,6 +279,12 @@ function EditAgentDrawerBody({
useAgentFormResources(true, agent.agent_id);
const [pathMappings, setPathMappings] = useState([]);
const [agentConfig, setAgentConfig] = useState>({});
+ const [runners, setRunners] = useState([]);
+ const [runnersReady, setRunnersReady] = useState(false);
+ const [skillPackages, setSkillPackages] = useState<
+ { id: string; name: string }[]
+ >([]);
+ const [skillPackagesLoading, setSkillPackagesLoading] = useState(false);
const [colorPalette, setColorPalette] = useState(
() => parseStoredColor(agent.color) ?? DEFAULT_PALETTE,
);
@@ -288,6 +326,14 @@ function EditAgentDrawerBody({
rootDir: watchedRootDir,
workspaceDir: workspaceDirFromConfig,
});
+ const runnerChoices = useMemo(() => {
+ const current =
+ typeof agentConfig.managed_runner === "string"
+ ? agentConfig.managed_runner.trim()
+ : "";
+ if (current && !runners.includes(current)) return [current, ...runners];
+ return runners;
+ }, [agentConfig.managed_runner, runners]);
useEffect(() => {
let cancelled = false;
@@ -331,10 +377,21 @@ function EditAgentDrawerBody({
typeof cfg.workspace_dir === "string" ? cfg.workspace_dir : "",
...readAgentRuntimeFormValues(ag),
enable_trajectory: cfg.enable_trajectory !== false,
+ runner:
+ typeof cfg.managed_runner === "string" ? cfg.managed_runner : "",
+ permission_mode: cfg.managed_permission_mode === "yolo",
+ session_mode:
+ typeof cfg.managed_session_mode === "string" &&
+ cfg.managed_session_mode.trim()
+ ? cfg.managed_session_mode.trim()
+ : String(form.getFieldValue("session_mode") ?? ""),
knowledge_base_ids: Array.isArray(ag.knowledge_base_ids)
? ag.knowledge_base_ids
: [],
mcp_servers: Array.isArray(ag.mcp_servers) ? ag.mcp_servers : [],
+ skill_package_ids: Array.isArray(ag.skill_package_ids)
+ ? ag.skill_package_ids
+ : [],
});
const nextVisibility: ResourceVisibilityMode =
ag.visibility === "groups" ||
@@ -412,6 +469,55 @@ function EditAgentDrawerBody({
};
}, [agent.agent_id, agent.state, form, message, t]);
+ useEffect(() => {
+ if (agent.kind !== "managed") return;
+ let cancelled = false;
+ setRunnersReady(false);
+ acpApi
+ .getGlobalRunners()
+ .then((data) => {
+ if (cancelled) return;
+ setRunners(
+ Object.entries(data.runners)
+ .filter(([, spec]) => spec.enabled)
+ .map(([name]) => name),
+ );
+ })
+ .catch((err: unknown) => {
+ if (!cancelled) {
+ setRunners([]);
+ message.error(
+ apiErrorMessage(err, t("experts.managed.loadFailed"), t),
+ );
+ }
+ })
+ .finally(() => {
+ if (!cancelled) setRunnersReady(true);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [agent.agent_id, agent.kind, message, t]);
+
+ useEffect(() => {
+ let cancelled = false;
+ setSkillPackagesLoading(true);
+ skillPackagesApi
+ .list()
+ .then((packages) => {
+ if (!cancelled) setSkillPackages(packages);
+ })
+ .catch(() => {
+ if (!cancelled) setSkillPackages([]);
+ })
+ .finally(() => {
+ if (!cancelled) setSkillPackagesLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [agent.agent_id]);
+
const handleSave = useCallback(async () => {
const values = await form.validateFields();
if (values.backend_choice === "composite") {
@@ -458,13 +564,26 @@ function EditAgentDrawerBody({
const nextColor = isCuratedPalette(colorPalette)
? expertPaletteColor(colorPalette)
: colorPalette;
+ const configPatch: Record =
+ agent.kind === "managed"
+ ? {}
+ : { conversation_mode: values.conversation_mode };
+ const managedRunner = values.runner?.trim();
+ if (agent.kind === "managed" && managedRunner) {
+ configPatch.managed_runner = managedRunner;
+ const sessionMode = values.session_mode?.trim() ?? "";
+ configPatch.managed_session_mode = sessionMode;
+ configPatch.managed_permission_mode = permissionForSessionMode(
+ sessionModes,
+ sessionMode,
+ values.permission_mode === true,
+ );
+ }
const nextConfig = omitAgentRuntimeConfig({
...agentConfig,
backend: backendSpec,
enable_trajectory: values.enable_trajectory === true,
- ...(agent.kind === "managed"
- ? {}
- : { conversation_mode: values.conversation_mode }),
+ ...configPatch,
});
if (agent.kind === "managed") {
delete nextConfig.conversation_mode;
@@ -514,11 +633,18 @@ function EditAgentDrawerBody({
visibility: expertVisibility,
group_ids: expertVisibility === "groups" ? expertGroupIds : [],
...(agent.kind === "managed"
- ? {}
+ ? {
+ knowledge_base_ids: stored.knowledge_base_ids ?? [],
+ mcp_servers: stored.mcp_servers ?? [],
+ skill_package_ids: stored.skill_package_ids ?? [],
+ }
: {
default_model: defaultModelFromForm(values.default_model),
knowledge_base_ids: stored.knowledge_base_ids ?? [],
mcp_servers: stored.mcp_servers ?? [],
+ ...(skillPackagesSupported
+ ? { skill_package_ids: stored.skill_package_ids ?? [] }
+ : {}),
...buildAgentRuntimeRequest(values, { clearMissing: true }),
}),
color: nextColor,
@@ -899,7 +1025,79 @@ function EditAgentDrawerBody({
form.setFieldsValue({ welcome_message: text })
}
/>
- {agent.kind === "managed" ? null : (
+ {agent.kind === "managed" ? (
+ <>
+ {runnersReady && runnerChoices.length === 0 ? (
+
+ ) : null}
+
+ {t("experts.managed.runner")}
+
+ {t("experts.managed.manageAcp")}
+
+
+ }
+ rules={[
+ {
+ required: true,
+ message: t("experts.managed.runnerRequired"),
+ },
+ ]}
+ >
+
+
+ {sessionModes.length > 0 ? (
+
+ ({
+ value: mode.id,
+ label: acpSessionModeText(
+ mode,
+ i18n.language,
+ "name",
+ ),
+ title: acpSessionModeText(
+ mode,
+ i18n.language,
+ "hint",
+ ),
+ }))}
+ />
+
+ ) : null}
+ {catalogOffersUnattendedMode(sessionModes) ? null : (
+
+
+
+ )}
+
+
+
+ >
+ ) : (
)}
+ {agent.kind === "managed" ? null : (
+ <>
+
+ ({
+ value: mode,
+ label: t(`chat.conversationMode.${mode}`),
+ }))}
+ />
+
+
+
+ ((opt?.label as string) ?? "")
+ .toLowerCase()
+ .includes(input.toLowerCase())
+ }
+ />
+
+ >
+ )}
+
+ ({
+ value: pack.id,
+ label: pack.name,
+ }))}
+ placeholder={t("experts.skillPackagesPlaceholder")}
+ />
+
+
- ({
- value: mode,
- label: t(`chat.conversationMode.${mode}`),
- }))}
- />
-
- )}
- {agent.kind === "managed" ? null : (
-
-
- ((opt?.label as string) ?? "")
- .toLowerCase()
- .includes(input.toLowerCase())
- }
- />
-
- )}
-
- {agent.kind === "managed" ? null : (
-
- )}
- {agent.kind !== "managed" && !skillPackagesSupported ? (
-
- ) : null}
{isAgentChatReady(agent.state) ? (
@@ -1485,9 +1695,11 @@ export default function EditAgentDrawer({
}
- width={520}
+ width={agent?.kind === "managed" ? 600 : 520}
onClose={onClose}
destroyOnHidden
+ className={styles.expertDrawer}
+ rootClassName={styles.expertDrawerRoot}
footer={
diff --git a/dashboard/src/pages/Experts/components/EditExpertDrawerTitle.test.tsx b/dashboard/src/pages/Experts/components/EditExpertDrawerTitle.test.tsx
index 581b9d60e3..89446450f3 100644
--- a/dashboard/src/pages/Experts/components/EditExpertDrawerTitle.test.tsx
+++ b/dashboard/src/pages/Experts/components/EditExpertDrawerTitle.test.tsx
@@ -34,6 +34,18 @@ describe("EditExpertDrawerTitle", () => {
);
});
+ it("uses the edit title for a managed expert", () => {
+ render(
+ ,
+ );
+ expect(screen.getByText("experts.managed.editTitle")).toBeInTheDocument();
+ expect(
+ screen.queryByText("experts.managed.createTitle"),
+ ).not.toBeInTheDocument();
+ });
+
it("keeps the plain title for a local expert", () => {
render(
,
diff --git a/dashboard/src/pages/Experts/components/EditExpertDrawerTitle.tsx b/dashboard/src/pages/Experts/components/EditExpertDrawerTitle.tsx
index 0775fd7858..02c41d3686 100644
--- a/dashboard/src/pages/Experts/components/EditExpertDrawerTitle.tsx
+++ b/dashboard/src/pages/Experts/components/EditExpertDrawerTitle.tsx
@@ -20,11 +20,15 @@ export default function EditExpertDrawerTitle({
}: EditExpertDrawerTitleProps) {
const { t } = useTranslation();
const remote = Boolean(agent?.bridge) || isBridgeAgentId(agent?.agent_id);
- const beta = agent?.kind === "managed" ? : null;
+ const managed = agent?.kind === "managed";
+ const title = managed
+ ? t("experts.managed.editTitle")
+ : t("experts.editExpert");
+ const beta = managed ? : null;
if (remote && agent) {
return (
- {beta ? t("experts.managed.createTitle") : t("experts.editExpert")}
+ {title}
{beta}
@@ -33,7 +37,7 @@ export default function EditExpertDrawerTitle({
if (beta) {
return (
- {t("experts.managed.createTitle")}
+ {title}
{beta}
);
diff --git a/dashboard/src/pages/Experts/components/ManagedAvatarMark.tsx b/dashboard/src/pages/Experts/components/ManagedAvatarMark.tsx
index 18d9467d6d..9953084fb2 100644
--- a/dashboard/src/pages/Experts/components/ManagedAvatarMark.tsx
+++ b/dashboard/src/pages/Experts/components/ManagedAvatarMark.tsx
@@ -34,7 +34,7 @@ export function ManagedAvatarMark({
if (!id) return children;
const label = isBuiltinRunner(id) ? t(runnerLabelKey(id)) : id;
return (
-
+
{children}
diff --git a/dashboard/src/pages/Experts/components/ManagedDrawer.tsx b/dashboard/src/pages/Experts/components/ManagedDrawer.tsx
index 13590c7d48..c3fd80ec3d 100644
--- a/dashboard/src/pages/Experts/components/ManagedDrawer.tsx
+++ b/dashboard/src/pages/Experts/components/ManagedDrawer.tsx
@@ -1,10 +1,27 @@
import { useEffect, useRef, useState } from "react";
import { Link } from "react-router-dom";
import { useTranslation } from "react-i18next";
-import { Alert, Button, Collapse, Drawer, Form, Input } from "antd";
+import {
+ Alert,
+ Button,
+ Collapse,
+ Drawer,
+ Form,
+ Input,
+ Select,
+ Switch,
+} from "antd";
import { message } from "@/utils/antdMessage";
-import { acpApi } from "../../../api/modules/acp";
+import {
+ acpApi,
+ acpSessionModeText,
+ catalogOffersUnattendedMode,
+ isUnattendedSessionMode,
+ permissionForSessionMode,
+} from "../../../api/modules/acp";
+import { useAcpSessionModes } from "../../../hooks/useAcpSessionModes";
+import { skillPackagesApi } from "../../../api/modules/skillPackages";
import {
managedAgentsApi,
managedWorkspaceDir,
@@ -29,6 +46,7 @@ import {
} from "../../../styles/themePalettes";
import AgentTrajectoryField from "./AgentTrajectoryField";
import ExpertAvatarPicker from "./ExpertAvatarPicker";
+import ExpertComposerDefaultsFields from "./ExpertComposerDefaultsFields";
import FileEditModal from "./FileEditModal";
import { metaForFile } from "./iconForName";
import ManagedRunnerPicker from "./ManagedRunnerPicker";
@@ -55,6 +73,11 @@ interface FormValues {
welcome_message?: string;
agent_id?: string;
enable_trajectory?: boolean;
+ skill_package_ids?: string[];
+ knowledge_base_ids?: string[];
+ mcp_servers?: string[];
+ permission_mode?: boolean;
+ session_mode?: string;
}
function storedColor(palette: string): string {
@@ -94,9 +117,13 @@ export default function ManagedDrawer({
onClose,
onCreated,
}: ManagedDrawerProps) {
- const { t } = useTranslation();
+ const { t, i18n } = useTranslation();
const [form] = Form.useForm();
const [runners, setRunners] = useState([]);
+ const [skillPackages, setSkillPackages] = useState<
+ { id: string; name: string }[]
+ >([]);
+ const [skillPackagesLoading, setSkillPackagesLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [colorPalette, setColorPalette] = useState(DEFAULT_PALETTE);
const [visibility, setVisibility] = useState("owner");
@@ -117,12 +144,27 @@ export default function ManagedDrawer({
const workspaceTouched = useRef(false);
const welcomeRef = useRef(null);
const watchedAgentId = Form.useWatch("agent_id", form);
+ const watchedRunner = Form.useWatch("runner", form);
+ const sessionModes = useAcpSessionModes(watchedRunner);
+
+ useEffect(() => {
+ if (!open || sessionModes.length === 0) return;
+ const current = String(form.getFieldValue("session_mode") ?? "");
+ if (sessionModes.some((mode) => mode.id === current)) return;
+ const yolo = form.getFieldValue("permission_mode") === true;
+ const preferred = yolo
+ ? sessionModes.find((mode) => isUnattendedSessionMode(mode.id))
+ : undefined;
+ form.setFieldValue("session_mode", (preferred ?? sessionModes[0]).id);
+ }, [form, open, sessionModes]);
useEffect(() => {
if (!open) return;
form.resetFields();
form.setFieldsValue({
enable_trajectory: true,
+ permission_mode: false,
+ session_mode: "",
});
setColorPalette(DEFAULT_PALETTE);
setVisibility("owner");
@@ -174,6 +216,18 @@ export default function ManagedDrawer({
);
}
});
+ setSkillPackagesLoading(true);
+ skillPackagesApi
+ .list()
+ .then((packages) => {
+ if (!cancelled) setSkillPackages(packages);
+ })
+ .catch(() => {
+ if (!cancelled) setSkillPackages([]);
+ })
+ .finally(() => {
+ if (!cancelled) setSkillPackagesLoading(false);
+ });
return () => {
cancelled = true;
};
@@ -225,6 +279,17 @@ export default function ManagedDrawer({
? undefined
: expertPresetSrc(avatarPresetId ?? "default"),
enable_trajectory: values.enable_trajectory === true,
+ permission_mode: permissionForSessionMode(
+ sessionModes,
+ values.session_mode ?? "",
+ values.permission_mode === true,
+ ),
+ ...(sessionModes.length > 0 && values.session_mode
+ ? { session_mode: values.session_mode }
+ : {}),
+ skill_package_ids: values.skill_package_ids ?? [],
+ knowledge_base_ids: values.knowledge_base_ids ?? [],
+ mcp_servers: values.mcp_servers ?? [],
visibility,
group_ids: visibility === "groups" ? groupIds : [],
...(prompts ? { quick_prompts: prompts } : {}),
@@ -257,6 +322,8 @@ export default function ManagedDrawer({
onClose={onClose}
width={600}
destroyOnHidden
+ className={styles.expertDrawer}
+ rootClassName={styles.expertDrawerRoot}
footer={
{t("common.cancel")}
@@ -376,6 +443,31 @@ export default function ManagedDrawer({
>
+ {sessionModes.length > 0 ? (
+
+ ({
+ value: mode.id,
+ label: acpSessionModeText(mode, i18n.language, "name"),
+ title: acpSessionModeText(mode, i18n.language, "hint"),
+ }))}
+ />
+
+ ) : null}
+ {catalogOffersUnattendedMode(sessionModes) ? null : (
+
+
+
+ )}
+
+ ({
+ value: pack.id,
+ label: pack.name,
+ }))}
+ placeholder={t("experts.skillPackagesPlaceholder")}
+ />
+
+
{visibleMembers.map((member) => (
-
- {member.iconUrl || member.iconName ? (
-
- ) : (
- member.name.slice(0, 1)
- )}
-
+
+
+ {member.iconUrl || member.iconName ? (
+
+ ) : (
+ member.name.slice(0, 1)
+ )}
+
+
+
))}
{hiddenCount > 0 && (
diff --git a/dashboard/src/pages/Experts/components/TeamDrawer.tsx b/dashboard/src/pages/Experts/components/TeamDrawer.tsx
index 7659bbdaec..de2b9b2046 100644
--- a/dashboard/src/pages/Experts/components/TeamDrawer.tsx
+++ b/dashboard/src/pages/Experts/components/TeamDrawer.tsx
@@ -90,7 +90,10 @@ export default function TeamDrawer({
onIconUrlChange,
}: TeamDrawerProps) {
const { t } = useTranslation();
- const allowedBackendTypes = useCurrentUser()?.allowed_backend_types;
+ const currentUser = useCurrentUser();
+ const allowedBackendTypes = currentUser?.allowed_backend_types;
+ const viewerIdRef = useRef(currentUser?.id);
+ viewerIdRef.current = currentUser?.id;
const createBackendChoice = defaultCreateBackendChoice(allowedBackendTypes);
const [form] = Form.useForm();
const { models, modelsLoading, backends, backendsLoading } =
@@ -176,9 +179,17 @@ export default function TeamDrawer({
color: member.color,
icon_name: member.icon_name,
icon_url: member.icon_url,
- kind: "expert",
+ kind: member.kind || "expert",
+ config:
+ member.kind === "managed" && member.managed_runner
+ ? { managed_runner: member.managed_runner }
+ : null,
is_shared: member.is_shared,
- is_owner: true,
+ user_id: member.user_id,
+ is_owner:
+ member.user_id != null && viewerIdRef.current != null
+ ? Number(member.user_id) === Number(viewerIdRef.current)
+ : undefined,
})),
);
})
@@ -384,6 +395,8 @@ export default function TeamDrawer({
onClose={onClose}
width={600}
destroyOnHidden
+ className={styles.expertDrawer}
+ rootClassName={styles.expertDrawerRoot}
footer={
diff --git a/dashboard/src/pages/Experts/components/TeamMemberPicker.tsx b/dashboard/src/pages/Experts/components/TeamMemberPicker.tsx
index 26f980f0e5..d9b7376799 100644
--- a/dashboard/src/pages/Experts/components/TeamMemberPicker.tsx
+++ b/dashboard/src/pages/Experts/components/TeamMemberPicker.tsx
@@ -6,6 +6,11 @@ import cx from "classnames";
import { isOwnedExpert } from "../../../utils/sharedExpert";
import { isBridgeAgentId } from "../../../utils/remoteExpert";
import { ExpertIcon } from "./iconForName";
+import { ManagedAvatarMark, managedRunnerId } from "./ManagedAvatarMark";
+import {
+ incomingShareProps,
+ SharedAvatarMark,
+} from "../../../components/SharedResourceBadge";
import styles from "../index.module.less";
export interface TeamMemberOption {
@@ -16,8 +21,11 @@ export interface TeamMemberOption {
icon_name?: string | null;
icon_url?: string | null;
kind?: string;
+ config?: Record | null;
is_shared?: boolean;
is_owner?: boolean;
+ user_id?: number | null;
+ owner_username?: string | null;
bridge?: boolean | null;
}
@@ -141,16 +149,20 @@ export default function TeamMemberPicker({
)}
-
-
-
+
+
+
+
+
+
+
{expert.name}
diff --git a/dashboard/src/pages/Experts/components/ToolCatalogDrawer.tsx b/dashboard/src/pages/Experts/components/ToolCatalogDrawer.tsx
index 62ae006549..26f18547d4 100644
--- a/dashboard/src/pages/Experts/components/ToolCatalogDrawer.tsx
+++ b/dashboard/src/pages/Experts/components/ToolCatalogDrawer.tsx
@@ -7,6 +7,7 @@ interface ToolCatalogDrawerProps {
agentId: string;
open: boolean;
onClose: () => void;
+ managed?: boolean;
}
/** Experts drawer embedding the full Tools surface (mirrors SkillCatalogDrawer). */
@@ -14,6 +15,7 @@ export default function ToolCatalogDrawer({
agentId,
open,
onClose,
+ managed = false,
}: ToolCatalogDrawerProps) {
const { t } = useTranslation();
@@ -25,7 +27,7 @@ export default function ToolCatalogDrawer({
agentId={agentId}
remoteHintKey="editTools"
>
-
+
);
}
diff --git a/dashboard/src/pages/Experts/index.module.less b/dashboard/src/pages/Experts/index.module.less
index 7c5209e060..1b02b20253 100644
--- a/dashboard/src/pages/Experts/index.module.less
+++ b/dashboard/src/pages/Experts/index.module.less
@@ -1771,6 +1771,20 @@
/* ── Drawer shared styles ──────────────────────────────────────── */
+.expertDrawerRoot,
+.expertDrawer,
+.drawerSection,
+.moreConfig {
+ :global(.octop-form-item-extra),
+ :global(.ant-form-item-extra) {
+ min-height: unset;
+ margin-top: 4px;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--fn-text-tertiary);
+ }
+}
+
.textAssistField {
margin-bottom: 4px !important;
}
diff --git a/dashboard/src/pages/KnowledgeBases/index.module.less b/dashboard/src/pages/KnowledgeBases/index.module.less
index adf17e39b6..5cafefddae 100644
--- a/dashboard/src/pages/KnowledgeBases/index.module.less
+++ b/dashboard/src/pages/KnowledgeBases/index.module.less
@@ -15,6 +15,7 @@
margin-top: 4px;
font-size: 12px;
line-height: 1.5;
+ color: var(--fn-text-tertiary);
}
.ocrSettings {
diff --git a/dashboard/src/pages/KnowledgeBases/index.tsx b/dashboard/src/pages/KnowledgeBases/index.tsx
index e6c6932b1f..f6e6be40be 100644
--- a/dashboard/src/pages/KnowledgeBases/index.tsx
+++ b/dashboard/src/pages/KnowledgeBases/index.tsx
@@ -4075,12 +4075,9 @@ export default function KnowledgeBasesPage() {
(remoteProviders.find(
(provider) => provider.provider_id === featureProviderId,
)?.models.length ?? 0) === 0 ? (
-
+
{t("knowledgeBases.noModels")}
-
+
) : null}
@@ -4144,12 +4141,9 @@ export default function KnowledgeBasesPage() {
);
})}
{catalog.length === 0 ? (
-
+
{t("knowledgeBases.noModels")}
-
+
) : null}
{catalog.length > 0 && !onnxExpanded ? (
) : null}
-
+
{t("knowledgeBases.enableDescription")}
-
+
navigate("/admin/models")}>
{t("knowledgeBases.manageModels")}
@@ -4428,12 +4422,9 @@ export default function KnowledgeBasesPage() {
(graphProviders.find(
(provider) => provider.provider_id === graphProviderId,
)?.models.length ?? 0) === 0 ? (
-
+
{t("knowledgeBases.graphNoModels")}
-
+
) : null}
-
+
{t("models.localDownloadBackgroundHint")}
-
+
);
diff --git a/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.module.less b/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.module.less
index 560a1af271..cbbe18f9ad 100644
--- a/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.module.less
+++ b/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.module.less
@@ -560,10 +560,11 @@
font-weight: 500;
}
+ :global(.octop-form-item-extra),
:global(.ant-form-item-extra) {
- margin-top: 6px;
+ margin-top: 4px;
font-size: 12px;
- line-height: 1.45;
+ line-height: 1.5;
color: var(--fn-text-tertiary);
}
diff --git a/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.tsx b/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.tsx
index 91dfe0d7cc..a2d9536b9c 100644
--- a/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.tsx
+++ b/dashboard/src/pages/Settings/AdvancedSettings/BridgeSettings.tsx
@@ -75,6 +75,10 @@ import { useCardTableView } from "../../../hooks/useCardTableView";
import { useIsMobile } from "../../../hooks/useIsMobile";
import { apiErrorMessage } from "../../../utils/apiError";
import { ExpertIcon } from "../../Experts/components/iconForName";
+import {
+ ManagedAvatarMark,
+ managedRunnerId,
+} from "../../Experts/components/ManagedAvatarMark";
import {
bridgeApi,
type BridgeConnection,
@@ -388,25 +392,29 @@ function AgentAvatar({
iconUrl,
iconName,
color,
+ managedRunner,
}: {
name: string;
iconUrl?: string | null;
iconName?: string | null;
color?: string | null;
+ managedRunner?: string | null;
}) {
return (
-
-
-
+
+
+
+
+
);
}
@@ -430,6 +438,7 @@ function AgentListItem({
iconName,
color,
kind,
+ managedRunner,
onClick,
flat,
}: {
@@ -440,6 +449,7 @@ function AgentListItem({
iconName?: string | null;
color?: string | null;
kind?: string | null;
+ managedRunner?: string | null;
onClick?: () => void;
flat?: boolean;
}) {
@@ -451,6 +461,7 @@ function AgentListItem({
iconUrl={iconUrl}
iconName={iconName}
color={color}
+ managedRunner={managedRunner}
/>
@@ -578,6 +589,15 @@ function RemoteAgentsBlock({
}
color={typeof agent.color === "string" ? agent.color : null}
kind={typeof agent.kind === "string" ? agent.kind : null}
+ managedRunner={managedRunnerId({
+ kind: typeof agent.kind === "string" ? agent.kind : null,
+ config:
+ agent.config && typeof agent.config === "object"
+ ? (agent.config as Record)
+ : typeof agent.managed_runner === "string"
+ ? { managed_runner: agent.managed_runner }
+ : null,
+ })}
onClick={() => onOpen(agent.id)}
flat
/>
diff --git a/dashboard/src/pages/Settings/Models/components/DecisionSettingsPanel.module.less b/dashboard/src/pages/Settings/Models/components/DecisionSettingsPanel.module.less
index e4c89968b0..11e2054b9e 100644
--- a/dashboard/src/pages/Settings/Models/components/DecisionSettingsPanel.module.less
+++ b/dashboard/src/pages/Settings/Models/components/DecisionSettingsPanel.module.less
@@ -229,9 +229,12 @@
margin-bottom: 22px;
}
- :global(.octop-form-item-extra) {
- margin-top: 8px;
- line-height: 1.6;
+ :global(.octop-form-item-extra),
+ :global(.ant-form-item-extra) {
+ margin-top: 4px;
+ font-size: 12px;
+ line-height: 1.5;
+ color: var(--fn-text-tertiary);
}
}
diff --git a/dashboard/src/styles/layout.css b/dashboard/src/styles/layout.css
index 58d437ccc4..2c451a3470 100644
--- a/dashboard/src/styles/layout.css
+++ b/dashboard/src/styles/layout.css
@@ -511,6 +511,13 @@ html[data-theme="dark"] .octop-ant-modal-header {
}
/* Form */
+.octop-form-item-extra,
+.ant-form-item-extra {
+ font-size: 12px;
+ color: var(--fn-text-tertiary);
+ line-height: 1.5;
+}
+
html[data-theme="dark"] .ant-form-item-label > label,
html[data-theme="dark"] .octop-ant-form-item-label > label {
color: var(--fn-text-secondary) !important;
diff --git a/dashboard/src/utils/chatStreamError.test.ts b/dashboard/src/utils/chatStreamError.test.ts
index d00b25225c..0d12ad2236 100644
--- a/dashboard/src/utils/chatStreamError.test.ts
+++ b/dashboard/src/utils/chatStreamError.test.ts
@@ -6,7 +6,13 @@ import {
isChatStreamError,
} from "./chatStreamError";
-const t = ((key: string) => `translated:${key}`) as unknown as (
+const t = ((
+ key: string,
+ opts?: { tool?: string; count?: string; limit?: string },
+) =>
+ opts?.tool
+ ? `translated:${key}:${opts.tool}:${opts.count}:${opts.limit}`
+ : `translated:${key}`) as unknown as (
key: string,
opts?: { defaultValue?: string },
) => string;
@@ -65,6 +71,19 @@ describe("classifyChatStreamError", () => {
);
});
+ it("classifies a repeated tool call as a friendly config error", () => {
+ const msg = "[tool_call_repeat]\ntool: search\ncount: 41\nlimit: 40";
+ expect(classifyChatStreamError(msg)).toBe("stream_errors.tool_call_repeat");
+ expect(isChatStreamError(msg)).toBe(true);
+ expect(formatChatStreamError(msg, t)).toBe(
+ "translated:stream_errors.tool_call_repeat:search:41:40",
+ );
+ expect(chatStreamErrorAction(msg)).toEqual({
+ path: "/agent-config",
+ labelKey: "chat.goToAgentConfig",
+ });
+ });
+
it("classifies LangGraph recursion limit as recursion_limit", () => {
const msg =
"Recursion limit of 2 reached without hitting a stop condition. " +
diff --git a/dashboard/src/utils/chatStreamError.ts b/dashboard/src/utils/chatStreamError.ts
index 669e05ae9c..89e6dcf04a 100644
--- a/dashboard/src/utils/chatStreamError.ts
+++ b/dashboard/src/utils/chatStreamError.ts
@@ -9,6 +9,7 @@ const _STREAM_ERROR_KEYS = [
"stream_errors.insufficient_balance",
"stream_errors.context_length",
"stream_errors.recursion_limit",
+ "stream_errors.tool_call_repeat",
"stream_errors.timeout_network",
"stream_errors.provider_unavailable",
"stream_errors.invalid_request",
@@ -26,6 +27,9 @@ export type StreamErrorAction = {
};
const MODEL_RETRY_FAILURE_MARK = "[model_call_failed]";
+const TOOL_CALL_REPEAT_MARK = "[tool_call_repeat]";
+const TOOL_CALL_REPEAT_RE =
+ /\[tool_call_repeat\]\s*tool:\s*(.+)\ncount:\s*(\d+)\nlimit:\s*(\d+)/i;
const RETRY_WRAPPER_RE = /^model call failed after \d+ attempts?\s+with\s+/i;
const TECHNICAL_DETAIL_RE = /technical detail:\s*([\s\S]+)$/i;
const COMPLETION_USAGE_RE = /\s*-?\s*CompletionUsage\([\s\S]*\)\s*$/;
@@ -53,6 +57,10 @@ const STREAM_ERROR_ACTIONS: Partial> =
path: "/agent-config",
labelKey: "chat.goToAgentConfig",
},
+ "stream_errors.tool_call_repeat": {
+ path: "/agent-config",
+ labelKey: "chat.goToAgentConfig",
+ },
"stream_errors.path_outside_root": {
path: "/agent-config",
labelKey: "chat.goToAgentConfig",
@@ -94,11 +102,24 @@ function unwrapModelRetryMessage(message: string): string {
return msg || normalizeMessage(message);
}
+function toolCallRepeatVars(
+ message: string,
+): { tool: string; count: string; limit: string } | null {
+ const match = message.match(TOOL_CALL_REPEAT_RE);
+ if (!match?.[1] || !match[2] || !match[3]) return null;
+ return {
+ tool: match[1].trim(),
+ count: match[2],
+ limit: match[3],
+ };
+}
+
/** Return a stable i18n key for known model/stream failures, else null. */
export function classifyChatStreamError(
message: string | null | undefined,
): StreamErrorKey | null {
if (!message) return null;
+ if (toolCallRepeatVars(message)) return "stream_errors.tool_call_repeat";
const raw = normalizeMessage(message);
const msg = unwrapModelRetryMessage(message);
if (!msg && !raw) return null;
@@ -235,6 +256,8 @@ function isModelRetryEnvelope(message: string | null | undefined): boolean {
/** True only for ModelRetryMiddleware envelopes, not ordinary answers. */
export function isChatStreamError(message: string | null | undefined): boolean {
+ if (!message) return false;
+ if (message.includes(TOOL_CALL_REPEAT_MARK)) return true;
return isModelRetryEnvelope(message);
}
@@ -246,6 +269,10 @@ export function formatChatStreamError(
if (!message) return "";
const key = classifyChatStreamError(message);
const detail = unwrapModelRetryMessage(message);
+ if (key === "stream_errors.tool_call_repeat") {
+ const fields = toolCallRepeatVars(message) ?? {};
+ return t(key, { ...fields, defaultValue: message });
+ }
if (key && key !== "stream_errors.model_call_failed") {
return t(key, { defaultValue: message });
}
diff --git a/deploy/helm/octop/Chart.yaml b/deploy/helm/octop/Chart.yaml
index ec0913b591..0741963c67 100644
--- a/deploy/helm/octop/Chart.yaml
+++ b/deploy/helm/octop/Chart.yaml
@@ -3,5 +3,5 @@ name: octop
description: Octop with shared PostgreSQL, sticky replicas, and single-active cron and channels
type: application
version: 0.1.0
-appVersion: "1.0.3b6"
+appVersion: "1.0.3b7"
kubeVersion: ">=1.25.0-0"
diff --git a/deploy/helm/octop/README.md b/deploy/helm/octop/README.md
index 8c343c4727..4ff7068bef 100644
--- a/deploy/helm/octop/README.md
+++ b/deploy/helm/octop/README.md
@@ -12,11 +12,11 @@ The longer multi-replica guide is [docs/cluster_CN.md](../../../docs/cluster_CN.
## Where to install from
-Install the chart from GHCR. A clone is not required. The chart sits next to the image. There is no separate HTTP Helm repository. A `v*` tag publishes the package. `appVersion` is the image tag, for example `1.0.3b6`. Helm chart `version` must be SemVer, so `1.0.3b6` is published as `1.0.3-b6` and `1.0.3` stays `1.0.3`. The published `appVersion` is already the image tag, so the install does not set `image.tag`.
+Install the chart from GHCR. A clone is not required. The chart sits next to the image. There is no separate HTTP Helm repository. A `v*` tag publishes the package. `appVersion` is the image tag, for example `1.0.3b7`. Helm chart `version` must be SemVer, so `1.0.3b7` is published as `1.0.3-b7` and `1.0.3` stays `1.0.3`. The published `appVersion` is already the image tag, so the install does not set `image.tag`.
```bash
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--set ingress.host=octop.example.com
```
@@ -25,11 +25,11 @@ Edit chart source in `deploy/helm/octop` and install that directory from the rep
## What you set
-The chart does not store passwords and does not create Secrets from values. Published defaults are `helm show values oci://ghcr.io/tencentcloud/octop/charts/octop --version 1.0.3-b6`. In this repository, `values.example.yaml` is the same knobs with comments, and `secrets.example.yaml` is the password sample. Copy them, change the hostname and image, replace the placeholders, and do not commit filled-in passwords.
+The chart does not store passwords and does not create Secrets from values. Published defaults are `helm show values oci://ghcr.io/tencentcloud/octop/charts/octop --version 1.0.3-b7`. In this repository, `values.example.yaml` is the same knobs with comments, and `secrets.example.yaml` is the password sample. Copy them, change the hostname and image, replace the placeholders, and do not commit filled-in passwords.
```bash
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
-f my-values.yaml
```
@@ -95,7 +95,7 @@ kubectl -n octop create secret tls octop-tls \
--cert=fullchain.pem --key=privkey.pem
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--set ingress.host=octop.example.com
```
@@ -104,7 +104,7 @@ Without a public hostname, or when the ingress controller is not Ingress NGINX,
```bash
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--set ingress.enabled=false
@@ -138,7 +138,7 @@ Sign in through the Ingress host with the `octop-admin` username and password. T
```bash
helm upgrade octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--reuse-values \
--set ingress.host=octop.example.com
@@ -150,7 +150,7 @@ Keep the TLS secret's names in step with that host. If TLS is turned off, also s
```bash
helm upgrade octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--reuse-values \
--set replicaCount=3
@@ -164,7 +164,7 @@ Leave the extension to the database operator (`CREATE EXTENSION vector`). The ch
```bash
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--set postgresql.enabled=false \
--set database.host=pg.example.com \
diff --git a/deploy/helm/octop/README_CN.md b/deploy/helm/octop/README_CN.md
index 2328c376b8..2416e21579 100644
--- a/deploy/helm/octop/README_CN.md
+++ b/deploy/helm/octop/README_CN.md
@@ -12,11 +12,11 @@
## 从哪里安装
-安装用 GHCR 上的 chart,不必克隆仓库。地址和镜像在同一个仓库,没有单独的 HTTP Helm 仓库。打 `v*` 标签时流水线推包。`appVersion` 是镜像 tag,例如 `1.0.3b6`。Helm 的 chart `version` 必须是 SemVer,所以 `1.0.3b6` 会发成 `1.0.3-b6`,`1.0.3` 保持 `1.0.3`。发布包里的 `appVersion` 已经是镜像 tag,安装时不用再写 `image.tag`。
+安装用 GHCR 上的 chart,不必克隆仓库。地址和镜像在同一个仓库,没有单独的 HTTP Helm 仓库。打 `v*` 标签时流水线推包。`appVersion` 是镜像 tag,例如 `1.0.3b7`。Helm 的 chart `version` 必须是 SemVer,所以 `1.0.3b7` 会发成 `1.0.3-b7`,`1.0.3` 保持 `1.0.3`。发布包里的 `appVersion` 已经是镜像 tag,安装时不用再写 `image.tag`。
```bash
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--set ingress.host=octop.example.com
```
@@ -25,11 +25,11 @@ helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
## 要准备什么
-Chart 不保存口令,也不会在 values 里生成 Secret。线上包的默认值用 `helm show values oci://ghcr.io/tencentcloud/octop/charts/octop --version 1.0.3-b6` 查看。仓库里的 `values.example.yaml` 把同一批参数写成带注释的样例,`secrets.example.yaml` 是口令样例。复制后改域名和镜像,占位符换成真实口令,不要把填好的口令文件提交进仓库。
+Chart 不保存口令,也不会在 values 里生成 Secret。线上包的默认值用 `helm show values oci://ghcr.io/tencentcloud/octop/charts/octop --version 1.0.3-b7` 查看。仓库里的 `values.example.yaml` 把同一批参数写成带注释的样例,`secrets.example.yaml` 是口令样例。复制后改域名和镜像,占位符换成真实口令,不要把填好的口令文件提交进仓库。
```bash
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
-f my-values.yaml
```
@@ -95,7 +95,7 @@ kubectl -n octop create secret tls octop-tls \
--cert=fullchain.pem --key=privkey.pem
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--set ingress.host=octop.example.com
```
@@ -104,7 +104,7 @@ helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
```bash
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--set ingress.enabled=false
@@ -138,7 +138,7 @@ curl -fsS http://127.0.0.1:8088/api/health
```bash
helm upgrade octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--reuse-values \
--set ingress.host=octop.example.com
@@ -150,7 +150,7 @@ TLS Secret 里的域名要和这里一致。如果关掉 TLS,把注解 `nginx.
```bash
helm upgrade octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--reuse-values \
--set replicaCount=3
@@ -164,7 +164,7 @@ helm upgrade octop oci://ghcr.io/tencentcloud/octop/charts/octop \
```bash
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--set postgresql.enabled=false \
--set database.host=pg.example.com \
diff --git a/deploy/helm/octop/values.example.yaml b/deploy/helm/octop/values.example.yaml
index 90aede8c60..cc8f0a2ac8 100644
--- a/deploy/helm/octop/values.example.yaml
+++ b/deploy/helm/octop/values.example.yaml
@@ -1,6 +1,6 @@
# 安装样例。复制后改域名、镜像和资源,再:
# helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
-# --version 1.0.3-b6 -n octop -f my-values.yaml
+# --version 1.0.3-b7 -n octop -f my-values.yaml
#
# 口令不要写在这个文件里。安装前另建 Secret,见 secrets.example.yaml。
# octop-admin username / password 控制台账号,只在第一次初始化时创建
@@ -14,7 +14,7 @@ image:
repository: ghcr.io/tencentcloud/octop
# 留空则用 chart 的 appVersion。请写成仓库里真实存在的版本。
# 精简版没有虚拟桌面、本地向量和 OCR。那些能力用 <版本>-full,并打开下面的 shm。
- tag: "1.0.3b6"
+ tag: "1.0.3b7"
pullPolicy: IfNotPresent
# 完整版镜像需要约 1Gi 的 /dev/shm。精简版保持 false。
diff --git a/docs/agent-backend-file-io.md b/docs/agent-backend-file-io.md
index 21fa9b2469..25a4cd4e7e 100644
--- a/docs/agent-backend-file-io.md
+++ b/docs/agent-backend-file-io.md
@@ -290,7 +290,7 @@ Harness 侧只认调用方传入的 ``workspace_dir``;Docker 默认把它镜
| `sandbox_id` | `fixed` 必填 |
| `username` | `user` 用;缺省时 Octop 注入专家所有者用户名 |
| `previewable` | 仅影响 Admin「我的存储」浏览按钮;默认仅 `fixed` 为 true。专家工作区始终可预览 |
-| `volumes` | 忽略。宿主目录挂载不会传给 Docker,避免把任意宿主路径挂进沙箱 |
+| `volumes` | Octop 跑在容器里时原样透传,供 Docker 专家挂载宿主机目录。Octop 直接跑在宿主机上时忽略,避免把任意宿主路径挂进沙箱 |
容器命名:
@@ -304,7 +304,7 @@ Harness 侧只认调用方传入的 ``workspace_dir``;Docker 默认把它镜
- `bucket` 或 `config_json.image`:镜像名(必填)
- Admin 表单可配 `sandbox_scope` / `sandbox_prefix` / `sandbox_id` / `username`,写入 `config_json`
-- 其余可选:`allow_network`、`memory`、`cpus`、`pids_limit`、`command_timeout` 等。`volumes` 会被忽略 |
+- 其余可选:`allow_network`、`memory`、`cpus`、`pids_limit`、`command_timeout`、`volumes` 等。Octop 直接跑在宿主机上时 `volumes` 会被忽略 |
```json
{ "type": "named", "name": "my-docker-sandbox" }
diff --git a/docs/cluster_CN.md b/docs/cluster_CN.md
index 7ee702b106..5b2a045964 100644
--- a/docs/cluster_CN.md
+++ b/docs/cluster_CN.md
@@ -216,7 +216,7 @@ curl -fsS http://127.0.0.1:8089/api/health
机器已经在 Kubernetes 里时,用 Helm 一次装上三部分:带 pgvector 的 PostgreSQL、默认两个副本的 Octop,以及对外的 Ingress。数据库是单副本,数据卷 20Gi,集群需要有默认的 StorageClass。要能拉取 `pgvector/pgvector:pg16` 和 `ghcr.io/tencentcloud/octop:<版本>`。需要 Kubernetes 1.25 或更新版本,以及 Helm 3。参数说明写在 [deploy/helm/octop/README_CN.md](../deploy/helm/octop/README_CN.md)。Chart 不安装 HorizontalPodAutoscaler,副本数只通过 `replicaCount` 修改。
-安装直接用线上包 `oci://ghcr.io/tencentcloud/octop/charts/octop`,不必克隆仓库。打 `v*` 标签时流水线推这个包。镜像 tag 是 `1.0.3b6` 这种形式。Helm 要求 chart 版本是 SemVer,所以同一次发布里 chart 版本写成 `1.0.3-b6`;没有字母后缀的 `1.0.3` 两边相同。发布包里的 `appVersion` 已经是镜像 tag,安装命令不用再写 `image.tag`。要虚拟桌面、本地向量或 OCR 时,把 `image.tag` 设为 `<版本>-full`,并设 `shm.enabled=true`。改 chart 源码时仍用仓库目录 `deploy/helm/octop`。已经发出的 `v1.0.3b5` 不含这份 chart,要等下一次版本标签。
+安装直接用线上包 `oci://ghcr.io/tencentcloud/octop/charts/octop`,不必克隆仓库。打 `v*` 标签时流水线推这个包。镜像 tag 是 `1.0.3b7` 这种形式。Helm 要求 chart 版本是 SemVer,所以同一次发布里 chart 版本写成 `1.0.3-b7`;没有字母后缀的 `1.0.3` 两边相同。发布包里的 `appVersion` 已经是镜像 tag,安装命令不用再写 `image.tag`。要虚拟桌面、本地向量或 OCR 时,把 `image.tag` 设为 `<版本>-full`,并设 `shm.enabled=true`。改 chart 源码时仍用仓库目录 `deploy/helm/octop`。已经发出的 `v1.0.3b5` 不含这份 chart,要等下一次版本标签。
【插图 5】Kubernetes 里的三个部分
@@ -227,7 +227,7 @@ curl -fsS http://127.0.0.1:8089/api/health
Chart 不保存口令,也不会根据 values 生成 Secret。线上包的默认值用下面这条命令查看:
```bash
-helm show values oci://ghcr.io/tencentcloud/octop/charts/octop --version 1.0.3-b6
+helm show values oci://ghcr.io/tencentcloud/octop/charts/octop --version 1.0.3-b7
```
仓库里的 `deploy/helm/octop/values.example.yaml` 是带注释的同一批参数,`secrets.example.yaml` 是口令样例。复制后改域名,占位符换成真实口令。填好的口令文件不要提交进仓库。
@@ -265,7 +265,7 @@ kubectl -n octop create secret tls octop-tls \
--cert=fullchain.pem --key=privkey.pem
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--set ingress.host=octop.example.com
```
@@ -278,7 +278,7 @@ helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
```bash
helm upgrade octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--reuse-values \
--set ingress.host=octop.example.com
@@ -307,7 +307,7 @@ curl -fsS http://127.0.0.1:8088/api/health
```bash
helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--set postgresql.enabled=false \
--set database.host=pg.example.com \
@@ -318,7 +318,7 @@ helm upgrade --install octop oci://ghcr.io/tencentcloud/octop/charts/octop \
```bash
helm upgrade octop oci://ghcr.io/tencentcloud/octop/charts/octop \
- --version 1.0.3-b6 \
+ --version 1.0.3-b7 \
-n octop \
--reuse-values \
--set replicaCount=3
diff --git a/pyproject.toml b/pyproject.toml
index d32f5a46c5..272a4e157b 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "octop"
-version = "1.0.3b6"
+version = "1.0.3b7"
description = "Smarter self-hosted AI assistant for multiple users and agents, built on octop-harness"
readme = "README.md"
license = { text = "MIT" }
@@ -21,10 +21,10 @@ dependencies = [
"apscheduler>=3.10,<4",
"argon2-cffi>=23.1",
"pyjwt>=2.8",
- "octop-harness[all]>=1.0.10",
- "octop-memory>=1.0.4",
+ "octop-harness[all]>=1.0.11",
+ "octop-memory>=1.0.5",
"lark-oapi>=1.7.3",
- "octop-gateway>=1.0.3",
+ "octop-gateway>=1.0.4",
"cryptography>=41",
"scalar-fastapi>=1.0",
"edge-tts>=6.1",
diff --git a/src/octop/__init__.py b/src/octop/__init__.py
index 3f999fe4b9..56a8039f5e 100644
--- a/src/octop/__init__.py
+++ b/src/octop/__init__.py
@@ -4,7 +4,7 @@
from octop.infra.utils.httpx_proxy import install_httpx_cidr_no_proxy
-__version__ = "1.0.3b6"
+__version__ = "1.0.3b7"
# httpx 0.28 treats NO_PROXY CIDR as an exact IP (see issue #1347). Patch once
# at import so CLI, ``octop run``, and in-process harness clients all honor it.
diff --git a/src/octop/api/common/agent_runtime.py b/src/octop/api/common/agent_runtime.py
index 16e486301f..0a74124214 100644
--- a/src/octop/api/common/agent_runtime.py
+++ b/src/octop/api/common/agent_runtime.py
@@ -65,12 +65,18 @@ class AgentRuntimeFields(BaseModel):
max_tokens: int | None = Field(default=None, ge=1)
tool_call_limit_enabled: bool | None = Field(
default=None,
- description="Limit tool calls in one run. Omit to leave the limit on.",
+ description=(
+ "Stop a turn that repeats one tool call with the same arguments. "
+ "Omit to leave the limit on."
+ ),
)
tool_call_run_limit: int | None = Field(
default=None,
ge=1,
- description="Maximum tool calls in one run. Omit to use 40.",
+ description=(
+ "How many times the same tool may be called in a row with the same "
+ "arguments. Omit to use 40."
+ ),
)
model_retry_enabled: bool | None = Field(
default=None,
diff --git a/src/octop/api/routers/acp.py b/src/octop/api/routers/acp.py
index d4347966b2..86dbbd9a25 100644
--- a/src/octop/api/routers/acp.py
+++ b/src/octop/api/routers/acp.py
@@ -164,6 +164,22 @@ async def get_global_acp_runners(
return {"runners": registry.acp_settings.load_runners(user.id)}
+@router.get("/acp/session-modes", summary="Session modes for one ACP runner")
+async def acp_session_modes(
+ runner: str,
+ _user: Any = Depends(current_user),
+) -> dict[str, Any]:
+ """Modes this underlying agent documents for ``session/set_mode``.
+
+ The list follows the runner. An empty list means Octop has no catalog for
+ it, and the chat keeps that agent's own default.
+ """
+ from octop.infra.agents.acp.session_modes import session_modes
+
+ rows = session_modes(runner)
+ return {"runner": runner.strip(), "modes": [row.to_dict() for row in rows]}
+
+
@router.put("/acp", summary="Update global ACP runners")
async def put_global_acp_runners(
body: ACPRunnersBody,
diff --git a/src/octop/api/routers/agent_tools.py b/src/octop/api/routers/agent_tools.py
index dfc7592abd..853a8134a5 100644
--- a/src/octop/api/routers/agent_tools.py
+++ b/src/octop/api/routers/agent_tools.py
@@ -10,12 +10,16 @@
from octop.api.common.agent import assert_agent_owner as _assert_agent_owner
from octop.api.deps import get_server, require_permission
from octop.i18n.domains.tools import tool_display_name
+from octop.infra.agents.managed import is_managed_agent
from octop.infra.agents.plugins.plugin_tool_defaults import merge_plugins_tool_settings
+from octop.infra.agents.settings.profile import parse_id_list_json
from octop.infra.agents.settings.tool_catalog import (
BUILTIN_TOOL_CATALOG,
CRITICAL_TOOLS,
+ MANAGED_BUILTIN_TOOLS,
agent_plugin_enabled,
builtin_tool_available,
+ managed_builtin_available,
normalize_tools_disabled,
)
from octop.infra.agents.teams import HOST_TOOLS_ALLOWED, is_team_agent
@@ -64,6 +68,27 @@ class ToolSettingPatchBody(BaseModel):
plugin_id: str | None = None
+def _managed_has_peers(server: OctopServer, user: Any, agent_id: str) -> bool:
+ """True when this user can call some other expert."""
+ user_id = getattr(user, "id", None)
+ if not isinstance(user_id, int):
+ return False
+ registry = server.app_runtime.agent_registry if server.app_runtime is not None else None
+ if registry is None:
+ return False
+ harness = getattr(registry, "_harness_manager", None)
+ team = getattr(harness, "team", None)
+ if team is not None:
+ try:
+ return bool(team.list_peers(user_id, exclude_agent_id=agent_id))
+ except Exception:
+ return False
+ for other in registry.list_agents(user_id):
+ if other.agent_id != agent_id and not is_team_agent(other):
+ return True
+ return False
+
+
def _plugin_manager(server: OctopServer) -> Any:
mgr = server.plugin_manager
if mgr is None:
@@ -176,17 +201,36 @@ async def get_tool_settings(
agent_cfg = server.app_runtime.agent_registry.get_config(agent_id)
disabled = set(normalize_tools_disabled(agent_cfg.get("tools_disabled")))
mobile_enabled = bool(server.config is not None and server.config.capabilities.mobile.enabled)
- team_host = is_team_agent(row)
+ managed = is_managed_agent(row)
+ team_host = is_team_agent(row) and not managed
tools: list[ToolSettingsItem] = []
- catalog = (
- tuple(entry for entry in BUILTIN_TOOL_CATALOG if entry.name in HOST_TOOLS_ALLOWED)
- if team_host
- else BUILTIN_TOOL_CATALOG
- )
+ if managed:
+ catalog = tuple(
+ entry for entry in BUILTIN_TOOL_CATALOG if entry.name in MANAGED_BUILTIN_TOOLS
+ )
+ elif team_host:
+ catalog = tuple(entry for entry in BUILTIN_TOOL_CATALOG if entry.name in HOST_TOOLS_ALLOWED)
+ else:
+ catalog = BUILTIN_TOOL_CATALOG
+ knowledge_ids = parse_id_list_json(getattr(row, "knowledge_base_ids", None)) or []
+ has_peers = _managed_has_peers(server, user, agent_id) if managed else False
for entry in catalog:
allowed = not team_host or entry.name in HOST_TOOLS_ALLOWED
disableable = (not team_host) and entry.name not in CRITICAL_TOOLS
+ if managed:
+ available = managed_builtin_available(
+ entry.name,
+ agent_cfg=agent_cfg,
+ knowledge_base_ids=knowledge_ids,
+ has_peers=has_peers,
+ )
+ else:
+ available = builtin_tool_available(
+ entry.name,
+ agent_cfg=agent_cfg,
+ mobile_enabled=mobile_enabled,
+ )
tools.append(
ToolSettingsItem(
name=entry.name,
@@ -196,12 +240,7 @@ async def get_tool_settings(
description=None,
enabled=allowed and (entry.name not in disabled if disableable else True),
disableable=disableable,
- available=allowed
- and builtin_tool_available(
- entry.name,
- agent_cfg=agent_cfg,
- mobile_enabled=mobile_enabled,
- ),
+ available=allowed and available,
plugin_id=None,
)
)
diff --git a/src/octop/api/routers/chat/history.py b/src/octop/api/routers/chat/history.py
index 6079da54d0..0a92fe2843 100644
--- a/src/octop/api/routers/chat/history.py
+++ b/src/octop/api/routers/chat/history.py
@@ -41,8 +41,61 @@ def _agent_is_busy(server: Any, agent_id: str) -> bool:
return callable(checker) and checker(agent_id) is True
-def _hitl_policy_payload(row: Any) -> dict[str, Any]:
- return parse_hitl_session_policy(getattr(row, "hitl_policy", None)).to_dict()
+def _agent_config(server: Any, agent_id: str) -> dict[str, Any]:
+ repo = getattr(getattr(server, "services", None), "agent_repo", None)
+ get = getattr(repo, "get", None)
+ if not callable(get):
+ return {}
+ row = get(agent_id)
+ if row is None:
+ return {}
+ from octop.infra.agents.settings.profile import parse_config_json
+
+ config = parse_config_json(getattr(row, "config_json", None))
+ kind = getattr(row, "kind", None)
+ if isinstance(kind, str):
+ config = {**config, "kind": kind}
+ return config
+
+
+def _managed_yolo_default(server: Any, agent_id: str) -> bool:
+ from octop.infra.agents.managed import read_managed_permission_mode
+
+ return read_managed_permission_mode(_agent_config(server, agent_id)) == "yolo"
+
+
+def _listed_session_mode(config: dict[str, Any], row: Any) -> str | None:
+ from octop.infra.agents.acp.session_modes import resolve_managed_session_mode
+
+ if config.get("kind") != "managed":
+ return None
+ mode = resolve_managed_session_mode(
+ stored=getattr(row, "conversation_mode", None),
+ config=config,
+ )
+ return mode or None
+
+
+def _session_mode_payload(server: Any, agent_id: str, row: Any) -> str | None:
+ from octop.infra.agents.acp.session_modes import resolve_managed_session_mode
+
+ config = _agent_config(server, agent_id)
+ if config.get("kind") != "managed":
+ return None
+ mode = resolve_managed_session_mode(
+ stored=getattr(row, "conversation_mode", None),
+ config=config,
+ )
+ return mode or None
+
+
+def _hitl_policy_payload(row: Any, *, default_yolo: bool = False) -> dict[str, Any]:
+ raw = getattr(row, "hitl_policy", None)
+ if isinstance(raw, str) and raw.strip():
+ return parse_hitl_session_policy(raw).to_dict()
+ if default_yolo:
+ return {"mode": "allow_all"}
+ return {"mode": "ask"}
def _message_author_profile(server: Any, user_id: int) -> dict[str, Any] | None:
@@ -201,6 +254,8 @@ async def list_threads(
message_repo = server.services.thread_message_repo
ids_with_messages = message_repo.threads_with_messages([r.thread_id for r in rows])
unread = thread_registry.unread_counts_for_threads([r.thread_id for r in rows])
+ default_yolo = _managed_yolo_default(server, agent_id)
+ agent_config = _agent_config(server, agent_id)
def _has_messages(row: Any) -> bool:
if not thread_row_has_messages(row):
@@ -228,8 +283,9 @@ def _has_messages(row: Any) -> bool:
"reasoning_mode": r.reasoning_mode,
"reasoning_effort": r.reasoning_effort,
"conversation_mode": r.conversation_mode or "craft",
+ "session_mode": _listed_session_mode(agent_config, r),
"pending_plan_path": r.pending_plan_path,
- "hitl_policy": _hitl_policy_payload(r),
+ "hitl_policy": _hitl_policy_payload(r, default_yolo=default_yolo),
"turn_active": hub.is_turn_active(r.thread_id),
"awaiting_user": r.thread_id
in (shared_awaiting_ids if r.contributed else awaiting_ids),
@@ -478,8 +534,11 @@ async def _work() -> None:
default_agent_id=agent_id,
),
"conversation_mode": row.conversation_mode or "craft",
+ "session_mode": _session_mode_payload(server, agent_id, row),
"pending_plan_path": row.pending_plan_path,
- "hitl_policy": _hitl_policy_payload(row),
+ "hitl_policy": _hitl_policy_payload(
+ row, default_yolo=_managed_yolo_default(server, agent_id)
+ ),
}
@@ -604,11 +663,13 @@ async def patch_thread(
"""Update sidebar metadata or sticky composer settings for a thread."""
row = _require_thread(server, agent_id, thread_id, user, as_user)
effective_uid = as_user if as_user is not None else user.id
+ default_yolo = _managed_yolo_default(server, agent_id)
composer_fields = {
"model_ref",
"reasoning_mode",
"reasoning_effort",
"conversation_mode",
+ "session_mode",
"hitl_policy",
}
managing = bool(body.model_fields_set)
@@ -630,8 +691,9 @@ async def patch_thread(
"reasoning_mode": row.reasoning_mode,
"reasoning_effort": row.reasoning_effort,
"conversation_mode": row.conversation_mode or "craft",
+ "session_mode": _session_mode_payload(server, agent_id, row),
"pending_plan_path": row.pending_plan_path,
- "hitl_policy": _hitl_policy_payload(row),
+ "hitl_policy": _hitl_policy_payload(row, default_yolo=default_yolo),
}
registry = server.app_runtime.gateway.thread_registry
if "contributed" in body.model_fields_set:
@@ -674,7 +736,11 @@ async def patch_thread(
reasoning_mode = body.reasoning_mode
if "reasoning_effort" in body.model_fields_set:
reasoning_effort = (body.reasoning_effort or "").strip().lower() or None
- if "conversation_mode" in body.model_fields_set:
+ if "session_mode" in body.model_fields_set:
+ from octop.infra.agents.acp.session_modes import resolve_managed_session_mode
+
+ conversation_mode = resolve_managed_session_mode(explicit=body.session_mode) or None
+ elif "conversation_mode" in body.model_fields_set:
conversation_mode = body.conversation_mode or "craft"
if "hitl_policy" in body.model_fields_set:
policy = parse_hitl_session_policy(
@@ -704,8 +770,9 @@ async def patch_thread(
"reasoning_mode": updated.reasoning_mode,
"reasoning_effort": updated.reasoning_effort,
"conversation_mode": updated.conversation_mode or "craft",
+ "session_mode": _session_mode_payload(server, agent_id, updated),
"pending_plan_path": updated.pending_plan_path,
- "hitl_policy": _hitl_policy_payload(updated),
+ "hitl_policy": _hitl_policy_payload(updated, default_yolo=default_yolo),
}
diff --git a/src/octop/api/routers/chat/models.py b/src/octop/api/routers/chat/models.py
index e221151c5f..7bea6ee1af 100644
--- a/src/octop/api/routers/chat/models.py
+++ b/src/octop/api/routers/chat/models.py
@@ -57,6 +57,11 @@ class ChatTurnBody(BaseModel):
default=None,
description="Turn permission mode: ask (read-only), plan (write plans/*.md), craft (default).",
)
+ session_mode: str | None = Field(
+ default=None,
+ max_length=64,
+ description="ACP session mode id for a managed expert, such as plan or bypassPermissions.",
+ )
hitl_policy: HitlSessionPolicyBody | None = Field(
default=None,
description="Thread-scoped tool-approval bypass for this turn (does not change global HITL).",
@@ -117,6 +122,9 @@ def from_ws_payload(cls, payload: dict[str, Any]) -> ChatTurnBody:
conversation_mode=payload.get("conversation_mode")
if payload.get("conversation_mode") in ("ask", "plan", "craft")
else None,
+ session_mode=str(payload["session_mode"]).strip()
+ if isinstance(payload.get("session_mode"), str) and str(payload["session_mode"]).strip()
+ else None,
hitl_policy=payload.get("hitl_policy")
if isinstance(payload.get("hitl_policy"), dict)
else None,
@@ -152,6 +160,7 @@ class UserTurnWsFrame(BaseModel):
reasoning_mode: Literal["auto", "enabled", "disabled"] | None = None
reasoning_effort: str | None = None
conversation_mode: Literal["ask", "plan", "craft"] | None = None
+ session_mode: str | None = None
hitl_policy: HitlSessionPolicyBody | None = None
mcp_servers: list[str] | None = None
knowledge_base_ids: list[str] | None = None
@@ -202,6 +211,11 @@ class RenameThreadBody(BaseModel):
reasoning_mode: Literal["auto", "enabled", "disabled"] | None = None
reasoning_effort: str | None = None
conversation_mode: Literal["ask", "plan", "craft"] | None = None
+ session_mode: str | None = Field(
+ default=None,
+ max_length=64,
+ description="ACP session mode id for a managed expert.",
+ )
hitl_policy: HitlSessionPolicyBody | None = None
diff --git a/src/octop/api/routers/chat/turn.py b/src/octop/api/routers/chat/turn.py
index 5855c6fc3c..81e366b846 100644
--- a/src/octop/api/routers/chat/turn.py
+++ b/src/octop/api/routers/chat/turn.py
@@ -269,7 +269,9 @@ async def prepare_dashboard_turn(
user=user,
names=turn.skills,
)
- if mcp_servers:
+ from octop.infra.agents.managed import is_managed_agent # noqa: PLC0415
+
+ if mcp_servers and not is_managed_agent(row):
failed = await server.app_runtime.agent_registry.prepare_chat_mcp(
agent_id,
mcp_servers,
@@ -332,6 +334,9 @@ async def prepare_dashboard_turn(
target_agent_ids=target_ids,
model_ref=model_ref,
default_model=default_model,
+ knowledge_base_ids=list(turn.knowledge_base_ids)
+ if isinstance(turn.knowledge_base_ids, list)
+ else None,
)
inbound_content = content_parts_from_dashboard_turn(turn)
inbound_attachments = inbound_attachments_from_parts(inbound_content)
@@ -378,6 +383,8 @@ def build_dashboard_inbound(
metadata["reasoning_effort"] = turn.reasoning_effort
if turn.conversation_mode:
metadata["conversation_mode"] = turn.conversation_mode
+ if turn.session_mode:
+ metadata["session_mode"] = turn.session_mode
if turn.hitl_policy is not None:
metadata["hitl_policy"] = turn.hitl_policy.model_dump()
if prepared.composer_context:
diff --git a/src/octop/api/routers/internal_mcp.py b/src/octop/api/routers/internal_mcp.py
index bfff7e767a..8d5085518e 100644
--- a/src/octop/api/routers/internal_mcp.py
+++ b/src/octop/api/routers/internal_mcp.py
@@ -148,3 +148,388 @@ async def internal_mcp_delete(
if svc.verify_internal_token(instance_id, token) is None:
raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
return Response(status_code=204)
+
+
+def _mcp_json(
+ request: Request,
+ body: dict[str, Any],
+ resp: dict[str, Any],
+ *,
+ session_id: str | None,
+) -> Response:
+ if not resp:
+ return Response(status_code=202)
+ resp = _negotiate_initialize_result(body, resp)
+ headers = {"content-type": "application/json"}
+ if session_id:
+ headers[MCP_SESSION_HEADER] = session_id
+ protocol = request.headers.get(MCP_PROTOCOL_HEADER)
+ if protocol:
+ headers[MCP_PROTOCOL_HEADER] = protocol
+ return JSONResponse(content=resp, headers=headers)
+
+
+@router.post("/internal/mcp/knowledge")
+async def knowledge_mcp_post(
+ request: Request,
+ token: str = Query(...),
+ server: Any = Depends(get_server),
+) -> Response:
+ """Search the knowledge bases selected for one managed-agent turn."""
+ from octop.infra.agents.acp.turn import knowledge_scope
+ from octop.infra.knowledge.mcp_gateway import handle_knowledge_mcp
+ from octop.infra.knowledge.tools import KnowledgeToolServices
+
+ scope = knowledge_scope(token)
+ if scope is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ try:
+ body = await request.json()
+ except json.JSONDecodeError as exc:
+ raise OctopError(ErrorCode.CONNECTOR_INVALID_CREDENTIALS, "invalid JSON body") from exc
+ if not isinstance(body, dict):
+ raise OctopError(ErrorCode.CONNECTOR_INVALID_CREDENTIALS, "expected JSON object")
+
+ method = str(body.get("method") or "")
+ if method == "notifications/initialized":
+ return Response(status_code=202)
+ session_id = request.headers.get(MCP_SESSION_HEADER)
+ if method == "initialize":
+ session_id = secrets.token_urlsafe(16)
+ resp = await handle_knowledge_mcp(
+ body,
+ user_id=scope.user_id,
+ is_admin=scope.is_admin,
+ knowledge_base_ids=list(scope.knowledge_base_ids),
+ locale=scope.locale,
+ catalog=scope.catalog_rows(),
+ services=KnowledgeToolServices(server.app_runtime.agent_registry),
+ )
+ return _mcp_json(request, body, resp, session_id=session_id)
+
+
+@router.get("/internal/mcp/knowledge")
+async def knowledge_mcp_get(
+ request: Request,
+ token: str = Query(...),
+) -> Response:
+ """Keep a streamable-HTTP session open after initialize."""
+ from octop.infra.agents.acp.turn import knowledge_scope
+
+ if knowledge_scope(token) is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ if not request.headers.get(MCP_SESSION_HEADER):
+ return JSONResponse(status_code=405, content={"error": "missing mcp-session-id"})
+
+ async def _sse_keepalive() -> Any:
+ yield "event: message\ndata: \n\n"
+ while True:
+ await asyncio.sleep(3600)
+
+ return StreamingResponse(
+ _sse_keepalive(),
+ media_type="text/event-stream",
+ headers={"cache-control": "no-cache", "connection": "keep-alive"},
+ )
+
+
+@router.delete("/internal/mcp/knowledge")
+async def knowledge_mcp_delete(token: str = Query(...)) -> Response:
+ from octop.infra.agents.acp.turn import knowledge_scope
+
+ if knowledge_scope(token) is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ return Response(status_code=204)
+
+
+@router.post("/internal/mcp/agents")
+async def agents_mcp_post(
+ request: Request,
+ token: str = Query(...),
+ server: Any = Depends(get_server),
+) -> Response:
+ """Let a managed runner call another expert with ``ask_agent``."""
+ from octop.infra.agents.acp.agents_mcp import handle_agents_mcp
+ from octop.infra.agents.acp.delegation import agent_scope
+
+ scope = agent_scope(token)
+ if scope is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ registry = server.app_runtime.agent_registry
+ team = getattr(getattr(registry, "_harness_manager", None), "team", None)
+ if team is None:
+ raise OctopError(ErrorCode.NOT_FOUND, "expert calls are not available")
+ try:
+ body = await request.json()
+ except json.JSONDecodeError as exc:
+ raise OctopError(ErrorCode.CONNECTOR_INVALID_CREDENTIALS, "invalid JSON body") from exc
+ if not isinstance(body, dict):
+ raise OctopError(ErrorCode.CONNECTOR_INVALID_CREDENTIALS, "expected JSON object")
+
+ method = str(body.get("method") or "")
+ if method == "notifications/initialized":
+ return Response(status_code=202)
+ session_id = request.headers.get(MCP_SESSION_HEADER)
+ if method == "initialize":
+ session_id = secrets.token_urlsafe(16)
+ resp = await handle_agents_mcp(body, scope=scope, team=team)
+ return _mcp_json(request, body, resp, session_id=session_id)
+
+
+@router.get("/internal/mcp/agents")
+async def agents_mcp_get(request: Request, token: str = Query(...)) -> Response:
+ from octop.infra.agents.acp.delegation import agent_scope
+
+ if agent_scope(token) is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ if not request.headers.get(MCP_SESSION_HEADER):
+ return JSONResponse(status_code=405, content={"error": "missing mcp-session-id"})
+
+ async def _sse_keepalive() -> Any:
+ yield "event: message\ndata: \n\n"
+ while True:
+ await asyncio.sleep(3600)
+
+ return StreamingResponse(
+ _sse_keepalive(),
+ media_type="text/event-stream",
+ headers={"cache-control": "no-cache", "connection": "keep-alive"},
+ )
+
+
+@router.delete("/internal/mcp/agents")
+async def agents_mcp_delete(token: str = Query(...)) -> Response:
+ from octop.infra.agents.acp.delegation import agent_scope
+
+ if agent_scope(token) is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ return Response(status_code=204)
+
+
+def _mcp_keepalive(request: Request, *, authorized: bool) -> Response:
+ if not authorized:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ if not request.headers.get(MCP_SESSION_HEADER):
+ return JSONResponse(status_code=405, content={"error": "missing mcp-session-id"})
+
+ async def _sse_keepalive() -> Any:
+ yield "event: message\ndata: \n\n"
+ while True:
+ await asyncio.sleep(3600)
+
+ return StreamingResponse(
+ _sse_keepalive(),
+ media_type="text/event-stream",
+ headers={"cache-control": "no-cache", "connection": "keep-alive"},
+ )
+
+
+async def _mcp_body(request: Request) -> dict[str, Any]:
+ try:
+ body = await request.json()
+ except json.JSONDecodeError as exc:
+ raise OctopError(ErrorCode.CONNECTOR_INVALID_CREDENTIALS, "invalid JSON body") from exc
+ if not isinstance(body, dict):
+ raise OctopError(ErrorCode.CONNECTOR_INVALID_CREDENTIALS, "expected JSON object")
+ return body
+
+
+def _mcp_session(request: Request, body: dict[str, Any]) -> str | None:
+ session_id = request.headers.get(MCP_SESSION_HEADER)
+ if str(body.get("method") or "") == "initialize":
+ return secrets.token_urlsafe(16)
+ return session_id
+
+
+@router.post("/internal/mcp/cron")
+async def cron_mcp_post(
+ request: Request,
+ token: str = Query(...),
+ server: Any = Depends(get_server),
+) -> Response:
+ """Let a managed runner manage this expert's scheduled jobs."""
+ from octop.infra.agents.acp.cron_mcp import cron_scope, handle_cron_mcp
+
+ scope = cron_scope(token)
+ if scope is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ body = await _mcp_body(request)
+ if str(body.get("method") or "") == "notifications/initialized":
+ return Response(status_code=202)
+ registry = server.app_runtime.agent_registry
+ resp = await handle_cron_mcp(body, scope=scope, cron_manager=registry._cron_manager)
+ return _mcp_json(request, body, resp, session_id=_mcp_session(request, body))
+
+
+@router.get("/internal/mcp/cron")
+async def cron_mcp_get(request: Request, token: str = Query(...)) -> Response:
+ from octop.infra.agents.acp.cron_mcp import cron_scope
+
+ return _mcp_keepalive(request, authorized=cron_scope(token) is not None)
+
+
+@router.delete("/internal/mcp/cron")
+async def cron_mcp_delete(token: str = Query(...)) -> Response:
+ from octop.infra.agents.acp.cron_mcp import cron_scope
+
+ if cron_scope(token) is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ return Response(status_code=204)
+
+
+def _memory_service(registry: Any, agent_id: str) -> Any:
+ try:
+ agent = registry.get_agent(agent_id)
+ except Exception:
+ return None
+ runtime = getattr(agent, "_memory_runtime", None)
+ return getattr(runtime, "service", None)
+
+
+@router.post("/internal/mcp/memory")
+async def memory_mcp_post(
+ request: Request,
+ token: str = Query(...),
+ server: Any = Depends(get_server),
+) -> Response:
+ """Let a managed runner search and save memory when this expert has it on."""
+ from octop.infra.agents.acp.memory_mcp import handle_memory_mcp, memory_scope
+
+ scope = memory_scope(token)
+ if scope is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ body = await _mcp_body(request)
+ if str(body.get("method") or "") == "notifications/initialized":
+ return Response(status_code=202)
+ registry = server.app_runtime.agent_registry
+ resp = await handle_memory_mcp(
+ body,
+ service=_memory_service(registry, scope.agent_id),
+ tools_allowed=scope.tools,
+ )
+ return _mcp_json(request, body, resp, session_id=_mcp_session(request, body))
+
+
+@router.get("/internal/mcp/memory")
+async def memory_mcp_get(request: Request, token: str = Query(...)) -> Response:
+ from octop.infra.agents.acp.memory_mcp import memory_scope
+
+ return _mcp_keepalive(request, authorized=memory_scope(token) is not None)
+
+
+@router.delete("/internal/mcp/memory")
+async def memory_mcp_delete(token: str = Query(...)) -> Response:
+ from octop.infra.agents.acp.memory_mcp import memory_scope
+
+ if memory_scope(token) is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ return Response(status_code=204)
+
+
+@router.post("/internal/mcp/plugins")
+async def plugins_mcp_post(
+ request: Request,
+ token: str = Query(...),
+ server: Any = Depends(get_server),
+) -> Response:
+ """Let a managed runner call the plugin tools enabled for this expert."""
+ from octop.infra.agents.acp.plugins_mcp import (
+ handle_plugins_mcp,
+ plugin_scope,
+ plugin_tool_configs,
+ plugin_tools,
+ )
+
+ scope = plugin_scope(token)
+ if scope is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ body = await _mcp_body(request)
+ if str(body.get("method") or "") == "notifications/initialized":
+ return Response(status_code=202)
+ registry = server.app_runtime.agent_registry
+ config = registry.get_config(scope.agent_id)
+ resp = await handle_plugins_mcp(
+ body,
+ tools=plugin_tools(registry, config),
+ tool_configs=plugin_tool_configs(config),
+ )
+ return _mcp_json(request, body, resp, session_id=_mcp_session(request, body))
+
+
+@router.get("/internal/mcp/plugins")
+async def plugins_mcp_get(request: Request, token: str = Query(...)) -> Response:
+ from octop.infra.agents.acp.plugins_mcp import plugin_scope
+
+ return _mcp_keepalive(request, authorized=plugin_scope(token) is not None)
+
+
+@router.delete("/internal/mcp/plugins")
+async def plugins_mcp_delete(token: str = Query(...)) -> Response:
+ from octop.infra.agents.acp.plugins_mcp import plugin_scope
+
+ if plugin_scope(token) is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ return Response(status_code=204)
+
+
+@router.post("/internal/mcp/files")
+async def files_mcp_post(
+ request: Request,
+ token: str = Query(...),
+ server: Any = Depends(get_server),
+) -> Response:
+ """Let a managed runner deliver a workspace file with ``send_file_to_user``."""
+ from octop.infra.agents.acp.files_mcp import file_scope, handle_files_mcp
+
+ scope = file_scope(token)
+ if scope is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ try:
+ body = await request.json()
+ except json.JSONDecodeError as exc:
+ raise OctopError(ErrorCode.CONNECTOR_INVALID_CREDENTIALS, "invalid JSON body") from exc
+ if not isinstance(body, dict):
+ raise OctopError(ErrorCode.CONNECTOR_INVALID_CREDENTIALS, "expected JSON object")
+
+ method = str(body.get("method") or "")
+ if method == "notifications/initialized":
+ return Response(status_code=202)
+ session_id = request.headers.get(MCP_SESSION_HEADER)
+ if method == "initialize":
+ session_id = secrets.token_urlsafe(16)
+ registry = server.app_runtime.agent_registry
+ workspace = await asyncio.to_thread(registry.workspace_for_agent, scope.agent_id)
+ if workspace is None:
+ raise OctopError(ErrorCode.NOT_FOUND, "expert workspace is not available")
+ resp = await handle_files_mcp(body, workspace=workspace)
+ return _mcp_json(request, body, resp, session_id=session_id)
+
+
+@router.get("/internal/mcp/files")
+async def files_mcp_get(request: Request, token: str = Query(...)) -> Response:
+ from octop.infra.agents.acp.files_mcp import file_scope
+
+ if file_scope(token) is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ if not request.headers.get(MCP_SESSION_HEADER):
+ return JSONResponse(status_code=405, content={"error": "missing mcp-session-id"})
+
+ async def _sse_keepalive() -> Any:
+ yield "event: message\ndata: \n\n"
+ while True:
+ await asyncio.sleep(3600)
+
+ return StreamingResponse(
+ _sse_keepalive(),
+ media_type="text/event-stream",
+ headers={"cache-control": "no-cache", "connection": "keep-alive"},
+ )
+
+
+@router.delete("/internal/mcp/files")
+async def files_mcp_delete(token: str = Query(...)) -> Response:
+ from octop.infra.agents.acp.files_mcp import file_scope
+
+ if file_scope(token) is None:
+ raise OctopError(ErrorCode.AUTH_FAILED, "invalid internal token")
+ return Response(status_code=204)
diff --git a/src/octop/api/routers/managed.py b/src/octop/api/routers/managed.py
index 5658a8a965..96e5e60e8e 100644
--- a/src/octop/api/routers/managed.py
+++ b/src/octop/api/routers/managed.py
@@ -10,6 +10,10 @@
from octop.api.common.agent import apply_agent_audience
from octop.api.deps import current_user, get_server
from octop.api.routers.agents import _row_dict
+from octop.infra.agents.acp.session_modes import (
+ approval_for_session,
+ resolve_managed_session_mode,
+)
from octop.infra.agents.experts.composer_files import (
apply_composer_workspace_patch,
composer_patch_from_payload,
@@ -66,6 +70,15 @@ class ManagedCreateBody(BaseModel):
group_ids: list[str] | None = None
quick_prompts: list[_QuickPromptBody] | None = None
file_overrides: list[_FileOverrideBody] | None = None
+ skill_package_ids: list[str] | None = None
+ knowledge_base_ids: list[str] | None = None
+ mcp_servers: list[str] | None = None
+ permission_mode: Literal["ask", "yolo"] = "ask"
+ session_mode: str | None = Field(
+ default=None,
+ max_length=64,
+ description="Default ACP session mode id, such as plan or bypassPermissions.",
+ )
def _prompt_dict(prompt: _QuickPromptBody) -> dict[str, Any]:
@@ -138,7 +151,34 @@ async def create_managed_agent(
"""
runner = body.runner.strip()
_enabled_runner(server, user.id, runner)
- config: dict[str, Any] = {"managed_runner": runner}
+ assert server.app_runtime is not None
+ registry = server.app_runtime.agent_registry
+ package_ids = (
+ registry.validate_skill_package_ids(body.skill_package_ids)
+ if body.skill_package_ids is not None
+ else None
+ )
+ knowledge_ids = (
+ registry.validate_knowledge_base_ids(user.id, body.knowledge_base_ids)
+ if body.knowledge_base_ids is not None
+ else None
+ )
+ mcp_servers = (
+ registry.validate_mcp_servers(user.id, body.mcp_servers)
+ if body.mcp_servers is not None
+ else None
+ )
+ session_mode = resolve_managed_session_mode(explicit=body.session_mode)
+ config: dict[str, Any] = {
+ "managed_runner": runner,
+ "managed_permission_mode": approval_for_session(
+ session_mode,
+ body.permission_mode,
+ runner=runner,
+ ),
+ }
+ if session_mode:
+ config["managed_session_mode"] = session_mode
apply_enable_trajectory(config, body.enable_trajectory)
apply_managed_backend(config)
pin_managed_runtime(config)
@@ -155,10 +195,11 @@ async def create_managed_agent(
icon_url=(body.icon_url or "").strip() or None,
kind=MANAGED_KIND,
config=config,
- mcp_servers=[],
+ skill_package_ids=package_ids,
+ knowledge_base_ids=knowledge_ids,
+ mcp_servers=mcp_servers if mcp_servers is not None else [],
)
- assert server.app_runtime is not None
- row = await server.app_runtime.agent_registry.create(
+ row = await registry.create(
spec,
workspace_initializer=_workspace_initializer(body),
)
diff --git a/src/octop/cli/commands/chats.py b/src/octop/cli/commands/chats.py
index 74d1de0e53..ef6c069f99 100644
--- a/src/octop/cli/commands/chats.py
+++ b/src/octop/cli/commands/chats.py
@@ -220,32 +220,58 @@ def gc_orphans(agent_id: str | None, yes: bool) -> None:
"""Report checkpoint rows whose thread was already removed.
Without ``--yes`` this only prints the orphans. With ``--yes`` it
- deletes them from each agent's memory store.
+ deletes them from SQLite memory stores. PostgreSQL checkpoints are only
+ reported: their tables are shared and record no owner.
"""
- from octop.cli.support.db import open_cli_services
+ from octop.cli.support.db import open_cli_services, resolve_cli_locale
+ from octop.i18n import tr
from octop.infra.agents.memory.thread_cleanup import gc_orphan_checkpoints
from octop.infra.errors import OctopError
try:
with open_cli_services(None) as svc:
- orphans = gc_orphan_checkpoints(svc, agent_id=agent_id, apply=yes)
+ scan = gc_orphan_checkpoints(svc, agent_id=agent_id, apply=yes)
except OctopError as exc:
raise click.ClickException(exc.message) from exc
+ orphans = scan.orphans
payload = [
{"agent_id": item.agent_id, "thread_id": item.thread_id, "bytes": item.nbytes}
for item in orphans
]
if json_output_enabled():
- click.echo(_json.dumps({"deleted": yes, "orphans": payload}, indent=2))
+ skipped = [
+ {
+ "agent_id": kept.agent_id,
+ "reason": kept.reason,
+ "threads": kept.threads,
+ "bytes": kept.nbytes,
+ }
+ for kept in scan.skipped
+ ]
+ click.echo(_json.dumps({"deleted": yes, "orphans": payload, "skipped": skipped}, indent=2))
return
+ locale = resolve_cli_locale()
+ for kept in scan.skipped:
+ if kept.reason == "external_database":
+ click.echo(tr("threads.gc_kept_external", locale, agent=kept.agent_id))
+ else:
+ click.echo(
+ tr(
+ "threads.gc_kept_postgres",
+ locale,
+ agent=kept.agent_id,
+ threads=kept.threads,
+ bytes=kept.nbytes,
+ )
+ )
if not payload:
- click.echo("no orphan checkpoints")
+ click.echo(tr("threads.gc_none", locale))
return
total = sum(item.nbytes for item in orphans)
for item in orphans:
click.echo(f"{item.agent_id} {item.thread_id} {item.nbytes}")
- verb = "deleted" if yes else "would delete"
- click.echo(f"{verb} {len(payload)} orphan thread(s), {total} bytes")
+ key = "threads.gc_deleted" if yes else "threads.gc_would_delete"
+ click.echo(tr(key, locale, count=len(payload), bytes=total))
@chats.command("send")
diff --git a/src/octop/cli/commands/memory.py b/src/octop/cli/commands/memory.py
index 9a838bb3f0..99676b9a91 100644
--- a/src/octop/cli/commands/memory.py
+++ b/src/octop/cli/commands/memory.py
@@ -16,6 +16,7 @@
list_orphan_agent_dirs,
request_memory_slim,
)
+from octop.infra.agents.memory.thread_cleanup import describe_sweep
from octop.infra.utils.paths import PathLayout
@@ -109,15 +110,7 @@ def _slim_agent(
if status.get("phase") == "done":
sweep = status.get("sweep")
if isinstance(sweep, dict):
- click.echo(
- tr(
- "memory_slim.swept",
- locale,
- namespaces=sweep.get("namespaces", 0),
- threads=sweep.get("threads", 0),
- directories=sweep.get("directories", 0),
- )
- )
+ click.echo(describe_sweep(sweep, locale))
report = status.get("report")
if isinstance(report, dict) and "before" in report:
click.echo(
diff --git a/src/octop/i18n/domains/stream.py b/src/octop/i18n/domains/stream.py
index 7afd627920..51cc059f1f 100644
--- a/src/octop/i18n/domains/stream.py
+++ b/src/octop/i18n/domains/stream.py
@@ -26,6 +26,11 @@
INSUFFICIENT_BALANCE = f"{_PREFIX}stream_errors.insufficient_balance"
CONTEXT_LENGTH = f"{_PREFIX}stream_errors.context_length"
RECURSION_LIMIT = f"{_PREFIX}stream_errors.recursion_limit"
+TOOL_CALL_REPEAT = f"{_PREFIX}stream_errors.tool_call_repeat"
+_TOOL_CALL_REPEAT_RE = re.compile(
+ r"\[tool_call_repeat\]\s*tool:\s*(?P.+)\ncount:\s*(?P\d+)\nlimit:\s*(?P\d+)",
+ re.IGNORECASE,
+)
TIMEOUT_NETWORK = f"{_PREFIX}stream_errors.timeout_network"
PROVIDER_UNAVAILABLE = f"{_PREFIX}stream_errors.provider_unavailable"
MODEL_CALL_FAILED = f"{_PREFIX}stream_errors.model_call_failed"
@@ -43,9 +48,11 @@
"PROVIDER_UNAVAILABLE",
"RATE_LIMIT",
"RECURSION_LIMIT",
+ "TOOL_CALL_REPEAT",
"STREAM_STALL",
"TIMEOUT_NETWORK",
"classify_stream_error_message",
+ "tool_call_repeat_vars",
"exception_display_message",
"format_stream_error",
"model_retry_failure_prompt",
@@ -100,8 +107,22 @@ def unwrap_model_retry_message(message: str) -> str:
return stripped or msg
+def tool_call_repeat_vars(message: str) -> dict[str, str] | None:
+ """Parse the consecutive-call marker emitted by the limit middleware."""
+ match = _TOOL_CALL_REPEAT_RE.search(message)
+ if match is None:
+ return None
+ return {
+ "tool": match.group("tool").strip(),
+ "count": match.group("count"),
+ "limit": match.group("limit"),
+ }
+
+
def classify_stream_error_message(message: str) -> str | None:
"""Return a stable ``octop:stream_errors.*`` key for known model failures."""
+ if tool_call_repeat_vars(message) is not None:
+ return TOOL_CALL_REPEAT
msg = unwrap_model_retry_message(message)
if not msg:
return None
@@ -235,6 +256,14 @@ def exception_display_message(exc: BaseException | str) -> str:
return f"{type(exc).__name__} <- {type(cause).__name__}"
+def _localized_classified(classified: str, source: str, locale: str | Locale) -> str:
+ key = classified.removeprefix(_PREFIX)
+ if classified == TOOL_CALL_REPEAT:
+ fields = tool_call_repeat_vars(source) or {}
+ return _format_template(key, locale, **fields)
+ return tr(key, locale)
+
+
def stream_error_message(error: str | None, locale: str | Locale = "en") -> str:
"""Localized stream / model error for user-facing chat and IM output."""
if not error:
@@ -245,7 +274,7 @@ def stream_error_message(error: str | None, locale: str | Locale = "en") -> str:
return tr(key, locale)
classified = classify_stream_error_message(error)
if classified is not None:
- return tr(classified.removeprefix(_PREFIX), locale)
+ return _localized_classified(classified, error, locale)
return error
@@ -279,7 +308,7 @@ def format_stream_error(exc: BaseException | str, locale: str | Locale = "en") -
inner = unwrap_model_retry_message(message)
classified = classify_stream_error_message(inner)
if classified is not None and classified != MODEL_CALL_FAILED:
- return tr(classified.removeprefix(_PREFIX), locale)
+ return _localized_classified(classified, inner, locale)
if _looks_like_send_file_tool_error(message) or _looks_like_send_file_tool_error(inner):
return message if _looks_like_send_file_tool_error(message) else inner
if inner:
diff --git a/src/octop/i18n/en.json b/src/octop/i18n/en.json
index db75648bec..a38228ef7c 100644
--- a/src/octop/i18n/en.json
+++ b/src/octop/i18n/en.json
@@ -487,7 +487,7 @@
"SKILL_PACKAGE_NOT_FOUND": "Skill package not found.",
"SKILL_PACKAGE_NAME_TAKEN": "Skill package {name} already exists.",
"SKILL_PACKAGE_BACKEND_UNSUPPORTED": "Skill packages currently support only “Full local environment (filesystem + shell)” or “Local filesystem (no shell commands)”, with storage root / (POSIX) or the agent workspace root (Windows default).",
- "ACP_BACKEND_UNSUPPORTED": "This agent has a sandbox enabled, so external runners can’t be enabled or edited here. The outbound acp_runner tool toggle is unaffected; connecting via IDE / octop acp is also unaffected.",
+ "ACP_BACKEND_UNSUPPORTED": "This agent has a sandbox enabled, so external agents can’t be enabled or edited here. External agent collaboration for this expert is unaffected; connecting via IDE / octop acp is also unaffected.",
"PUBLISHED_EXPERT_SLUG_TAKEN": "Published expert slug {slug} already exists.",
"PUBLISHED_EXPERT_ALREADY_EXISTS": "This agent is already published as “{name}”. Refresh the published template instead.",
"OIDC_BAD_REQUEST": "Invalid OIDC request: {detail}",
@@ -667,7 +667,7 @@
"ask_agent": "Ask expert",
"call_agent": "Call expert",
"call_deferred_tool": "Call on demand",
- "acp_runner": "ACP external agent",
+ "acp_runner": "External agent collaboration",
"external-agent": "Managed agent",
"browser_use": "Use browser",
"browser_control": "Browser control",
@@ -764,6 +764,11 @@
}
},
"threads": {
+ "gc_kept_postgres": "Kept {threads} orphan checkpoint threads of {agent} ({bytes} bytes): PostgreSQL checkpoints are reported only, not deleted.",
+ "gc_kept_external": "Did not scan {agent}: its memory is in an external PostgreSQL database.",
+ "gc_none": "No deletable orphan checkpoints.",
+ "gc_would_delete": "Would delete {count} orphan threads, {bytes} bytes.",
+ "gc_deleted": "Deleted {count} orphan threads, {bytes} bytes.",
"fork_title_suffix": " (fork)",
"fork_default_title": "Forked chat"
},
@@ -802,6 +807,7 @@
"insufficient_balance": "The model provider rejected this request due to insufficient balance or quota. Top up or upgrade the plan for this API key, then try again.",
"context_length": "This conversation is too long for the model's context window. Start a new chat, or shorten the history and try again.",
"recursion_limit": "The agent hit its max iteration / recursion limit before finishing. Open Configuration and raise Max Iterations, then try again.",
+ "tool_call_repeat": "\"{tool}\" was called {count} times in a row with the same arguments and reached the limit of {limit}, so this turn stopped. Try a different approach, or open Configuration, raise Repeated calls in a row, and reload the expert.",
"timeout_network": "Connecting to the model timed out or the network failed. Check your network and retry. If you use a proxy or self-hosted endpoint, confirm it is reachable.",
"provider_unavailable": "The model provider is temporarily unavailable. Retry later, or switch to another model.",
"invalid_request": "The model rejected this request as invalid. Strict OpenAI-compatible endpoints (for example Huawei MindIE) often reject extra fields such as stream_options. Custom providers now omit streamed usage by default; if it still fails, check whether the model supports tool calling. The full error is in the server log.",
@@ -937,6 +943,8 @@
}
},
"memory_slim": {
+ "postgres_kept": "PostgreSQL leftovers are counted only, not deleted: {threads} checkpoint threads with no conversation, {namespaces} memory namespaces with no agent.",
+ "skipped_databases": "Skipped {count} external PostgreSQL memory databases: they may be shared with other installs.",
"waiting": "Waiting for the current task to finish…",
"backing_up": "Backing up memory…",
"sweeping": "Removing leftovers from deleted agents and conversations…",
@@ -990,6 +998,7 @@
"channel_line": "{name}: {text}",
"channel_wrapup": "[Host wrap-up] {text}",
"channel_dispatched": "Asked {name} to handle this — please wait…",
+ "connector_auth_skipped": "These connectors need re-authorization and were left off this turn: {servers}",
"host_briefing": "[Host dispatch — do not do the work yourself]\nUser messages arrive here first. Digest intent, scope, constraints, and the deliverable; ask one clarifying question if a key fact is missing. For real work, rewrite a self-contained assignment for that member before ask_agent: goal, scope, delivery format, and needed context. Never paste the user's wording unchanged. Tailor each member's task. Answer greetings or clarifications yourself in one or two sentences. After ask_agent returns, do not repeat that you assigned someone. If this turn is a member-finished wake-up, wrap up or reassign per that notice — do not repeat the same task.",
"member_briefing": "[Team assignment, not a direct user question]\nYou are a member of this expert team. The host has already processed the user's request and assigned you this task. Do the work and deliver the result. Do not treat the user's original wording as a one-to-one question to you, and do not speak as the host.",
"member_briefing_with_history": "[Team assignment, not a direct user question]\nYou are a member of this expert team. The host has already processed the user's request and assigned you this task. Do the work and deliver the result. Do not treat the user's original wording as a one-to-one question to you, and do not speak as the host. The group transcript below is background only.\n\n{history}"
diff --git a/src/octop/i18n/zh.json b/src/octop/i18n/zh.json
index ab7bc10d21..cbea5a2f2b 100644
--- a/src/octop/i18n/zh.json
+++ b/src/octop/i18n/zh.json
@@ -487,7 +487,7 @@
"SKILL_PACKAGE_NOT_FOUND": "未找到技能包。",
"SKILL_PACKAGE_NAME_TAKEN": "技能包 {name} 已存在。",
"SKILL_PACKAGE_BACKEND_UNSUPPORTED": "技能包目前仅支持「本地完整环境(文件系统+指令执行)」或「本地文件系统(不能执行指令)」,且存储根目录须为 /(POSIX)或专家的工作区根目录(Windows 默认)。",
- "ACP_BACKEND_UNSUPPORTED": "当前专家已启用沙箱环境,不可启用或编辑外部 Runner。启用向外委托(acp_runner)不受影响;通过 IDE / octop acp 接入也不受影响。",
+ "ACP_BACKEND_UNSUPPORTED": "当前专家已启用沙箱环境,不可启用或编辑外部智能体。在当前专家中启用外部智能体协作不受影响;通过 IDE / octop acp 接入也不受影响。",
"PUBLISHED_EXPERT_SLUG_TAKEN": "已存在发布专家 slug:{slug}。",
"PUBLISHED_EXPERT_ALREADY_EXISTS": "该专家已发布为「{name}」,请改为刷新已发布模板。",
"OIDC_BAD_REQUEST": "OIDC 请求无效:{detail}",
@@ -667,7 +667,7 @@
"ask_agent": "咨询专家",
"call_agent": "调用专家",
"call_deferred_tool": "按需调用",
- "acp_runner": "ACP 外部 Agent",
+ "acp_runner": "外部智能体协作",
"external-agent": "托管智能体",
"browser_use": "使用浏览器",
"browser_control": "浏览器控制",
@@ -764,6 +764,11 @@
}
},
"threads": {
+ "gc_kept_postgres": "保留了 {agent} 的 {threads} 个孤儿检查点会话({bytes} 字节):PostgreSQL 上的检查点只报告、不删除。",
+ "gc_kept_external": "没有扫描 {agent}:它的记忆在外部 PostgreSQL 库里。",
+ "gc_none": "没有可删除的孤儿检查点。",
+ "gc_would_delete": "将删除 {count} 个孤儿会话,共 {bytes} 字节。",
+ "gc_deleted": "已删除 {count} 个孤儿会话,共 {bytes} 字节。",
"fork_title_suffix": "(分叉)",
"fork_default_title": "分叉对话"
},
@@ -802,6 +807,7 @@
"insufficient_balance": "模型服务返回余额或额度不足。请为该 API Key 对应的账户充值或升级套餐后再试。",
"context_length": "对话上下文过长,超出模型限制。请新开会话,或精简历史后再试。",
"recursion_limit": "智能体已达到最大迭代次数(递归上限),任务尚未完成。请前往「运行配置」调高「最大迭代次数」后重试。",
+ "tool_call_repeat": "工具「{tool}」带着相同参数已连续调用 {count} 次,达到上限 {limit},本轮已停止。请换一种做法,或前往「运行配置」调高「连续相同调用上限」,保存后重新加载该专家。",
"timeout_network": "连接模型服务超时或网络异常。请检查网络后重试;若使用代理或自建服务,请确认其可达。",
"provider_unavailable": "模型服务暂时不可用。请稍后重试,或切换其他模型。",
"invalid_request": "模型接口拒绝了本次请求参数。华为 MindIE 等严格的 OpenAI 兼容服务通常不接受 stream_options 等扩展字段。自定义供应商现已默认关闭流式用量;若仍失败,请确认该模型是否支持工具调用。完整错误已写入服务端日志。",
@@ -937,6 +943,8 @@
}
},
"memory_slim": {
+ "postgres_kept": "PostgreSQL 上的残留只统计、不删除:没有对应会话的检查点会话 {threads} 个,没有对应专家的记忆命名空间 {namespaces} 个。",
+ "skipped_databases": "跳过了 {count} 个外部 PostgreSQL 记忆库:它们可能和其他安装共用。",
"waiting": "等待当前任务结束…",
"backing_up": "正在备份记忆库…",
"sweeping": "正在清理已删除专家和会话的残留…",
@@ -990,6 +998,7 @@
"channel_line": "{name}: {text}",
"channel_wrapup": "【主持人总结】{text}",
"channel_dispatched": "已请 {name} 处理,请稍候…",
+ "connector_auth_skipped": "以下连接器需要重新授权,本轮未使用:{servers}",
"host_briefing": "[主持人调度,不是让你代答]\n用户消息先到你这里。先消化意图、范围、约束和交付物;缺关键信息就先问一句,不要空派。专业工作必须改写成给该成员的任务说明书后再 ask_agent:写清目标、范围、交付格式和必要上下文,禁止原样转发用户原话。不同成员给不同任务。寒暄或澄清自己短答。ask_agent 返回后不要重复「已安排 / 稍等」。若当前是成员完成或失败的系统唤醒,按唤醒说明收口或改派,不要重复同一任务。",
"member_briefing": "[团队派工,不是用户在直接问你]\n你是这个专家团队的成员。主持人已消化用户问题,并为你分配了本次任务。请按任务执行并直接给出成果;不要把用户原话当成对你的一对一提问,也不要复述或扮演主持人。",
"member_briefing_with_history": "[团队派工,不是用户在直接问你]\n你是这个专家团队的成员。主持人已消化用户问题,并为你分配了本次任务。请按任务执行并直接给出成果;不要把用户原话当成对你的一对一提问,也不要复述或扮演主持人。下面的群聊记录只作背景。\n\n{history}"
diff --git a/src/octop/infra/agents/acp/__init__.py b/src/octop/infra/agents/acp/__init__.py
new file mode 100644
index 0000000000..bc708489a9
--- /dev/null
+++ b/src/octop/infra/agents/acp/__init__.py
@@ -0,0 +1,18 @@
+"""Host-side ACP wiring for managed experts.
+
+Protocol conversion and session attach live in octop-harness. This package
+decides which MCP servers a managed turn adds, and keeps the chat cards aligned
+with native file edits.
+"""
+
+from octop.infra.agents.acp.file_edits import install_acp_file_edits
+from octop.infra.agents.acp.permissions import install_acp_permission_queue
+from octop.infra.agents.acp.tool_names import install_acp_tool_titles
+from octop.infra.agents.acp.turn import attach_managed_turn
+
+__all__ = [
+ "attach_managed_turn",
+ "install_acp_file_edits",
+ "install_acp_permission_queue",
+ "install_acp_tool_titles",
+]
diff --git a/src/octop/infra/agents/acp/agents_mcp.py b/src/octop/infra/agents/acp/agents_mcp.py
new file mode 100644
index 0000000000..6f51496ea2
--- /dev/null
+++ b/src/octop/infra/agents/acp/agents_mcp.py
@@ -0,0 +1,133 @@
+"""Loopback MCP so a managed runner can call ``ask_agent`` like a native expert."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from octop.infra.agents.acp.delegation import AgentScope
+
+_PROTOCOL = "2024-11-05"
+
+_ASK = {
+ "name": "ask_agent",
+ "description": (
+ "Ask another expert and wait for the answer. "
+ "When the user writes @Name, call this with expert set to that name "
+ "and do not answer in their place."
+ ),
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "expert": {"type": "string", "description": "Expert name from the user's @mention."},
+ "message": {"type": "string", "description": "What to ask that expert."},
+ },
+ "required": ["expert", "message"],
+ },
+}
+
+_LIST = {
+ "name": "agent_list",
+ "description": "List other experts the current user can call by name.",
+ "inputSchema": {"type": "object", "properties": {}},
+}
+
+
+def _ok(req_id: Any, result: dict[str, Any]) -> dict[str, Any]:
+ if req_id is None:
+ return {}
+ return {"jsonrpc": "2.0", "id": req_id, "result": result}
+
+
+def _err(req_id: Any, code: int, message: str) -> dict[str, Any]:
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
+
+
+def _arguments(params: Any) -> dict[str, Any]:
+ if not isinstance(params, dict):
+ return {}
+ raw = params.get("arguments") or {}
+ if not isinstance(raw, dict):
+ return {}
+ nested = raw.get("kwargs")
+ if nested is not None and set(raw.keys()) == {"kwargs"} and isinstance(nested, dict):
+ return nested
+ return raw
+
+
+def _text_result(req_id: Any, text: str, *, failed: bool = False) -> dict[str, Any]:
+ return _ok(req_id, {"content": [{"type": "text", "text": text}], "isError": failed})
+
+
+def _peer_lines(team: Any, scope: AgentScope) -> str:
+ from octop_harness.teams.team_manager import TeamManager
+
+ peers = team.list_peers(scope.user_id, exclude_agent_id=scope.from_agent_id)
+ lines: list[str] = []
+ for entry in peers:
+ name = TeamManager.peer_display_name(entry)
+ description = str((entry.metadata or {}).get("description") or "").strip()
+ lines.append(f"- {name}: {description}" if description else f"- {name}")
+ return "\n".join(lines) if lines else "No other experts are available."
+
+
+async def handle_agents_mcp(
+ body: dict[str, Any],
+ *,
+ scope: AgentScope,
+ team: Any,
+) -> dict[str, Any]:
+ """Answer one JSON-RPC request. An empty dict means the caller should return 202."""
+ method = str(body.get("method") or "")
+ req_id = body.get("id")
+ params = body.get("params") or {}
+
+ if method == "initialize":
+ return _ok(
+ req_id,
+ {
+ "protocolVersion": _PROTOCOL,
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "octop-agents", "version": "0.1.0"},
+ },
+ )
+ if method == "notifications/initialized":
+ return {}
+ if method == "tools/list":
+ allowed = set(scope.tools)
+ cards = [card for card in (_LIST, _ASK) if card["name"] in allowed]
+ return _ok(req_id, {"tools": cards})
+ if method == "ping":
+ return _ok(req_id, {})
+ if method != "tools/call":
+ return _err(req_id, -32601, f"Method not found: {method}")
+
+ arguments = _arguments(params)
+ name = str(params.get("name") or "") if isinstance(params, dict) else ""
+ if name not in set(scope.tools):
+ return _text_result(req_id, f"Unknown tool: {name}", failed=True)
+ if name == "agent_list":
+ return _text_result(req_id, _peer_lines(team, scope))
+ if name != "ask_agent":
+ return _text_result(req_id, f"Unknown tool: {name}", failed=True)
+
+ expert = str(arguments.get("expert") or "").strip().lstrip("@")
+ message = str(arguments.get("message") or "").strip()
+ if not expert or not message:
+ return _text_result(req_id, "expert and message are required.", failed=True)
+ entry = team.resolve_peer(scope.user_id, expert, exclude_agent_id=scope.from_agent_id)
+ if entry is None:
+ return _text_result(req_id, f"expert not found: {expert}", failed=True)
+ try:
+ result = await team.call_peer(
+ from_agent_id=scope.from_agent_id,
+ to_agent_id=entry.agent_id,
+ message=message,
+ user_id=scope.user_id,
+ source_thread_id=scope.thread_id or None,
+ session_key=scope.session_key or None,
+ )
+ except Exception as exc:
+ return _text_result(req_id, f"ask_agent failed: {exc}", failed=True)
+ answer = str(getattr(result, "response", "") or "").strip() or "No answer."
+ who = str(getattr(result, "name", "") or expert)
+ return _text_result(req_id, f"{who}: {answer}")
diff --git a/src/octop/infra/agents/acp/cron_mcp.py b/src/octop/infra/agents/acp/cron_mcp.py
new file mode 100644
index 0000000000..72a4a8bdd6
--- /dev/null
+++ b/src/octop/infra/agents/acp/cron_mcp.py
@@ -0,0 +1,65 @@
+"""Loopback MCP for the cron tools a native expert already has."""
+
+from __future__ import annotations
+
+import secrets
+from dataclasses import dataclass
+from typing import Any
+
+from octop.infra.agents.acp.mcp_tools import dispatch
+
+_SCOPES: dict[str, CronScope] = {}
+_TOKENS: dict[tuple[int, str, str, str, tuple[str, ...]], str] = {}
+
+
+@dataclass(frozen=True)
+class CronScope:
+ user_id: int
+ agent_id: str
+ thread_id: str
+ session_key: str
+ tools: tuple[str, ...] = ()
+
+
+def cron_scope(token: str) -> CronScope | None:
+ return _SCOPES.get(token)
+
+
+def retain_cron_scope(scope: CronScope) -> str:
+ """Reuse one token per expert, conversation, and enabled tool set."""
+ key = (scope.user_id, scope.agent_id, scope.thread_id, scope.session_key, scope.tools)
+ token = _TOKENS.get(key)
+ if token is None:
+ token = secrets.token_urlsafe(32)
+ _TOKENS[key] = token
+ _SCOPES[token] = scope
+ return token
+
+
+async def handle_cron_mcp(
+ body: dict[str, Any],
+ *,
+ scope: CronScope,
+ cron_manager: Any,
+) -> dict[str, Any]:
+ from octop.infra.cron.tools import build_cronjob_tools
+
+ tools = build_cronjob_tools(cron_manager) if cron_manager is not None else []
+ if scope.tools:
+ allowed = set(scope.tools)
+ tools = [tool for tool in tools if str(getattr(tool, "name", "")) in allowed]
+ if cron_manager is None and str(body.get("method") or "") == "tools/call":
+ from octop.infra.agents.acp.mcp_tools import text_result
+
+ return text_result(body.get("id"), "cron jobs are not available", failed=True)
+ return await dispatch(
+ body,
+ server_name="octop-cron",
+ tools=tools,
+ config={
+ "agent_id": scope.agent_id,
+ "user": scope.user_id,
+ "thread_id": scope.thread_id,
+ "session_key": scope.session_key,
+ },
+ )
diff --git a/src/octop/infra/agents/acp/delegation.py b/src/octop/infra/agents/acp/delegation.py
new file mode 100644
index 0000000000..1ffd9864bc
--- /dev/null
+++ b/src/octop/infra/agents/acp/delegation.py
@@ -0,0 +1,221 @@
+"""@mentions for a managed ACP agent: subagents stay with the runner, experts call back.
+
+The runner already loads subagents from its own project directory. An ``@slug``
+in the prompt tells it to delegate. Other Octop experts are not in that
+directory, so ``ask_agent`` is a loopback MCP tool, the same idea as knowledge
+search.
+"""
+
+from __future__ import annotations
+
+import re
+import secrets
+from dataclasses import dataclass
+from typing import Any
+
+# Same rule as octop-harness ``has_agent_at_mention``: an @name, not @file.ext.
+_AGENT_AT_RE = re.compile(r"@([^\W\d_][\w\-]*)(?![\w./\-~]*\.\w)")
+
+_SCOPES: dict[str, AgentScope] = {}
+_TOKENS: dict[tuple[int, str, str, tuple[str, ...]], str] = {}
+
+
+@dataclass
+class AgentScope:
+ user_id: int
+ from_agent_id: str
+ thread_id: str
+ session_key: str
+ tools: tuple[str, ...] = ("agent_list", "ask_agent")
+
+
+def agent_scope(token: str) -> AgentScope | None:
+ return _SCOPES.get(token)
+
+
+def retain_agent_scope(scope: AgentScope) -> str:
+ """Reuse one token per caller, thread, and enabled tool set."""
+ key = (scope.user_id, scope.from_agent_id, scope.thread_id, scope.tools)
+ token = _TOKENS.get(key)
+ if token is None:
+ token = secrets.token_urlsafe(32)
+ _TOKENS[key] = token
+ _SCOPES[token] = scope
+ return token
+
+
+def _is_user_message(message: Any) -> bool:
+ if isinstance(message, dict):
+ role = str(message.get("role") or message.get("type") or "user")
+ else:
+ role = str(getattr(message, "type", None) or getattr(message, "role", None) or "user")
+ return role in {"user", "human"}
+
+
+def user_text(request: dict[str, Any]) -> str:
+ messages = request.get("messages")
+ if not isinstance(messages, list):
+ return ""
+ for message in reversed(messages):
+ if not _is_user_message(message):
+ continue
+ content = (
+ message.get("content") if isinstance(message, dict) else getattr(message, "content", "")
+ )
+ if isinstance(content, str):
+ return content
+ if isinstance(content, list):
+ parts: list[str] = []
+ for block in content:
+ if isinstance(block, str):
+ parts.append(block)
+ elif isinstance(block, dict) and block.get("type") == "text":
+ parts.append(str(block.get("text") or ""))
+ return "".join(parts)
+ return ""
+
+
+def _token(name: str) -> str:
+ return "-".join(name.split())
+
+
+def _mentions(text: str) -> list[str]:
+ return [match.group(1) for match in _AGENT_AT_RE.finditer(text)]
+
+
+def delegation_note_for(
+ text: str,
+ *,
+ experts: list[tuple[str, str]],
+ subagents: list[tuple[str, str]],
+ locale: str,
+) -> str | None:
+ """One note when the user wrote ``@Name``. Experts win over a same-named subagent."""
+ wanted = _mentions(text)
+ if not wanted:
+ return None
+ expert_by_token = {_token(name): name for name, _desc in experts if _token(name)}
+ sub_by_token = {_token(name): (name, desc) for name, desc in subagents if _token(name)}
+ expert_hits: list[str] = []
+ sub_hits: list[str] = []
+ seen: set[str] = set()
+ for raw in wanted:
+ key = raw.strip()
+ if not key or key in seen:
+ continue
+ seen.add(key)
+ if key in expert_by_token:
+ expert_hits.append(expert_by_token[key])
+ continue
+ sub = sub_by_token.get(key)
+ if sub is not None:
+ label, desc = sub
+ sub_hits.append(f"@{label}: {desc}" if desc else f"@{label}")
+ if not expert_hits and not sub_hits:
+ return None
+ chinese = locale.lower().startswith("zh")
+ lines: list[str] = []
+ if expert_hits:
+ names = (
+ "、".join(f"@{name}" for name in expert_hits)
+ if chinese
+ else ", ".join(f"@{name}" for name in expert_hits)
+ )
+ if chinese:
+ lines.append(
+ f"用户点名了专家 {names}。调用 ask_agent,expert 用这个名字,不要代替对方回答。"
+ )
+ else:
+ lines.append(
+ f"The user named expert {names}. Call ask_agent with that name and do not answer in their place."
+ )
+ if sub_hits:
+ listed = ";".join(sub_hits) if chinese else "; ".join(sub_hits)
+ if chinese:
+ lines.append(f"用户点名了子智能体 {listed}。把这件事交给同名子智能体。")
+ else:
+ lines.append(
+ f"The user named subagent {listed}. Delegate this request to that subagent."
+ )
+ return "\n".join(lines)
+
+
+def _peer_rows(team: Any, *, user_id: int, agent_id: str) -> list[tuple[str, str]]:
+ from octop_harness.teams.team_manager import TeamManager
+
+ try:
+ peers = team.list_peers(user_id, exclude_agent_id=agent_id)
+ except Exception:
+ return []
+ rows: list[tuple[str, str]] = []
+ for entry in peers:
+ name = TeamManager.peer_display_name(entry)
+ description = str((entry.metadata or {}).get("description") or "").strip()
+ if name:
+ rows.append((name, description))
+ return rows
+
+
+async def _subagent_rows(manager: Any, agent_id: str) -> list[tuple[str, str]]:
+ lister = getattr(manager, "list_subagent_summaries", None)
+ if not callable(lister):
+ return []
+ try:
+ rows = await lister(agent_id)
+ except Exception:
+ return []
+ out: list[tuple[str, str]] = []
+ if not isinstance(rows, list):
+ return out
+ for row in rows:
+ if not isinstance(row, dict):
+ continue
+ slug = str(row.get("slug") or row.get("name") or "").strip()
+ if not slug:
+ continue
+ out.append((slug, str(row.get("description") or "").strip()))
+ return out
+
+
+async def prepare_managed_delegation(
+ manager: Any,
+ agent_id: str,
+ request: dict[str, Any],
+ *,
+ user_id: int | None,
+ tools: tuple[str, ...] = ("agent_list", "ask_agent"),
+) -> tuple[str | None, dict[str, Any] | None]:
+ """Return the @ note and, when this user has peers, an expert-call MCP spec."""
+ from octop.infra.connectors.builder import agents_mcp_url
+
+ configurable = request.get("configurable")
+ cfg = configurable if isinstance(configurable, dict) else {}
+ locale = str(cfg.get("locale") or "en")
+ thread_id = str(request.get("thread_id") or "").strip()
+ session_key = str(cfg.get("session_key") or "").strip()
+ harness = getattr(manager, "_harness_manager", None)
+ team = getattr(harness, "team", None)
+ experts = (
+ _peer_rows(team, user_id=user_id, agent_id=agent_id)
+ if team is not None and user_id is not None
+ else []
+ )
+ enabled = tuple(name for name in ("agent_list", "ask_agent") if name in tools)
+ subagents = await _subagent_rows(manager, agent_id)
+ note = delegation_note_for(
+ user_text(request),
+ experts=experts if "ask_agent" in enabled else [],
+ subagents=subagents,
+ locale=locale,
+ )
+ if user_id is None or not experts or not enabled:
+ return note, None
+ scope = AgentScope(
+ user_id=user_id,
+ from_agent_id=agent_id,
+ thread_id=thread_id,
+ session_key=session_key,
+ tools=enabled,
+ )
+ url = agents_mcp_url(config=manager._config, token=retain_agent_scope(scope))
+ return note, {"transport": "http", "url": url}
diff --git a/src/octop/infra/agents/acp/file_edits.py b/src/octop/infra/agents/acp/file_edits.py
new file mode 100644
index 0000000000..5d3d9d851a
--- /dev/null
+++ b/src/octop/infra/agents/acp/file_edits.py
@@ -0,0 +1,342 @@
+"""Show ACP file edits with the same chat card as ``write_file`` / ``edit_file``.
+
+External agents report edits as ACP ``diff`` content and ``locations``. The
+harness keeps only a title, so the chat never sees a path or a line count.
+This restores the native tool arguments on the managed-agent stream and on
+the checkpoint that history reloads.
+"""
+
+from __future__ import annotations
+
+import json
+from dataclasses import dataclass, field
+from typing import Any
+
+_INSTALLED = False
+_FILE_KINDS = frozenset({"edit", "delete", "move"})
+_NATIVE_FILE_TOOLS = frozenset({"edit_file", "write_file"})
+# Full-file diffs can be large. Past this, keep the path and skip the body
+# so the chip still opens and the transcript stays bounded.
+_BODY_CHAR_CAP = 200_000
+_PATH_KEYS = ("path", "file_path", "filePath", "filepath")
+
+
+@dataclass
+class _Pending:
+ by_path: dict[str, dict[str, Any]] = field(default_factory=dict)
+ emitted: set[str] = field(default_factory=set)
+ extras: list[str] = field(default_factory=list)
+ primary_emitted: bool = False
+
+
+_PENDING: dict[str, _Pending] = {}
+
+
+def _block_map(block: Any) -> dict[str, Any]:
+ if isinstance(block, dict):
+ return block
+ dump = getattr(block, "model_dump", None)
+ if callable(dump):
+ data = dump(by_alias=True)
+ if isinstance(data, dict):
+ return data
+ return {}
+
+
+def _text(value: Any) -> str | None:
+ if isinstance(value, str):
+ return value
+ return None
+
+
+def _too_big(value: str | None) -> bool:
+ return isinstance(value, str) and len(value) > _BODY_CHAR_CAP
+
+
+def file_edits_from_update(update: Any) -> list[dict[str, Any]]:
+ """Paths and optional before/after text from one ACP tool update."""
+ diffs: list[dict[str, Any]] = []
+ seen: set[str] = set()
+ for block in getattr(update, "content", None) or []:
+ data = _block_map(block)
+ if str(data.get("type") or "") != "diff":
+ continue
+ path = str(data.get("path") or "").strip()
+ if not path or path in seen:
+ continue
+ seen.add(path)
+ old = _text(data.get("oldText", data.get("old_text")))
+ new = _text(data.get("newText", data.get("new_text")))
+ diffs.append({"path": path, "old": old, "new": new})
+ if diffs:
+ return diffs
+
+ kind = str(getattr(update, "kind", "") or "").strip().lower()
+ if kind not in _FILE_KINDS:
+ return []
+ paths: list[str] = []
+ for loc in getattr(update, "locations", None) or []:
+ path = str(_block_map(loc).get("path") or "").strip()
+ if path:
+ paths.append(path)
+ raw = getattr(update, "raw_input", None)
+ if isinstance(raw, dict):
+ for key in _PATH_KEYS:
+ value = raw.get(key)
+ if isinstance(value, str) and value.strip():
+ paths.append(value.strip())
+ out: list[dict[str, Any]] = []
+ for path in paths:
+ if path in seen:
+ continue
+ seen.add(path)
+ out.append({"path": path, "old": None, "new": None})
+ return out
+
+
+def _merge(pending: _Pending, files: Any) -> None:
+ if not isinstance(files, list):
+ return
+ for item in files:
+ if not isinstance(item, dict):
+ continue
+ path = str(item.get("path") or "").strip()
+ if not path or path in pending.emitted:
+ continue
+ old = item.get("old") if isinstance(item.get("old"), str) else None
+ new = item.get("new") if isinstance(item.get("new"), str) else None
+ current = pending.by_path.get(path)
+ if current is None or (
+ current.get("old") is None
+ and current.get("new") is None
+ and (old is not None or new is not None)
+ ):
+ pending.by_path[path] = {"path": path, "old": old, "new": new}
+
+
+def _ready(pending: _Pending, *, finished: bool) -> list[dict[str, Any]]:
+ ready: list[dict[str, Any]] = []
+ for path, item in pending.by_path.items():
+ if path in pending.emitted:
+ continue
+ has_body = item.get("old") is not None or item.get("new") is not None
+ if has_body or finished:
+ ready.append(item)
+ return ready
+
+
+def _file_tool_args(item: dict[str, Any]) -> tuple[str, str]:
+ path = str(item.get("path") or "")
+ old = item.get("old") if isinstance(item.get("old"), str) else None
+ new = item.get("new") if isinstance(item.get("new"), str) else None
+ if _too_big(old) or _too_big(new):
+ old = None
+ new = None
+ if isinstance(new, str) and old is None:
+ payload: dict[str, Any] = {"file_path": path, "content": new}
+ return "write_file", json.dumps(payload, ensure_ascii=False)
+ if isinstance(old, str) and isinstance(new, str):
+ payload = {"file_path": path, "old_string": old, "new_string": new}
+ return "edit_file", json.dumps(payload, ensure_ascii=False)
+ return "edit_file", json.dumps({"file_path": path}, ensure_ascii=False)
+
+
+def _open_chunk(name: str, args: str, call_id: str, index: int) -> Any:
+ from langchain_core.messages import AIMessageChunk
+ from langchain_core.outputs import ChatGenerationChunk
+
+ return ChatGenerationChunk(
+ message=AIMessageChunk(
+ content="",
+ tool_call_chunks=[
+ {
+ "name": name,
+ "args": args,
+ "id": call_id,
+ "index": index,
+ }
+ ],
+ )
+ )
+
+
+def _call_field(call: Any, key: str) -> Any:
+ if isinstance(call, dict):
+ return call.get(key)
+ return getattr(call, key, None)
+
+
+def install_acp_file_edits() -> None:
+ """Map ACP file edits onto ``write_file`` / ``edit_file`` tool calls."""
+ global _INSTALLED
+ if _INSTALLED:
+ return
+ import octop_harness.acp.managed as managed
+ from octop_harness.acp.client import ACPHostedClient
+ from octop_harness.acp.managed import (
+ _collect_managed_chunk,
+ _managed_history_messages,
+ _tool_finished,
+ _tool_result_chunk,
+ )
+
+ original_event = ACPHostedClient._tool_event_from_state
+ original_collect = _collect_managed_chunk
+ original_history = _managed_history_messages
+
+ def _tool_event_from_state(self: Any, update: Any) -> dict[str, Any] | None:
+ event = original_event(self, update)
+ if not isinstance(event, dict):
+ return event
+ files = file_edits_from_update(update)
+ if files:
+ event["files"] = files
+ return event
+
+ def tool_chunks(
+ payload: dict[str, Any],
+ opened: dict[str, int],
+ tool_index: int,
+ ) -> tuple[list[Any], int]:
+ call_id = str(payload.get("call_id") or "")
+ chunks: list[Any] = []
+ pending = _PENDING.setdefault(call_id, _Pending())
+ _merge(pending, payload.get("files"))
+ finished = _tool_finished(payload)
+ ready = _ready(pending, finished=finished)
+
+ if not ready and call_id not in opened:
+ opened[call_id] = tool_index
+ tool_index += 1
+ chunks.append(
+ _open_chunk(
+ str(payload.get("name") or "tool"),
+ "",
+ call_id,
+ opened[call_id],
+ )
+ )
+
+ for item in ready:
+ name, args = _file_tool_args(item)
+ if not pending.primary_emitted:
+ if call_id not in opened:
+ opened[call_id] = tool_index
+ tool_index += 1
+ file_id = call_id
+ index = opened[call_id]
+ pending.primary_emitted = True
+ else:
+ file_id = f"{call_id}:{len(pending.extras) + 1}"
+ opened[file_id] = tool_index
+ tool_index += 1
+ index = opened[file_id]
+ pending.extras.append(file_id)
+ pending.emitted.add(str(item.get("path") or ""))
+ chunks.append(_open_chunk(name, args, file_id, index))
+
+ if finished:
+ extras = list(pending.extras)
+ opened.pop(call_id, None)
+ chunks.append(_tool_result_chunk(payload))
+ status = str(payload.get("status") or "completed")
+ for file_id in extras:
+ opened.pop(file_id, None)
+ chunks.append(
+ _tool_result_chunk(
+ {"call_id": file_id, "status": status, "output": ""},
+ )
+ )
+ _PENDING.pop(call_id, None)
+ return chunks, tool_index
+
+ def collect(
+ chunk: Any,
+ text_parts: list[str],
+ reasoning_parts: list[str],
+ tools: list[dict[str, Any]],
+ tools_by_id: dict[str, dict[str, Any]],
+ ) -> None:
+ original_collect(chunk, text_parts, reasoning_parts, tools, tools_by_id)
+ message = getattr(chunk, "message", None)
+ if message is None:
+ message = chunk
+ for call in getattr(message, "tool_call_chunks", None) or []:
+ call_id = str(_call_field(call, "id") or "")
+ if not call_id:
+ continue
+ record = tools_by_id.get(call_id)
+ name = str(_call_field(call, "name") or "")
+ args = _call_field(call, "args") or ""
+ if record is None:
+ record = {
+ "id": call_id,
+ "name": name or "tool",
+ "output": "",
+ "failed": False,
+ }
+ tools_by_id[call_id] = record
+ tools.append(record)
+ if name in _NATIVE_FILE_TOOLS:
+ record["name"] = name
+ if isinstance(args, str) and args.strip():
+ record["args_json"] = str(record.get("args_json") or "") + args
+
+ def history(
+ text_parts: list[str],
+ reasoning_parts: list[str],
+ tools: list[dict[str, Any]],
+ ) -> list[Any]:
+ messages = original_history(text_parts, reasoning_parts, tools)
+ by_id = {str(record.get("id") or ""): record for record in tools}
+ rewritten: list[Any] = []
+ for message in messages:
+ calls = getattr(message, "tool_calls", None)
+ if not calls:
+ rewritten.append(message)
+ continue
+ new_calls: list[Any] = []
+ changed = False
+ for call in calls:
+ if not isinstance(call, dict):
+ new_calls.append(call)
+ continue
+ record = by_id.get(str(call.get("id") or ""))
+ args_json = str(record.get("args_json") or "") if record else ""
+ parsed: dict[str, Any] | None = None
+ if args_json.strip():
+ try:
+ loaded = json.loads(args_json)
+ except json.JSONDecodeError:
+ loaded = None
+ if isinstance(loaded, dict):
+ parsed = loaded
+ name = str(record.get("name") or "") if record else ""
+ if parsed is None and not name:
+ new_calls.append(call)
+ continue
+ updated = dict(call)
+ if name:
+ updated["name"] = name
+ if parsed is not None:
+ updated["args"] = parsed
+ changed = True
+ new_calls.append(updated)
+ if not changed:
+ rewritten.append(message)
+ continue
+ copy = getattr(message, "model_copy", None)
+ if callable(copy):
+ rewritten.append(copy(update={"tool_calls": new_calls}))
+ else:
+ rewritten.append(message)
+ return rewritten
+
+ ACPHostedClient._tool_event_from_state = _tool_event_from_state # type: ignore[method-assign]
+ managed._tool_chunks = tool_chunks
+ managed._collect_managed_chunk = collect
+ managed._managed_history_messages = history
+ _INSTALLED = True
+
+
+__all__ = ["file_edits_from_update", "install_acp_file_edits"]
diff --git a/src/octop/infra/agents/acp/files_mcp.py b/src/octop/infra/agents/acp/files_mcp.py
new file mode 100644
index 0000000000..0c04ea0c11
--- /dev/null
+++ b/src/octop/infra/agents/acp/files_mcp.py
@@ -0,0 +1,124 @@
+"""Loopback MCP so a managed runner can call ``send_file_to_user``.
+
+The runner is another process, so it cannot use the in-process tool. This
+server reads the file through that expert's workspace and returns the same
+media block the chat and IM channels already push.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+import secrets
+from dataclasses import dataclass
+from typing import Any
+
+_PROTOCOL = "2024-11-05"
+_DELIVERY = "send_file_to_user"
+
+_SCOPES: dict[str, FileScope] = {}
+_TOKENS: dict[str, str] = {}
+
+_TOOL = {
+ "name": _DELIVERY,
+ "description": (
+ "Send an existing workspace file to the user in this chat and on "
+ "connected messaging channels. Pass the path the file was written to."
+ ),
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "file_path": {
+ "type": "string",
+ "description": "Workspace path of a file that already exists.",
+ },
+ },
+ "required": ["file_path"],
+ },
+}
+
+
+@dataclass(frozen=True)
+class FileScope:
+ agent_id: str
+
+
+def file_scope(token: str) -> FileScope | None:
+ return _SCOPES.get(token)
+
+
+def retain_file_scope(agent_id: str) -> str:
+ """Reuse one token per expert so the ACP session is not reloaded each turn."""
+ token = _TOKENS.get(agent_id)
+ if token is None:
+ token = secrets.token_urlsafe(32)
+ _TOKENS[agent_id] = token
+ _SCOPES[token] = FileScope(agent_id=agent_id)
+ return token
+
+
+def _ok(req_id: Any, result: dict[str, Any]) -> dict[str, Any]:
+ if req_id is None:
+ return {}
+ return {"jsonrpc": "2.0", "id": req_id, "result": result}
+
+
+def _err(req_id: Any, code: int, message: str) -> dict[str, Any]:
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
+
+
+def _arguments(params: Any) -> dict[str, Any]:
+ if not isinstance(params, dict):
+ return {}
+ raw = params.get("arguments") or {}
+ if not isinstance(raw, dict):
+ return {}
+ nested = raw.get("kwargs")
+ if nested is not None and set(raw.keys()) == {"kwargs"} and isinstance(nested, dict):
+ return nested
+ return raw
+
+
+def _text_result(req_id: Any, text: str, *, failed: bool = False) -> dict[str, Any]:
+ return _ok(req_id, {"content": [{"type": "text", "text": text}], "isError": failed})
+
+
+async def handle_files_mcp(body: dict[str, Any], *, workspace: Any) -> dict[str, Any]:
+ """Answer one JSON-RPC request. An empty dict means the caller should return 202."""
+ method = str(body.get("method") or "")
+ req_id = body.get("id")
+ params = body.get("params") or {}
+
+ if method == "initialize":
+ return _ok(
+ req_id,
+ {
+ "protocolVersion": _PROTOCOL,
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "octop-files", "version": "0.1.0"},
+ },
+ )
+ if method == "notifications/initialized":
+ return {}
+ if method == "tools/list":
+ return _ok(req_id, {"tools": [_TOOL]})
+ if method == "ping":
+ return _ok(req_id, {})
+ if method != "tools/call":
+ return _err(req_id, -32601, f"Method not found: {method}")
+
+ name = str(params.get("name") or "") if isinstance(params, dict) else ""
+ if name != _DELIVERY:
+ return _text_result(req_id, f"Unknown tool: {name}", failed=True)
+ file_path = str(_arguments(params).get("file_path") or "").strip()
+ if not file_path:
+ return _text_result(req_id, "file_path is required.", failed=True)
+
+ from octop_harness.builtin.tools.send_file import build_send_file_to_user_tool
+
+ tool = build_send_file_to_user_tool(workspace)
+ result = await asyncio.to_thread(tool.invoke, {"file_path": file_path})
+ if not isinstance(result, dict):
+ return _text_result(req_id, str(result), failed=True)
+ marked = {**result, "octop_delivery": _DELIVERY}
+ return _text_result(req_id, json.dumps(marked, ensure_ascii=False))
diff --git a/src/octop/infra/agents/acp/mcp_tools.py b/src/octop/infra/agents/acp/mcp_tools.py
new file mode 100644
index 0000000000..c1c18397ed
--- /dev/null
+++ b/src/octop/infra/agents/acp/mcp_tools.py
@@ -0,0 +1,119 @@
+"""JSON-RPC helpers for Octop loopback MCP servers."""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from typing import Any
+
+_PROTOCOL = "2024-11-05"
+
+
+def ok(req_id: Any, result: dict[str, Any]) -> dict[str, Any]:
+ if req_id is None:
+ return {}
+ return {"jsonrpc": "2.0", "id": req_id, "result": result}
+
+
+def err(req_id: Any, code: int, message: str) -> dict[str, Any]:
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
+
+
+def arguments(params: Any) -> dict[str, Any]:
+ if not isinstance(params, dict):
+ return {}
+ raw = params.get("arguments") or {}
+ if not isinstance(raw, dict):
+ return {}
+ nested = raw.get("kwargs")
+ if nested is not None and set(raw.keys()) == {"kwargs"} and isinstance(nested, dict):
+ return nested
+ return raw
+
+
+def text_result(req_id: Any, text: str, *, failed: bool = False) -> dict[str, Any]:
+ return ok(req_id, {"content": [{"type": "text", "text": text}], "isError": failed})
+
+
+def tool_card(tool: Any) -> dict[str, Any]:
+ schema: dict[str, Any] = {"type": "object", "properties": {}}
+ model = getattr(tool, "args_schema", None)
+ if model is not None and hasattr(model, "model_json_schema"):
+ raw = model.model_json_schema()
+ if isinstance(raw, dict):
+ schema = dict(raw)
+ schema.pop("title", None)
+ return {
+ "name": str(getattr(tool, "name", "") or "tool"),
+ "description": str(getattr(tool, "description", "") or ""),
+ "inputSchema": schema,
+ }
+
+
+def _invoke_sync(tool: Any, payload: dict[str, Any], config: dict[str, Any]) -> Any:
+ from langchain_core.runnables.config import var_child_runnable_config
+
+ token = var_child_runnable_config.set({"configurable": config})
+ try:
+ return tool.invoke(payload)
+ finally:
+ var_child_runnable_config.reset(token)
+
+
+async def invoke_tool(tool: Any, payload: dict[str, Any], config: dict[str, Any]) -> str:
+ """Run one structured tool. Cron and plugins read ``get_config()`` from this config."""
+ try:
+ if getattr(tool, "coroutine", None) is not None:
+ from langchain_core.runnables.config import var_child_runnable_config
+
+ token = var_child_runnable_config.set({"configurable": config})
+ try:
+ result = await tool.ainvoke(payload)
+ finally:
+ var_child_runnable_config.reset(token)
+ else:
+ result = await asyncio.to_thread(_invoke_sync, tool, payload, config)
+ except Exception as exc:
+ name = str(getattr(tool, "name", "") or "tool")
+ return f"{name} failed: {exc}"
+ if isinstance(result, str):
+ return result
+ return json.dumps(result, ensure_ascii=False, default=str)
+
+
+async def dispatch(
+ body: dict[str, Any],
+ *,
+ server_name: str,
+ tools: list[Any],
+ config: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ """Answer one JSON-RPC request. An empty dict means the caller should return 202."""
+ method = str(body.get("method") or "")
+ req_id = body.get("id")
+ params = body.get("params") or {}
+ if method == "initialize":
+ return ok(
+ req_id,
+ {
+ "protocolVersion": _PROTOCOL,
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": server_name, "version": "0.1.0"},
+ },
+ )
+ if method == "notifications/initialized":
+ return {}
+ if method == "tools/list":
+ return ok(req_id, {"tools": [tool_card(tool) for tool in tools]})
+ if method == "ping":
+ return ok(req_id, {})
+ if method != "tools/call":
+ return err(req_id, -32601, f"Method not found: {method}")
+
+ name = str(params.get("name") or "") if isinstance(params, dict) else ""
+ tool = next((item for item in tools if getattr(item, "name", None) == name), None)
+ if tool is None:
+ return text_result(req_id, f"Unknown tool: {name}", failed=True)
+ text = await invoke_tool(tool, arguments(params), config or {})
+ failed = text.startswith(f"{name} failed:")
+ return text_result(req_id, text, failed=failed)
diff --git a/src/octop/infra/agents/acp/memory_mcp.py b/src/octop/infra/agents/acp/memory_mcp.py
new file mode 100644
index 0000000000..ef334e3282
--- /dev/null
+++ b/src/octop/infra/agents/acp/memory_mcp.py
@@ -0,0 +1,64 @@
+"""Loopback MCP for memory tools. Attached only when this expert enables memory."""
+
+from __future__ import annotations
+
+import secrets
+from dataclasses import dataclass
+from typing import Any
+
+from octop.infra.agents.acp.mcp_tools import dispatch
+
+_SCOPES: dict[str, MemoryScope] = {}
+_TOKENS: dict[tuple[str, tuple[str, ...]], str] = {}
+
+
+@dataclass(frozen=True)
+class MemoryScope:
+ agent_id: str
+ tools: tuple[str, ...] = ()
+
+
+def memory_scope(token: str) -> MemoryScope | None:
+ return _SCOPES.get(token)
+
+
+def retain_memory_scope(agent_id: str, tools: tuple[str, ...] = ()) -> str:
+ """Reuse one token per expert and enabled tool set."""
+ key = (agent_id, tools)
+ token = _TOKENS.get(key)
+ if token is None:
+ token = secrets.token_urlsafe(32)
+ _TOKENS[key] = token
+ _SCOPES[token] = MemoryScope(agent_id=agent_id, tools=tools)
+ return token
+
+
+def memory_enabled(config: Any) -> bool:
+ """True only when the stored expert config explicitly turns memory on."""
+ if not isinstance(config, dict):
+ return False
+ memory = config.get("memory")
+ return isinstance(memory, dict) and memory.get("memory_enabled") is True
+
+
+async def handle_memory_mcp(
+ body: dict[str, Any],
+ *,
+ service: Any,
+ tools_allowed: tuple[str, ...] = (),
+) -> dict[str, Any]:
+ from octop_harness.builtin.tools.memory_tools import build_memory_tools
+
+ from octop.infra.agents.acp.mcp_tools import text_result
+
+ if service is None and str(body.get("method") or "") == "tools/call":
+ return text_result(
+ body.get("id"),
+ "memory is enabled but this expert has not reloaded yet",
+ failed=True,
+ )
+ tools = build_memory_tools(service) if service is not None else []
+ if tools_allowed:
+ allowed = set(tools_allowed)
+ tools = [tool for tool in tools if str(getattr(tool, "name", "")) in allowed]
+ return await dispatch(body, server_name="octop-memory", tools=tools)
diff --git a/src/octop/infra/agents/acp_permission_compat.py b/src/octop/infra/agents/acp/permissions.py
similarity index 100%
rename from src/octop/infra/agents/acp_permission_compat.py
rename to src/octop/infra/agents/acp/permissions.py
diff --git a/src/octop/infra/agents/acp/plugins_mcp.py b/src/octop/infra/agents/acp/plugins_mcp.py
new file mode 100644
index 0000000000..418e5a4120
--- /dev/null
+++ b/src/octop/infra/agents/acp/plugins_mcp.py
@@ -0,0 +1,106 @@
+"""Loopback MCP for the plugin tools enabled on this expert."""
+
+from __future__ import annotations
+
+import secrets
+from dataclasses import dataclass
+from typing import Any
+
+from octop.infra.agents.acp.mcp_tools import dispatch
+
+_SCOPES: dict[str, PluginScope] = {}
+_TOKENS: dict[tuple[str, tuple[str, ...]], str] = {}
+
+_RESERVED = frozenset(
+ {
+ "cronjob_list",
+ "cronjob_get",
+ "cronjob_create",
+ "cronjob_update",
+ "cronjob_delete",
+ "cronjob_run_now",
+ "memory_search",
+ "memory_get",
+ "memory_save",
+ "send_file_to_user",
+ "ask_agent",
+ "agent_list",
+ "search_knowledge",
+ }
+)
+
+
+@dataclass(frozen=True)
+class PluginScope:
+ agent_id: str
+
+
+def plugin_scope(token: str) -> PluginScope | None:
+ return _SCOPES.get(token)
+
+
+def retain_plugin_scope(agent_id: str, tool_names: tuple[str, ...]) -> str:
+ """Change the token when the enabled tool set changes, so the session reloads."""
+ key = (agent_id, tool_names)
+ token = _TOKENS.get(key)
+ if token is None:
+ token = secrets.token_urlsafe(32)
+ _TOKENS[key] = token
+ _SCOPES[token] = PluginScope(agent_id=agent_id)
+ return token
+
+
+def plugin_tools(manager: Any, config: dict[str, Any]) -> list[Any]:
+ """Enabled plugin tools, with the same names a native expert would expose."""
+ plugin_manager = getattr(manager, "_plugin_manager", None)
+ if plugin_manager is None:
+ return []
+ from octop_harness.plugins import PluginRegistry, build_plugin_tools
+
+ from octop.infra.agents.plugins.plugin_tool_defaults import (
+ agent_plugin_enabled,
+ expand_plugin_tools_default_on,
+ )
+ from octop.infra.agents.plugins.plugin_tool_names import sanitize_plugin_tool_names
+ from octop.infra.agents.settings.tool_catalog import tools_disabled_set
+
+ global_plugins = plugin_manager.global_enabled_map()
+ if not isinstance(global_plugins, dict):
+ global_plugins = {}
+ registered = [(reg.plugin_id, reg.name) for reg in PluginRegistry().all_tools()]
+ agent_plugins = config.get("plugins")
+ agent_plugins_map = agent_plugins if isinstance(agent_plugins, dict) else {}
+ effective = dict(global_plugins)
+ for plugin in PluginRegistry().list_plugins():
+ if not agent_plugin_enabled(agent_plugins_map, plugin.manifest.id):
+ effective[plugin.manifest.id] = False
+ mount = expand_plugin_tools_default_on(
+ agent_plugins_map,
+ registered_tools=registered,
+ global_plugins=effective,
+ )
+ tools = build_plugin_tools(agent_plugins=mount, global_plugins=effective)
+ disabled = tools_disabled_set(config)
+ tools = [tool for tool in tools if str(getattr(tool, "name", "")) not in disabled]
+ return sanitize_plugin_tool_names(tools, reserved=set(_RESERVED))
+
+
+def plugin_tool_configs(config: dict[str, Any]) -> dict[str, Any]:
+ from octop_harness.plugins import collect_plugin_tool_configs
+
+ plugins = config.get("plugins")
+ return collect_plugin_tool_configs(plugins if isinstance(plugins, dict) else None)
+
+
+async def handle_plugins_mcp(
+ body: dict[str, Any],
+ *,
+ tools: list[Any],
+ tool_configs: dict[str, Any] | None = None,
+) -> dict[str, Any]:
+ return await dispatch(
+ body,
+ server_name="octop-plugins",
+ tools=tools,
+ config={"plugin_tool_configs": tool_configs or {}},
+ )
diff --git a/src/octop/infra/agents/acp/session_modes.py b/src/octop/infra/agents/acp/session_modes.py
new file mode 100644
index 0000000000..d0ef0deaf9
--- /dev/null
+++ b/src/octop/infra/agents/acp/session_modes.py
@@ -0,0 +1,211 @@
+"""Session modes a managed expert can pin, keyed by the underlying agent.
+
+These are the mode ids each agent documents for ``session/set_mode``. A live
+session still only switches to an id that agent actually advertises.
+"""
+
+from __future__ import annotations
+
+from dataclasses import asdict, dataclass
+from typing import Any
+
+# Same markers as octop-harness ``is_unattended_mode``. Kept here so this
+# package does not import a harness module newer than the pinned release.
+_UNATTENDED_MARKERS = (
+ "yolo",
+ "bypass",
+ "full-access",
+ "fullaccess",
+ "auto-accept",
+ "autoaccept",
+ "unrestricted",
+ "danger",
+)
+
+
+def is_unattended_mode(value: object) -> bool:
+ """True when a session mode id means the agent should run without asking."""
+ folded = str(value or "").lower()
+ return any(marker in folded for marker in _UNATTENDED_MARKERS)
+
+
+# ``ask`` and ``craft`` are Octop's own conversation modes. ``plan`` is also an
+# ACP mode id (CodeBuddy, OpenCode), so a stored ``plan`` is kept.
+_NATIVE = frozenset({"ask", "craft"})
+
+
+@dataclass(frozen=True)
+class AcpSessionMode:
+ id: str
+ name_zh: str
+ name_en: str
+ hint_zh: str
+ hint_en: str
+
+ def to_dict(self) -> dict[str, str]:
+ return asdict(self)
+
+
+def _mode(mode_id: str, name_zh: str, name_en: str, hint_zh: str, hint_en: str) -> AcpSessionMode:
+ return AcpSessionMode(mode_id, name_zh, name_en, hint_zh, hint_en)
+
+
+_CODEBUDDY = (
+ _mode(
+ "default",
+ "默认",
+ "Default",
+ "危险操作需要确认。",
+ "Asks before dangerous actions.",
+ ),
+ _mode(
+ "acceptEdits",
+ "接受编辑",
+ "Accept edits",
+ "信任目录里的改文件不再询问。",
+ "Auto-approves file edits in trusted directories.",
+ ),
+ _mode(
+ "plan",
+ "规划",
+ "Plan",
+ "先规划,基本只读。",
+ "Plan first. Mostly read-only.",
+ ),
+ _mode(
+ "auto",
+ "自动",
+ "Auto",
+ "安全操作自动通过,有风险的仍会询问。",
+ "Approves safe actions automatically. Risky ones still ask.",
+ ),
+ _mode(
+ "bypassPermissions",
+ "YOLO",
+ "YOLO",
+ "跳过大部分审批,包括改文件和运行命令。",
+ "Skips most approvals, including file edits and commands.",
+ ),
+)
+
+_CATALOG: dict[str, tuple[AcpSessionMode, ...]] = {
+ "codebuddy": _CODEBUDDY,
+ "claude_code": _CODEBUDDY,
+ "opencode": (
+ _mode(
+ "build",
+ "构建",
+ "Build",
+ "默认可改代码。敏感操作仍可能询问。",
+ "Default coding agent. Sensitive actions may still ask.",
+ ),
+ _mode(
+ "plan",
+ "规划",
+ "Plan",
+ "分析为主,少改项目文件。",
+ "Explore and plan, with few project edits.",
+ ),
+ ),
+ "kimi_code": (
+ _mode(
+ "default",
+ "默认",
+ "Default",
+ "按 Kimi 自己的规则确认操作。",
+ "Kimi asks under its own rules.",
+ ),
+ _mode(
+ "yolo",
+ "YOLO",
+ "YOLO",
+ "不再弹出审批。",
+ "Runs without approval prompts.",
+ ),
+ ),
+ # Ids from ``@zed-industries/codex-acp``, the adapter Octop launches.
+ "codex": (
+ _mode(
+ "auto",
+ "自动",
+ "Auto",
+ "可在工作区里改文件。",
+ "Can edit files inside the workspace.",
+ ),
+ _mode(
+ "read-only",
+ "只读",
+ "Read-only",
+ "只读,不改文件。",
+ "Read-only. Does not edit files.",
+ ),
+ _mode(
+ "full-access",
+ "完全访问",
+ "Full access",
+ "关闭沙箱,相当于 YOLO。",
+ "Turns the sandbox off. This is the YOLO mode.",
+ ),
+ ),
+}
+
+
+def session_modes(runner: str) -> list[AcpSessionMode]:
+ return list(_CATALOG.get((runner or "").strip(), ()))
+
+
+def yolo_session_mode_id(runner: str) -> str:
+ for mode in session_modes(runner):
+ if is_unattended_mode(mode.id):
+ return mode.id
+ return ""
+
+
+def approval_for_session(session_mode: str, permission_mode: str, *, runner: str) -> str:
+ """``ask`` or ``yolo`` for this turn.
+
+ An unattended mode id skips approval. When the agent publishes one, every
+ other mode asks. Agents with no such mode keep the chat's own setting.
+ """
+ if is_unattended_mode(session_mode):
+ return "yolo"
+ if session_mode and yolo_session_mode_id(runner):
+ return "ask"
+ return "yolo" if permission_mode == "yolo" else "ask"
+
+
+def resolve_managed_session_mode(
+ *,
+ explicit: object = None,
+ stored: object = None,
+ config: dict[str, Any] | None = None,
+) -> str:
+ """Mode id for this turn.
+
+ Stored ``ask`` and ``craft`` are Octop conversation modes and are ignored.
+ ``plan`` is also an ACP mode id, so a stored plan is kept.
+ """
+ chosen = _acp_mode_id(explicit) or _acp_mode_id(stored)
+ if chosen:
+ return chosen
+ cfg = config if isinstance(config, dict) else {}
+ pinned = _acp_mode_id(cfg.get("managed_session_mode"))
+ if pinned:
+ return pinned
+ if cfg.get("managed_permission_mode") == "yolo":
+ runner = cfg.get("managed_runner")
+ return yolo_session_mode_id(runner if isinstance(runner, str) else "")
+ return ""
+
+
+def _acp_mode_id(value: object) -> str:
+ if not isinstance(value, str):
+ return ""
+ text = value.strip()
+ if not text or text in _NATIVE:
+ return ""
+ if len(text) > 64 or any(
+ ch not in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-" for ch in text
+ ):
+ return ""
+ return text
diff --git a/src/octop/infra/agents/acp_tool_name_compat.py b/src/octop/infra/agents/acp/tool_names.py
similarity index 100%
rename from src/octop/infra/agents/acp_tool_name_compat.py
rename to src/octop/infra/agents/acp/tool_names.py
diff --git a/src/octop/infra/agents/acp/turn.py b/src/octop/infra/agents/acp/turn.py
new file mode 100644
index 0000000000..27bcbc5b7e
--- /dev/null
+++ b/src/octop/infra/agents/acp/turn.py
@@ -0,0 +1,464 @@
+"""Attach this turn's MCP specs when the expert is a managed ACP runner.
+
+The harness converts those specs and sends them on ``session/new`` and
+``session/load``. Connectors are the specs a native expert already loads.
+Knowledge search, ``ask_agent``, ``send_file_to_user``, cron, enabled plugin
+tools, and memory (only when this expert turns memory on) are extra loopback
+servers, because the runner is another process and cannot see Octop's
+in-process tools.
+"""
+
+from __future__ import annotations
+
+import logging
+import secrets
+from dataclasses import dataclass
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+_KNOWLEDGE_NAME = "octop-knowledge"
+_AGENTS_NAME = "octop-agents"
+_FILES_NAME = "octop-files"
+_CRON_NAME = "octop-cron"
+_MEMORY_NAME = "octop-memory"
+_PLUGINS_NAME = "octop-plugins"
+_LOOPBACK_NAMES = {
+ _KNOWLEDGE_NAME,
+ _AGENTS_NAME,
+ _FILES_NAME,
+ _CRON_NAME,
+ _MEMORY_NAME,
+ _PLUGINS_NAME,
+}
+
+_SCOPES: dict[str, KnowledgeScope] = {}
+_TOKENS: dict[tuple[Any, ...], str] = {}
+
+
+@dataclass(frozen=True)
+class KnowledgeScope:
+ user_id: int
+ is_admin: bool
+ knowledge_base_ids: tuple[str, ...]
+ locale: str
+ catalog: tuple[tuple[str, str, str], ...]
+
+ def catalog_rows(self) -> list[dict[str, str]]:
+ return [
+ {"id": kb_id, "name": name, "description": description}
+ for kb_id, name, description in self.catalog
+ ]
+
+
+def knowledge_scope(token: str) -> KnowledgeScope | None:
+ return _SCOPES.get(token)
+
+
+def retain_knowledge_scope(scope: KnowledgeScope) -> str:
+ """Reuse one token for the same user and knowledge-base selection."""
+ key = (scope.user_id, scope.is_admin, scope.knowledge_base_ids, scope.locale)
+ token = _TOKENS.get(key)
+ if token is None:
+ token = secrets.token_urlsafe(32)
+ _TOKENS[key] = token
+ _SCOPES[token] = scope
+ return token
+
+
+def _catalog(raw: Any) -> tuple[tuple[str, str, str], ...]:
+ if not isinstance(raw, list):
+ return ()
+ rows: list[tuple[str, str, str]] = []
+ for item in raw:
+ if not isinstance(item, dict):
+ continue
+ kb_id = str(item.get("id") or "").strip()
+ name = str(item.get("name") or kb_id).strip()
+ if not kb_id and not name:
+ continue
+ rows.append((kb_id or name, name or kb_id, str(item.get("description") or "").strip()))
+ return tuple(rows)
+
+
+def _ids(raw: Any) -> list[str]:
+ if not isinstance(raw, list):
+ return []
+ seen: set[str] = set()
+ out: list[str] = []
+ for item in raw:
+ text = str(item).strip()
+ if text and text not in seen:
+ seen.add(text)
+ out.append(text)
+ return out
+
+
+def _user_id(request: dict[str, Any]) -> int | None:
+ raw = request.get("user")
+ if raw is None:
+ configurable = request.get("configurable")
+ if isinstance(configurable, dict):
+ raw = configurable.get("user")
+ if isinstance(raw, bool) or raw is None:
+ return None
+ try:
+ return int(raw)
+ except (TypeError, ValueError):
+ return None
+
+
+def _http_spec(url: str) -> dict[str, Any]:
+ return {"transport": "http", "url": url}
+
+
+def _enabled(disabled: set[str], names: tuple[str, ...]) -> tuple[str, ...]:
+ return tuple(name for name in names if name not in disabled)
+
+
+def _attach(specs: dict[str, Any], server_name: str, url: str | None) -> None:
+ if url:
+ specs[server_name] = _http_spec(url)
+
+
+def _connectors_allowed(request: dict[str, Any], cfg: dict[str, Any]) -> bool:
+ mode = str(request.get("conversation_mode") or cfg.get("conversation_mode") or "craft")
+ return mode.strip().lower() not in {"ask", "plan"}
+
+
+def _tool_limit_note(specs: dict[str, Any], locale: str) -> str | None:
+ """Tell the agent which connector tools it may call. ACP cannot filter them."""
+ chinese = locale.lower().startswith("zh")
+ lines: list[str] = []
+ for name, spec in specs.items():
+ if name in _LOOPBACK_NAMES or not isinstance(spec, dict):
+ continue
+ allowed = spec.get("allowed_tools")
+ if not isinstance(allowed, list) or not allowed:
+ continue
+ listed = (
+ "、".join(str(item) for item in allowed)
+ if chinese
+ else ", ".join(str(item) for item in allowed)
+ )
+ if chinese:
+ lines.append(f"连接器 {name} 只使用这些工具:{listed}。")
+ else:
+ lines.append(f"For connector {name}, use only these tools: {listed}.")
+ return "\n".join(lines) if lines else None
+
+
+def _send_file_note(locale: str) -> str:
+ if locale.lower().startswith("zh"):
+ return "要把文件发给用户时,调用 send_file_to_user,传入工作区里已有的文件路径。"
+ return (
+ "To deliver a file to the user, call send_file_to_user "
+ "with an existing path in the workspace."
+ )
+
+
+def _server_timezone(manager: Any) -> str:
+ config = getattr(manager, "_config", None)
+ raw = getattr(config, "default_timezone", None)
+ text = raw.strip() if isinstance(raw, str) else ""
+ return text or "Asia/Shanghai"
+
+
+def _cron_note(locale: str, timezone_name: str) -> str:
+ """Point a managed runner at Octop's cron tools, not its own session scheduler."""
+ from datetime import datetime
+ from zoneinfo import ZoneInfo, ZoneInfoNotFoundError
+
+ try:
+ now = datetime.now(ZoneInfo(timezone_name)).strftime("%Y-%m-%d %H:%M")
+ except ZoneInfoNotFoundError:
+ now = ""
+ if locale.lower().startswith("zh"):
+ clock = f"当前时间是 {now}({timezone_name})。" if now else ""
+ return (
+ f"{clock}"
+ "定时提醒和周期任务只用 octop-cron 的 cronjob_create、cronjob_list、"
+ "cronjob_update、cronjob_delete。"
+ "不要调用 CronCreate、CronDelete、CronList:那些只存在于当前会话,不会出现在任务列表里。"
+ f"日程按 {timezone_name} 解释。"
+ "固定提醒用 task_type=text;重复用 trigger=cron:五段表达式或 interval:秒数;"
+ "一次性用 trigger=date:带时区的 ISO 时间。"
+ )
+ clock = f"The current time is {now} ({timezone_name}). " if now else ""
+ return (
+ f"{clock}"
+ "For reminders and recurring jobs, call only the octop-cron tools "
+ "cronjob_create, cronjob_list, cronjob_update, and cronjob_delete. "
+ "Do not call CronCreate, CronDelete, or CronList: those live only in this session "
+ "and never appear in the task list. "
+ f"Interpret schedules in {timezone_name}. "
+ "Use task_type=text for a fixed reminder; "
+ "trigger=cron:<5 fields> or interval: to repeat; "
+ "trigger=date: to run once."
+ )
+
+
+def _stored_config(manager: Any, agent_id: str) -> dict[str, Any]:
+ getter = getattr(manager, "get_config", None)
+ if not callable(getter):
+ return {}
+ try:
+ config = getter(agent_id)
+ except Exception:
+ logger.warning("managed ACP could not read config for %s", agent_id, exc_info=True)
+ return {}
+ return config if isinstance(config, dict) else {}
+
+
+def _session_key(request: dict[str, Any], cfg: dict[str, Any], agent_id: str, user_id: int) -> str:
+ raw = cfg.get("session_key") or request.get("session_key")
+ text = str(raw or "").strip()
+ if text:
+ return text
+ from octop.infra.gateway.threads import ThreadRegistry
+
+ return ThreadRegistry.dashboard_key(agent_id=agent_id, user_id=user_id)
+
+
+def _managed_session_mode(
+ manager: Any, agent_id: str, request: dict[str, Any], cfg: dict[str, Any]
+) -> str:
+ from octop.infra.agents.acp.session_modes import resolve_managed_session_mode
+
+ explicit = request.get("session_mode") or cfg.get("acp_session_mode")
+ thread_id = _thread_id(request, cfg)
+ stored = None
+ store = getattr(manager, "_hitl_session_store", None)
+ repo = getattr(store, "_repo", None)
+ getter = getattr(repo, "get", None)
+ if callable(getter) and thread_id:
+ row = getter(thread_id)
+ stored = getattr(row, "conversation_mode", None) if row is not None else None
+ return resolve_managed_session_mode(
+ explicit=explicit,
+ stored=stored,
+ config=_stored_config(manager, agent_id),
+ )
+
+
+def _thread_id(request: dict[str, Any], cfg: dict[str, Any]) -> str:
+ raw = request.get("thread_id") or cfg.get("thread_id")
+ return str(raw or "").strip()
+
+
+def _stored_thread_mode(manager: Any, thread_id: str) -> str | None:
+ """Saved chat policy, or ``None`` when this thread has never chosen one."""
+ store = getattr(manager, "_hitl_session_store", None)
+ repo = getattr(store, "_repo", None)
+ getter = getattr(repo, "get", None)
+ if callable(getter) and thread_id:
+ row = getter(thread_id)
+ raw = getattr(row, "hitl_policy", None) if row is not None else None
+ if not isinstance(raw, str) or not raw.strip():
+ return None
+ from octop.infra.agents.security.hitl_session import parse_hitl_session_policy
+
+ policy = parse_hitl_session_policy(raw)
+ return "yolo" if policy.mode == "allow_all" else "ask"
+ read = getattr(store, "get", None)
+ if callable(read) and thread_id:
+ policy = read(thread_id)
+ return "yolo" if getattr(policy, "mode", None) == "allow_all" else "ask"
+ return None
+
+
+def _expert_permission_mode(manager: Any, agent_id: str) -> str:
+ repos = getattr(manager, "_repos", None)
+ get = getattr(getattr(repos, "agent_repo", None), "get", None)
+ if not callable(get) or not agent_id:
+ return "ask"
+ row = get(agent_id)
+ if row is None:
+ return "ask"
+ from octop.infra.agents.managed import read_managed_permission_mode
+ from octop.infra.agents.settings.profile import parse_config_json
+
+ return read_managed_permission_mode(parse_config_json(getattr(row, "config_json", None)))
+
+
+def acp_permission_mode(manager: Any, request: dict[str, Any], agent_id: str = "") -> str:
+ """``yolo`` when this chat, or the expert's default, has turned off approval."""
+ configurable = request.get("configurable")
+ cfg = configurable if isinstance(configurable, dict) else {}
+ explicit = cfg.get("acp_permission_mode")
+ if explicit in {"ask", "yolo"}:
+ return str(explicit)
+ thread_id = _thread_id(request, cfg)
+ stored = _stored_thread_mode(manager, thread_id)
+ if stored is not None:
+ return stored
+ return _expert_permission_mode(manager, agent_id)
+
+
+async def managed_mcp_specs(
+ manager: Any, agent_id: str, request: dict[str, Any]
+) -> tuple[dict[str, Any], str | None] | None:
+ """Specs and @ note for a managed turn. ``None`` when the agent is native."""
+ from octop.infra.agents.acp.cron_mcp import CronScope, retain_cron_scope
+ from octop.infra.agents.acp.delegation import prepare_managed_delegation
+ from octop.infra.agents.acp.files_mcp import retain_file_scope
+ from octop.infra.agents.acp.memory_mcp import memory_enabled, retain_memory_scope
+ from octop.infra.agents.acp.plugins_mcp import plugin_tools, retain_plugin_scope
+ from octop.infra.agents.managed import is_managed_agent
+ from octop.infra.agents.settings.tool_catalog import (
+ MANAGED_AGENT_TOOLS,
+ MANAGED_CRON_TOOLS,
+ MANAGED_FILE_TOOLS,
+ MANAGED_KNOWLEDGE_TOOLS,
+ MANAGED_MEMORY_TOOLS,
+ tools_disabled_set,
+ )
+ from octop.infra.connectors.builder import (
+ cron_mcp_url,
+ files_mcp_url,
+ knowledge_mcp_url,
+ memory_mcp_url,
+ plugins_mcp_url,
+ )
+
+ row = manager.get_row(agent_id)
+ if not is_managed_agent(row):
+ return None
+
+ configurable = request.get("configurable")
+ cfg = configurable if isinstance(configurable, dict) else {}
+ connector_names = _ids(request.get("mcp_servers")) or _ids(cfg.get("mcp_servers"))
+ user_id = _user_id(request)
+ loaded: dict[str, Any] = {}
+ if user_id is not None and connector_names:
+ try:
+ raw = await manager._connector_svc.mcp_configs_for_user(user_id)
+ except Exception:
+ logger.warning("managed ACP MCP specs failed for agent %s", agent_id, exc_info=True)
+ raw = {}
+ if isinstance(raw, dict):
+ loaded = raw
+ specs: dict[str, Any] = {}
+ if _connectors_allowed(request, cfg):
+ specs = {
+ name: loaded[name] for name in connector_names if isinstance(loaded.get(name), dict)
+ }
+
+ stored = _stored_config(manager, agent_id)
+ disabled = tools_disabled_set(stored)
+ locale = str(cfg.get("locale") or "en")
+ # Loopback servers, in the order the runner sees them.
+ kb_ids = tuple(_ids(cfg.get("knowledge_base_ids")))
+ if kb_ids and user_id is not None and _enabled(disabled, MANAGED_KNOWLEDGE_TOOLS):
+ scope = KnowledgeScope(
+ user_id=user_id,
+ is_admin=bool(cfg.get("user_is_admin")),
+ knowledge_base_ids=kb_ids,
+ locale=locale,
+ catalog=_catalog(cfg.get("knowledge_base_catalog")),
+ )
+ _attach(
+ specs,
+ _KNOWLEDGE_NAME,
+ knowledge_mcp_url(config=manager._config, token=retain_knowledge_scope(scope)),
+ )
+ agent_tools = _enabled(disabled, MANAGED_AGENT_TOOLS)
+ try:
+ note, agents = await prepare_managed_delegation(
+ manager,
+ agent_id,
+ request,
+ user_id=user_id,
+ tools=agent_tools,
+ )
+ except Exception:
+ logger.warning("managed ACP expert delegation failed for %s", agent_id, exc_info=True)
+ note, agents = None, None
+ if agents is not None:
+ specs[_AGENTS_NAME] = agents
+ if _enabled(disabled, MANAGED_FILE_TOOLS):
+ _attach(
+ specs,
+ _FILES_NAME,
+ files_mcp_url(config=manager._config, token=retain_file_scope(agent_id)),
+ )
+ cron_tools = _enabled(disabled, MANAGED_CRON_TOOLS)
+ if user_id is not None and cron_tools and getattr(manager, "_cron_manager", None) is not None:
+ cron_scope = CronScope(
+ user_id=user_id,
+ agent_id=agent_id,
+ thread_id=_thread_id(request, cfg),
+ session_key=_session_key(request, cfg, agent_id, user_id),
+ tools=cron_tools,
+ )
+ _attach(
+ specs,
+ _CRON_NAME,
+ cron_mcp_url(config=manager._config, token=retain_cron_scope(cron_scope)),
+ )
+ memory_tools = _enabled(disabled, MANAGED_MEMORY_TOOLS)
+ if memory_enabled(stored) and memory_tools:
+ _attach(
+ specs,
+ _MEMORY_NAME,
+ memory_mcp_url(
+ config=manager._config,
+ token=retain_memory_scope(agent_id, memory_tools),
+ ),
+ )
+ try:
+ enabled_plugins = plugin_tools(manager, stored)
+ except Exception:
+ logger.warning("managed ACP plugin tools failed for %s", agent_id, exc_info=True)
+ enabled_plugins = []
+ if enabled_plugins:
+ plugin_tool_names = tuple(
+ sorted(str(getattr(tool, "name", "")) for tool in enabled_plugins)
+ )
+ _attach(
+ specs,
+ _PLUGINS_NAME,
+ plugins_mcp_url(
+ config=manager._config,
+ token=retain_plugin_scope(agent_id, plugin_tool_names),
+ ),
+ )
+ if _enabled(disabled, MANAGED_FILE_TOOLS):
+ file_note = _send_file_note(locale)
+ note = f"{note}\n{file_note}" if note else file_note
+ if _CRON_NAME in specs:
+ cron_note = _cron_note(locale, _server_timezone(manager))
+ note = f"{note}\n{cron_note}" if note else cron_note
+ limit = _tool_limit_note(specs, locale)
+ if limit:
+ note = f"{note}\n{limit}" if note else limit
+ if specs:
+ logger.info("managed ACP MCP agent=%s servers=%s", agent_id, sorted(specs))
+ return specs, note
+
+
+async def attach_managed_turn(manager: Any, agent_id: str, request: dict[str, Any]) -> None:
+ """Put this turn's MCP specs and @ note on ``request`` for the harness."""
+ extras = await managed_mcp_specs(manager, agent_id, request)
+ if extras is None:
+ return
+ specs, note = extras
+ configurable = request.get("configurable")
+ if not isinstance(configurable, dict):
+ configurable = {}
+ request["configurable"] = configurable
+ configurable["acp_mcp_servers"] = specs
+ session_mode = _managed_session_mode(manager, agent_id, request, configurable)
+ if session_mode:
+ configurable["acp_session_mode"] = session_mode
+ from octop.infra.agents.acp.session_modes import approval_for_session
+
+ stored = _stored_config(manager, agent_id)
+ runner = stored.get("managed_runner") if isinstance(stored, dict) else ""
+ configurable["acp_permission_mode"] = approval_for_session(
+ session_mode,
+ acp_permission_mode(manager, request, agent_id),
+ runner=runner if isinstance(runner, str) else "",
+ )
+ if note:
+ configurable["acp_prompt_note"] = note
diff --git a/src/octop/infra/agents/managed.py b/src/octop/infra/agents/managed.py
index 90608d7ae7..4c4d029a7d 100644
--- a/src/octop/infra/agents/managed.py
+++ b/src/octop/infra/agents/managed.py
@@ -3,11 +3,15 @@
from __future__ import annotations
import json
+import logging
+import sys
from pathlib import Path
from typing import Any
from octop.infra.errors import ErrorCode, OctopError
+logger = logging.getLogger(__name__)
+
_SEED_DIR = Path(__file__).with_name("managed_seed")
MANAGED_KIND = "managed"
@@ -23,19 +27,30 @@ def is_managed_agent(row: Any) -> bool:
return getattr(row, "kind", None) == MANAGED_KIND
+def read_managed_permission_mode(config: dict[str, Any] | None) -> str:
+ """``yolo`` when this expert was created to skip approval. Otherwise ``ask``."""
+ if isinstance(config, dict) and config.get("managed_permission_mode") == "yolo":
+ return "yolo"
+ return "ask"
+
+
def apply_managed_backend(config: dict[str, Any]) -> None:
"""Pin storage to the local filesystem root. The user picks the workspace."""
config["backend"] = dict(MANAGED_BACKEND)
-def pin_managed_runtime(config: dict[str, Any]) -> None:
- """Drop expert-only runtime knobs. The ACP runner owns the turn."""
+def pin_managed_runtime(config: dict[str, Any], *, previous: dict[str, Any] | None = None) -> None:
+ """Drop expert-only runtime knobs. Memory stays off unless this expert enables it."""
config.pop("conversation_mode", None)
memory = config.get("memory")
- section = dict(memory) if isinstance(memory, dict) else {}
- section["memory_enabled"] = False
- section["memory_capture_enabled"] = False
- section["memory_recall_inject_enabled"] = False
+ if isinstance(memory, dict):
+ section = dict(memory)
+ else:
+ prior = (previous or {}).get("memory")
+ section = dict(prior) if isinstance(prior, dict) else {}
+ section.setdefault("memory_enabled", False)
+ section.setdefault("memory_capture_enabled", False)
+ section.setdefault("memory_recall_inject_enabled", False)
config["memory"] = section
@@ -83,6 +98,112 @@ def managed_subagent_dir(runner: str) -> str:
return f"{managed_project_root(runner)}/agents"
+def _owned_link(path: Path) -> bool:
+ if path.is_symlink():
+ return True
+ is_junction = getattr(path, "is_junction", None)
+ return bool(callable(is_junction) and is_junction())
+
+
+def _known_skill_dirs(workspace: Path) -> list[Path]:
+ roots = set(_RUNNER_PROJECT_ROOTS.values())
+ roots.add(_DEFAULT_PROJECT_ROOT)
+ return [workspace / f"{root}/skills" for root in sorted(roots)]
+
+
+def _load_skill_manifest(path: Path) -> tuple[str, list[str]]:
+ if not path.is_file():
+ return "", []
+ try:
+ raw = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, json.JSONDecodeError):
+ return "", []
+ if isinstance(raw, list):
+ return "", [str(item) for item in raw if str(item).strip()]
+ if isinstance(raw, dict):
+ runner = str(raw.get("runner") or "").strip()
+ links = raw.get("links")
+ if isinstance(links, list):
+ return runner, [str(item) for item in links if str(item).strip()]
+ return "", []
+
+
+def _remove_owned_links(dest_root: Path, names: list[str]) -> None:
+ for name in names:
+ link = dest_root / name
+ if _owned_link(link):
+ link.unlink()
+
+
+def _place_skill_link(target: Path, source: Path) -> None:
+ resolved = source.resolve()
+ try:
+ target.symlink_to(resolved, target_is_directory=True)
+ except OSError:
+ if sys.platform == "win32":
+ import _winapi
+
+ _winapi.CreateJunction(str(resolved), str(target))
+ return
+ raise
+
+
+def link_managed_skill_packages(
+ workspace: Path,
+ runner: str,
+ package_dirs: list[Path],
+) -> list[str]:
+ """Expose selected skill packages inside the runner's own skills directory.
+
+ Returns skill names that were skipped because another package, or a real
+ directory, already owns that name. The first package wins. Links this
+ function created earlier are removed, including after the runner changes.
+ """
+ root = runner.strip()
+ if not root:
+ return []
+ dest_root = workspace / managed_skill_dir(root)
+ dest_root.mkdir(parents=True, exist_ok=True)
+ manifest_path = workspace / ".octop" / "managed-skill-links.json"
+ previous_runner, previous = _load_skill_manifest(manifest_path)
+ if previous_runner:
+ _remove_owned_links(workspace / managed_skill_dir(previous_runner), previous)
+ else:
+ for skill_dir in _known_skill_dirs(workspace):
+ _remove_owned_links(skill_dir, previous)
+ created: list[str] = []
+ skipped: list[str] = []
+ for package_dir in package_dirs:
+ if not package_dir.is_dir():
+ continue
+ for child in sorted(package_dir.iterdir()):
+ if not child.is_dir() or not (child / "SKILL.md").is_file():
+ continue
+ slug = child.name
+ target = dest_root / slug
+ if slug in created or target.exists() or _owned_link(target):
+ if slug not in skipped:
+ skipped.append(slug)
+ continue
+ try:
+ _place_skill_link(target, child)
+ except OSError:
+ logger.warning("managed skill link failed for %s", slug, exc_info=True)
+ continue
+ created.append(slug)
+ manifest_path.parent.mkdir(parents=True, exist_ok=True)
+ manifest_path.write_text(
+ json.dumps({"runner": root, "links": created}),
+ encoding="utf-8",
+ )
+ if skipped:
+ logger.warning(
+ "managed skill names already exist, kept the first: %s",
+ ", ".join(skipped),
+ )
+ return skipped
+
+
def managed_template_payload() -> dict[str, Any]:
"""Welcome cards and prompt files copied into a new managed workspace."""
manifest = json.loads((_SEED_DIR / "manifest.json").read_text(encoding="utf-8"))
@@ -128,12 +249,39 @@ async def seed_managed_workspace(
await apply_workspace_quick_prompts(workspace, quick_prompts)
+def _keep_offered_session_mode(config: dict[str, Any]) -> None:
+ """Drop a mode id this underlying agent does not publish."""
+ from octop.infra.agents.acp.session_modes import session_modes
+
+ mode = config.get("managed_session_mode")
+ text = mode.strip() if isinstance(mode, str) else ""
+ runner = config.get("managed_runner")
+ runner_name = runner.strip() if isinstance(runner, str) else ""
+ offered = {item.id for item in session_modes(runner_name)}
+ if text and (not runner_name or not offered or text not in offered):
+ config.pop("managed_session_mode", None)
+ return
+ if text:
+ config["managed_session_mode"] = text
+ return
+ config.pop("managed_session_mode", None)
+
+
def preserve_managed_config(config: dict[str, Any], previous: dict[str, Any]) -> None:
"""Keep the ACP binding and filesystem root across later edits."""
apply_managed_backend(config)
- pin_managed_runtime(config)
+ pin_managed_runtime(config, previous=previous)
runner = config.get("managed_runner")
if not isinstance(runner, str) or not runner.strip():
previous_runner = previous.get("managed_runner")
if isinstance(previous_runner, str) and previous_runner.strip():
config["managed_runner"] = previous_runner.strip()
+ if config.get("managed_permission_mode") not in {"ask", "yolo"}:
+ previous_mode = previous.get("managed_permission_mode")
+ if previous_mode in {"ask", "yolo"}:
+ config["managed_permission_mode"] = previous_mode
+ if "managed_session_mode" not in config:
+ previous_session = previous.get("managed_session_mode")
+ if isinstance(previous_session, str) and previous_session.strip():
+ config["managed_session_mode"] = previous_session.strip()
+ _keep_offered_session_mode(config)
diff --git a/src/octop/infra/agents/manager.py b/src/octop/infra/agents/manager.py
index e62e216ff0..e978be2a84 100644
--- a/src/octop/infra/agents/manager.py
+++ b/src/octop/infra/agents/manager.py
@@ -24,8 +24,12 @@
NO_MODELS_CONFIGURED,
format_agent_start_error,
)
-from octop.infra.agents.acp_permission_compat import install_acp_permission_queue
-from octop.infra.agents.acp_tool_name_compat import install_acp_tool_titles
+from octop.infra.agents.acp import (
+ attach_managed_turn,
+ install_acp_file_edits,
+ install_acp_permission_queue,
+ install_acp_tool_titles,
+)
from octop.infra.agents.memory.backend import memory_backend_from_agent_config
from octop.infra.agents.memory.slim import MemorySlimCoordinator
from octop.infra.agents.providers import HostModelFactory, ProviderStore, sync_providers_to_harness
@@ -112,6 +116,7 @@
install_acp_permission_queue()
install_acp_tool_titles()
+install_acp_file_edits()
def _model_retry_on_failure(
@@ -2092,6 +2097,7 @@ async def stream(self, agent_id: str, request: dict[str, Any]) -> AsyncIterator[
):
self._apply_pending_bootstrap_graph_refresh(agent_id)
req = self._prepare_stream_request(agent_id, request)
+ await attach_managed_turn(self, agent_id, req)
with (
hitl_thread_scope(thread_id_from_request(req)),
turn_model_scope(self._stream_model_label(agent_id, req, thread_id)),
@@ -2147,6 +2153,7 @@ async def call(self, agent_id: str, request: dict[str, Any]) -> dict[str, Any]:
self._apply_pending_bootstrap_graph_refresh(agent_id)
req = self._prepare_stream_request(agent_id, request)
thread_id = str(req.get("thread_id") or thread_id_from_request(req) or "")
+ await attach_managed_turn(self, agent_id, req)
with (
hitl_thread_scope(thread_id_from_request(req)),
turn_model_scope(self._stream_model_label(agent_id, req, thread_id)),
@@ -2688,7 +2695,12 @@ async def prepare_chat_mcp(
agent_id,
sorted(awaiting_auth),
)
- return sorted(awaiting_auth)
+ # Keep loading the rest. Callers that need every server still see
+ # the blocked names in the returned list.
+ mapped_blocked = {aliases.get(name, name) for name in awaiting_auth}
+ names = [
+ name for name in names if name not in awaiting_auth and name not in mapped_blocked
+ ]
if aliases and uid is not None and owner_id is not None:
# Load the owner's spec when the turn asked for the shared server.
# A viewer's own server with the same short name stays theirs unless
@@ -2732,7 +2744,7 @@ async def prepare_chat_mcp(
agent_id,
matched,
)
- return []
+ return sorted(awaiting_auth)
custom_missing = [n for n in missing_tools if n in custom_configs]
builtin_missing = [n for n in missing_tools if n not in custom_configs]
@@ -2887,6 +2899,12 @@ async def prepare_chat_mcp(
else name
for name in still_missing
]
+ if awaiting_auth:
+ missing = list(still_missing)
+ for name in sorted(awaiting_auth):
+ if name not in missing:
+ missing.append(name)
+ still_missing = missing
return still_missing
async def connector_auth_blocked(
@@ -3255,8 +3273,26 @@ async def persist_skill_package_ids(self, agent_id: str, package_ids: list[str])
skill_package_ids=dump_id_list(normalized_ids),
config_json=dumps_config(cfg),
)
+ if getattr(row, "kind", None) == "managed":
+ fresh = self._repos.agent_repo.get(agent_id)
+ if fresh is not None:
+ self._link_managed_skill_packages(fresh)
self.sync_skill_package_dirs(agent_id)
+ def _link_managed_skill_packages(self, row: AgentRow) -> None:
+ """Point the runner's skills directory at the selected packages."""
+ cfg = self.get_config(row.agent_id)
+ runner = cfg.get("managed_runner")
+ if not isinstance(runner, str) or not runner.strip():
+ return
+ from octop.infra.agents.managed import link_managed_skill_packages # noqa: PLC0415
+
+ link_managed_skill_packages(
+ self.resolve_workspace_dir(row.agent_id),
+ runner.strip(),
+ [Path(item) for item in self._resolve_skill_package_dirs(row.agent_id)],
+ )
+
def sync_skill_package_dirs(self, agent_id: str) -> None:
"""Hot-update ``skills_dir`` on the running harness agent (no rebuild)."""
try:
@@ -3275,7 +3311,18 @@ def sync_skill_package_dirs(self, agent_id: str) -> None:
)
configured = self._normalize_skills_dir_config(cfg.get("skills"))
package_dirs = self._resolve_skill_package_dirs(agent_id) if supports_packages else []
- skill_dirs = configured + package_dirs
+ if getattr(row, "kind", None) == "managed":
+ from octop.infra.agents.managed import managed_skill_dir # noqa: PLC0415
+
+ runner = cfg.get("managed_runner")
+ runner_dir = (
+ managed_skill_dir(runner.strip())
+ if isinstance(runner, str) and runner.strip()
+ else ""
+ )
+ skill_dirs = [runner_dir, *package_dirs] if runner_dir else list(package_dirs)
+ else:
+ skill_dirs = configured + package_dirs
config = getattr(agent, "config", None)
if config is None:
config = getattr(agent, "_config", None)
@@ -4337,8 +4384,9 @@ def _managed_harness_config(
"""Harness config for an ACP-backed agent.
Chat, workspace files, skills, and subagents still go through the
- same surfaces as an expert. Bootstrap, memory, and the model tool
- stack stay off: the connected runner executes the turn.
+ same surfaces as an expert. Bootstrap and the model tool stack stay
+ off: the connected runner executes the turn. Memory follows this
+ expert's stored config and stays off unless that config enables it.
"""
from octop_harness.acp.models import ACPConfig # noqa: PLC0415
@@ -4357,14 +4405,18 @@ def _managed_harness_config(
acp_config = ACPConfig.from_dict({"runners": runners})
runner = cfg.get("managed_runner")
runner_id = runner.strip() if isinstance(runner, str) else ""
- off: dict[str, Any] = {}
- for key in (
- "memory_capture_enabled",
- "memory_recall_inject_enabled",
- "memory_extract_on_session_end",
- ):
- if key in _HARNESS_AGENT_CONFIG_FIELDS:
- off[key] = False
+ memory_settings = _memory_extract_settings(cfg)
+ if memory_settings.get("memory_enabled") is not True:
+ memory_settings = {
+ key: False
+ for key in (
+ "memory_enabled",
+ "memory_capture_enabled",
+ "memory_recall_inject_enabled",
+ "memory_extract_on_session_end",
+ )
+ if key in _HARNESS_AGENT_CONFIG_FIELDS
+ }
built = HarnessAgentConfig(
name=_memory_namespace(row.agent_id),
workspace_dir=harness_workspace,
@@ -4375,15 +4427,22 @@ def _managed_harness_config(
),
backend=backend,
bootstrap_enabled=False,
- memory_enabled=False,
acp_runners=acp_config.runners,
acp_delegate_enabled=False,
default_timezone=self._config.default_timezone,
- **off,
+ **memory_settings,
)
if runner_id and "managed_runner" in _HARNESS_AGENT_CONFIG_FIELDS:
built.managed_runner = runner_id
- built.skills_dir = managed_skill_dir(runner_id)
+ from octop.infra.agents.managed import link_managed_skill_packages # noqa: PLC0415
+
+ package_dirs = self._resolve_skill_package_dirs(row.agent_id)
+ link_managed_skill_packages(
+ harness_workspace,
+ runner_id,
+ [Path(item) for item in package_dirs],
+ )
+ built.skills_dir = [managed_skill_dir(runner_id), *package_dirs]
if "subagents_path" in _HARNESS_AGENT_CONFIG_FIELDS:
built.subagents_path = managed_subagent_dir(runner_id)
return built
@@ -4430,7 +4489,8 @@ def _build_harness_config(self, row: AgentRow) -> HarnessAgentConfig:
backend = self._backend_spec_for_row(row, cfg=cfg, workspace_dir=workspace_dir)
if getattr(row, "kind", None) == "managed":
# The ACP runner is the agent. Reuse the workspace and runner
- # binding; do not assemble the expert tool, memory, or bootstrap stack.
+ # binding; do not assemble the expert tool or bootstrap stack.
+ # Memory starts only when this expert's config enables it.
return self._managed_harness_config(
row,
cfg=cfg,
diff --git a/src/octop/infra/agents/memory/thread_cleanup.py b/src/octop/infra/agents/memory/thread_cleanup.py
index 12effc2595..9cb8dfc657 100644
--- a/src/octop/infra/agents/memory/thread_cleanup.py
+++ b/src/octop/infra/agents/memory/thread_cleanup.py
@@ -62,6 +62,9 @@
# the namespace. ``harness_memory`` is the pre-rename shared schema.
_SHARED_MEMORY_SCHEMAS = frozenset({"octop_memory", "harness_memory", "public"})
_IDENT = re.compile(r"[A-Za-z_][A-Za-z0-9_]*")
+# Schema octop_memory's Postgres pool puts first on ``search_path``. Its
+# checkpoint tables land in the first of these that exists at setup.
+_MEMORY_SCHEMA = "octop_memory"
@dataclass(frozen=True)
@@ -71,6 +74,28 @@ class OrphanCheckpoint:
nbytes: int
+@dataclass(frozen=True)
+class SkippedCheckpoints:
+ """Orphans of ``agent_id`` that were reported but not deleted.
+
+ ``reason`` is ``postgres_report_only`` (checkpoint tables are shared by
+ every agent and host on the DSN and record no owner, so nothing there is
+ deleted) or ``external_database`` (the agent's Postgres store is not the
+ control-plane database; it is not scanned and ``threads`` is ``None``).
+ """
+
+ agent_id: str
+ reason: str
+ threads: int | None
+ nbytes: int
+
+
+@dataclass(frozen=True)
+class OrphanScan:
+ orphans: list[OrphanCheckpoint]
+ skipped: list[SkippedCheckpoints]
+
+
def workspace_for_agent_row(row: Any, *, paths: Any) -> Path:
"""On-disk workspace for an agent row. Does not create the directory."""
return workspace_dir_from_config_json(
@@ -244,7 +269,12 @@ def checkpoint_thread_bytes(
octop_config: OctopConfig,
workspace_dir: Path,
) -> dict[str, int]:
- """``thread_id -> checkpoint payload bytes`` currently stored for the agent."""
+ """``thread_id -> checkpoint payload bytes`` currently stored for the agent.
+
+ Postgres stores every agent's checkpoints in shared tables, so rows are
+ attributed by the ``agent_id`` Octop writes into checkpoint metadata.
+ The Postgres query is read-only and does not open ``Memory``.
+ """
_ns, backend, backend_config, sqlite_path = _memory_location(
agent_id=agent_id,
cfg=cfg,
@@ -255,34 +285,51 @@ def checkpoint_thread_bytes(
if sqlite_path is None or not sqlite_path.is_file():
return {}
return _sqlite_thread_bytes(sqlite_path)
- memory = _open_memory(_ns, backend, backend_config)
- try:
- return _postgres_thread_bytes(memory)
- finally:
- close_memory(memory)
+ return _postgres_thread_bytes(str((backend_config or {}).get("dsn") or ""), agent_id)
-def gc_orphan_checkpoints(
- services: Any, *, agent_id: str | None, apply: bool
-) -> list[OrphanCheckpoint]:
+def gc_orphan_checkpoints(services: Any, *, agent_id: str | None, apply: bool) -> OrphanScan:
"""Checkpoints whose thread row is already gone.
- ``apply=False`` only reports them. ``apply=True`` deletes each one
- through :func:`delete_stored_thread`.
+ ``apply=False`` only reports them. ``apply=True`` deletes SQLite orphans
+ through :func:`delete_stored_thread`. Postgres orphans are never deleted:
+ the control-plane database is counted read-only and other databases are
+ not scanned. Both are reported in ``skipped``.
"""
rows = services.agent_repo.list_all(include_disabled=True)
if agent_id is not None:
rows = [row for row in rows if row.agent_id == agent_id]
+ config = services.config
+ control_dsn = config.database.postgresql_conninfo() if config.database.is_postgresql else None
+ live_threads: set[str] | None = None
found: list[OrphanCheckpoint] = []
+ skipped: list[SkippedCheckpoints] = []
for row in rows:
cfg = agent_config_from_row(row)
workspace = workspace_for_agent_row(row, paths=services.paths)
- usage = checkpoint_thread_bytes(
+ _ns, backend, backend_config, _path = _memory_location(
agent_id=row.agent_id,
cfg=cfg,
- octop_config=services.config,
+ octop_config=config,
workspace_dir=workspace,
)
+ if backend == "postgres":
+ dsn = str((backend_config or {}).get("dsn") or "")
+ if dsn != control_dsn:
+ skipped.append(SkippedCheckpoints(row.agent_id, "external_database", None, 0))
+ continue
+ if live_threads is None:
+ live_threads = _all_live_threads(services)
+ usage = _postgres_thread_bytes(dsn, row.agent_id)
+ kept = [nbytes for tid, nbytes in usage.items() if tid not in live_threads]
+ if kept:
+ skipped.append(
+ SkippedCheckpoints(row.agent_id, "postgres_report_only", len(kept), sum(kept))
+ )
+ continue
+ usage = checkpoint_thread_bytes(
+ agent_id=row.agent_id, cfg=cfg, octop_config=config, workspace_dir=workspace
+ )
known = services.thread_repo.list_ids_for_agent(row.agent_id)
orphans = [
OrphanCheckpoint(agent_id=row.agent_id, thread_id=tid, nbytes=nbytes)
@@ -295,11 +342,19 @@ def gc_orphan_checkpoints(
agent_id=row.agent_id,
thread_id=orphan.thread_id,
cfg=cfg,
- octop_config=services.config,
+ octop_config=config,
workspace_dir=workspace,
)
found.extend(orphans)
- return found
+ return OrphanScan(orphans=found, skipped=skipped)
+
+
+def _all_live_threads(services: Any) -> set[str]:
+ """Thread ids of every agent: a Postgres thread may be listed under any of them."""
+ live: set[str] = set()
+ for row in services.agent_repo.list_all(include_disabled=True):
+ live |= services.thread_repo.list_ids_for_agent(row.agent_id)
+ return live
def close_memory(memory: Any) -> None:
@@ -687,30 +742,35 @@ def _sqlite_thread_bytes(path: Path) -> dict[str, int]:
return {str(thread_id): int(nbytes or 0) for thread_id, nbytes in rows}
-def _postgres_thread_bytes(memory: Any) -> dict[str, int]:
- memory._ensure_checkpointer()
- saver = memory._checkpointer
- cursor = getattr(saver, "_cursor", None)
- if cursor is None:
- return {}
- try:
- with cursor() as cur:
- cur.execute(
- "SELECT thread_id, COALESCE(SUM(pg_column_size(checkpoint)), 0) AS nbytes "
- "FROM checkpoints GROUP BY thread_id"
- )
- rows = cur.fetchall()
- except Exception as exc:
- if _store_has_no_checkpoints(exc):
+def _connect_read_only(dsn: str) -> Any:
+ import psycopg
+
+ conn = psycopg.connect(dsn)
+ conn.read_only = True
+ return conn
+
+
+def _postgres_checkpoints_table(cur: Any) -> str | None:
+ """Schema-qualified ``checkpoints`` table as octop_memory's saver resolves it."""
+ for schema in (_MEMORY_SCHEMA, "public"):
+ cur.execute("SELECT to_regclass(%s)", (f"{schema}.checkpoints",))
+ found = cur.fetchone()
+ if found is not None and found[0] is not None:
+ return f"{schema}.checkpoints"
+ return None
+
+
+def _postgres_thread_bytes(dsn: str, agent_id: str) -> dict[str, int]:
+ with _connect_read_only(dsn) as conn, conn.cursor() as cur:
+ table = _postgres_checkpoints_table(cur)
+ if table is None:
return {}
- raise
- out: dict[str, int] = {}
- for row in rows:
- if isinstance(row, dict):
- out[str(row["thread_id"])] = int(row["nbytes"] or 0)
- else:
- out[str(row[0])] = int(row[1] or 0)
- return out
+ cur.execute(
+ "SELECT thread_id, COALESCE(SUM(pg_column_size(checkpoint)), 0) "
+ f"FROM {table} WHERE metadata->>'agent_id' = %s GROUP BY thread_id",
+ (agent_id,),
+ )
+ return {str(tid): int(nbytes or 0) for tid, nbytes in cur.fetchall()}
def _store_has_no_checkpoints(exc: BaseException) -> bool:
@@ -735,14 +795,26 @@ def sweep_deleted_residuals(
Safe to call from memory slim. Live agents and their current threads are
kept. Directories under ``agents/`` and ``workspaces/`` whose names match
no agent are only removed when ``remove_directories`` is true; otherwise
- their paths are returned for a second confirmation. Postgres namespaces
- and checkpoint rows are removed only from databases this instance uses.
+ their paths are returned for a second confirmation.
+
+ Postgres is only counted, never cleaned: checkpoint tables record no
+ owner and may be shared with other installs or hosts. The control-plane
+ database's leftovers are counted read-only in ``postgres_kept``; other
+ Postgres databases are not scanned and are counted in
+ ``skipped_databases``.
"""
repos = getattr(agent_manager, "_repos", None)
paths = getattr(agent_manager, "_paths", None)
config = getattr(agent_manager, "_config", None)
if repos is None or paths is None or config is None:
- return {"namespaces": 0, "threads": 0, "directories": 0, "directory_paths": []}
+ return {
+ "namespaces": 0,
+ "threads": 0,
+ "directories": 0,
+ "directory_paths": [],
+ "postgres_kept": None,
+ "skipped_databases": 0,
+ }
rows = repos.agent_repo.list_all(include_disabled=True)
live_ids = {str(row.agent_id) for row in rows}
live_namespaces = {memory_namespace(agent_id) for agent_id in live_ids}
@@ -751,13 +823,12 @@ def sweep_deleted_residuals(
live_threads |= repos.thread_repo.list_ids_for_agent(agent_id)
threads_removed = 0
- namespaces_removed = 0
- seen_dsn: set[str] = set()
+ postgres_kept: dict[str, int] | None = None
+ control_dsn: str | None = None
if config.database.is_postgresql:
- dsn = config.database.postgresql_conninfo()
- seen_dsn.add(dsn)
- threads_removed += _delete_postgres_orphan_checkpoints(dsn, live_threads)
- namespaces_removed += _delete_postgres_orphan_namespaces(dsn, live_namespaces)
+ control_dsn = config.database.postgresql_conninfo()
+ postgres_kept = _count_postgres_residuals(control_dsn, live_threads, live_namespaces)
+ external: set[str] = set()
for row in rows:
cfg = agent_config_from_row(row)
workspace = workspace_for_agent_row(row, paths=paths)
@@ -769,10 +840,8 @@ def sweep_deleted_residuals(
)
if backend == "postgres":
dsn = str((backend_config or {}).get("dsn") or "")
- if dsn and dsn not in seen_dsn:
- seen_dsn.add(dsn)
- threads_removed += _delete_postgres_orphan_checkpoints(dsn, live_threads)
- namespaces_removed += _delete_postgres_orphan_namespaces(dsn, live_namespaces)
+ if dsn != control_dsn:
+ external.add(dsn)
continue
agent_threads = repos.thread_repo.list_ids_for_agent(row.agent_id)
files = _sqlite_memory_files(
@@ -785,13 +854,43 @@ def sweep_deleted_residuals(
directory_paths = [str(path) for path in list_deleted_agent_dirs(paths, live_ids)]
directories_removed = _remove_deleted_agent_dirs(paths, live_ids) if remove_directories else 0
return {
- "namespaces": namespaces_removed,
+ "namespaces": 0,
"threads": threads_removed,
"directories": directories_removed,
"directory_paths": directory_paths,
+ "postgres_kept": postgres_kept,
+ "skipped_databases": len(external),
}
+def describe_sweep(sweep: dict[str, Any], locale: str) -> str:
+ """User-facing summary of :func:`sweep_deleted_residuals`, one line per fact."""
+ from octop.i18n import tr
+
+ lines = [
+ tr(
+ "memory_slim.swept",
+ locale,
+ namespaces=sweep.get("namespaces", 0),
+ threads=sweep.get("threads", 0),
+ directories=sweep.get("directories", 0),
+ )
+ ]
+ kept = sweep.get("postgres_kept")
+ if isinstance(kept, dict) and (kept.get("threads") or kept.get("namespaces")):
+ lines.append(
+ tr(
+ "memory_slim.postgres_kept",
+ locale,
+ threads=kept.get("threads", 0),
+ namespaces=kept.get("namespaces", 0),
+ )
+ )
+ if sweep.get("skipped_databases"):
+ lines.append(tr("memory_slim.skipped_databases", locale, count=sweep["skipped_databases"]))
+ return "\n".join(lines)
+
+
def _delete_sqlite_orphan_checkpoints(path: Path, live_threads: set[str]) -> int:
if not path.is_file():
return 0
@@ -824,85 +923,41 @@ def _delete_sqlite_orphan_checkpoints(path: Path, live_threads: set[str]) -> int
conn.close()
-def _delete_postgres_orphan_checkpoints(dsn: str, live_threads: set[str]) -> int:
- import psycopg
+def _count_postgres_residuals(
+ dsn: str, live_threads: set[str], live_namespaces: set[str]
+) -> dict[str, int]:
+ """Count, read-only, checkpoint threads and memory namespaces nothing here owns.
- with psycopg.connect(dsn, autocommit=True) as conn, conn.cursor() as cur:
- cur.execute("SELECT to_regclass('public.checkpoints')")
- found = cur.fetchone()
- if found is None or found[0] is None:
- return 0
- if live_threads:
+ Only Octop-written checkpoints (``agent_id`` in metadata) and namespaces in
+ the current memory schema are counted. The pre-rename ``harness_memory``
+ schema is left alone until octop_memory migrates it.
+ """
+ with _connect_read_only(dsn) as conn, conn.cursor() as cur:
+ threads = 0
+ table = _postgres_checkpoints_table(cur)
+ if table is not None:
cur.execute(
- "SELECT DISTINCT thread_id FROM checkpoints WHERE NOT (thread_id = ANY(%s))",
+ f"SELECT COUNT(DISTINCT thread_id) FROM {table} "
+ "WHERE metadata->>'agent_id' IS NOT NULL AND NOT (thread_id = ANY(%s))",
(list(live_threads),),
)
- else:
- cur.execute("SELECT DISTINCT thread_id FROM checkpoints")
- orphan_ids = [str(row[0]) for row in cur.fetchall()]
- if not orphan_ids:
- return 0
- for table in ("checkpoints", "checkpoint_blobs", "checkpoint_writes"):
- cur.execute("SELECT to_regclass(%s)", (f"public.{table}",))
found = cur.fetchone()
- if found is None or found[0] is None:
- continue
- cur.execute(
- f"DELETE FROM public.{table} WHERE thread_id = ANY(%s)",
- (orphan_ids,),
- )
- return len(orphan_ids)
-
-
-def _delete_postgres_orphan_namespaces(dsn: str, live_namespaces: set[str]) -> int:
- import psycopg
-
- removed = 0
- with psycopg.connect(dsn, autocommit=True) as conn, conn.cursor() as cur:
+ threads = int(found[0]) if found else 0
cur.execute(
- """
- SELECT table_schema, table_name
- FROM information_schema.columns
- WHERE column_name = 'namespace'
- AND table_name = ANY(%s)
- AND table_schema NOT IN ('pg_catalog', 'information_schema')
- """,
- (list(_NAMESPACE_TABLES),),
+ "SELECT table_name FROM information_schema.tables "
+ "WHERE table_schema = %s AND table_name = ANY(%s)",
+ (_MEMORY_SCHEMA, list(_NAMESPACE_TABLES)),
)
- targets = [(str(schema), str(table)) for schema, table in cur.fetchall()]
+ tables = [str(name) for (name,) in cur.fetchall() if _IDENT.fullmatch(str(name))]
namespaces: set[str] = set()
- for schema, table in targets:
- if _IDENT.fullmatch(schema) is None or _IDENT.fullmatch(table) is None:
- continue
+ for name in tables:
cur.execute(
- f"SELECT DISTINCT namespace FROM {_quote_ident(schema)}.{_quote_ident(table)} "
- "WHERE namespace LIKE 'agent_%'"
+ f"SELECT DISTINCT namespace FROM {_MEMORY_SCHEMA}.{_quote_ident(name)} "
+ "WHERE namespace LIKE %s",
+ (r"agent\_%",),
)
- namespaces.update(str(row[0]) for row in cur.fetchall() if row[0])
- stale = sorted(
- ns for ns in namespaces if ns not in live_namespaces and _IDENT.fullmatch(ns)
- )
- if not stale:
- return 0
- for schema, table in targets:
- if _IDENT.fullmatch(schema) is None or _IDENT.fullmatch(table) is None:
- continue
- cur.execute(
- f"DELETE FROM {_quote_ident(schema)}.{_quote_ident(table)} WHERE namespace = ANY(%s)",
- (stale,),
- )
- for namespace in stale:
- for legacy in (namespace, f"{namespace[:56]}__old"):
- if legacy in _SHARED_MEMORY_SCHEMAS or _IDENT.fullmatch(legacy) is None:
- continue
- cur.execute(
- "SELECT 1 FROM information_schema.schemata WHERE schema_name = %s",
- (legacy,),
- )
- if cur.fetchone() is not None:
- cur.execute(f"DROP SCHEMA {_quote_ident(legacy)} CASCADE")
- removed = len(stale)
- return removed
+ namespaces.update(str(ns) for (ns,) in cur.fetchall() if ns)
+ return {"threads": threads, "namespaces": len(namespaces - live_namespaces)}
def list_deleted_agent_dirs(paths: Any, live_ids: set[str]) -> list[Path]:
diff --git a/src/octop/infra/agents/middleware/consecutive_tool_call.py b/src/octop/infra/agents/middleware/consecutive_tool_call.py
new file mode 100644
index 0000000000..1d466fec5c
--- /dev/null
+++ b/src/octop/infra/agents/middleware/consecutive_tool_call.py
@@ -0,0 +1,149 @@
+"""Stop a turn that repeats one tool call with the same arguments.
+
+A normal turn may call many different tools. This middleware only counts a
+streak of the same tool and the same arguments. A different tool, different
+arguments, or a model reply with no tool call starts the streak over.
+"""
+
+from __future__ import annotations
+
+import json
+from typing import Annotated, Any, NotRequired, override
+
+from langchain.agents.middleware import AgentMiddleware, AgentState, hook_config
+from langchain.agents.middleware.types import PrivateStateAttr
+from langchain_core.messages import AIMessage, ToolMessage
+from langgraph.channels.untracked_value import UntrackedValue
+
+_STREAK_KEY = "tool_call_streak"
+
+
+class ConsecutiveToolCallState(AgentState[Any]):
+ """Run-local streak. ``UntrackedValue`` drops it at the next user turn."""
+
+ tool_call_streak: NotRequired[Annotated[dict[str, Any], UntrackedValue, PrivateStateAttr]]
+
+
+def tool_call_signature(tool_call: dict[str, Any]) -> str:
+ """Stable identity of one tool invocation: name plus arguments."""
+ name = str(tool_call.get("name") or "")
+ args = tool_call.get("args")
+ payload = args if isinstance(args, dict) else {"__args__": args}
+ try:
+ encoded = json.dumps(payload, sort_keys=True, ensure_ascii=False, default=str)
+ except (TypeError, ValueError):
+ encoded = str(payload)
+ return f"{name}\n{encoded}"
+
+
+class ConsecutiveToolCallMiddleware(AgentMiddleware[ConsecutiveToolCallState, Any, Any]):
+ """End the turn when one identical tool call repeats past ``limit``."""
+
+ state_schema = ConsecutiveToolCallState
+
+ def __init__(self, *, limit: int) -> None:
+ super().__init__()
+ if limit < 1:
+ msg = f"limit must be at least 1, got {limit}"
+ raise ValueError(msg)
+ self.limit = limit
+
+ @hook_config(can_jump_to=["end"])
+ @override
+ def after_model(
+ self,
+ state: ConsecutiveToolCallState,
+ runtime: Any,
+ ) -> dict[str, Any] | None:
+ del runtime
+ messages = state.get("messages", [])
+ if not messages:
+ return None
+
+ last_ai: AIMessage | None = None
+ for message in reversed(messages):
+ if isinstance(message, AIMessage):
+ last_ai = message
+ break
+ if last_ai is None:
+ return None
+
+ raw_streak = state.get(_STREAK_KEY)
+ streak: dict[str, Any] = raw_streak if isinstance(raw_streak, dict) else {}
+ if not last_ai.tool_calls:
+ if not streak.get("count"):
+ return None
+ return {_STREAK_KEY: {"signature": "", "count": 0}}
+
+ signature = str(streak.get("signature") or "")
+ count = int(streak.get("count") or 0)
+ blocked: list[dict[str, Any]] = []
+ exceeded_name = ""
+ exceeded_count = 0
+ for tool_call in last_ai.tool_calls:
+ call = dict(tool_call)
+ next_signature = tool_call_signature(call)
+ if next_signature == signature:
+ count += 1
+ else:
+ signature = next_signature
+ count = 1
+ if count > self.limit:
+ blocked.append(call)
+ if not exceeded_name:
+ exceeded_name = str(call.get("name") or "")
+ exceeded_count = count
+
+ if not blocked:
+ return {_STREAK_KEY: {"signature": signature, "count": count}}
+
+ blocked_ids = {str(call.get("id") or "") for call in blocked}
+ artificial: list[ToolMessage | AIMessage] = [
+ ToolMessage(
+ content=(
+ "Tool call limit exceeded. Do not repeat this tool call "
+ "with the same arguments."
+ ),
+ tool_call_id=str(call.get("id") or ""),
+ name=call.get("name"),
+ status="error",
+ )
+ for call in blocked
+ ]
+ artificial.extend(
+ ToolMessage(
+ content=(
+ "Execution stopped before this tool call could run because "
+ "a repeated tool call in the same batch exceeded the limit."
+ ),
+ tool_call_id=str(tool_call.get("id") or ""),
+ name=tool_call.get("name"),
+ status="error",
+ )
+ for tool_call in last_ai.tool_calls
+ if str(tool_call.get("id") or "") not in blocked_ids
+ )
+ shown = exceeded_name or "tool"
+ artificial.append(
+ AIMessage(
+ content=(
+ "[tool_call_repeat]\n"
+ f"tool: {shown}\n"
+ f"count: {exceeded_count}\n"
+ f"limit: {self.limit}"
+ )
+ )
+ )
+ return {
+ _STREAK_KEY: {"signature": signature, "count": count},
+ "jump_to": "end",
+ "messages": artificial,
+ }
+
+ @hook_config(can_jump_to=["end"])
+ async def aafter_model(
+ self,
+ state: ConsecutiveToolCallState,
+ runtime: Any,
+ ) -> dict[str, Any] | None:
+ return self.after_model(state, runtime)
diff --git a/src/octop/infra/agents/security/hitl_session.py b/src/octop/infra/agents/security/hitl_session.py
index ff3244a005..7fd0ea70fe 100644
--- a/src/octop/infra/agents/security/hitl_session.py
+++ b/src/octop/infra/agents/security/hitl_session.py
@@ -86,10 +86,9 @@ def to_dict(self) -> dict[str, Any]:
return {"mode": "ask"}
def to_json(self) -> str | None:
- data = self.to_dict()
- if data.get("mode") == "ask":
- return None
- return json.dumps(data, ensure_ascii=False)
+ # Ask is stored too. An empty column means the thread never chose, so a
+ # managed expert can apply its own default on the next turn.
+ return json.dumps(self.to_dict(), ensure_ascii=False)
def parse_hitl_session_policy(raw: object) -> HitlSessionPolicy:
diff --git a/src/octop/infra/agents/settings/runtime_limits.py b/src/octop/infra/agents/settings/runtime_limits.py
index df215d30af..f641ce765e 100644
--- a/src/octop/infra/agents/settings/runtime_limits.py
+++ b/src/octop/infra/agents/settings/runtime_limits.py
@@ -12,7 +12,7 @@
Start-time middleware (read in ``AgentManager._build_harness_config``)
-----------------------------------------------------------------------
``tool_call_limit_enabled`` / ``tool_call_run_limit``
- → LangChain ``ToolCallLimitMiddleware`` (per run; default 40)
+ → ``ConsecutiveToolCallMiddleware`` (identical calls in a row; default 40)
``model_retry_*`` → the host model-retry middleware (default on, 2 retries)
``tool_retry_*`` → LangChain ``ToolRetryMiddleware`` (default on, 5 retries)
"""
@@ -156,9 +156,10 @@ def resolve_tool_retry(cfg: dict[str, Any]) -> RetryBudget:
def resolve_tool_call_run_limit(cfg: dict[str, Any]) -> int | None:
- """Per-run tool-call cap. ``None`` means the limiter is not mounted.
+ """Cap on identical tool calls in a row. ``None`` means it is not mounted.
- An absent switch stays on. An absent count uses :data:`DEFAULT_TOOL_CALL_RUN_LIMIT`.
+ Different tools and different arguments do not add up. An absent switch
+ stays on. An absent count uses :data:`DEFAULT_TOOL_CALL_RUN_LIMIT`.
"""
if not _stored_bool(cfg.get("tool_call_limit_enabled"), default=True):
return None
@@ -167,13 +168,17 @@ def resolve_tool_call_run_limit(cfg: dict[str, Any]) -> int | None:
def call_guard_middleware(cfg: dict[str, Any]) -> list[Any]:
- """Tool-call cap and tool-exception retry mounted for one expert."""
- from langchain.agents.middleware import ToolCallLimitMiddleware, ToolRetryMiddleware
+ """Consecutive identical-call cap and tool-exception retry for one expert."""
+ from langchain.agents.middleware import ToolRetryMiddleware
+
+ from octop.infra.agents.middleware.consecutive_tool_call import (
+ ConsecutiveToolCallMiddleware,
+ )
middleware: list[Any] = []
run_limit = resolve_tool_call_run_limit(cfg)
if run_limit is not None:
- middleware.append(ToolCallLimitMiddleware(run_limit=run_limit, exit_behavior="end"))
+ middleware.append(ConsecutiveToolCallMiddleware(limit=run_limit))
tool_retry = resolve_tool_retry(cfg)
if tool_retry.enabled:
middleware.append(
diff --git a/src/octop/infra/agents/settings/tool_catalog.py b/src/octop/infra/agents/settings/tool_catalog.py
index b022e6e19c..e2fb699b35 100644
--- a/src/octop/infra/agents/settings/tool_catalog.py
+++ b/src/octop/infra/agents/settings/tool_catalog.py
@@ -50,6 +50,29 @@ class BuiltinToolEntry:
category: str
+# Octop tools a managed expert can actually turn on. The runner keeps its own
+# file, shell, and web tools; these are the loopback tools Octop attaches.
+MANAGED_FILE_TOOLS: tuple[str, ...] = ("send_file_to_user",)
+MANAGED_MEMORY_TOOLS: tuple[str, ...] = ("memory_search", "memory_get", "memory_save")
+MANAGED_CRON_TOOLS: tuple[str, ...] = (
+ "cronjob_list",
+ "cronjob_get",
+ "cronjob_create",
+ "cronjob_update",
+ "cronjob_delete",
+ "cronjob_run_now",
+)
+MANAGED_KNOWLEDGE_TOOLS: tuple[str, ...] = ("search_knowledge",)
+MANAGED_AGENT_TOOLS: tuple[str, ...] = ("agent_list", "ask_agent")
+MANAGED_BUILTIN_TOOLS: frozenset[str] = frozenset(
+ MANAGED_FILE_TOOLS
+ + MANAGED_MEMORY_TOOLS
+ + MANAGED_CRON_TOOLS
+ + MANAGED_KNOWLEDGE_TOOLS
+ + MANAGED_AGENT_TOOLS
+)
+
+
# Runtime tool names exposed in the tool-settings dialog (MCP excluded).
BUILTIN_TOOL_CATALOG: tuple[BuiltinToolEntry, ...] = (
# filesystem / orchestration (critical ones still listed, disableable=false)
@@ -187,6 +210,23 @@ def effective_tools_disabled(
return disabled - CRITICAL_TOOLS
+def managed_builtin_available(
+ name: str,
+ *,
+ agent_cfg: Mapping[str, Any],
+ knowledge_base_ids: list[str],
+ has_peers: bool,
+) -> bool:
+ """Whether a managed catalog tool can attach on the next turn."""
+ if name in MANAGED_MEMORY_TOOLS:
+ return builtin_tool_available(name, agent_cfg=agent_cfg)
+ if name in MANAGED_KNOWLEDGE_TOOLS:
+ return bool(knowledge_base_ids)
+ if name in MANAGED_AGENT_TOOLS:
+ return has_peers
+ return True
+
+
def builtin_tool_available(
name: str,
*,
@@ -218,6 +258,13 @@ def builtin_tool_available(
__all__ = [
"BUILTIN_TOOL_CATALOG",
+ "MANAGED_AGENT_TOOLS",
+ "MANAGED_BUILTIN_TOOLS",
+ "MANAGED_CRON_TOOLS",
+ "MANAGED_FILE_TOOLS",
+ "MANAGED_KNOWLEDGE_TOOLS",
+ "MANAGED_MEMORY_TOOLS",
+ "managed_builtin_available",
"BuiltinToolEntry",
"CRITICAL_TOOLS",
"agent_plugin_enabled",
diff --git a/src/octop/infra/agents/teams/service.py b/src/octop/infra/agents/teams/service.py
index d772b7fe19..8b15b4ed0b 100644
--- a/src/octop/infra/agents/teams/service.py
+++ b/src/octop/infra/agents/teams/service.py
@@ -18,6 +18,23 @@
TEAM_TEMPLATE_NAME = "team-host"
TEAM_MIN_MEMBERS = 2
TEAM_AVATAR_URL = "/experts/avatars/team-host.svg"
+
+
+def _member_runner(member: AgentRow) -> str | None:
+ if getattr(member, "kind", None) != "managed":
+ return None
+ raw = member.config_json
+ try:
+ cfg = json.loads(raw) if isinstance(raw, str) and raw.strip() else {}
+ except json.JSONDecodeError:
+ return None
+ runner = cfg.get("managed_runner") if isinstance(cfg, dict) else None
+ if not isinstance(runner, str):
+ return None
+ text = runner.strip()
+ return text or None
+
+
TEMPLATE_DIR = Path(__file__).resolve().parent / "template"
TEAM_MANIFEST_WORKSPACE = ".octop/manifest.json"
@@ -294,6 +311,8 @@ def team_payload(self, row: AgentRow) -> dict[str, Any]:
"state": member.last_state or "unknown",
"is_shared": bool(int(member.is_shared or 0)),
"user_id": member.user_id,
+ "kind": getattr(member, "kind", None) or "expert",
+ "managed_runner": _member_runner(member),
}
for member in member_rows
if member is not None
diff --git a/src/octop/infra/agents/teams/team_manager.py b/src/octop/infra/agents/teams/team_manager.py
index b27bddcab0..2527af0c94 100644
--- a/src/octop/infra/agents/teams/team_manager.py
+++ b/src/octop/infra/agents/teams/team_manager.py
@@ -66,6 +66,7 @@
_HISTORY_TOOL_RESULT_SUFFIX = "…"
# Member answer excerpt injected into the host wrap-up wake-up prompt.
_FOLLOWUP_RESULT_MAX_CHARS = 6000
+_PEER_RESOURCES_KEY = "octop_peer_resources"
if TYPE_CHECKING:
from octop.infra.agents.manager import AgentManager
@@ -477,6 +478,7 @@ async def emit(chunk: dict[str, Any]) -> None:
room_turn_id = self._pin_room_turn(room_thread_id)
if hold_room and self._host_turn_busy(host_id, room_thread_id):
room_open = await self._wait_host_dispatch_idle(host_id, room_thread_id)
+ await self._prepare_member_request(speaker_id, payload)
agen = self._agent_manager.stream(speaker_id, payload)
while True:
pause: dict[str, Any] | None = None
@@ -779,6 +781,300 @@ def stamp_host_runtime(self, request: dict[str, Any], agent_id: str) -> None:
if callable(strip):
strip(agent_id)
+ async def _prepare_member_request(self, agent_id: str, request: Any) -> None:
+ """Stamp a peer turn. Sync ``ask_agent`` and room dispatch both call this."""
+ payload, writeback = _member_request_view(request, agent_id)
+ try:
+ await self._attach_member_resources(
+ payload,
+ agent_id,
+ room_thread_id=str(payload.get("thread_id") or ""),
+ )
+ finally:
+ writeback()
+
+ async def _attach_member_resources(
+ self,
+ payload: dict[str, Any],
+ speaker_id: str,
+ *,
+ room_thread_id: str,
+ ) -> None:
+ """Give a dispatched member that expert's knowledge, connectors, and model.
+
+ Host wrap-up uses the same stream path and stays without them. Plan mode
+ is a direct-chat permission; a dispatch is work, so the turn is craft.
+ """
+ configurable = payload.get("configurable")
+ if isinstance(configurable, dict) and configurable.get(_PEER_RESOURCES_KEY):
+ return
+ if is_team_agent(self._agent_manager.get_row(speaker_id)):
+ return
+ user_id = self._payload_user_id(payload, room_thread_id)
+ if user_id is None:
+ return
+ if not payload.get("user"):
+ payload["user"] = str(user_id)
+ self._stamp_member_knowledge(payload, speaker_id, user_id)
+ await self._stamp_member_connectors(payload, speaker_id, user_id)
+ self._stamp_member_model(payload, speaker_id, user_id)
+ self._stamp_member_craft(payload)
+ cfg = payload.get("configurable")
+ if isinstance(cfg, dict):
+ cfg[_PEER_RESOURCES_KEY] = True
+ from octop.infra.agents.acp.turn import attach_managed_turn
+
+ await attach_managed_turn(self._agent_manager, speaker_id, payload)
+
+ def _payload_user_id(self, payload: dict[str, Any], room_thread_id: str) -> int | None:
+ raw_user = payload.get("user")
+ user_id = (
+ _octop_user_id(raw_user)
+ if isinstance(raw_user, str | int) and not isinstance(raw_user, bool)
+ else None
+ )
+ if user_id is not None:
+ return user_id
+ getter = getattr(self._thread_registry, "get_thread", None)
+ if not callable(getter) or not room_thread_id:
+ return None
+ row = getter(room_thread_id)
+ raw = getattr(row, "user_id", None)
+ if isinstance(raw, int) and raw > 0:
+ return raw
+ return None
+
+ def _team_room_id(self, member_thread_id: str, speaker_id: str) -> str:
+ suffix = f"~{speaker_id}"
+ if not member_thread_id.endswith(suffix):
+ return ""
+ room = member_thread_id[: -len(suffix)]
+ getter = getattr(self._thread_registry, "get_thread", None)
+ if not room or not callable(getter):
+ return ""
+ row = getter(room)
+ agent_id = str(getattr(row, "agent_id", "") or "")
+ if not is_team_agent(self._agent_manager.get_row(agent_id)):
+ return ""
+ return room
+
+ async def _notify_connector_auth(self, room_thread_id: str, text: str) -> None:
+ """IM channels do not see the room socket, so tell them directly."""
+ if self._gateway is None:
+ return
+ for session in self._thread_registry.im_sessions_for_thread(room_thread_id):
+ try:
+ await self._push_session_channel(session, text)
+ except Exception:
+ logger.warning(
+ "failed to push team connector auth notice thread=%s",
+ room_thread_id,
+ exc_info=True,
+ )
+
+ def _stamp_member_knowledge(
+ self,
+ payload: dict[str, Any],
+ speaker_id: str,
+ user_id: int,
+ ) -> None:
+ from octop.infra.agents.turn_resources import attach_turn_knowledge
+
+ repos = getattr(self._agent_manager, "_repos", None)
+ knowledge_repo = getattr(repos, "knowledge_repo", None) if repos is not None else None
+ list_visible = getattr(knowledge_repo, "list_visible", None) if knowledge_repo else None
+ if not callable(list_visible):
+ return
+ defaults = getattr(self._agent_manager, "default_knowledge_base_ids", None)
+ extra: list[str] | None = None
+ if callable(defaults):
+ raw = defaults(speaker_id)
+ if isinstance(raw, list) and all(isinstance(item, str) for item in raw):
+ extra = raw
+ elif raw is not None and not isinstance(raw, list):
+ return
+ user = self._user_repo.get(user_id) if self._user_repo is not None else None
+ is_admin = str(getattr(user, "role", "") or "") == "admin"
+ try:
+ selected = attach_turn_knowledge(
+ payload,
+ knowledge_repo=knowledge_repo,
+ user_id=user_id,
+ is_admin=is_admin,
+ explicit_ids=None,
+ extra_ids=extra,
+ locale=self._locale_for(user_id),
+ )
+ except Exception:
+ logger.warning(
+ "team member knowledge lookup failed agent=%s user=%s",
+ speaker_id,
+ user_id,
+ exc_info=True,
+ )
+ return
+ if selected:
+ logger.info(
+ "team member knowledge agent=%s user=%s bases=%s",
+ speaker_id,
+ user_id,
+ selected,
+ )
+
+ async def _stamp_member_connectors(
+ self,
+ payload: dict[str, Any],
+ speaker_id: str,
+ user_id: int,
+ ) -> None:
+ from octop.infra.agents.turn_resources import harness_names_for_ready, resolve_turn_mcp
+
+ defaults = getattr(self._agent_manager, "default_mcp_servers", None)
+ if not callable(defaults):
+ return
+ extra = defaults(speaker_id)
+ if not isinstance(extra, list) or any(not isinstance(item, str) for item in extra):
+ return
+ try:
+ resolved = await resolve_turn_mcp(
+ self._agent_manager,
+ agent_id=speaker_id,
+ user_id=user_id,
+ explicit=None,
+ apply_defaults=True,
+ )
+ except Exception:
+ logger.warning(
+ "team member connectors failed to load agent=%s user=%s",
+ speaker_id,
+ user_id,
+ exc_info=True,
+ )
+ return
+ if resolved is None:
+ return
+ row = self._agent_manager.get_row(speaker_id)
+ owner_raw = getattr(row, "user_id", None) if row is not None else None
+ owner_id = owner_raw if isinstance(owner_raw, int) else None
+ ready = harness_names_for_ready(
+ self._agent_manager,
+ resolved,
+ owner_id=owner_id,
+ user_id=user_id,
+ )
+ if ready:
+ payload["mcp_servers"] = ready
+ logger.info(
+ "team member connectors agent=%s user=%s servers=%s",
+ speaker_id,
+ user_id,
+ ready,
+ )
+ if resolved.failed:
+ logger.warning(
+ "team member connectors unavailable agent=%s user=%s failed=%s",
+ speaker_id,
+ user_id,
+ resolved.failed,
+ )
+ await self._note_member_connector_auth(
+ payload,
+ speaker_id,
+ user_id,
+ resolved.failed,
+ )
+
+ def _stamp_member_model(self, payload: dict[str, Any], speaker_id: str, user_id: int) -> None:
+ if isinstance(payload.get("model"), str) and str(payload.get("model")).strip():
+ return
+ ref = self._member_model_ref(speaker_id, user_id)
+ if ref:
+ payload["model"] = ref
+
+ def _member_model_ref(self, agent_id: str, user_id: int) -> str | None:
+ """Expert pin only. An unpinned expert stays on harness auto-route."""
+ manager = self._agent_manager
+ row = manager.get_row(agent_id)
+ providers = getattr(manager, "providers", None)
+ resolve = getattr(providers, "resolve_explicit_default_model", None)
+ get_config = getattr(manager, "get_config", None)
+ if row is None or not callable(resolve) or not callable(get_config):
+ return None
+ try:
+ cfg = get_config(agent_id)
+ except Exception:
+ logger.warning("team member model config failed agent=%s", agent_id, exc_info=True)
+ return None
+ if not isinstance(cfg, dict):
+ cfg = {}
+ try:
+ ref = resolve(row, cfg)
+ except Exception:
+ logger.warning("team member model resolve failed agent=%s", agent_id, exc_info=True)
+ return None
+ if not isinstance(ref, str) or not ref.strip():
+ return None
+ allowed = getattr(manager, "model_ref_allowed_for_user", None)
+ if callable(allowed):
+ try:
+ ok = allowed(user_id, ref)
+ except Exception:
+ return None
+ if ok is False:
+ return None
+ return ref.strip()
+
+ def _stamp_member_craft(self, payload: dict[str, Any]) -> None:
+ """Dispatch ignores Ask/Plan. Those modes would hide connectors."""
+ payload["conversation_mode"] = "craft"
+ configurable = dict(payload.get("configurable") or {})
+ configurable["conversation_mode"] = "craft"
+ payload["configurable"] = configurable
+
+ async def _note_member_connector_auth(
+ self,
+ payload: dict[str, Any],
+ speaker_id: str,
+ user_id: int,
+ failed: list[str],
+ ) -> None:
+ blocked_fn = getattr(self._agent_manager, "connector_auth_blocked", None)
+ if not callable(blocked_fn):
+ return
+ try:
+ blocked = await blocked_fn(user_id, failed)
+ except Exception:
+ logger.warning(
+ "team member connector auth check failed agent=%s",
+ speaker_id,
+ exc_info=True,
+ )
+ return
+ if not isinstance(blocked, list) or not blocked:
+ return
+ names = [
+ str(item.get("display_name") or item.get("server") or "").strip()
+ for item in blocked
+ if isinstance(item, dict)
+ ]
+ names = [name for name in names if name]
+ if not names:
+ return
+ locale = self._locale_for(user_id)
+ note = tr("teams.connector_auth_skipped", locale, servers=", ".join(names))
+ from octop.infra.agents.middleware.team_dispatch import CONFIG_KEY as BRIEFING_KEY
+
+ configurable = dict(payload.get("configurable") or {})
+ existing = configurable.get(BRIEFING_KEY)
+ if isinstance(existing, str) and existing.strip():
+ configurable[BRIEFING_KEY] = f"{existing.rstrip()}\n\n{note}"
+ else:
+ configurable[BRIEFING_KEY] = note
+ payload["configurable"] = configurable
+ room = self._team_room_id(str(payload.get("thread_id") or ""), speaker_id)
+ if room:
+ await self._notify_connector_auth(room, note)
+
def stash_peer_prompt(
self,
agent_id: str,
@@ -816,6 +1112,7 @@ def install_host_dispatch(self, harness_team: Any) -> None:
stream_peer=self.stream_peer_to_room,
stream_host=self.stream_host_followup_to_room,
take_prompt=self.take_peer_prompt,
+ prepare_member=self._prepare_member_request,
)
# -- jobs / runtime -------------------------------------------------------
@@ -1806,6 +2103,31 @@ def _make_peer_session(**kwargs: Any) -> PeerSession:
return PeerSession(**{key: value for key, value in kwargs.items() if key in allowed})
+def _member_request_view(
+ request: Any,
+ speaker_id: str,
+) -> tuple[dict[str, Any], Callable[[], None]]:
+ """Return a dict view and a write-back for ChatRequest-shaped objects."""
+ if isinstance(request, dict):
+ return request, lambda: None
+ payload = _chat_request_payload(request, speaker_id)
+
+ def writeback() -> None:
+ configurable = payload.get("configurable")
+ if isinstance(configurable, dict):
+ request.configurable = configurable
+ servers = payload.get("mcp_servers")
+ if isinstance(servers, list):
+ request.mcp_servers = servers
+ model = payload.get("model")
+ if isinstance(model, str) and model.strip():
+ request.model = model
+ if payload.get("conversation_mode") == "craft":
+ request.conversation_mode = "craft"
+
+ return payload, writeback
+
+
def _chat_request_payload(request: Any, speaker_id: str) -> dict[str, Any]:
if isinstance(request, dict):
payload = dict(request)
@@ -2381,6 +2703,7 @@ def wire_host_dispatch(
stream_peer: Callable[..., Any] | None = None,
stream_host: Callable[..., Any] | None = None,
take_prompt: Callable[[str, str | None], tuple[str, str] | None] | None = None,
+ prepare_member: Callable[[str, Any], Awaitable[None]] | None = None,
) -> None:
"""Patch harness TeamManager so async ``ask_agent`` uses inbox + room stream."""
if harness_team is None:
@@ -2519,29 +2842,30 @@ async def enrich(agent_id: str, req: Any) -> Any:
if original_enrich is not None:
req = await original_enrich(agent_id, req)
pair = take_prompt(agent_id, getattr(req, "thread_id", None))
- if not pair:
- return req
- from langchain_core.messages import HumanMessage
+ if pair:
+ from langchain_core.messages import HumanMessage
- from octop.infra.agents.middleware.team_dispatch import (
- CONFIG_KEY as BRIEFING_KEY,
- )
+ from octop.infra.agents.middleware.team_dispatch import (
+ CONFIG_KEY as BRIEFING_KEY,
+ )
- question, dispatch = pair
- if dispatch and dispatch != question:
- # Briefing belongs on the leading system prompt. A SystemMessage in
- # the turn input lands mid-thread on the next dispatch, and strict
- # providers reject it. TeamDispatchBriefingMiddleware appends it.
- configurable = dict(getattr(req, "configurable", None) or {})
- configurable[BRIEFING_KEY] = dispatch
- req.configurable = configurable
- if question:
- req.messages = [
- HumanMessage(
- content=question,
- id=f"team-peer:{getattr(req, 'thread_id', None)}:{new_ulid()}:human",
- )
- ]
+ question, dispatch = pair
+ if dispatch and dispatch != question:
+ # Briefing belongs on the leading system prompt. A SystemMessage in
+ # the turn input lands mid-thread on the next dispatch, and strict
+ # providers reject it. TeamDispatchBriefingMiddleware appends it.
+ configurable = dict(getattr(req, "configurable", None) or {})
+ configurable[BRIEFING_KEY] = dispatch
+ req.configurable = configurable
+ if question:
+ req.messages = [
+ HumanMessage(
+ content=question,
+ id=f"team-peer:{getattr(req, 'thread_id', None)}:{new_ulid()}:human",
+ )
+ ]
+ if prepare_member is not None and not is_team(agent_id):
+ await prepare_member(agent_id, req)
return req
harness_team._enrich_request = enrich
diff --git a/src/octop/infra/agents/turn_resources.py b/src/octop/infra/agents/turn_resources.py
new file mode 100644
index 0000000000..e254404619
--- /dev/null
+++ b/src/octop/infra/agents/turn_resources.py
@@ -0,0 +1,135 @@
+"""Knowledge bases and connectors for one expert turn.
+
+Chat, cron, and team dispatch all resolve a turn through here so the
+selection rules stay in one place.
+"""
+
+from __future__ import annotations
+
+import logging
+from dataclasses import dataclass
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+
+@dataclass(frozen=True)
+class ResolvedTurnMcp:
+ """Viewer names were requested; harness names are what the model sees."""
+
+ requested: list[str]
+ harness: list[str]
+ shown: list[str]
+ failed: list[str]
+
+
+def attach_turn_knowledge(
+ request: dict[str, Any],
+ *,
+ knowledge_repo: Any,
+ user_id: int,
+ is_admin: bool,
+ explicit_ids: list[str] | None,
+ extra_ids: list[str] | None,
+ locale: str,
+) -> list[str]:
+ """Stamp this turn's visible knowledge bases onto ``request``."""
+ from octop.infra.knowledge.default_open import stamp_turn_knowledge_config
+
+ bases = knowledge_repo.list_all() if is_admin else knowledge_repo.list_visible(user_id)
+ if not isinstance(bases, list):
+ return []
+ return stamp_turn_knowledge_config(
+ request,
+ visible_bases=bases,
+ explicit_ids=explicit_ids,
+ owner_user_id=user_id,
+ extra_ids=extra_ids,
+ is_admin=is_admin,
+ locale=locale,
+ )
+
+
+async def resolve_turn_mcp(
+ agent_manager: Any,
+ *,
+ agent_id: str,
+ user_id: int,
+ explicit: list[str] | None,
+ apply_defaults: bool | None = None,
+) -> ResolvedTurnMcp | None:
+ """Merge expert picks with default-open connectors and load their tools.
+
+ ``failed`` lists servers that did not load. Callers that abort on any
+ failure ignore ``harness`` when it is non-empty. Team dispatch keeps the
+ names that loaded.
+ """
+ from octop.infra.agents.teams.service import is_team_agent
+
+ row = agent_manager.get_row(agent_id)
+ if is_team_agent(row):
+ return None
+ owner_raw = getattr(row, "user_id", None) if row is not None else None
+ owner_id = owner_raw if isinstance(owner_raw, int) else None
+ extra_defaults = agent_manager.default_mcp_servers(agent_id)
+ merged = agent_manager.merge_turn_mcp_servers(
+ user_id,
+ explicit,
+ apply_defaults=apply_defaults,
+ extra_defaults=extra_defaults,
+ agent_owner_id=owner_id,
+ )
+ if not isinstance(merged, list) or not merged:
+ return None
+ requested = [str(name) for name in merged if str(name).strip()]
+ if not requested:
+ return None
+ harness = list(requested)
+ shown = list(requested)
+ if owner_id is not None and owner_id != user_id:
+ harness = list(agent_manager.align_mcp_names_to_harness(owner_id, user_id, requested))
+ shown = list(agent_manager.mcp_names_for_chips(owner_id, user_id, requested, harness))
+ from octop.infra.agents.managed import is_managed_agent
+
+ # Managed experts receive these servers on the ACP session. Loading the
+ # same tools into the in-process graph is not how that turn runs.
+ if is_managed_agent(row):
+ return ResolvedTurnMcp(
+ requested=requested,
+ harness=harness,
+ shown=shown,
+ failed=[],
+ )
+ failed = await agent_manager.prepare_chat_mcp(
+ agent_id,
+ requested,
+ connector_user_id=user_id,
+ )
+ missing = [str(name) for name in failed] if isinstance(failed, list) else list(requested)
+ return ResolvedTurnMcp(
+ requested=requested,
+ harness=harness,
+ shown=shown,
+ failed=missing,
+ )
+
+
+def harness_names_for_ready(
+ agent_manager: Any,
+ resolved: ResolvedTurnMcp,
+ *,
+ owner_id: int | None,
+ user_id: int,
+) -> list[str]:
+ """Harness names for the servers that actually loaded."""
+ failed = set(resolved.failed)
+ ready = [name for name in resolved.requested if name not in failed]
+ if not ready:
+ return []
+ if len(ready) == len(resolved.requested):
+ return list(resolved.harness)
+ if owner_id is not None and owner_id != user_id:
+ aligned = agent_manager.align_mcp_names_to_harness(owner_id, user_id, ready)
+ if isinstance(aligned, list):
+ return [str(name) for name in aligned if str(name).strip()]
+ return ready
diff --git a/src/octop/infra/backend/docker_spec.py b/src/octop/infra/backend/docker_spec.py
index 21941bc508..b1a82e4fa5 100644
--- a/src/octop/infra/backend/docker_spec.py
+++ b/src/octop/infra/backend/docker_spec.py
@@ -6,12 +6,14 @@
from pathlib import Path
from typing import Any, cast
+from octop.infra.utils.host_dirs import running_in_container
+
logger = logging.getLogger(__name__)
DEFAULT_SANDBOX_PREFIX = "octop_sandbox"
-# ``volumes`` is intentionally absent. Host bind mounts run as the Docker
-# daemon and are not covered by the local-backend root policy.
+# ``volumes`` stays in the stored spec. ``omit_docker_volumes`` drops it only
+# when Octop itself is not running in a container.
_DOCKER_PASSTHROUGH_KEYS = (
"allow_network",
"memory",
@@ -21,6 +23,7 @@
"max_output_bytes",
"auto_remove",
"workspace_path",
+ "volumes",
"environment",
"environment_file",
"agent_id",
@@ -41,11 +44,20 @@ def apply_docker_cfg_keys(spec: dict[str, Any], cfg: dict[str, Any]) -> None:
def omit_docker_volumes(spec: Any) -> Any:
- """Drop ``volumes`` from docker specs, including composite children.
+ """Drop ``volumes`` from docker specs outside a container deployment.
+
+ Docker-deployed Octop keeps the mounts. The operator already chose which
+ host directories the container can see, and a Docker expert only reaches
+ those paths when ``volumes`` is passed to the daemon. A host install still
+ drops them, including on composite children, so a normal user cannot bind
+ arbitrary host paths into a sandbox.
A returned docker or composite dict is a shallow copy when a mount was
- removed. Other specs are returned unchanged.
+ removed. Other specs, and every spec when Octop is in a container, are
+ returned unchanged.
"""
+ if running_in_container():
+ return spec
if not isinstance(spec, dict):
return spec
kind = str(spec.get("type") or "").strip().lower()
diff --git a/src/octop/infra/bridge/peer_turn.py b/src/octop/infra/bridge/peer_turn.py
index 86041dca1f..68acd1ae41 100644
--- a/src/octop/infra/bridge/peer_turn.py
+++ b/src/octop/infra/bridge/peer_turn.py
@@ -16,6 +16,7 @@
"reasoning_mode",
"reasoning_effort",
"conversation_mode",
+ "session_mode",
"hitl_policy",
"mcp_servers",
"knowledge_base_ids",
diff --git a/src/octop/infra/connectors/builder.py b/src/octop/infra/connectors/builder.py
index 82b5ae1852..cae07bb5c8 100644
--- a/src/octop/infra/connectors/builder.py
+++ b/src/octop/infra/connectors/builder.py
@@ -123,6 +123,43 @@ def internal_mcp_url(
return f"{scheme}://{host}:{config.port}/api/internal/mcp/{gateway_kind}/{instance_id}?token={token_q}"
+def _loopback_mcp_url(config: OctopConfig, suffix: str, token: str) -> str:
+ host = config.bind_host if config.bind_host not in ("0.0.0.0", "::") else "127.0.0.1"
+ token_q = quote(token, safe="")
+ scheme = "https" if _internal_mcp_uses_https(config) else "http"
+ return f"{scheme}://{host}:{config.port}/api/internal/mcp/{suffix}?token={token_q}"
+
+
+def knowledge_mcp_url(*, config: OctopConfig, token: str) -> str:
+ """Loopback URL for the knowledge-base MCP a managed ACP agent can call."""
+ return _loopback_mcp_url(config, "knowledge", token)
+
+
+def agents_mcp_url(*, config: OctopConfig, token: str) -> str:
+ """Loopback URL for ``ask_agent`` on a managed ACP session."""
+ return _loopback_mcp_url(config, "agents", token)
+
+
+def files_mcp_url(*, config: OctopConfig, token: str) -> str:
+ """Loopback URL for ``send_file_to_user`` on a managed ACP session."""
+ return _loopback_mcp_url(config, "files", token)
+
+
+def cron_mcp_url(*, config: OctopConfig, token: str) -> str:
+ """Loopback URL for cron tools on a managed ACP session."""
+ return _loopback_mcp_url(config, "cron", token)
+
+
+def memory_mcp_url(*, config: OctopConfig, token: str) -> str:
+ """Loopback URL for memory tools on a managed ACP session."""
+ return _loopback_mcp_url(config, "memory", token)
+
+
+def plugins_mcp_url(*, config: OctopConfig, token: str) -> str:
+ """Loopback URL for this expert's enabled plugin tools."""
+ return _loopback_mcp_url(config, "plugins", token)
+
+
def new_internal_token() -> str:
return secrets.token_urlsafe(32)
diff --git a/src/octop/infra/connectors/oauth/mcp.py b/src/octop/infra/connectors/oauth/mcp.py
index 718a8778a2..09533fa126 100644
--- a/src/octop/infra/connectors/oauth/mcp.py
+++ b/src/octop/infra/connectors/oauth/mcp.py
@@ -102,7 +102,16 @@ async def _validate_metadata_endpoints(metadata: dict[str, Any], *, issuer: str)
async def fetch_authorization_metadata(issuer: str) -> dict[str, Any]:
- metadata_url = f"{issuer.rstrip('/')}/.well-known/oauth-authorization-server"
+ # RFC 8414 §3.1: insert the well-known suffix between authority and path.
+ # A path-scoped issuer such as https://auth.example.com/realms/tenant is
+ # fetched at
+ # https://auth.example.com/.well-known/oauth-authorization-server/realms/tenant
+ # — not at …/realms/tenant/.well-known/oauth-authorization-server (404).
+ parsed = urlparse(issuer)
+ issuer_path = parsed.path.rstrip("/")
+ metadata_url = (
+ f"{parsed.scheme}://{parsed.netloc}/.well-known/oauth-authorization-server{issuer_path}"
+ )
await _ensure_mcp_oauth_url(metadata_url, issuer=issuer, field="issuer_metadata")
r = await safe_request("GET", metadata_url, timeout=20.0)
r.raise_for_status()
@@ -166,7 +175,13 @@ def build_authorize_url(
params["scope"] = scope
if resource:
params["resource"] = resource
- return f"{metadata['authorization_endpoint']}?{urlencode(params)}"
+ # RFC 6749 §3.1: keep any query the authorization endpoint already has
+ # and append OAuth params.
+ endpoint = urlparse(str(metadata["authorization_endpoint"]))
+ query = urlencode(params)
+ if endpoint.query:
+ query = f"{endpoint.query}&{query}"
+ return endpoint._replace(query=query).geturl()
def _http_error_detail(resp: Any) -> str:
diff --git a/src/octop/infra/cron/delivery.py b/src/octop/infra/cron/delivery.py
index 580eb81b03..7ff2b469ac 100644
--- a/src/octop/infra/cron/delivery.py
+++ b/src/octop/infra/cron/delivery.py
@@ -9,6 +9,7 @@
from langchain_core.messages import AIMessage, HumanMessage
from octop.i18n import tr
+from octop.infra.agents.turn_resources import attach_turn_knowledge, resolve_turn_mcp
from octop.infra.cron.session_target import pinned_thread_id
from octop.infra.cron.task_type import CronTaskType, normalize_cron_task_type
from octop.infra.db.repos.threads import ThreadRow
@@ -17,7 +18,6 @@
from octop.infra.gateway.process.usage_record import UsageTracker, record_turn_usage
from octop.infra.gateway.threads import ThreadRegistry
from octop.infra.history.projection import TurnHistoryTracker, message_inputs
-from octop.infra.knowledge.default_open import stamp_turn_knowledge_config
from octop.infra.utils.llm_text import strip_thinking
from octop.infra.utils.locale import resolve_user_locale
from octop.infra.utils.turn_failure import log_failed_tool_results
@@ -203,45 +203,18 @@ async def _build_agent_request(
command: CronDeliveryCommand,
session: SessionRow,
) -> dict[str, Any]:
- from octop.infra.agents.teams import is_team_agent
-
- row = self._agent_manager.get_row(command.agent_id)
- if is_team_agent(row):
- requested: list[str] = []
- servers: list[str] = []
- shown_servers: list[str] = []
- else:
- owner_raw = getattr(row, "user_id", None) if row is not None else None
- owner_id = owner_raw if isinstance(owner_raw, int) else None
- picked = [name.strip() for name in command.mcp_servers if name.strip()]
- extra_defaults = self._agent_manager.default_mcp_servers(command.agent_id)
- requested = (
- self._agent_manager.merge_turn_mcp_servers(
- session.user_id,
- picked or None,
- apply_defaults=not picked,
- extra_defaults=extra_defaults,
- agent_owner_id=owner_id,
- )
- or []
- )
- servers = requested
- shown_servers = requested
- if owner_id is not None and owner_id != session.user_id and requested:
- servers = self._agent_manager.align_mcp_names_to_harness(
- owner_id, session.user_id, requested
- )
- shown_servers = self._agent_manager.mcp_names_for_chips(
- owner_id, session.user_id, requested, servers
- )
- if requested:
- failed = await self._agent_manager.prepare_chat_mcp(
- command.agent_id,
- requested,
- connector_user_id=session.user_id,
- )
- if failed:
- raise RuntimeError(f"mcp load failed: {', '.join(failed)}")
+ picked = [name.strip() for name in command.mcp_servers if name.strip()]
+ resolved = await resolve_turn_mcp(
+ self._agent_manager,
+ agent_id=command.agent_id,
+ user_id=session.user_id,
+ explicit=picked or None,
+ apply_defaults=not picked,
+ )
+ if resolved is not None and resolved.failed:
+ raise RuntimeError(f"mcp load failed: {', '.join(resolved.failed)}")
+ servers = resolved.harness if resolved is not None else []
+ shown_servers = resolved.shown if resolved is not None else []
row = self._agent_manager.get_row(command.agent_id)
default_model = (row.default_model if row is not None else None) or None
@@ -276,22 +249,18 @@ def _attach_turn_knowledge_config(
) -> None:
user_row = self._repos.user_repo.get(session.user_id)
is_admin = str(getattr(user_row, "role", "") or "") == "admin"
- knowledge_repo = self._repos.knowledge_repo
- bases = (
- knowledge_repo.list_all() if is_admin else knowledge_repo.list_visible(session.user_id)
- )
locale = resolve_user_locale(
user_repo=self._repos.user_repo,
user_id=session.user_id,
channel_type=session.channel_type,
)
- stamp_turn_knowledge_config(
+ attach_turn_knowledge(
request,
- visible_bases=bases,
+ knowledge_repo=self._repos.knowledge_repo,
+ user_id=session.user_id,
+ is_admin=is_admin,
explicit_ids=None,
- owner_user_id=session.user_id,
extra_ids=self._agent_manager.default_knowledge_base_ids(command.agent_id),
- is_admin=is_admin,
locale=locale,
)
diff --git a/src/octop/infra/gateway/media/tool_media.py b/src/octop/infra/gateway/media/tool_media.py
index 035155a998..9d96f85b09 100644
--- a/src/octop/infra/gateway/media/tool_media.py
+++ b/src/octop/infra/gateway/media/tool_media.py
@@ -83,6 +83,20 @@ def is_media_push_tool(name: str | None) -> bool:
return tool_name_base(name or "").lower() in MEDIA_PUSH_TOOL_BASES
+def _delivers_media(message: Any, *, chunk_name: str | None) -> bool:
+ """Allowlisted tool names, or the managed ``send_file_to_user`` marker.
+
+ An external ACP agent reports its own title for the MCP call. The loopback
+ result still carries ``octop_delivery`` so the file reaches the user.
+ """
+ if is_media_push_tool(tool_message_name(message, chunk_name=chunk_name)):
+ return True
+ for block in iter_media_blocks(extract_message_content(message)):
+ if block.get("octop_delivery") == "send_file_to_user":
+ return True
+ return False
+
+
def tool_message_name(message: Any, *, chunk_name: str | None = None) -> str | None:
"""Resolve tool name from a ToolMessage / dict, falling back to chunk.name."""
if isinstance(message, dict):
@@ -761,7 +775,7 @@ async def attachment_frames_from_tool_result(
chunk_name = chunk.get("name") if isinstance(chunk.get("name"), str) else None
for message in messages:
- if not is_media_push_tool(tool_message_name(message, chunk_name=chunk_name)):
+ if not _delivers_media(message, chunk_name=chunk_name):
continue
for block in iter_media_blocks(extract_message_content(message)):
preview_url = block.get("preview_url")
@@ -966,7 +980,7 @@ async def media_events_from_tool_result(
chunk_name = chunk.get("name") if isinstance(chunk.get("name"), str) else None
for message in messages:
- if not is_media_push_tool(tool_message_name(message, chunk_name=chunk_name)):
+ if not _delivers_media(message, chunk_name=chunk_name):
continue
for block in iter_media_blocks(extract_message_content(message)):
try:
diff --git a/src/octop/infra/gateway/process/harness_request.py b/src/octop/infra/gateway/process/harness_request.py
index 4c120058aa..959ae36dd9 100644
--- a/src/octop/infra/gateway/process/harness_request.py
+++ b/src/octop/infra/gateway/process/harness_request.py
@@ -193,9 +193,13 @@ async def build_content_from_message(
current_text = "\n\n".join(part for part in [msg.text or "", *file_hints, *extracted] if part)
# Commands and HITL answers are consumed before request assembly. Keep their
# control text intact and add quoted context only to the model's user turn.
+ # Telegram replies may refer to another expert, topic, or an older message
+ # outside the current history. Keep their context even when we sent it.
if msg.channel_type in ("telegram", "qq"):
quote = msg.metadata.get("reply_quote_text") or (
- None if msg.metadata.get("reply_to_is_own_bot") else msg.metadata.get("reply_to_text")
+ None
+ if msg.channel_type == "qq" and msg.metadata.get("reply_to_is_own_bot")
+ else msg.metadata.get("reply_to_text")
)
if isinstance(quote, str) and quote:
current_text = telegram_quote_prompt(quote, locale) + current_text
diff --git a/src/octop/infra/gateway/process/message_keys.py b/src/octop/infra/gateway/process/message_keys.py
index f0a25caa5c..db38f44c3b 100644
--- a/src/octop/infra/gateway/process/message_keys.py
+++ b/src/octop/infra/gateway/process/message_keys.py
@@ -37,11 +37,12 @@ def build_composer_context(
target_agent_ids: list[str] | None,
model_ref: str | None,
default_model: str | None,
+ knowledge_base_ids: list[str] | None = None,
) -> dict[str, Any] | None:
"""Snapshot of per-turn composer selections for history display chips.
Shared by dashboard chat and cron agent runs so MessageBubble can render
- connector / skill / model tags the same way.
+ connector / skill / knowledge / model tags the same way.
Only stamped on newly written HumanMessages — existing history is not
backfilled when job/chat settings change.
@@ -49,6 +50,8 @@ def build_composer_context(
ctx: dict[str, Any] = {}
if mcp_servers:
ctx["connectors"] = list(mcp_servers)
+ if knowledge_base_ids:
+ ctx["knowledgeBaseIds"] = [str(item) for item in knowledge_base_ids if str(item).strip()]
if skills:
ctx["skills"] = list(skills)
if target_agent_ids:
@@ -60,6 +63,31 @@ def build_composer_context(
return ctx or None
+def stamp_composer_fields(request: dict[str, Any], **updates: Any) -> None:
+ """Add chip fields onto the turn's human message after the request exists."""
+ messages = request.get("messages")
+ if not isinstance(messages, list):
+ return
+ for message in messages:
+ kwargs = getattr(message, "additional_kwargs", None)
+ if not isinstance(kwargs, dict):
+ continue
+ role = str(getattr(message, "type", None) or getattr(message, "role", "")).lower()
+ if role not in {"human", "user"}:
+ continue
+ current = kwargs.get(COMPOSER_CTX_KEY)
+ ctx = dict(current) if isinstance(current, dict) else {}
+ connectors = updates.get("connectors")
+ if isinstance(connectors, list) and connectors:
+ ctx["connectors"] = [str(item) for item in connectors if str(item).strip()]
+ knowledge = updates.get("knowledge_base_ids")
+ if isinstance(knowledge, list) and knowledge:
+ ctx["knowledgeBaseIds"] = [str(item) for item in knowledge if str(item).strip()]
+ if ctx:
+ kwargs[COMPOSER_CTX_KEY] = ctx
+ return
+
+
try:
from octop_gateway.push_routing import EPHEMERAL_PUSH_META
except ImportError: # pragma: no cover - older octop-gateway
diff --git a/src/octop/infra/gateway/process/processor.py b/src/octop/infra/gateway/process/processor.py
index 5a100cba2b..1ef95f5eda 100644
--- a/src/octop/infra/gateway/process/processor.py
+++ b/src/octop/infra/gateway/process/processor.py
@@ -32,6 +32,7 @@
from octop.infra.agents.teams.team_manager import (
stamp_team_host_chunk as _maybe_stamp_team_host,
)
+from octop.infra.agents.turn_resources import attach_turn_knowledge, resolve_turn_mcp
from octop.infra.errors import OctopError
from octop.infra.gateway.cli.events import message_event_to_cli_chunks
from octop.infra.gateway.hitl.coordinator import (
@@ -83,7 +84,6 @@
message_inputs,
)
from octop.infra.history.trajectory.settings import agent_trajectory_enabled
-from octop.infra.knowledge.default_open import stamp_turn_knowledge_config
from octop.infra.users.preferences import (
get_model_reasoning_from_json,
get_preferred_model_from_json,
@@ -1053,7 +1053,7 @@ async def __call__(self, msg: InboundMessage) -> AsyncIterator[MessageEvent]:
reasoning_overrides=reasoning_overrides,
)
self.teams.stamp_host_runtime(request, agent_id)
- self._attach_turn_knowledge_config(
+ knowledge_ids = self._attach_turn_knowledge_config(
request,
user_id=user_id,
is_admin=False,
@@ -1061,6 +1061,9 @@ async def __call__(self, msg: InboundMessage) -> AsyncIterator[MessageEvent]:
locale=locale,
agent_id=agent_id,
)
+ from octop.infra.gateway.process.message_keys import stamp_composer_fields # noqa: PLC0415
+
+ stamp_composer_fields(request, knowledge_base_ids=knowledge_ids)
request = self._stamp_turn_conversation_mode(
request,
agent_id=agent_id,
@@ -1725,7 +1728,7 @@ async def _build_dashboard_request(
message_id=client_message_id if isinstance(client_message_id, str) else None,
)
self.teams.stamp_host_runtime(request, agent_id)
- self._attach_turn_knowledge_config(
+ knowledge_ids = self._attach_turn_knowledge_config(
request,
user_id=user_id,
is_admin=bool(meta.get("user_is_admin")),
@@ -1735,6 +1738,13 @@ async def _build_dashboard_request(
locale=locale,
agent_id=agent_id,
)
+ from octop.infra.gateway.process.message_keys import stamp_composer_fields # noqa: PLC0415
+
+ stamp_composer_fields(
+ request,
+ connectors=shown_mcp,
+ knowledge_base_ids=knowledge_ids,
+ )
if mcp_servers:
request["mcp_servers"] = mcp_servers
@@ -1808,6 +1818,10 @@ def _stamp_turn_conversation_mode(
) -> dict[str, Any]:
from octop.infra.agents.conversation_mode import execute_user_message
+ if self._is_managed_agent(agent_id):
+ return self._stamp_managed_session_mode(
+ request, agent_id=agent_id, thread_id=thread_id, meta=meta
+ )
mode, execute_path = self._sync_and_resolve_conversation_mode(
agent_id, thread_id, meta=meta, user_text=user_text
)
@@ -1821,6 +1835,54 @@ def _stamp_turn_conversation_mode(
request["mcp_servers"] = mcp_servers
return request
+ def _is_managed_agent(self, agent_id: str) -> bool:
+ getter = getattr(self._agent_manager, "get_row", None)
+ if not callable(getter):
+ return False
+ try:
+ row = getter(agent_id)
+ except Exception:
+ return False
+ from octop.infra.agents.managed import is_managed_agent
+
+ return is_managed_agent(row)
+
+ def _stamp_managed_session_mode(
+ self,
+ request: dict[str, Any],
+ *,
+ agent_id: str,
+ thread_id: str,
+ meta: dict[str, Any] | None,
+ ) -> dict[str, Any]:
+ """Keep the underlying agent's mode id. Do not apply Ask / Plan / Craft."""
+ from octop.infra.agents.acp.session_modes import resolve_managed_session_mode
+
+ explicit = (meta or {}).get("session_mode")
+ thread = self._thread_registry.get_thread(thread_id)
+ stored = thread.conversation_mode if thread is not None else None
+ config: dict[str, Any] = {}
+ getter = getattr(self._agent_manager, "get_config", None)
+ if callable(getter):
+ try:
+ loaded = getter(agent_id)
+ except Exception:
+ loaded = None
+ if isinstance(loaded, dict):
+ config = loaded
+ pinned = resolve_managed_session_mode(explicit=explicit, stored=None, config={})
+ if pinned:
+ self._thread_registry.update_composer(thread_id, conversation_mode=pinned)
+ stored = pinned
+ mode = resolve_managed_session_mode(explicit=explicit, stored=stored, config=config)
+ if mode:
+ configurable = request.get("configurable")
+ if not isinstance(configurable, dict):
+ configurable = {}
+ request["configurable"] = configurable
+ configurable["acp_session_mode"] = mode
+ return request
+
def _attach_conversation_mode(self, request: dict[str, Any], mode: Any) -> None:
from octop.infra.agents.conversation_mode import stamp_conversation_mode
@@ -1862,23 +1924,18 @@ def _attach_turn_knowledge_config(
explicit_ids: list[str] | None,
locale: str,
agent_id: str | None = None,
- ) -> None:
+ ) -> list[str]:
"""Expose selected knowledge-base ids for the search_knowledge tool."""
if self._knowledge_services is None:
- return
- bases = (
- self._knowledge_services.knowledge_repo.list_all()
- if is_admin
- else self._knowledge_services.knowledge_repo.list_visible(user_id)
- )
+ return []
extra_ids = self._agent_manager.default_knowledge_base_ids(agent_id) if agent_id else None
- stamp_turn_knowledge_config(
+ return attach_turn_knowledge(
request,
- visible_bases=bases,
+ knowledge_repo=self._knowledge_services.knowledge_repo,
+ user_id=user_id,
+ is_admin=is_admin,
explicit_ids=explicit_ids,
- owner_user_id=user_id,
extra_ids=extra_ids,
- is_admin=is_admin,
locale=locale,
)
@@ -1897,36 +1954,19 @@ async def _resolve_turn_mcp_servers(
client sees a clear MCP load error. IM ingress uses ``False`` so a
flaky connector does not abort the whole message turn.
"""
- from octop.infra.agents.teams import is_team_agent # noqa: PLC0415
from octop.infra.errors import ErrorCode, OctopError # noqa: PLC0415
# Team hosts only dispatch — never attach MCP tools.
- row = self._agent_manager.get_row(agent_id)
- if is_team_agent(row):
- return None
- owner_raw = getattr(row, "user_id", None) if row is not None else None
- owner_id = owner_raw if isinstance(owner_raw, int) else None
-
- extra_defaults = self._agent_manager.default_mcp_servers(agent_id)
- merged = self._agent_manager.merge_turn_mcp_servers(
- user_id,
- explicit,
+ resolved = await resolve_turn_mcp(
+ self._agent_manager,
+ agent_id=agent_id,
+ user_id=user_id,
+ explicit=explicit,
apply_defaults=apply_defaults,
- extra_defaults=extra_defaults,
- agent_owner_id=owner_id,
)
- if not merged:
+ if resolved is None:
return None
- harness = list(merged)
- shown = list(merged)
- if owner_id is not None and owner_id != user_id:
- harness = self._agent_manager.align_mcp_names_to_harness(owner_id, user_id, merged)
- shown = self._agent_manager.mcp_names_for_chips(owner_id, user_id, merged, harness)
- failed = await self._agent_manager.prepare_chat_mcp(
- agent_id,
- merged,
- connector_user_id=user_id,
- )
+ failed = resolved.failed
if failed:
detail = f"mcp load failed: {', '.join(failed)}"
if raise_on_failure:
@@ -1946,7 +1986,7 @@ async def _resolve_turn_mcp_servers(
detail,
)
return None
- return _ResolvedTurnMcp(harness=harness, shown=shown)
+ return _ResolvedTurnMcp(harness=resolved.harness, shown=resolved.shown)
async def _record_stream_error(
self,
diff --git a/src/octop/infra/gateway/slash/handlers/memory.py b/src/octop/infra/gateway/slash/handlers/memory.py
index 5f0adb357b..9ee97f2d65 100644
--- a/src/octop/infra/gateway/slash/handlers/memory.py
+++ b/src/octop/infra/gateway/slash/handlers/memory.py
@@ -36,13 +36,9 @@ def _status_line(state: dict[str, Any], locale: str) -> str:
report = state.get("report")
sweep = state.get("sweep")
if phase == "done" and isinstance(sweep, dict):
- line += "\n" + full_tr(
- "memory_slim.swept",
- locale,
- namespaces=sweep.get("namespaces", 0),
- threads=sweep.get("threads", 0),
- directories=sweep.get("directories", 0),
- )
+ from octop.infra.agents.memory.thread_cleanup import describe_sweep # noqa: PLC0415
+
+ line += "\n" + describe_sweep(sweep, locale)
if phase == "done" and report and report.get("backend") == "postgres":
line += "\n" + full_tr(
"memory_slim.postgres_result",
diff --git a/src/octop/infra/knowledge/mcp_gateway.py b/src/octop/infra/knowledge/mcp_gateway.py
new file mode 100644
index 0000000000..59b5e54b01
--- /dev/null
+++ b/src/octop/infra/knowledge/mcp_gateway.py
@@ -0,0 +1,132 @@
+"""One-tool MCP server so an external ACP agent can search Octop knowledge bases."""
+
+from __future__ import annotations
+
+from typing import Any
+
+from octop.infra.knowledge.retrieve import DEFAULT_RETRIEVAL_K, retrieve_context
+from octop.infra.knowledge.tools import format_search_knowledge_description
+
+_PROTOCOL = "2024-11-05"
+
+
+def knowledge_tool_schema(catalog: list[dict[str, str]]) -> dict[str, Any]:
+ """Tool definition advertised by ``tools/list``."""
+ return {
+ "name": "search_knowledge",
+ "description": format_search_knowledge_description(catalog),
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "query": {
+ "type": "string",
+ "description": (
+ "Focused search string: key terms, names, and synonyms. Not a chat reply."
+ ),
+ },
+ "k": {
+ "type": "integer",
+ "description": "Max passages to return (default 8).",
+ "minimum": 1,
+ "maximum": 20,
+ },
+ },
+ "required": ["query"],
+ },
+ }
+
+
+def _ok(req_id: Any, result: dict[str, Any]) -> dict[str, Any]:
+ if req_id is None:
+ return {}
+ return {"jsonrpc": "2.0", "id": req_id, "result": result}
+
+
+def _err(req_id: Any, code: int, message: str) -> dict[str, Any]:
+ return {"jsonrpc": "2.0", "id": req_id, "error": {"code": code, "message": message}}
+
+
+def _arguments(params: Any) -> dict[str, Any]:
+ if not isinstance(params, dict):
+ return {}
+ raw = params.get("arguments") or {}
+ if not isinstance(raw, dict):
+ return {}
+ nested = raw.get("kwargs")
+ if nested is not None and set(raw.keys()) == {"kwargs"} and isinstance(nested, dict):
+ return nested
+ return raw
+
+
+def _passage_limit(raw: Any) -> int:
+ try:
+ k = int(raw)
+ except (TypeError, ValueError):
+ return DEFAULT_RETRIEVAL_K
+ return min(20, max(1, k))
+
+
+async def handle_knowledge_mcp(
+ body: dict[str, Any],
+ *,
+ user_id: int,
+ is_admin: bool,
+ knowledge_base_ids: list[str],
+ locale: str,
+ catalog: list[dict[str, str]],
+ services: Any,
+) -> dict[str, Any]:
+ """Answer one JSON-RPC request. An empty dict means the caller should return 202."""
+ method = str(body.get("method") or "")
+ req_id = body.get("id")
+ params = body.get("params") or {}
+
+ if method == "initialize":
+ return _ok(
+ req_id,
+ {
+ "protocolVersion": _PROTOCOL,
+ "capabilities": {"tools": {}},
+ "serverInfo": {"name": "octop-knowledge", "version": "0.1.0"},
+ },
+ )
+ if method == "notifications/initialized":
+ return {}
+ if method == "tools/list":
+ return _ok(req_id, {"tools": [knowledge_tool_schema(catalog)]})
+ if method == "ping":
+ return _ok(req_id, {})
+ if method != "tools/call":
+ return _err(req_id, -32601, f"Method not found: {method}")
+
+ arguments = _arguments(params)
+ name = str(params.get("name") or "") if isinstance(params, dict) else ""
+ if name != "search_knowledge":
+ return _ok(
+ req_id,
+ {"content": [{"type": "text", "text": f"Unknown tool: {name}"}], "isError": True},
+ )
+ query = str(arguments.get("query") or "").strip()
+ if not query:
+ return _ok(
+ req_id,
+ {
+ "content": [{"type": "text", "text": "query is required."}],
+ "isError": True,
+ },
+ )
+ if not knowledge_base_ids:
+ text = "No knowledge bases selected for this turn."
+ else:
+ text = await retrieve_context(
+ services,
+ user_id=user_id,
+ is_admin=is_admin,
+ query=query,
+ knowledge_base_ids=knowledge_base_ids,
+ k=_passage_limit(arguments.get("k")),
+ locale=locale,
+ )
+ if not text:
+ text = "No relevant passages found."
+ return _ok(req_id, {"content": [{"type": "text", "text": text}], "isError": False})
diff --git a/tests/integration/test_pg_orphan_checkpoints.py b/tests/integration/test_pg_orphan_checkpoints.py
new file mode 100644
index 0000000000..464434396f
--- /dev/null
+++ b/tests/integration/test_pg_orphan_checkpoints.py
@@ -0,0 +1,300 @@
+"""Orphan checkpoint reporting on a live PostgreSQL memory store.
+
+LangGraph's checkpoint tables are shared by every agent and host on a DSN and
+record no owner, so Octop only counts orphans there and never deletes them.
+
+Each test creates throwaway databases on the server from
+``OCTOP_TEST_DATABASE_URL`` and drops them afterwards. That role needs the
+``CREATEDB`` privilege.
+"""
+
+from __future__ import annotations
+
+import contextlib
+import json
+import os
+import uuid
+from collections.abc import Iterator
+from pathlib import Path
+from typing import Any, TypedDict
+
+import pytest
+
+from octop.config import DatabaseConfig, OctopConfig
+from octop.infra.agents.memory.thread_cleanup import (
+ close_memory,
+ gc_orphan_checkpoints,
+ sweep_deleted_residuals,
+)
+from octop.infra.db.migrate import run_migrations
+from octop.infra.db.pool import SqlitePool
+from octop.infra.db.services import build_shared_services
+from octop.infra.utils.paths import PathLayout
+from octop.infra.utils.ulid import new_ulid
+from tests.support.postgresql import requires_postgresql
+
+pytestmark = requires_postgresql
+
+
+@pytest.fixture
+def make_database() -> Iterator[Any]:
+ import psycopg
+ from psycopg.conninfo import make_conninfo
+
+ created: list[str] = []
+ admin_url = os.environ["OCTOP_TEST_DATABASE_URL"]
+
+ def make() -> DatabaseConfig:
+ name = f"octop_orphan_{uuid.uuid4().hex[:12]}"
+ with psycopg.connect(admin_url, autocommit=True) as conn:
+ conn.execute(f'CREATE DATABASE "{name}"')
+ created.append(name)
+ # Only the database name changes; every other connection option is kept.
+ return DatabaseConfig(driver="postgresql", url=make_conninfo(admin_url, dbname=name))
+
+ yield make
+ with psycopg.connect(admin_url, autocommit=True) as conn:
+ for name in created:
+ with contextlib.suppress(psycopg.Error):
+ conn.execute(f'DROP DATABASE IF EXISTS "{name}" WITH (FORCE)')
+
+
+def _services(tmp_path: Path, control_plane: DatabaseConfig) -> tuple[Any, SqlitePool]:
+ paths = PathLayout(tmp_path / ".octop")
+ paths.ensure_root()
+ db = SqlitePool(paths.db)
+ run_migrations(db)
+ return build_shared_services(db=db, paths=paths, config=OctopConfig(database=control_plane)), db
+
+
+class _State(TypedDict):
+ n: int
+
+
+def _write_threads(dsn: str, agent_id: str | None, thread_ids: list[str]) -> None:
+ """Run a one-step graph so LangGraph writes real checkpoints for each thread."""
+ from langgraph.graph import END, START, StateGraph
+ from octop_memory.core import Memory
+
+ namespace = f"agent_{agent_id}" if agent_id else "other_host"
+ memory = Memory(namespace=namespace, backend="postgres", backend_config={"dsn": dsn})
+ try:
+ memory._ensure_checkpointer()
+ graph = StateGraph(_State)
+ graph.add_node("step", lambda state: {"n": state["n"] + 1})
+ graph.add_edge(START, "step")
+ graph.add_edge("step", END)
+ app = graph.compile(checkpointer=memory._checkpointer)
+ for thread_id in thread_ids:
+ # Octop's harness config carries agent_id; LangGraph copies it into metadata.
+ configurable = {"thread_id": thread_id}
+ if agent_id:
+ configurable["agent_id"] = agent_id
+ app.invoke({"n": 0}, {"configurable": configurable})
+ finally:
+ close_memory(memory)
+
+
+def _write_memory(dsn: str, namespace: str) -> None:
+ from octop_memory.core import Memory
+
+ memory = Memory(namespace=namespace, backend="postgres", backend_config={"dsn": dsn})
+ try:
+ memory.add_raw("hello", event_type="user_message")
+ finally:
+ close_memory(memory)
+
+
+def _checkpoint_rows(dsn: str) -> dict[str, int]:
+ """Row count per thread across all three checkpoint tables."""
+ import psycopg
+
+ counts: dict[str, int] = {}
+ with psycopg.connect(dsn) as conn:
+ for table in ("checkpoints", "checkpoint_blobs", "checkpoint_writes"):
+ found = conn.execute(
+ "SELECT COALESCE(to_regclass(%s), to_regclass(%s))::text",
+ (f"octop_memory.{table}", f"public.{table}"),
+ ).fetchone()
+ if found is None or found[0] is None:
+ continue
+ for thread_id, n in conn.execute(
+ f"SELECT thread_id, COUNT(*) FROM {found[0]} GROUP BY thread_id"
+ ):
+ counts[str(thread_id)] = counts.get(str(thread_id), 0) + int(n)
+ return counts
+
+
+def _tid() -> str:
+ return f"thr_{new_ulid()}"
+
+
+def _seed_two_agents(services: Any, dsn: str) -> dict[str, str]:
+ """A: one live thread and one orphan. B: two live threads."""
+ user_id = services.user_repo.create(username="alice", password_hash="x", role="admin")
+ ids = {
+ "a_live": _tid(),
+ "a_orphan": _tid(),
+ "b_live1": _tid(),
+ "b_live2": _tid(),
+ }
+ for agent_id in ("A", "B"):
+ services.agent_repo.create(agent_id=agent_id, user_id=user_id, name=agent_id)
+ for key, agent_id in (("a_live", "A"), ("b_live1", "B"), ("b_live2", "B")):
+ services.thread_repo.insert(
+ thread_id=ids[key],
+ agent_id=agent_id,
+ user_id=user_id,
+ channel_type="dashboard",
+ session_key=key,
+ )
+ _write_threads(dsn, "A", [ids["a_live"], ids["a_orphan"]])
+ _write_threads(dsn, "B", [ids["b_live1"], ids["b_live2"]])
+ return ids
+
+
+def _add_external_agent(services: Any, dsn: str) -> None:
+ user = services.user_repo.get_by_username("alice")
+ user_id = (
+ user.id
+ if user is not None
+ else services.user_repo.create(username="alice", password_hash="x", role="admin")
+ )
+ services.agent_repo.create(
+ agent_id="EXT",
+ user_id=user_id,
+ name="ext",
+ config_json=json.dumps({"memory": {"backend": {"type": "postgres", "dsn": dsn}}}),
+ )
+
+
+def test_gc_orphans_reports_postgres_orphans_without_deleting(
+ tmp_path: Path, make_database: Any
+) -> None:
+ control = make_database()
+ dsn = control.postgresql_conninfo()
+ services, db = _services(tmp_path, control)
+ try:
+ ids = _seed_two_agents(services, dsn)
+ before = _checkpoint_rows(dsn)
+
+ for agent_id in ("A", None):
+ result = gc_orphan_checkpoints(services, agent_id=agent_id, apply=True)
+
+ assert result.orphans == []
+ assert [(s.agent_id, s.reason, s.threads) for s in result.skipped] == [
+ ("A", "postgres_report_only", 1)
+ ]
+ assert result.skipped[0].nbytes > 0
+ assert _checkpoint_rows(dsn) == before
+ assert set(before) == set(ids.values())
+ finally:
+ db.close()
+
+
+def test_gc_orphans_does_not_report_a_thread_live_under_another_agent(
+ tmp_path: Path, make_database: Any
+) -> None:
+ control = make_database()
+ dsn = control.postgresql_conninfo()
+ services, db = _services(tmp_path, control)
+ try:
+ ids = _seed_two_agents(services, dsn)
+ # Same thread id written under A's tag, but B owns it in ``threads``.
+ _write_threads(dsn, "A", [ids["b_live1"]])
+
+ result = gc_orphan_checkpoints(services, agent_id="A", apply=False)
+
+ assert [(s.agent_id, s.threads) for s in result.skipped] == [("A", 1)]
+ finally:
+ db.close()
+
+
+def test_gc_orphans_does_not_scan_other_databases(tmp_path: Path, make_database: Any) -> None:
+ control = make_database()
+ external = make_database()
+ control_dsn = control.postgresql_conninfo()
+ services, db = _services(tmp_path, control)
+ try:
+ _seed_two_agents(services, control_dsn)
+ external_dsn = external.postgresql_conninfo()
+ _add_external_agent(services, external_dsn)
+ _write_threads(external_dsn, "EXT", [_tid()])
+ # Same server and database, spelled differently: still not the control plane.
+ _write_threads(control_dsn, "SAME", [_tid()])
+ services.agent_repo.create(
+ agent_id="SAME",
+ user_id=services.user_repo.get_by_username("alice").id,
+ name="same",
+ config_json=json.dumps(
+ {
+ "memory": {
+ "backend": {
+ "type": "postgres",
+ "dsn": f"{control_dsn} application_name=octop_test",
+ }
+ }
+ }
+ ),
+ )
+ external_before = _checkpoint_rows(external_dsn)
+ control_before = _checkpoint_rows(control_dsn)
+
+ result = gc_orphan_checkpoints(services, agent_id=None, apply=True)
+
+ skipped = {(s.agent_id, s.reason, s.threads) for s in result.skipped}
+ assert ("EXT", "external_database", None) in skipped
+ assert ("SAME", "external_database", None) in skipped
+ assert _checkpoint_rows(external_dsn) == external_before
+ assert _checkpoint_rows(control_dsn) == control_before
+ finally:
+ db.close()
+
+
+def test_sweep_counts_postgres_residuals_without_deleting(
+ tmp_path: Path, make_database: Any
+) -> None:
+ import psycopg
+
+ control = make_database()
+ external = make_database()
+ dsn = control.postgresql_conninfo()
+ external_dsn = external.postgresql_conninfo()
+ services, db = _services(tmp_path, control)
+ try:
+ _seed_two_agents(services, dsn)
+ _add_external_agent(services, external_dsn)
+ _write_threads(external_dsn, "EXT", [_tid()])
+ _write_threads(dsn, None, [_tid()]) # another host: no agent_id, never counted
+ _write_memory(dsn, "agent_A")
+ _write_memory(dsn, "agent_GONE")
+ # octop_memory has not migrated the pre-rename schema yet: it must stay untouched.
+ with psycopg.connect(dsn, autocommit=True) as conn:
+ conn.execute("CREATE SCHEMA harness_memory")
+ conn.execute("CREATE TABLE harness_memory.raw_events (namespace text, id text)")
+ conn.execute("INSERT INTO harness_memory.raw_events VALUES ('agent_OLD', '1')")
+ control_before = _checkpoint_rows(dsn)
+ external_before = _checkpoint_rows(external_dsn)
+ manager = type(
+ "Manager",
+ (),
+ {"_repos": services.repos, "_paths": services.paths, "_config": services.config},
+ )()
+
+ result = sweep_deleted_residuals(manager)
+
+ assert result["namespaces"] == 0
+ assert result["threads"] == 0
+ assert result["postgres_kept"] == {"threads": 1, "namespaces": 1}
+ assert result["skipped_databases"] == 1
+ assert _checkpoint_rows(dsn) == control_before
+ assert _checkpoint_rows(external_dsn) == external_before
+ with psycopg.connect(dsn) as conn:
+ gone = conn.execute(
+ "SELECT COUNT(*) FROM octop_memory.raw_events WHERE namespace = 'agent_gone'"
+ ).fetchone()
+ old = conn.execute("SELECT COUNT(*) FROM harness_memory.raw_events").fetchone()
+ assert gone is not None and gone[0] == 1
+ assert old is not None and old[0] == 1
+ finally:
+ db.close()
diff --git a/tests/unit/agents/test_acp_delegation.py b/tests/unit/agents/test_acp_delegation.py
new file mode 100644
index 0000000000..2578ce8c10
--- /dev/null
+++ b/tests/unit/agents/test_acp_delegation.py
@@ -0,0 +1,126 @@
+"""@mentions on a managed turn become a prompt note and an ask_agent call."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from octop.infra.agents.acp.agents_mcp import handle_agents_mcp
+from octop.infra.agents.acp.delegation import AgentScope, delegation_note_for
+
+
+def test_punctuated_mention_still_names_the_expert() -> None:
+ note = delegation_note_for(
+ "请@分析师,看一下",
+ experts=[("分析师", "财务")],
+ subagents=[],
+ locale="zh",
+ )
+ assert note is not None
+ assert "ask_agent" in note
+ assert "@分析师" in note
+
+
+def test_expert_mention_asks_the_agent_to_call_ask_agent() -> None:
+ note = delegation_note_for(
+ "请 @分析师 看一下",
+ experts=[("分析师", "财务")],
+ subagents=[("分析师", "同名子智能体")],
+ locale="zh",
+ )
+ assert note is not None
+ assert "ask_agent" in note
+ assert "子智能体" not in note
+
+
+def test_subagent_mention_asks_for_delegation() -> None:
+ note = delegation_note_for(
+ "@researcher 查一下",
+ experts=[],
+ subagents=[("researcher", "查资料")],
+ locale="en",
+ )
+ assert note is not None
+ assert "@researcher" in note
+ assert "Delegate" in note
+
+
+@pytest.mark.asyncio
+async def test_ask_agent_returns_the_peer_answer() -> None:
+ class Team:
+ def list_peers(self, user_id: int, *, exclude_agent_id: str | None = None) -> list[Any]:
+ return []
+
+ def resolve_peer(
+ self, user_id: int, query: str, *, exclude_agent_id: str | None = None
+ ) -> Any:
+ assert query == "分析师"
+ return SimpleNamespace(agent_id="peer1")
+
+ async def call_peer(self, **kwargs: Any) -> Any:
+ assert kwargs["to_agent_id"] == "peer1"
+ assert kwargs["source_thread_id"] == "thr"
+ return SimpleNamespace(name="分析师", response="42")
+
+ scope = AgentScope(user_id=7, from_agent_id="GWN", thread_id="thr", session_key="")
+ result = await handle_agents_mcp(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": {"name": "ask_agent", "arguments": {"expert": "@分析师", "message": "今天"}},
+ },
+ scope=scope,
+ team=Team(),
+ )
+ assert result["result"]["content"][0]["text"] == "分析师: 42"
+ assert result["result"]["isError"] is False
+
+
+@pytest.mark.asyncio
+async def test_managed_turn_attaches_experts_and_stores_the_note() -> None:
+ from octop.infra.agents.acp.turn import attach_managed_turn
+
+ class Entry:
+ agent_id = "peer1"
+ metadata = {"display_name": "分析师", "description": "财务"}
+ config = SimpleNamespace(name="分析师")
+
+ class Team:
+ def list_peers(self, user_id: int, *, exclude_agent_id: str | None = None) -> list[Entry]:
+ return [Entry()]
+
+ class Manager:
+ _harness_manager = SimpleNamespace(team=Team())
+ _config = SimpleNamespace(
+ bind_host="127.0.0.1",
+ port=8000,
+ tls=SimpleNamespace(enabled=False, cert_file="", key_file=""),
+ )
+ _connector_svc = SimpleNamespace()
+
+ def get_row(self, agent_id: str) -> SimpleNamespace:
+ return SimpleNamespace(kind="managed")
+
+ async def list_subagent_summaries(self, agent_id: str) -> list[dict[str, str]]:
+ return [{"slug": "researcher", "description": "查资料"}]
+
+ request: dict[str, Any] = {
+ "user": "7",
+ "thread_id": "thr",
+ "messages": [{"role": "user", "content": "@researcher 看一下"}],
+ "configurable": {"locale": "zh"},
+ }
+ await attach_managed_turn(Manager(), "GWN", request)
+ configurable = request["configurable"]
+ assert isinstance(configurable, dict)
+ specs = configurable["acp_mcp_servers"]
+ assert isinstance(specs, dict)
+ assert set(specs) == {"octop-agents", "octop-files"}
+ assert specs["octop-agents"]["transport"] == "http"
+ assert "/api/internal/mcp/agents?token=" in specs["octop-agents"]["url"]
+ note = configurable["acp_prompt_note"]
+ assert isinstance(note, str)
+ assert "@researcher" in note
diff --git a/tests/unit/agents/test_acp_file_edit_compat.py b/tests/unit/agents/test_acp_file_edit_compat.py
new file mode 100644
index 0000000000..2f91789ac0
--- /dev/null
+++ b/tests/unit/agents/test_acp_file_edit_compat.py
@@ -0,0 +1,228 @@
+"""ACP file edits become write_file / edit_file calls the chat card already understands."""
+
+from __future__ import annotations
+
+import json
+from types import SimpleNamespace
+from typing import Any
+
+from octop_harness.acp.client import ACPHostedClient
+from octop_harness.acp.models import ACPRunnerConfig
+
+from octop.infra.agents.acp.file_edits import (
+ file_edits_from_update,
+ install_acp_file_edits,
+)
+from octop.infra.agents.acp.tool_names import install_acp_tool_titles
+
+
+def _install() -> None:
+ install_acp_tool_titles()
+ install_acp_file_edits()
+
+
+def _client() -> ACPHostedClient:
+ _install()
+ client = ACPHostedClient(
+ runner_name="opencode",
+ runner_config=ACPRunnerConfig(command="opencode", args=["acp"]),
+ cwd=".",
+ )
+ client.start_prompt(lambda _payload, _is_last: None)
+ return client
+
+
+def _chunk_calls(chunk: Any) -> list[dict[str, Any]]:
+ message = chunk.message
+ calls = getattr(message, "tool_call_chunks", None) or []
+ out: list[dict[str, Any]] = []
+ for call in calls:
+ if isinstance(call, dict):
+ out.append(call)
+ continue
+ out.append(
+ {
+ "name": getattr(call, "name", ""),
+ "args": getattr(call, "args", ""),
+ "id": getattr(call, "id", ""),
+ "index": getattr(call, "index", 0),
+ }
+ )
+ return out
+
+
+def test_diff_update_keeps_path_and_body() -> None:
+ update = SimpleNamespace(
+ content=[
+ {
+ "type": "diff",
+ "path": "src/app.py",
+ "oldText": "a\n",
+ "newText": "b\n",
+ }
+ ],
+ locations=[{"path": "src/app.py"}],
+ kind="edit",
+ raw_input=None,
+ )
+ edits = file_edits_from_update(update)
+ assert edits == [{"path": "src/app.py", "old": "a\n", "new": "b\n"}]
+
+
+def test_read_without_diff_is_not_a_file_edit() -> None:
+ update = SimpleNamespace(
+ content=None,
+ locations=[{"path": "README.md"}],
+ kind="read",
+ raw_input={"path": "README.md"},
+ )
+ assert file_edits_from_update(update) == []
+
+
+def test_client_event_carries_files() -> None:
+ client = _client()
+ update = SimpleNamespace(
+ tool_call_id="call-1",
+ title="Edit app.py",
+ kind="edit",
+ status="in_progress",
+ raw_input=None,
+ raw_output=None,
+ content=[{"type": "diff", "path": "app.py", "oldText": None, "newText": "print(1)\n"}],
+ locations=None,
+ )
+ event = client._tool_event_from_state(update)
+ assert event is not None
+ assert event["files"] == [{"path": "app.py", "old": None, "new": "print(1)\n"}]
+
+
+def test_completed_diff_streams_as_edit_file() -> None:
+ _install()
+ from octop_harness.acp.managed import _tool_chunks
+
+ opened: dict[str, int] = {}
+ chunks, _index = _tool_chunks(
+ {
+ "call_id": "call-edit",
+ "name": "Edit app.py",
+ "status": "completed",
+ "output": "done",
+ "files": [{"path": "app.py", "old": "a\n", "new": "b\n"}],
+ },
+ opened,
+ 0,
+ )
+ calls = [call for chunk in chunks for call in _chunk_calls(chunk)]
+ assert len(calls) == 1
+ assert calls[0]["name"] == "edit_file"
+ assert json.loads(calls[0]["args"]) == {
+ "file_path": "app.py",
+ "old_string": "a\n",
+ "new_string": "b\n",
+ }
+ assert opened == {}
+
+
+def test_new_file_streams_as_write_file() -> None:
+ _install()
+ from octop_harness.acp.managed import _tool_chunks
+
+ chunks, _index = _tool_chunks(
+ {
+ "call_id": "call-write",
+ "name": "Write notes.md",
+ "status": "completed",
+ "files": [{"path": "notes.md", "old": None, "new": "hello\n"}],
+ },
+ {},
+ 0,
+ )
+ calls = [call for chunk in chunks for call in _chunk_calls(chunk)]
+ assert calls[0]["name"] == "write_file"
+ assert json.loads(calls[0]["args"]) == {"file_path": "notes.md", "content": "hello\n"}
+
+
+def test_path_only_waits_until_the_call_finishes() -> None:
+ _install()
+ from octop_harness.acp.managed import _tool_chunks
+
+ opened: dict[str, int] = {}
+ started, index = _tool_chunks(
+ {
+ "call_id": "call-path",
+ "name": "Edit README.md",
+ "status": "in_progress",
+ "files": [{"path": "README.md", "old": None, "new": None}],
+ },
+ opened,
+ 0,
+ )
+ started_calls = [call for chunk in started for call in _chunk_calls(chunk)]
+ assert started_calls[0]["name"] == "Edit README.md"
+ assert started_calls[0]["args"] == ""
+
+ finished, _index = _tool_chunks(
+ {"call_id": "call-path", "name": "Edit README.md", "status": "completed", "files": []},
+ opened,
+ index,
+ )
+ names = [call["name"] for chunk in finished for call in _chunk_calls(chunk)]
+ args = [call["args"] for chunk in finished for call in _chunk_calls(chunk)]
+ assert "edit_file" in names
+ assert json.loads(next(item for item in args if item)) == {"file_path": "README.md"}
+
+
+def test_two_diffs_open_two_file_tools() -> None:
+ _install()
+ from octop_harness.acp.managed import _tool_chunks
+
+ chunks, _index = _tool_chunks(
+ {
+ "call_id": "call-two",
+ "name": "Edit",
+ "status": "completed",
+ "files": [
+ {"path": "a.py", "old": "a", "new": "b"},
+ {"path": "b.py", "old": None, "new": "c"},
+ ],
+ },
+ {},
+ 0,
+ )
+ calls = [call for chunk in chunks for call in _chunk_calls(chunk)]
+ assert [call["name"] for call in calls] == ["edit_file", "write_file"]
+ assert [call["id"] for call in calls] == ["call-two", "call-two:1"]
+
+
+def test_history_keeps_the_edit_arguments() -> None:
+ _install()
+ from octop_harness.acp.managed import (
+ _collect_managed_chunk,
+ _managed_history_messages,
+ _tool_chunks,
+ )
+
+ chunks, _index = _tool_chunks(
+ {
+ "call_id": "call-hist",
+ "name": "Edit a.py",
+ "status": "completed",
+ "output": "ok",
+ "files": [{"path": "a.py", "old": "a\n", "new": "b\n"}],
+ },
+ {},
+ 0,
+ )
+ text: list[str] = []
+ reasoning: list[str] = []
+ tools: list[dict[str, Any]] = []
+ by_id: dict[str, dict[str, Any]] = {}
+ for chunk in chunks:
+ _collect_managed_chunk(chunk, text, reasoning, tools, by_id)
+ messages = _managed_history_messages(text, reasoning, tools)
+ ai = next(message for message in messages if getattr(message, "tool_calls", None))
+ call = ai.tool_calls[0]
+ assert call["name"] == "edit_file"
+ assert call["args"]["file_path"] == "a.py"
+ assert call["args"]["old_string"] == "a\n"
+ assert call["args"]["new_string"] == "b\n"
diff --git a/tests/unit/agents/test_acp_files_mcp.py b/tests/unit/agents/test_acp_files_mcp.py
new file mode 100644
index 0000000000..e7f48903ee
--- /dev/null
+++ b/tests/unit/agents/test_acp_files_mcp.py
@@ -0,0 +1,69 @@
+"""Managed runners deliver files through the send_file_to_user loopback."""
+
+from __future__ import annotations
+
+import json
+from pathlib import Path
+
+import pytest
+
+from octop.infra.agents.acp.files_mcp import (
+ file_scope,
+ handle_files_mcp,
+ retain_file_scope,
+)
+
+
+class _Workspace:
+ def __init__(self, root: Path) -> None:
+ self.root = root
+
+ def materialize_local(self, path: str) -> Path:
+ return self.root / path
+
+
+def test_file_token_is_stable_per_expert() -> None:
+ assert retain_file_scope("GWN") == retain_file_scope("GWN")
+ assert file_scope(retain_file_scope("GWN")) is not None
+
+
+@pytest.mark.asyncio
+async def test_send_file_returns_the_native_media_block(tmp_path: Path) -> None:
+ target = tmp_path / "report.txt"
+ target.write_text("hello", encoding="utf-8")
+ listed = await handle_files_mcp(
+ {"jsonrpc": "2.0", "id": 1, "method": "tools/list"}, workspace=_Workspace(tmp_path)
+ )
+ tools = listed["result"]["tools"]
+ assert [item["name"] for item in tools] == ["send_file_to_user"]
+
+ result = await handle_files_mcp(
+ {
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": {"name": "send_file_to_user", "arguments": {"file_path": "report.txt"}},
+ },
+ workspace=_Workspace(tmp_path),
+ )
+ content = result["result"]["content"]
+ assert result["result"]["isError"] is False
+ block = json.loads(content[0]["text"])
+ assert block["octop_delivery"] == "send_file_to_user"
+ assert block["path"] == "report.txt"
+ assert block["source"]["url"].startswith("file:")
+
+
+@pytest.mark.asyncio
+async def test_missing_file_is_an_error(tmp_path: Path) -> None:
+ result = await handle_files_mcp(
+ {
+ "jsonrpc": "2.0",
+ "id": 3,
+ "method": "tools/call",
+ "params": {"name": "send_file_to_user", "arguments": {"file_path": "missing.txt"}},
+ },
+ workspace=_Workspace(tmp_path),
+ )
+ assert result["result"]["isError"] is True
+ assert "missing.txt" in result["result"]["content"][0]["text"]
diff --git a/tests/unit/agents/test_acp_host_mcp.py b/tests/unit/agents/test_acp_host_mcp.py
new file mode 100644
index 0000000000..c30da12c27
--- /dev/null
+++ b/tests/unit/agents/test_acp_host_mcp.py
@@ -0,0 +1,200 @@
+"""Cron, memory, and plugin loopback MCP for managed experts."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+from typing import Any
+
+import pytest
+
+from octop.infra.agents.acp.cron_mcp import CronScope, handle_cron_mcp
+from octop.infra.agents.acp.memory_mcp import handle_memory_mcp, memory_enabled
+from octop.infra.agents.acp.plugins_mcp import handle_plugins_mcp, plugin_tools
+from octop.infra.agents.acp.turn import attach_managed_turn
+
+
+class _Cron:
+ def __init__(self) -> None:
+ self._repos = SimpleNamespace(
+ agent_repo=SimpleNamespace(get=lambda _agent_id: SimpleNamespace(user_id=7))
+ )
+
+ def list_by_agent(self, agent_id: str, include_disabled: bool = True) -> list[Any]:
+ assert agent_id == "GWN"
+ assert include_disabled is True
+ return [SimpleNamespace(to_public_dict=lambda: {"cron_id": "c1", "name": "喝水"})]
+
+
+@pytest.mark.asyncio
+async def test_cron_list_uses_the_calling_expert() -> None:
+ scope = CronScope(user_id=7, agent_id="GWN", thread_id="thr", session_key="dash")
+ result = await handle_cron_mcp(
+ {
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": {"name": "cronjob_list", "arguments": {}},
+ },
+ scope=scope,
+ cron_manager=_Cron(),
+ )
+ text = result["result"]["content"][0]["text"]
+ assert result["result"]["isError"] is False
+ assert "c1" in text
+
+
+def test_memory_stays_off_until_the_expert_enables_it() -> None:
+ assert memory_enabled({}) is False
+ assert memory_enabled({"memory": {"memory_enabled": False}}) is False
+ assert memory_enabled({"memory": {"memory_enabled": True}}) is True
+
+
+@pytest.mark.asyncio
+async def test_memory_call_reports_a_missing_service() -> None:
+ result = await handle_memory_mcp(
+ {
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": {"name": "memory_search", "arguments": {"query": "hi"}},
+ },
+ service=None,
+ )
+ assert result["result"]["isError"] is True
+
+
+@pytest.mark.asyncio
+async def test_plugin_tool_is_callable(monkeypatch: pytest.MonkeyPatch) -> None:
+ def ping_host(name: str) -> str:
+ """Say hello."""
+ return f"hi {name}"
+
+ registration = SimpleNamespace(
+ plugin_id="demo",
+ name="ping_host",
+ fn=ping_host,
+ description="Say hello.",
+ )
+
+ class Registry:
+ def all_tools(self) -> list[Any]:
+ return [registration]
+
+ def list_plugins(self) -> list[Any]:
+ return [SimpleNamespace(manifest=SimpleNamespace(id="demo"))]
+
+ monkeypatch.setattr("octop_harness.plugins.PluginRegistry", Registry)
+ monkeypatch.setattr("octop_harness.plugins.tools.PluginRegistry", Registry)
+ manager = SimpleNamespace(
+ _plugin_manager=SimpleNamespace(global_enabled_map=lambda: {"demo": True})
+ )
+ tools = plugin_tools(manager, {})
+ assert [tool.name for tool in tools] == ["ping_host"]
+ result = await handle_plugins_mcp(
+ {
+ "jsonrpc": "2.0",
+ "id": 3,
+ "method": "tools/call",
+ "params": {"name": "ping_host", "arguments": {"name": "Ada"}},
+ },
+ tools=tools,
+ )
+ assert result["result"]["content"][0]["text"] == "hi Ada"
+
+
+@pytest.mark.asyncio
+async def test_managed_turn_adds_cron_memory_and_plugins(monkeypatch: pytest.MonkeyPatch) -> None:
+ def ping_host(name: str) -> str:
+ """Say hello."""
+ return name
+
+ registration = SimpleNamespace(
+ plugin_id="demo",
+ name="ping_host",
+ fn=ping_host,
+ description="Say hello.",
+ )
+
+ class Registry:
+ def all_tools(self) -> list[Any]:
+ return [registration]
+
+ def list_plugins(self) -> list[Any]:
+ return [SimpleNamespace(manifest=SimpleNamespace(id="demo"))]
+
+ monkeypatch.setattr("octop_harness.plugins.PluginRegistry", Registry)
+ monkeypatch.setattr("octop_harness.plugins.tools.PluginRegistry", Registry)
+
+ class Manager:
+ _connector_svc = SimpleNamespace()
+ _cron_manager = object()
+ _plugin_manager = SimpleNamespace(global_enabled_map=lambda: {"demo": True})
+ _config = SimpleNamespace(
+ bind_host="127.0.0.1",
+ port=8000,
+ tls=SimpleNamespace(enabled=False, cert_file="", key_file=""),
+ )
+
+ def get_row(self, agent_id: str) -> SimpleNamespace:
+ return SimpleNamespace(kind="managed")
+
+ def get_config(self, agent_id: str) -> dict[str, Any]:
+ return {"memory": {"memory_enabled": True}}
+
+ request: dict[str, Any] = {"user": "7", "thread_id": "thr", "configurable": {"locale": "zh"}}
+ await attach_managed_turn(Manager(), "GWN", request)
+ configurable = request["configurable"]
+ assert isinstance(configurable, dict)
+ specs = configurable["acp_mcp_servers"]
+ assert isinstance(specs, dict)
+ assert {"octop-files", "octop-cron", "octop-memory", "octop-plugins"} <= set(specs)
+ assert "/api/internal/mcp/cron?token=" in specs["octop-cron"]["url"]
+ assert "/api/internal/mcp/memory?token=" in specs["octop-memory"]["url"]
+ assert "/api/internal/mcp/plugins?token=" in specs["octop-plugins"]["url"]
+ note = str(configurable.get("acp_prompt_note") or "")
+ assert "cronjob_create" in note
+ assert "CronCreate" in note
+ assert "Asia/Shanghai" in note
+
+
+@pytest.mark.asyncio
+async def test_disabled_managed_tools_are_left_off() -> None:
+ class Manager:
+ _connector_svc = SimpleNamespace()
+ _cron_manager = object()
+ _config = SimpleNamespace(
+ bind_host="127.0.0.1",
+ port=8000,
+ tls=SimpleNamespace(enabled=False, cert_file="", key_file=""),
+ )
+
+ def get_row(self, agent_id: str) -> SimpleNamespace:
+ return SimpleNamespace(kind="managed")
+
+ def get_config(self, agent_id: str) -> dict[str, Any]:
+ return {
+ "memory": {"memory_enabled": True},
+ "tools_disabled": [
+ "send_file_to_user",
+ "cronjob_list",
+ "cronjob_get",
+ "cronjob_create",
+ "cronjob_update",
+ "cronjob_delete",
+ "cronjob_run_now",
+ "memory_save",
+ ],
+ }
+
+ request: dict[str, Any] = {"user": "7", "thread_id": "thr", "configurable": {"locale": "zh"}}
+ await attach_managed_turn(Manager(), "GWN", request)
+ configurable = request["configurable"]
+ assert isinstance(configurable, dict)
+ specs = configurable["acp_mcp_servers"]
+ assert isinstance(specs, dict)
+ assert "octop-files" not in specs
+ assert "octop-cron" not in specs
+ assert "octop-memory" in specs
+ note = str(configurable.get("acp_prompt_note") or "")
+ assert "send_file_to_user" not in note
+ assert "cronjob_create" not in note
diff --git a/tests/unit/agents/test_acp_mcp.py b/tests/unit/agents/test_acp_mcp.py
new file mode 100644
index 0000000000..4a9c1f0edd
--- /dev/null
+++ b/tests/unit/agents/test_acp_mcp.py
@@ -0,0 +1,134 @@
+"""A managed turn hands harness MCP specs for connectors and knowledge."""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+
+from octop.infra.agents.acp.turn import (
+ KnowledgeScope,
+ attach_managed_turn,
+ knowledge_scope,
+ retain_knowledge_scope,
+)
+
+
+def test_knowledge_token_is_stable_for_the_same_selection() -> None:
+ scope = KnowledgeScope(
+ user_id=3,
+ is_admin=False,
+ knowledge_base_ids=("kb1",),
+ locale="zh",
+ catalog=(("kb1", "手册", "产品说明"),),
+ )
+ first = retain_knowledge_scope(scope)
+ second = retain_knowledge_scope(scope)
+ assert first == second
+
+
+@pytest.mark.asyncio
+async def test_managed_turn_adds_connector_and_knowledge_specs() -> None:
+ class Svc:
+ async def mcp_configs_for_user(self, user_id: int) -> dict[str, object]:
+ assert user_id == 7
+ return {"notes": {"transport": "http", "url": "http://127.0.0.1:9/mcp"}}
+
+ class Manager:
+ _connector_svc = Svc()
+ _config = SimpleNamespace(
+ bind_host="127.0.0.1",
+ port=8000,
+ tls=SimpleNamespace(enabled=False, cert_file="", key_file=""),
+ )
+
+ def get_row(self, agent_id: str) -> SimpleNamespace:
+ return SimpleNamespace(kind="managed")
+
+ request: dict[str, object] = {
+ "user": "7",
+ "mcp_servers": ["notes"],
+ "configurable": {
+ "knowledge_base_ids": ["kb1"],
+ "knowledge_base_catalog": [{"id": "kb1", "name": "手册", "description": ""}],
+ "locale": "zh",
+ "user_is_admin": False,
+ },
+ }
+ await attach_managed_turn(Manager(), "GWN", request)
+ configurable = request["configurable"]
+ assert isinstance(configurable, dict)
+ specs = configurable["acp_mcp_servers"]
+ assert isinstance(specs, dict)
+ assert set(specs) == {"notes", "octop-knowledge", "octop-files"}
+ assert "/api/internal/mcp/files?token=" in specs["octop-files"]["url"]
+ knowledge = specs["octop-knowledge"]
+ assert knowledge["transport"] == "http"
+ assert "127.0.0.1:8000/api/internal/mcp/knowledge?token=" in knowledge["url"]
+ token = knowledge["url"].split("token=", 1)[1]
+ scope = knowledge_scope(token)
+ assert scope is not None
+ assert scope.knowledge_base_ids == ("kb1",)
+ assert scope.catalog_rows()[0]["name"] == "手册"
+
+
+@pytest.mark.asyncio
+async def test_native_turn_leaves_the_request_alone() -> None:
+ class Manager:
+ def get_row(self, agent_id: str) -> SimpleNamespace:
+ return SimpleNamespace(kind="native")
+
+ request: dict[str, object] = {"configurable": {}}
+ await attach_managed_turn(Manager(), "GWN", request)
+ assert request["configurable"] == {}
+
+
+@pytest.mark.asyncio
+async def test_ask_mode_does_not_attach_connectors() -> None:
+ class Svc:
+ async def mcp_configs_for_user(self, user_id: int) -> dict[str, object]:
+ return {
+ "notes": {
+ "transport": "http",
+ "url": "http://127.0.0.1:9/mcp",
+ "allowed_tools": ["search"],
+ }
+ }
+
+ class Manager:
+ _connector_svc = Svc()
+ _config = SimpleNamespace(
+ bind_host="127.0.0.1",
+ port=8000,
+ tls=SimpleNamespace(enabled=False, cert_file="", key_file=""),
+ )
+
+ def get_row(self, agent_id: str) -> SimpleNamespace:
+ return SimpleNamespace(kind="managed")
+
+ request: dict[str, object] = {
+ "user": "7",
+ "conversation_mode": "ask",
+ "mcp_servers": ["notes"],
+ "configurable": {"locale": "zh"},
+ }
+ await attach_managed_turn(Manager(), "GWN", request)
+ configurable = request["configurable"]
+ assert isinstance(configurable, dict)
+ specs = configurable["acp_mcp_servers"]
+ assert isinstance(specs, dict)
+ assert set(specs) == {"octop-files"}
+ note = configurable["acp_prompt_note"]
+ assert isinstance(note, str)
+ assert "send_file_to_user" in note
+
+ request["conversation_mode"] = "craft"
+ await attach_managed_turn(Manager(), "GWN", request)
+ configurable = request["configurable"]
+ assert isinstance(configurable, dict)
+ specs = configurable["acp_mcp_servers"]
+ assert isinstance(specs, dict)
+ assert "notes" in specs
+ note = configurable["acp_prompt_note"]
+ assert isinstance(note, str)
+ assert "search" in note
diff --git a/tests/unit/agents/test_acp_permission_compat.py b/tests/unit/agents/test_acp_permission_compat.py
index aa5ba2db61..baa6cb941f 100644
--- a/tests/unit/agents/test_acp_permission_compat.py
+++ b/tests/unit/agents/test_acp_permission_compat.py
@@ -8,7 +8,7 @@
from octop_harness.acp.client import ACPHostedClient
from octop_harness.acp.models import ACPRunnerConfig
-from octop.infra.agents.acp_permission_compat import install_acp_permission_queue
+from octop.infra.agents.acp.permissions import install_acp_permission_queue
_OPTIONS = [
{"optionId": "allow-once", "name": "Allow once", "kind": "allow_once"},
diff --git a/tests/unit/agents/test_acp_permission_mode.py b/tests/unit/agents/test_acp_permission_mode.py
new file mode 100644
index 0000000000..eb9cf91eb2
--- /dev/null
+++ b/tests/unit/agents/test_acp_permission_mode.py
@@ -0,0 +1,89 @@
+"""Managed turns read the chat approval switch."""
+
+from __future__ import annotations
+
+from octop.infra.agents.acp.turn import acp_permission_mode
+
+
+class _Policy:
+ def __init__(self, mode: str) -> None:
+ self.mode = mode
+
+
+class _Store:
+ def __init__(self, mode: str) -> None:
+ self._mode = mode
+
+ def get(self, thread_id: str) -> _Policy:
+ assert thread_id == "thr"
+ return _Policy(self._mode)
+
+
+class _Manager:
+ def __init__(self, mode: str) -> None:
+ self._hitl_session_store = _Store(mode)
+
+
+def test_allow_all_chat_is_yolo() -> None:
+ request = {"thread_id": "thr", "configurable": {}}
+ assert acp_permission_mode(_Manager("allow_all"), request) == "yolo"
+
+
+def test_ask_is_the_default() -> None:
+ assert acp_permission_mode(object(), {"thread_id": "thr"}) == "ask"
+ request = {"thread_id": "thr", "configurable": {}}
+ assert acp_permission_mode(_Manager("ask"), request) == "ask"
+
+
+def test_explicit_mode_on_the_request_wins() -> None:
+ request = {"thread_id": "thr", "configurable": {"acp_permission_mode": "ask"}}
+ assert acp_permission_mode(_Manager("allow_all"), request) == "ask"
+
+
+class _ThreadRow:
+ def __init__(self, raw: str | None) -> None:
+ self.hitl_policy = raw
+
+
+class _ThreadRepo:
+ def __init__(self, raw: str | None) -> None:
+ self._raw = raw
+
+ def get(self, thread_id: str) -> _ThreadRow:
+ assert thread_id == "thr"
+ return _ThreadRow(self._raw)
+
+
+class _PersistedStore:
+ def __init__(self, raw: str | None) -> None:
+ self._repo = _ThreadRepo(raw)
+
+
+class _AgentRow:
+ config_json = '{"managed_permission_mode": "yolo"}'
+
+
+class _AgentRepo:
+ def get(self, agent_id: str) -> _AgentRow:
+ assert agent_id == "agt"
+ return _AgentRow()
+
+
+class _Repos:
+ agent_repo = _AgentRepo()
+
+
+class _ExpertManager:
+ def __init__(self, raw: str | None) -> None:
+ self._hitl_session_store = _PersistedStore(raw)
+ self._repos = _Repos()
+
+
+def test_new_chat_inherits_the_expert_yolo_default() -> None:
+ request = {"thread_id": "thr", "configurable": {}}
+ assert acp_permission_mode(_ExpertManager(None), request, "agt") == "yolo"
+
+
+def test_explicit_ask_on_the_chat_beats_the_expert_default() -> None:
+ request = {"thread_id": "thr", "configurable": {}}
+ assert acp_permission_mode(_ExpertManager('{"mode": "ask"}'), request, "agt") == "ask"
diff --git a/tests/unit/agents/test_acp_session_modes.py b/tests/unit/agents/test_acp_session_modes.py
new file mode 100644
index 0000000000..18662d5e59
--- /dev/null
+++ b/tests/unit/agents/test_acp_session_modes.py
@@ -0,0 +1,44 @@
+"""Managed experts pick an ACP session mode per underlying agent."""
+
+from octop.infra.agents.acp.session_modes import (
+ approval_for_session,
+ resolve_managed_session_mode,
+ session_modes,
+ yolo_session_mode_id,
+)
+
+
+def test_codebuddy_modes_include_plan_and_yolo() -> None:
+ ids = [mode.id for mode in session_modes("codebuddy")]
+ assert ids == ["default", "acceptEdits", "plan", "auto", "bypassPermissions"]
+ assert yolo_session_mode_id("codebuddy") == "bypassPermissions"
+ assert session_modes("claude_code") == session_modes("codebuddy")
+
+
+def test_opencode_modes_are_its_primary_agents() -> None:
+ assert [mode.id for mode in session_modes("opencode")] == ["build", "plan"]
+ assert session_modes("cursor_cli") == []
+
+
+def test_explicit_plan_beats_a_yolo_expert_default() -> None:
+ config = {
+ "managed_runner": "codebuddy",
+ "managed_permission_mode": "yolo",
+ "managed_session_mode": "bypassPermissions",
+ }
+ assert resolve_managed_session_mode(explicit="plan", config=config) == "plan"
+ assert resolve_managed_session_mode(stored="craft", config=config) == "bypassPermissions"
+ assert (
+ resolve_managed_session_mode(
+ config={"managed_runner": "codebuddy", "managed_permission_mode": "yolo"}
+ )
+ == "bypassPermissions"
+ )
+ assert yolo_session_mode_id("codex") == "full-access"
+
+
+def test_approval_follows_the_mode_when_the_agent_publishes_one() -> None:
+ assert approval_for_session("full-access", "ask", runner="codex") == "yolo"
+ assert approval_for_session("plan", "yolo", runner="codebuddy") == "ask"
+ assert approval_for_session("build", "yolo", runner="opencode") == "yolo"
+ assert approval_for_session("", "yolo", runner="cursor_cli") == "yolo"
diff --git a/tests/unit/agents/test_acp_tool_name_compat.py b/tests/unit/agents/test_acp_tool_name_compat.py
index bebd56fc33..91250f5d7a 100644
--- a/tests/unit/agents/test_acp_tool_name_compat.py
+++ b/tests/unit/agents/test_acp_tool_name_compat.py
@@ -7,7 +7,7 @@
from octop_harness.acp.client import ACPHostedClient
from octop_harness.acp.models import ACPRunnerConfig
-from octop.infra.agents.acp_tool_name_compat import install_acp_tool_titles
+from octop.infra.agents.acp.tool_names import install_acp_tool_titles
_CALL = "call-0\nfc_0"
diff --git a/tests/unit/agents/test_agent_manager.py b/tests/unit/agents/test_agent_manager.py
index 7160e4ab80..504c3db7f0 100644
--- a/tests/unit/agents/test_agent_manager.py
+++ b/tests/unit/agents/test_agent_manager.py
@@ -51,7 +51,11 @@ def _expected_default_backend(manager: AgentManager, agent_id: str) -> dict[str,
@pytest.fixture
-def manager(tmp_path: Path) -> AgentManager:
+def manager(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> AgentManager:
+ from octop_harness.plugins.registry import PluginRegistry
+
+ # Other test modules can leave tools in the process-wide plugin registry.
+ monkeypatch.setattr(PluginRegistry, "_instance", None)
paths = PathLayout(tmp_path / ".octop")
paths.ensure_root()
db = SqlitePool(paths.db)
@@ -1817,10 +1821,10 @@ def test_host_model_sdk_errors_keep_original_retry_budget(
def test_build_harness_config_applies_per_expert_retry_and_tool_cap(manager: AgentManager) -> None:
- from langchain.agents.middleware import (
- ModelRetryMiddleware,
- ToolCallLimitMiddleware,
- ToolRetryMiddleware,
+ from langchain.agents.middleware import ModelRetryMiddleware, ToolRetryMiddleware
+
+ from octop.infra.agents.middleware.consecutive_tool_call import (
+ ConsecutiveToolCallMiddleware,
)
cfg = manager._build_harness_config(
@@ -1835,15 +1839,16 @@ def test_build_harness_config_applies_per_expert_retry_and_tool_cap(manager: Age
)
)
)
- limit = next(item for item in cfg.middleware or [] if isinstance(item, ToolCallLimitMiddleware))
+ limit = next(
+ item for item in cfg.middleware or [] if isinstance(item, ConsecutiveToolCallMiddleware)
+ )
tool_retry = next(
item for item in cfg.middleware or [] if isinstance(item, ToolRetryMiddleware)
)
model_retry = next(
item for item in cfg.middleware or [] if isinstance(item, ModelRetryMiddleware)
)
- assert limit.run_limit == 12
- assert limit.thread_limit is None
+ assert limit.limit == 12
assert tool_retry.max_retries == 1
assert model_retry.max_retries == 4
assert model_retry.initial_delay == 0.25
@@ -1861,7 +1866,7 @@ def test_build_harness_config_applies_per_expert_retry_and_tool_cap(manager: Age
)
)
assert not any(
- isinstance(item, ToolCallLimitMiddleware | ToolRetryMiddleware | ModelRetryMiddleware)
+ isinstance(item, ConsecutiveToolCallMiddleware | ToolRetryMiddleware | ModelRetryMiddleware)
for item in (disabled.middleware or [])
)
assert not disabled.model_retry_enabled
diff --git a/tests/unit/agents/test_consecutive_tool_call.py b/tests/unit/agents/test_consecutive_tool_call.py
new file mode 100644
index 0000000000..d4993376e3
--- /dev/null
+++ b/tests/unit/agents/test_consecutive_tool_call.py
@@ -0,0 +1,78 @@
+"""Consecutive identical tool-call cap."""
+
+from __future__ import annotations
+
+from langchain_core.messages import AIMessage
+
+from octop.infra.agents.middleware.consecutive_tool_call import (
+ ConsecutiveToolCallMiddleware,
+ tool_call_signature,
+)
+
+
+def _call(name: str, args: dict[str, object], call_id: str) -> dict[str, object]:
+ return {"name": name, "args": args, "id": call_id, "type": "tool_call"}
+
+
+def _state(*calls: dict[str, object], streak: dict[str, object] | None = None) -> dict[str, object]:
+ state: dict[str, object] = {"messages": [AIMessage(content="", tool_calls=list(calls))]}
+ if streak is not None:
+ state["tool_call_streak"] = streak
+ return state
+
+
+def test_different_calls_do_not_add_up() -> None:
+ middleware = ConsecutiveToolCallMiddleware(limit=2)
+ first = middleware.after_model(
+ _state(_call("read_file", {"path": "a"}, "1")),
+ None,
+ )
+ assert first is not None
+ assert "jump_to" not in first
+ assert first["tool_call_streak"]["count"] == 1
+
+ second = middleware.after_model(
+ _state(
+ _call("read_file", {"path": "b"}, "2"),
+ streak=first["tool_call_streak"],
+ ),
+ None,
+ )
+ assert second is not None
+ assert "jump_to" not in second
+ assert second["tool_call_streak"]["count"] == 1
+ assert second["tool_call_streak"]["signature"] == tool_call_signature(
+ _call("read_file", {"path": "b"}, "2")
+ )
+
+
+def test_identical_streak_ends_the_turn_on_the_next_call() -> None:
+ middleware = ConsecutiveToolCallMiddleware(limit=2)
+ signature = tool_call_signature(_call("search", {"q": "x"}, "1"))
+ update = middleware.after_model(
+ _state(
+ _call("search", {"q": "x"}, "3"),
+ streak={"signature": signature, "count": 2},
+ ),
+ None,
+ )
+ assert update is not None
+ assert update["jump_to"] == "end"
+ content = str(update["messages"][-1].content)
+ assert "[tool_call_repeat]" in content
+ assert "tool: search" in content
+ assert "count: 3" in content
+ assert "limit: 2" in content
+ assert update["messages"][0].status == "error"
+
+
+def test_reply_without_a_tool_call_resets_the_streak() -> None:
+ middleware = ConsecutiveToolCallMiddleware(limit=2)
+ update = middleware.after_model(
+ {
+ "messages": [AIMessage(content="done")],
+ "tool_call_streak": {"signature": "search\n{}", "count": 2},
+ },
+ None,
+ )
+ assert update == {"tool_call_streak": {"signature": "", "count": 0}}
diff --git a/tests/unit/agents/test_managed.py b/tests/unit/agents/test_managed.py
index 3dcc1cb1e9..81d625a550 100644
--- a/tests/unit/agents/test_managed.py
+++ b/tests/unit/agents/test_managed.py
@@ -2,11 +2,15 @@
from __future__ import annotations
+import os
from pathlib import Path
from typing import Any
+import pytest
+
from octop.infra.agents.managed import (
apply_managed_backend,
+ link_managed_skill_packages,
managed_default_workspace,
managed_project_root,
managed_skill_dir,
@@ -50,6 +54,48 @@ def test_preserve_keeps_runner_and_filesystem_root() -> None:
assert config["memory"]["memory_recall_inject_enabled"] is False
+def test_preserve_keeps_yolo_when_the_patch_omits_it() -> None:
+ config: dict[str, Any] = {"workspace_dir": "/work"}
+ preserve_managed_config(
+ config,
+ {"managed_runner": "opencode", "managed_permission_mode": "yolo"},
+ )
+ assert config["managed_permission_mode"] == "yolo"
+
+
+def test_preserve_drops_a_session_mode_the_runner_does_not_offer() -> None:
+ foreign = {"managed_runner": "cursor_cli", "managed_session_mode": "bypassPermissions"}
+ preserve_managed_config(foreign, {})
+ assert "managed_session_mode" not in foreign
+
+ cleared = {"managed_runner": "codebuddy", "managed_session_mode": ""}
+ preserve_managed_config(cleared, {"managed_session_mode": "plan"})
+ assert "managed_session_mode" not in cleared
+
+ kept = {"managed_runner": "opencode", "managed_session_mode": "plan"}
+ preserve_managed_config(kept, {})
+ assert kept["managed_session_mode"] == "plan"
+
+ restored: dict[str, Any] = {"managed_runner": "codebuddy"}
+ preserve_managed_config(restored, {"managed_session_mode": "plan"})
+ assert restored["managed_session_mode"] == "plan"
+
+
+def test_preserve_keeps_an_enabled_memory_setting() -> None:
+ config = {"memory": {"memory_enabled": True, "memory_capture_enabled": True}}
+ preserve_managed_config(config, {"managed_runner": "opencode"})
+ assert config["memory"]["memory_enabled"] is True
+ assert config["memory"]["memory_capture_enabled"] is True
+ assert config["memory"]["memory_recall_inject_enabled"] is False
+
+ later: dict[str, Any] = {"workspace_dir": "/work"}
+ preserve_managed_config(
+ later,
+ {"managed_runner": "opencode", "memory": {"memory_enabled": True}},
+ )
+ assert later["memory"]["memory_enabled"] is True
+
+
def test_managed_template_is_programming_seed() -> None:
payload = managed_template_payload()
prompts = payload["quick_prompts"]
@@ -77,3 +123,47 @@ def test_require_managed_fields() -> None:
assert exc.status == 400
else:
raise AssertionError("expected missing runner to fail")
+
+
+def test_link_managed_skill_packages_tracks_owned_links(tmp_path: Path) -> None:
+ if os.name != "posix":
+ pytest.skip("skill package links use symlinks")
+
+ package = tmp_path / "pkg"
+ skill = package / "review"
+ skill.mkdir(parents=True)
+ (skill / "SKILL.md").write_text("name: review\n", encoding="utf-8")
+ (package / "notes.txt").write_text("skip", encoding="utf-8")
+ workspace = tmp_path / "ws"
+ link_managed_skill_packages(workspace, "codebuddy", [package])
+ link = workspace / ".codebuddy" / "skills" / "review"
+ assert link.is_symlink()
+ assert link.resolve() == skill.resolve()
+
+ local = workspace / ".codebuddy" / "skills" / "local"
+ local.mkdir()
+ (local / "SKILL.md").write_text("keep", encoding="utf-8")
+ link_managed_skill_packages(workspace, "codebuddy", [])
+ assert not link.exists()
+ assert (local / "SKILL.md").read_text(encoding="utf-8") == "keep"
+
+
+def test_link_managed_skill_packages_follows_the_runner(tmp_path: Path) -> None:
+ if os.name != "posix":
+ pytest.skip("skill package links use symlinks")
+
+ package = tmp_path / "pkg"
+ skill = package / "review"
+ skill.mkdir(parents=True)
+ (skill / "SKILL.md").write_text("name: review\n", encoding="utf-8")
+ other = tmp_path / "other" / "review"
+ other.mkdir(parents=True)
+ (other / "SKILL.md").write_text("second\n", encoding="utf-8")
+ workspace = tmp_path / "ws"
+ link_managed_skill_packages(workspace, "codebuddy", [package])
+ skipped = link_managed_skill_packages(workspace, "claude_code", [package, other.parent])
+ assert skipped == ["review"]
+ assert not (workspace / ".codebuddy" / "skills" / "review").exists()
+ kept = workspace / ".claude" / "skills" / "review"
+ assert kept.is_symlink()
+ assert kept.resolve() == skill.resolve()
diff --git a/tests/unit/agents/test_runtime_limits.py b/tests/unit/agents/test_runtime_limits.py
index 7c0adce465..88d28fe3bf 100644
--- a/tests/unit/agents/test_runtime_limits.py
+++ b/tests/unit/agents/test_runtime_limits.py
@@ -2,8 +2,9 @@
from __future__ import annotations
-from langchain.agents.middleware import ToolCallLimitMiddleware, ToolRetryMiddleware
+from langchain.agents.middleware import ToolRetryMiddleware
+from octop.infra.agents.middleware.consecutive_tool_call import ConsecutiveToolCallMiddleware
from octop.infra.agents.settings.runtime_limits import (
CONFIGURABLE_MAX_INPUT_TOKENS,
CONFIGURABLE_MODEL_SETTINGS,
@@ -80,7 +81,7 @@ def test_apply_agent_runtime_to_stream_request_merges_configurable() -> None:
assert req["configurable"][CONFIGURABLE_MAX_INPUT_TOKENS] == 32000
-def test_call_guard_defaults_cap_tool_calls_and_retry_tool_exceptions() -> None:
+def test_call_guard_defaults_cap_repeated_tool_calls_and_retry_tool_exceptions() -> None:
assert resolve_tool_call_run_limit({}) == DEFAULT_TOOL_CALL_RUN_LIMIT
assert resolve_model_retry({}).enabled is True
assert resolve_model_retry({}).max_retries == DEFAULT_MODEL_RETRY_MAX_RETRIES
@@ -88,11 +89,9 @@ def test_call_guard_defaults_cap_tool_calls_and_retry_tool_exceptions() -> None:
assert resolve_tool_retry({}).max_retries == DEFAULT_TOOL_RETRY_MAX_RETRIES
middleware = call_guard_middleware({})
- limit = next(item for item in middleware if isinstance(item, ToolCallLimitMiddleware))
+ limit = next(item for item in middleware if isinstance(item, ConsecutiveToolCallMiddleware))
tool_retry = next(item for item in middleware if isinstance(item, ToolRetryMiddleware))
- assert limit.run_limit == DEFAULT_TOOL_CALL_RUN_LIMIT
- assert limit.thread_limit is None
- assert limit.exit_behavior == "end"
+ assert limit.limit == DEFAULT_TOOL_CALL_RUN_LIMIT
assert tool_retry.max_retries == DEFAULT_TOOL_RETRY_MAX_RETRIES
assert tool_retry.initial_delay == 1.0
assert tool_retry.max_delay == 60.0
diff --git a/tests/unit/agents/test_thread_cleanup.py b/tests/unit/agents/test_thread_cleanup.py
index 118a1a8f3e..09025e3f3c 100644
--- a/tests/unit/agents/test_thread_cleanup.py
+++ b/tests/unit/agents/test_thread_cleanup.py
@@ -299,7 +299,7 @@ def test_gc_orphans_reports_then_deletes(tmp_path: Path) -> None:
_seed_checkpoint(db_path, "thr_live", b"live")
_seed_checkpoint(db_path, "thr_orphan", b"orphan-bytes")
- reported = gc_orphan_checkpoints(services, agent_id="ag1", apply=False)
+ reported = gc_orphan_checkpoints(services, agent_id="ag1", apply=False).orphans
assert [item.thread_id for item in reported] == ["thr_orphan"]
assert reported[0].nbytes == len(b"orphan-bytes")
assert _checkpoint_count(db_path, "thr_orphan") == 1
@@ -400,3 +400,19 @@ def test_compact_rebuilds_sqlite_after_delete(tmp_path: Path) -> None:
is True
)
assert sqlite_freelist_bytes(db_path) == 0
+
+
+def test_describe_sweep_mentions_postgres_leftovers_and_skipped_databases() -> None:
+ from octop.infra.agents.memory.thread_cleanup import describe_sweep
+
+ base = {"namespaces": 0, "threads": 2, "directories": 0}
+ assert describe_sweep(base, "en").count("\n") == 0
+
+ text = describe_sweep(
+ {**base, "postgres_kept": {"threads": 3, "namespaces": 1}, "skipped_databases": 2},
+ "en",
+ )
+ lines = text.splitlines()
+ assert len(lines) == 3
+ assert "3 checkpoint threads" in lines[1]
+ assert "2 external PostgreSQL" in lines[2]
diff --git a/tests/unit/agents/test_tool_catalog.py b/tests/unit/agents/test_tool_catalog.py
index f998d70312..b767d17d14 100644
--- a/tests/unit/agents/test_tool_catalog.py
+++ b/tests/unit/agents/test_tool_catalog.py
@@ -5,8 +5,10 @@
from octop.infra.agents.settings.tool_catalog import (
BUILTIN_TOOL_CATALOG,
CRITICAL_TOOLS,
+ MANAGED_BUILTIN_TOOLS,
builtin_tool_available,
effective_tools_disabled,
+ managed_builtin_available,
normalize_tools_disabled,
plugin_tools_disabled_names,
tools_disabled_set,
@@ -23,6 +25,66 @@ def test_team_host_tools_are_dispatch_only() -> None:
assert "task" in HOST_TOOLS_DISABLED
+def test_managed_catalog_is_only_tools_octop_can_attach() -> None:
+ names = {entry.name for entry in BUILTIN_TOOL_CATALOG}
+ assert names >= MANAGED_BUILTIN_TOOLS
+ assert "send_file_to_user" in MANAGED_BUILTIN_TOOLS
+ assert "search_knowledge" in MANAGED_BUILTIN_TOOLS
+ assert "ask_agent" in MANAGED_BUILTIN_TOOLS
+ assert "write_file" not in MANAGED_BUILTIN_TOOLS
+ assert "browser_use" not in MANAGED_BUILTIN_TOOLS
+ assert "acp_runner" not in MANAGED_BUILTIN_TOOLS
+
+
+def test_managed_tools_stay_unavailable_until_they_can_attach() -> None:
+ off = {"memory": {"memory_enabled": False}}
+ assert (
+ managed_builtin_available(
+ "memory_search",
+ agent_cfg=off,
+ knowledge_base_ids=[],
+ has_peers=False,
+ )
+ is False
+ )
+ assert (
+ managed_builtin_available(
+ "search_knowledge",
+ agent_cfg=off,
+ knowledge_base_ids=[],
+ has_peers=True,
+ )
+ is False
+ )
+ assert (
+ managed_builtin_available(
+ "ask_agent",
+ agent_cfg=off,
+ knowledge_base_ids=["kb"],
+ has_peers=False,
+ )
+ is False
+ )
+ assert (
+ managed_builtin_available(
+ "send_file_to_user",
+ agent_cfg=off,
+ knowledge_base_ids=[],
+ has_peers=False,
+ )
+ is True
+ )
+ assert (
+ managed_builtin_available(
+ "search_knowledge",
+ agent_cfg={"memory": {"memory_enabled": True}},
+ knowledge_base_ids=["kb"],
+ has_peers=True,
+ )
+ is True
+ )
+
+
def test_critical_tools_are_in_catalog() -> None:
names = {e.name for e in BUILTIN_TOOL_CATALOG}
assert names >= CRITICAL_TOOLS
diff --git a/tests/unit/api/test_chat_composer_context.py b/tests/unit/api/test_chat_composer_context.py
index eb6e2c76be..952db04eca 100644
--- a/tests/unit/api/test_chat_composer_context.py
+++ b/tests/unit/api/test_chat_composer_context.py
@@ -3,12 +3,19 @@
from __future__ import annotations
from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
import pytest
+from langchain_core.messages import HumanMessage
from octop.api.routers.chat.turn import resolve_thread_id
+from octop.infra.agents.turn_resources import resolve_turn_mcp
from octop.infra.errors import ErrorCode, OctopError
-from octop.infra.gateway.process.message_keys import build_composer_context
+from octop.infra.gateway.process.message_keys import (
+ COMPOSER_CTX_KEY,
+ build_composer_context,
+ stamp_composer_fields,
+)
class _ThreadRegistry:
@@ -55,6 +62,51 @@ def test_build_composer_context_omits_default_model() -> None:
}
+def test_build_composer_context_includes_knowledge_bases() -> None:
+ ctx = build_composer_context(
+ mcp_servers=["docs"],
+ skills=None,
+ target_agent_ids=None,
+ model_ref=None,
+ default_model=None,
+ knowledge_base_ids=["kb-1", ""],
+ )
+ assert ctx == {"connectors": ["docs"], "knowledgeBaseIds": ["kb-1"]}
+
+
+def test_stamp_composer_fields_adds_knowledge_to_the_user_message() -> None:
+ message = HumanMessage(content="hello", additional_kwargs={})
+ stamp_composer_fields(
+ {"messages": [message]},
+ connectors=["docs"],
+ knowledge_base_ids=["kb-1"],
+ )
+ assert message.additional_kwargs[COMPOSER_CTX_KEY] == {
+ "connectors": ["docs"],
+ "knowledgeBaseIds": ["kb-1"],
+ }
+
+
+async def test_managed_connectors_skip_inprocess_tool_load() -> None:
+ manager = MagicMock()
+ manager.get_row.return_value = SimpleNamespace(kind="managed", user_id=1)
+ manager.default_mcp_servers.return_value = []
+ manager.merge_turn_mcp_servers.return_value = ["docs"]
+ manager.prepare_chat_mcp = AsyncMock(return_value=["docs"])
+
+ resolved = await resolve_turn_mcp(
+ manager,
+ agent_id="managed-1",
+ user_id=1,
+ explicit=["docs"],
+ )
+
+ assert resolved is not None
+ assert resolved.shown == ["docs"]
+ assert resolved.failed == []
+ manager.prepare_chat_mcp.assert_not_awaited()
+
+
def test_build_composer_context_includes_model_override() -> None:
ctx = build_composer_context(
mcp_servers=None,
diff --git a/tests/unit/connectors/test_mcp_oauth_metadata_url.py b/tests/unit/connectors/test_mcp_oauth_metadata_url.py
new file mode 100644
index 0000000000..ffbbb7349f
--- /dev/null
+++ b/tests/unit/connectors/test_mcp_oauth_metadata_url.py
@@ -0,0 +1,74 @@
+"""AS metadata URL must follow RFC 8414 §3.1 for path-scoped issuers."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from octop.infra.connectors.oauth import mcp
+
+
+class _Resp:
+ def __init__(self, issuer: str) -> None:
+ self._issuer = issuer
+
+ def raise_for_status(self) -> None:
+ return None
+
+ def json(self) -> dict[str, str]:
+ return {
+ "issuer": self._issuer,
+ "authorization_endpoint": "https://auth.example.com/authorize",
+ "token_endpoint": "https://auth.example.com/token",
+ }
+
+
+@pytest.mark.parametrize(
+ ("issuer", "expected"),
+ [
+ (
+ "https://auth.example.com",
+ "https://auth.example.com/.well-known/oauth-authorization-server",
+ ),
+ (
+ "https://auth.example.com/realms/tenant",
+ "https://auth.example.com/.well-known/oauth-authorization-server/realms/tenant",
+ ),
+ (
+ "https://auth.example.com/realms/tenant/",
+ "https://auth.example.com/.well-known/oauth-authorization-server/realms/tenant",
+ ),
+ (
+ "https://mcp.example.com/tenant/https%3A%2F%2Fapp.example.com",
+ "https://mcp.example.com/.well-known/oauth-authorization-server"
+ "/tenant/https%3A%2F%2Fapp.example.com",
+ ),
+ ],
+)
+@pytest.mark.asyncio
+async def test_metadata_url_follows_rfc8414(
+ issuer: str, expected: str, monkeypatch: pytest.MonkeyPatch
+) -> None:
+ seen: list[str] = []
+
+ async def _safe_request(method: str, url: str, **kwargs: Any) -> _Resp:
+ del method, kwargs
+ seen.append(url)
+ return _Resp(issuer)
+
+ async def _passthrough(url: str, **kwargs: Any) -> str:
+ del kwargs
+ return url
+
+ async def _pass(data: dict[str, Any], **kwargs: Any) -> dict[str, Any]:
+ del kwargs
+ return data
+
+ monkeypatch.setattr(mcp, "safe_request", _safe_request)
+ monkeypatch.setattr(mcp, "_ensure_mcp_oauth_url", _passthrough)
+ monkeypatch.setattr(mcp, "_validate_metadata_endpoints", _pass)
+
+ await mcp.fetch_authorization_metadata(issuer)
+
+ assert seen == [expected]
diff --git a/tests/unit/connectors/test_mcp_oauth_url.py b/tests/unit/connectors/test_mcp_oauth_url.py
new file mode 100644
index 0000000000..084e6f0c70
--- /dev/null
+++ b/tests/unit/connectors/test_mcp_oauth_url.py
@@ -0,0 +1,104 @@
+"""Authorization endpoints retain their existing query during MCP OAuth."""
+
+from __future__ import annotations
+
+from typing import Any
+from unittest.mock import AsyncMock
+from urllib.parse import parse_qs, urlsplit
+
+import pytest
+
+from octop.infra.connectors.oauth import registry
+from octop.infra.connectors.oauth.mcp import build_authorize_url
+from octop.infra.connectors.oauth.pkce import s256_challenge
+
+ENDPOINT = "https://auth.example.com/authorize"
+CALLBACK = "https://octop.example.com/callback?from=mcp"
+RESOURCE = "https://mcp.example.com/tools"
+
+
+@pytest.mark.parametrize(
+ "suffix",
+ [
+ "",
+ "?",
+ "?tenant=acme",
+ "?tenant=acme&prompt=consent",
+ "?tenant=acme%20corp&hint=a%2Bb",
+ "?tenant=",
+ "?tenant=acme&tenant=beta",
+ "?region=us&tenant_host=https%253A%252F%252Fapp.example.com",
+ ],
+)
+@pytest.mark.parametrize("optional", [False, True])
+def test_authorize_url_retains_endpoint_query(suffix: str, optional: bool) -> None:
+ params = {
+ "client_id": "test-client",
+ "redirect_uri": CALLBACK,
+ "state": "state +/?",
+ "code_challenge": "challenge",
+ }
+ if optional:
+ params.update(scope="tools:read tools:write", resource=RESOURCE)
+ url = build_authorize_url({"authorization_endpoint": ENDPOINT + suffix}, **params)
+ parsed = urlsplit(url)
+ original = urlsplit(ENDPOINT + suffix).query
+ assert (parsed.scheme, parsed.netloc, parsed.path) == (
+ "https",
+ "auth.example.com",
+ "/authorize",
+ )
+ if original:
+ assert parsed.query.startswith(original + "&")
+ expected = parse_qs(original, keep_blank_values=True)
+ expected.update({key: [value] for key, value in params.items()})
+ expected.update(response_type=["code"], code_challenge_method=["S256"])
+ assert parse_qs(parsed.query, keep_blank_values=True) == expected
+
+
+@pytest.mark.asyncio
+async def test_custom_mcp_oauth_retains_discovered_query(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ metadata: dict[str, Any] = {
+ "authorization_endpoint": ENDPOINT + "?tenant=acme%20corp",
+ "scopes_supported": ["tools:read", "tools:write"],
+ }
+ discovery = AsyncMock(
+ return_value={
+ "available": True,
+ "issuer": "https://auth.example.com",
+ "resource": RESOURCE,
+ "metadata": metadata,
+ }
+ )
+ register = AsyncMock(return_value={"client_id": "test-client"})
+ monkeypatch.setattr(registry, "discover_oauth_from_mcp_url", discovery)
+ monkeypatch.setattr(registry, "register_dynamic_client", register)
+ url, verifier, ctx = await registry.start_custom_mcp_oauth(
+ server_name="example",
+ mcp_url=RESOURCE,
+ redirect_uri=CALLBACK,
+ state="test-state",
+ )
+ discovery.assert_awaited_once_with(RESOURCE)
+ register.assert_awaited_once_with(
+ metadata,
+ issuer="https://auth.example.com",
+ redirect_uri=CALLBACK,
+ )
+ query = urlsplit(url).query
+ assert query.startswith("tenant=acme%20corp&")
+ assert parse_qs(query) == {
+ "tenant": ["acme corp"],
+ "response_type": ["code"],
+ "client_id": ["test-client"],
+ "redirect_uri": [CALLBACK],
+ "state": ["test-state"],
+ "code_challenge": [s256_challenge(verifier)],
+ "code_challenge_method": ["S256"],
+ "scope": ["tools:read tools:write"],
+ "resource": [RESOURCE],
+ }
+ assert ctx["metadata"] == metadata
+ assert ctx["server_name"] == "example"
diff --git a/tests/unit/gateway/test_global_processor_team.py b/tests/unit/gateway/test_global_processor_team.py
index 998725b483..fdd0910f6f 100644
--- a/tests/unit/gateway/test_global_processor_team.py
+++ b/tests/unit/gateway/test_global_processor_team.py
@@ -1028,6 +1028,214 @@ def test_stamp_team_host_runtime_forces_async(processor_env: dict) -> None:
assert "configurable" not in expert_req
+@pytest.mark.asyncio
+async def test_member_dispatch_attaches_expert_knowledge_and_connectors(
+ processor_env: dict,
+) -> None:
+ from types import SimpleNamespace
+
+ from langchain_core.messages import AIMessage
+ from octop_harness.request import ChatRequest
+
+ processor = processor_env["processor"]
+ manager = processor._agent_manager
+ kb = SimpleNamespace(
+ id="kb-expert",
+ owner_user_id=1,
+ default_open=False,
+ name="Handbook",
+ description="Ops notes",
+ )
+ manager.default_knowledge_base_ids = MagicMock(return_value=["kb-expert"])
+ manager.default_mcp_servers = MagicMock(return_value=["wiki"])
+ manager.merge_turn_mcp_servers = MagicMock(return_value=["wiki", "news"])
+ manager.prepare_chat_mcp = AsyncMock(return_value=[])
+ manager.providers.resolve_explicit_default_model.return_value = "openai/gpt-test"
+ manager.model_ref_allowed_for_user.return_value = True
+ manager.get_config.return_value = {}
+ manager._repos.knowledge_repo.list_visible.return_value = [kb]
+ seen: dict[str, object] = {}
+
+ async def fake_stream(_agent_id: str, request: dict[str, object]) -> object:
+ seen["request"] = request
+ yield {"type": "token", "content": "ok"}
+
+ manager.stream = fake_stream
+ harness = MagicMock()
+ harness.aget_history = AsyncMock(return_value=[AIMessage(content="ok")])
+ manager.get_agent.return_value = harness
+
+ await processor.teams.stream_peer_to_room(
+ ChatRequest(
+ messages="task",
+ thread_id="thr_parent~child",
+ agent_id="child",
+ user="1",
+ configurable={"peer_invoke_mode": "sync", "team_peers": ["sibling"]},
+ ),
+ room_thread_id="thr_parent",
+ speaker_id="child",
+ )
+
+ request = seen["request"]
+ assert isinstance(request, dict)
+ assert request["mcp_servers"] == ["wiki", "news"]
+ configurable = request["configurable"]
+ assert isinstance(configurable, dict)
+ assert configurable["knowledge_base_ids"] == ["kb-expert"]
+ assert configurable["peer_invoke_mode"] == "sync"
+ assert configurable["team_peers"] == ["sibling"]
+ assert configurable["conversation_mode"] == "craft"
+ assert request["conversation_mode"] == "craft"
+ assert request["model"] == "openai/gpt-test"
+ manager.prepare_chat_mcp.assert_awaited_once_with(
+ "child",
+ ["wiki", "news"],
+ connector_user_id=1,
+ )
+ manager.merge_turn_mcp_servers.assert_called_once_with(
+ 1,
+ None,
+ apply_defaults=True,
+ extra_defaults=["wiki"],
+ agent_owner_id=1,
+ )
+
+
+@pytest.mark.asyncio
+async def test_member_dispatch_keeps_knowledge_when_connectors_fail(
+ processor_env: dict,
+) -> None:
+ from types import SimpleNamespace
+
+ from octop_harness.request import ChatRequest
+
+ processor = processor_env["processor"]
+ manager = processor._agent_manager
+ kb = SimpleNamespace(
+ id="kb-expert",
+ owner_user_id=1,
+ default_open=False,
+ name="Handbook",
+ description="",
+ )
+ manager.default_knowledge_base_ids = MagicMock(return_value=["kb-expert"])
+ manager.default_mcp_servers = MagicMock(return_value=["wiki"])
+ manager.merge_turn_mcp_servers = MagicMock(return_value=["wiki"])
+ manager.prepare_chat_mcp = AsyncMock(return_value=["wiki"])
+ manager._repos.knowledge_repo.list_visible.return_value = [kb]
+ seen: dict[str, object] = {}
+
+ async def fake_stream(_agent_id: str, request: dict[str, object]) -> object:
+ seen["request"] = request
+ yield {"type": "usage", "usage": {}}
+
+ manager.stream = fake_stream
+ harness = MagicMock()
+ harness.aget_history = AsyncMock(return_value=[])
+ manager.get_agent.return_value = harness
+
+ await processor.teams.stream_peer_to_room(
+ ChatRequest(messages="task", thread_id="thr_parent~child", agent_id="child", user="1"),
+ room_thread_id="thr_parent",
+ speaker_id="child",
+ )
+
+ request = seen["request"]
+ assert isinstance(request, dict)
+ assert "mcp_servers" not in request
+ configurable = request["configurable"]
+ assert isinstance(configurable, dict)
+ assert configurable["knowledge_base_ids"] == ["kb-expert"]
+
+
+@pytest.mark.asyncio
+async def test_member_dispatch_keeps_connectors_that_loaded(
+ processor_env: dict,
+) -> None:
+ from octop_harness.request import ChatRequest
+
+ processor = processor_env["processor"]
+ manager = processor._agent_manager
+ manager.default_knowledge_base_ids = MagicMock(return_value=[])
+ manager.default_mcp_servers = MagicMock(return_value=["wiki", "news"])
+ manager.merge_turn_mcp_servers = MagicMock(return_value=["wiki", "news"])
+ manager.prepare_chat_mcp = AsyncMock(return_value=["news"])
+ manager.connector_auth_blocked = AsyncMock(
+ return_value=[{"server": "news", "display_name": "News"}]
+ )
+ manager._repos.knowledge_repo.list_visible.return_value = []
+ seen: dict[str, object] = {}
+
+ async def fake_stream(_agent_id: str, request: dict[str, object]) -> object:
+ seen["request"] = request
+ yield {"type": "usage", "usage": {}}
+
+ manager.stream = fake_stream
+ harness = MagicMock()
+ harness.aget_history = AsyncMock(return_value=[])
+ manager.get_agent.return_value = harness
+
+ await processor.teams.stream_peer_to_room(
+ ChatRequest(
+ messages="task",
+ thread_id="thr_parent~child",
+ agent_id="child",
+ user="1",
+ configurable={"octop_team_dispatch_briefing": "do the task"},
+ ),
+ room_thread_id="thr_parent",
+ speaker_id="child",
+ )
+
+ request = seen["request"]
+ assert isinstance(request, dict)
+ assert request["mcp_servers"] == ["wiki"]
+ configurable = request["configurable"]
+ assert isinstance(configurable, dict)
+ assert configurable["conversation_mode"] == "craft"
+ briefing = configurable["octop_team_dispatch_briefing"]
+ assert isinstance(briefing, str)
+ assert "News" in briefing
+ assert "do the task" in briefing
+
+
+@pytest.mark.asyncio
+async def test_host_wrapup_does_not_attach_member_resources(processor_env: dict) -> None:
+ from octop_harness.request import ChatRequest
+
+ processor = processor_env["processor"]
+ processor._agent_repo.create(agent_id="host", user_id=1, name="Host", kind="team")
+ manager = processor._agent_manager
+ manager.default_knowledge_base_ids = MagicMock(return_value=["kb-expert"])
+ manager.default_mcp_servers = MagicMock(return_value=["wiki"])
+ manager.merge_turn_mcp_servers = MagicMock(return_value=["wiki"])
+ manager.prepare_chat_mcp = AsyncMock(return_value=[])
+ seen: dict[str, object] = {}
+
+ async def fake_stream(_agent_id: str, request: dict[str, object]) -> object:
+ seen["request"] = request
+ yield {"type": "usage", "usage": {}}
+
+ manager.stream = fake_stream
+ harness = MagicMock()
+ harness.aget_history = AsyncMock(return_value=[])
+ manager.get_agent.return_value = harness
+
+ await processor.teams.stream_peer_to_room(
+ ChatRequest(messages="wrap up", thread_id="thr_parent", agent_id="host", user="1"),
+ room_thread_id="thr_parent",
+ speaker_id="host",
+ )
+
+ request = seen["request"]
+ assert isinstance(request, dict)
+ assert "mcp_servers" not in request
+ configurable = request.get("configurable") or {}
+ assert "knowledge_base_ids" not in configurable
+ manager.prepare_chat_mcp.assert_not_awaited()
+
+
@pytest.mark.asyncio
async def test_stream_team_peer_relays_tokens_to_room(processor_env: dict) -> None:
from langchain_core.messages import AIMessage
diff --git a/tests/unit/gateway/test_harness_request.py b/tests/unit/gateway/test_harness_request.py
index 24357e2ab3..7e2958a1c2 100644
--- a/tests/unit/gateway/test_harness_request.py
+++ b/tests/unit/gateway/test_harness_request.py
@@ -16,7 +16,9 @@
@pytest.mark.asyncio
@pytest.mark.parametrize("channel_type", ["telegram", "qq"])
@pytest.mark.parametrize("locale,label", [("en", "[Quoted message]"), ("zh", "[引用消息]")])
-@pytest.mark.parametrize("own_reply,explicit", [(False, False), (True, False), (True, True)])
+@pytest.mark.parametrize(
+ "own_reply,explicit", [(False, False), (False, True), (True, False), (True, True)]
+)
async def test_quoted_message_is_added_only_to_model_content(
channel_type, locale, label, own_reply, explicit
):
@@ -32,7 +34,7 @@ async def test_quoted_message_is_added_only_to_model_content(
)
result = await build_content_from_message(msg, locale=locale)
assert msg.text == "explain this"
- if own_reply and not explicit:
+ if channel_type == "qq" and own_reply and not explicit:
assert result == "explain this"
else:
assert result.startswith(label)
diff --git a/tests/unit/gateway/test_tool_media.py b/tests/unit/gateway/test_tool_media.py
index a7375fe10d..0532547fd3 100644
--- a/tests/unit/gateway/test_tool_media.py
+++ b/tests/unit/gateway/test_tool_media.py
@@ -950,3 +950,49 @@ async def _stream(*_args: object, **_kwargs: object):
if isinstance(part, ImageContent)
]
assert images == []
+
+
+@pytest.mark.asyncio
+async def test_managed_send_file_marker_pushes_without_the_tool_name() -> None:
+ with tempfile.TemporaryDirectory() as ws:
+ report = Path(ws) / "report.txt"
+ report.write_text("hello", encoding="utf-8")
+ workspace = _workspace(ws)
+ payload = json.dumps(
+ {
+ "type": "file",
+ "path": "report.txt",
+ "filename": "report.txt",
+ "octop_delivery": "send_file_to_user",
+ "source": {"type": "url", "url": report.as_uri(), "media_type": "text/plain"},
+ }
+ )
+ frames = [
+ frame
+ async for frame in attachment_frames_from_tool_result(
+ {"messages": [{"name": "octop-files_send_file_to_user", "content": payload}]},
+ agent_id="agent-1",
+ workspace=workspace,
+ )
+ ]
+ assert len(frames) == 1
+ assert frames[0]["filename"] == "report.txt"
+
+ skipped = [
+ frame
+ async for frame in attachment_frames_from_tool_result(
+ {
+ "messages": [
+ {
+ "name": "write_file",
+ "content": payload.replace(
+ '"octop_delivery": "send_file_to_user"', '"octop_delivery": "no"'
+ ),
+ }
+ ]
+ },
+ agent_id="agent-1",
+ workspace=workspace,
+ )
+ ]
+ assert skipped == []
diff --git a/tests/unit/i18n/test_stream.py b/tests/unit/i18n/test_stream.py
index b75722c7e6..b3d2d1a312 100644
--- a/tests/unit/i18n/test_stream.py
+++ b/tests/unit/i18n/test_stream.py
@@ -183,6 +183,16 @@ def test_format_insufficient_balance_zh() -> None:
assert "Insufficient Balance" not in text
+def test_format_tool_call_repeat_zh_names_the_tool() -> None:
+ msg = "[tool_call_repeat]\ntool: search\ncount: 41\nlimit: 40"
+ text = format_stream_error(msg, "zh")
+ assert "search" in text
+ assert "41" in text
+ assert "40" in text
+ assert "运行配置" in text
+ assert "[tool_call_repeat]" not in text
+
+
def test_format_recursion_limit_zh_guides_to_config() -> None:
msg = (
"Recursion limit of 2 reached without hitting a stop condition. "
diff --git a/tests/unit/knowledge/test_mcp_gateway.py b/tests/unit/knowledge/test_mcp_gateway.py
new file mode 100644
index 0000000000..fde485b54d
--- /dev/null
+++ b/tests/unit/knowledge/test_mcp_gateway.py
@@ -0,0 +1,48 @@
+"""The loopback knowledge MCP speaks search_knowledge."""
+
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from octop.infra.knowledge.mcp_gateway import handle_knowledge_mcp
+
+
+@pytest.mark.asyncio
+async def test_lists_and_searches(monkeypatch: pytest.MonkeyPatch) -> None:
+ async def fake_retrieve(*args: Any, **kwargs: Any) -> str:
+ assert kwargs["knowledge_base_ids"] == ["kb1"]
+ assert kwargs["query"] == "部署"
+ return "passage"
+
+ monkeypatch.setattr("octop.infra.knowledge.mcp_gateway.retrieve_context", fake_retrieve)
+ listed = await handle_knowledge_mcp(
+ {"jsonrpc": "2.0", "id": 1, "method": "tools/list"},
+ user_id=1,
+ is_admin=False,
+ knowledge_base_ids=["kb1"],
+ locale="zh",
+ catalog=[{"id": "kb1", "name": "手册", "description": "安装"}],
+ services=object(),
+ )
+ tool = listed["result"]["tools"][0]
+ assert tool["name"] == "search_knowledge"
+ assert "手册" in tool["description"]
+
+ called = await handle_knowledge_mcp(
+ {
+ "jsonrpc": "2.0",
+ "id": 2,
+ "method": "tools/call",
+ "params": {"name": "search_knowledge", "arguments": {"query": "部署"}},
+ },
+ user_id=1,
+ is_admin=False,
+ knowledge_base_ids=["kb1"],
+ locale="zh",
+ catalog=[],
+ services=object(),
+ )
+ assert called["result"]["content"][0]["text"] == "passage"
+ assert called["result"]["isError"] is False
diff --git a/tests/unit/test_storage_spec.py b/tests/unit/test_storage_spec.py
index dca4c8ce2d..6ff77a096d 100644
--- a/tests/unit/test_storage_spec.py
+++ b/tests/unit/test_storage_spec.py
@@ -273,12 +273,16 @@ def test_enrich_docker_backend_spec_defaults() -> None:
assert "agent_id" not in fixed or fixed.get("agent_id") == "ZE6GR2"
-def test_omit_docker_volumes_drops_host_mounts() -> None:
+def test_omit_docker_volumes_drops_host_mounts(monkeypatch: pytest.MonkeyPatch) -> None:
from octop.infra.backend.docker_spec import (
enrich_docker_backend_spec,
omit_docker_volumes,
)
+ monkeypatch.setattr(
+ "octop.infra.backend.docker_spec.running_in_container",
+ lambda: False,
+ )
mounted = {
"type": "docker",
"image": "python:3.12-slim",
@@ -310,7 +314,28 @@ def test_omit_docker_volumes_drops_host_mounts() -> None:
assert enriched["agent_id"] == "ZE6GR2"
-def test_row_to_backend_spec_docker_ignores_volumes() -> None:
+def test_omit_docker_volumes_keeps_mounts_in_container(monkeypatch: pytest.MonkeyPatch) -> None:
+ from octop.infra.backend.docker_spec import (
+ enrich_docker_backend_spec,
+ omit_docker_volumes,
+ )
+
+ monkeypatch.setattr(
+ "octop.infra.backend.docker_spec.running_in_container",
+ lambda: True,
+ )
+ mounted = {
+ "type": "docker",
+ "image": "python:3.12-slim",
+ "volumes": {"/var/lib/octop": {"bind": "/host", "mode": "rw"}},
+ }
+ assert omit_docker_volumes(mounted) is mounted
+ enriched = enrich_docker_backend_spec(mounted, agent_id="ZE6GR2")
+ assert enriched["volumes"] == mounted["volumes"]
+ assert enriched["agent_id"] == "ZE6GR2"
+
+
+def test_row_to_backend_spec_docker_keeps_volumes() -> None:
row = BackendRow(
id=1,
name="sandbox",
@@ -329,7 +354,7 @@ def test_row_to_backend_spec_docker_ignores_volumes() -> None:
spec = row_to_backend_spec(row)
assert spec is not None
assert spec["memory"] == "512m"
- assert "volumes" not in spec
+ assert spec["volumes"] == {"/": {"bind": "/host", "mode": "rw"}}
def test_inject_docker_global_environment_sets_file() -> None:
diff --git a/uv.lock b/uv.lock
index cdc8d7a021..c42412c904 100644
--- a/uv.lock
+++ b/uv.lock
@@ -2589,7 +2589,7 @@ wheels = [
[[package]]
name = "octop"
-version = "1.0.3b6"
+version = "1.0.3b7"
source = { editable = "." }
dependencies = [
{ name = "acme" },
@@ -2706,9 +2706,9 @@ requires-dist = [
{ name = "mss", marker = "extra == 'desktop'", specifier = ">=9.0" },
{ name = "mypy", marker = "extra == 'dev'", specifier = ">=1.10" },
{ name = "octop-browser", specifier = ">=1.0.0" },
- { name = "octop-gateway", specifier = ">=1.0.3" },
- { name = "octop-harness", extras = ["all"], specifier = ">=1.0.10" },
- { name = "octop-memory", specifier = ">=1.0.4" },
+ { name = "octop-gateway", specifier = ">=1.0.4" },
+ { name = "octop-harness", extras = ["all"], specifier = ">=1.0.11" },
+ { name = "octop-memory", specifier = ">=1.0.5" },
{ name = "onnxruntime", marker = "extra == 'knowledge-ocr'", specifier = ">=1.17" },
{ name = "openpyxl", specifier = ">=3.1" },
{ name = "pillow", specifier = ">=13.0.0" },
@@ -2778,7 +2778,7 @@ wheels = [
[[package]]
name = "octop-gateway"
-version = "1.0.3"
+version = "1.0.4"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "aiohttp" },
@@ -2796,14 +2796,14 @@ dependencies = [
{ name = "websockets" },
{ name = "wecom-aibot-sdk" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/f1/7f/cc6d7f7af425fbcc2d999b3a187288fd99a9220acca4bf33e27026a58769/octop_gateway-1.0.3.tar.gz", hash = "sha256:ff679fe583ad13a66b680eee88708a1a9602054f9ecd461577bf7d521572895a", size = 642266, upload-time = "2026-10-16T09:18:50.867Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/8c/34/8bd52235aabd4cf6945ec5e1c20c0cd711efd8ed3ceeb9564e20a0cddcb6/octop_gateway-1.0.4.tar.gz", hash = "sha256:a4b33a71bcb85b0a20dc2d48a30a51b7f04f31cdacf09096f572fc4c756ee316", size = 665814, upload-time = "2026-11-17T13:01:34.912Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/0b/2a/367c124660188fbd3a230057f28e33bdb09950a6684fc8c3cbd4215d494d/octop_gateway-1.0.3-py3-none-any.whl", hash = "sha256:66d4942cc26b9b1d8653b007540e928e40541185803c560853fc0acdfa444d1e", size = 178059, upload-time = "2026-10-16T09:18:49.638Z" },
+ { url = "https://files.pythonhosted.org/packages/07/b9/1a77418edb3c0f0f1af84431f5607eb732ae72c2306830aca75788c9a564/octop_gateway-1.0.4-py3-none-any.whl", hash = "sha256:9e5209080f6db477b5f79842d99775aa2af6bce49f33be0c972b9a183c37a12e", size = 188945, upload-time = "2026-11-17T13:01:33.794Z" },
]
[[package]]
name = "octop-harness"
-version = "1.0.10"
+version = "1.0.11"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "deepagents" },
@@ -2821,9 +2821,9 @@ dependencies = [
{ name = "octop-memory" },
{ name = "pyyaml" },
]
-sdist = { url = "https://files.pythonhosted.org/packages/22/d7/cc7ada944e0c5dec954fd5cad5c18acec6067dc113610ea68dde081f8962/octop_harness-1.0.10.tar.gz", hash = "sha256:1dbd95a0ce5c0dd2b24828df7763db86a6acbb1b6cfd719acf6bc31f264fd12b", size = 1031842, upload-time = "2026-11-15T11:49:28.761Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/3b/70/d84beb04aaee40833a9ff09ee5799f08d1a968767b5b86f02c3922a8e1d8/octop_harness-1.0.11.tar.gz", hash = "sha256:8e6cf38731247b57fce81339aeda2dbf2c88afe7962a9879aa4ccf4471f942ac", size = 1040612, upload-time = "2026-11-17T13:50:10.653Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/7b/17/6945030f10986dae0d1638c337b7ab23095590502be61c2a9c3cd8bab5ae/octop_harness-1.0.10-py3-none-any.whl", hash = "sha256:6c01f0604a2ceb9a8607dbb517b1e1d07f9f2751dcef6c0517042d5e3e8d28c4", size = 1230546, upload-time = "2026-11-15T11:49:27.298Z" },
+ { url = "https://files.pythonhosted.org/packages/b4/8a/f780abb74552b0da7b5052dd503f2b19daa69cb0ae1fd943b0993e12f644/octop_harness-1.0.11-py3-none-any.whl", hash = "sha256:2972e5a345943c97eebf00ebfef067606c1ea172f245d54bd464a6ba3f401362", size = 1239294, upload-time = "2026-11-17T13:50:08.993Z" },
]
[package.optional-dependencies]
@@ -2848,11 +2848,11 @@ all = [
[[package]]
name = "octop-memory"
-version = "1.0.4"
+version = "1.0.5"
source = { registry = "https://pypi.org/simple" }
-sdist = { url = "https://files.pythonhosted.org/packages/83/34/84bd86a2b4042322d23badba90f9ce47f5f96900d046c83708d271570d2a/octop_memory-1.0.4.tar.gz", hash = "sha256:c7375ac29fecf222b76ca738a9547ce1f34743d32a81d3287de230d4e7c9a566", size = 628000, upload-time = "2026-11-10T10:38:26.693Z" }
+sdist = { url = "https://files.pythonhosted.org/packages/64/b6/d9f3bd989aea1fd799ad026338d662c59f65aeaa8e687b94b3f6e50c1080/octop_memory-1.0.5.tar.gz", hash = "sha256:c406870d598cd38bc9424817b51c4d69832e36c89c83d1b8c80698eef57ca55f", size = 647402, upload-time = "2026-11-17T12:15:12.763Z" }
wheels = [
- { url = "https://files.pythonhosted.org/packages/6b/97/54a6a30f227e54464326769f53568761cb12b90a7f31cdda976befd590d9/octop_memory-1.0.4-py3-none-any.whl", hash = "sha256:73e54ec492990fb5556da82808f7c65e690e717f02e3f8d06ea90a9669e1a3dc", size = 389426, upload-time = "2026-11-10T10:38:25.241Z" },
+ { url = "https://files.pythonhosted.org/packages/dc/26/c95a66fe2d925391102d0b17fc8353e265dffc5f587bcdd83c76305b6388/octop_memory-1.0.5-py3-none-any.whl", hash = "sha256:aa17fa4c2576cc2f9bef15f61f2a8e103233bc86fd479d2c50208b11e2fc1ca9", size = 405810, upload-time = "2026-11-17T12:15:11.121Z" },
]
[[package]]