Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(agents): let agent owners restrict who sees tool details in run logs (MUL-10284) (#11727)
Jiayuan Zhang105434734b00
diff --git a/apps/mobile/data/realtime/chat-ws-updaters.test.ts b/apps/mobile/data/realtime/chat-ws-updaters.test.tsindex 0cd5142695..7da53d9a16 100644--- a/apps/mobile/data/realtime/chat-ws-updaters.test.ts+++ b/apps/mobile/data/realtime/chat-ws-updaters.test.ts@@ -5,9 +5,11 @@ import type {ChatMessage,ChatPendingTask,ChatQuickActionsPayload,+ TaskMessagePayload,} from "@multica/core/types";import {+ appendTaskMessage,applyChatDoneToCache,applyChatQuickActionsToCache,promotePendingTaskToRunning,@@ -618,3 +620,36 @@ describe("reconcileAcceptedChatSend", () => {});});});++describe("appendTaskMessage", () => {+ const call = (over: Partial<TaskMessagePayload> = {}): TaskMessagePayload => ({+ task_id: "task-1",+ issue_id: "issue-1",+ seq: 2,+ type: "tool_use",+ tool: "Bash",+ input: { command: "ls" },+ ...over,+ });+ const hidden = call({ input: undefined, details_hidden: true });+ const cached = (qc: QueryClient) => qc.getQueryData<TaskMessagePayload[]>(chatKeys.taskMessages("task-1"));++ it("keeps the full copy of a tool call whichever copy arrives first", () => {+ for (const order of [[hidden, call()], [call(), hidden]]) {+ const qc = new QueryClient();+ for (const payload of order) appendTaskMessage(qc, payload);+ expect(cached(qc)).toEqual([call()]);+ }+ });++ it("ignores a repeat of a seq it already has", () => {+ const qc = new QueryClient();+ appendTaskMessage(qc, call());+ appendTaskMessage(qc, call({ input: { command: "pwd" } }));+ appendTaskMessage(qc, call({ seq: 1, type: "text", tool: undefined, input: undefined, content: "hi" }));+ expect(cached(qc)?.map((m) => [m.seq, m.input?.command ?? m.content])).toEqual([+ [1, "hi"],+ [2, "ls"],+ ]);+ });+});diff --git a/apps/mobile/data/realtime/chat-ws-updaters.ts b/apps/mobile/data/realtime/chat-ws-updaters.tsindex a9c3621888..638625ae8a 100644--- a/apps/mobile/data/realtime/chat-ws-updaters.ts+++ b/apps/mobile/data/realtime/chat-ws-updaters.ts@@ -365,7 +365,10 @@ export function reconcileAcceptedChatSend(/*** Append a `task:message` payload into the per-task timeline cache.*- * - De-dupes on `seq` (server may re-emit on flaky network).+ * - De-dupes on `seq` (server may re-emit on flaky network). A reader of a+ * restricted agent's tool details gets both the stripped and the full copy+ * of a tool call, so a full copy replaces a `details_hidden` one, as+ * `mergeTaskMessagesBySeq` does on web.* - Sorts by `seq` ASC after insert so reordered late-arriving rows still* render in execution order.* - Creates the cache entry on first event (empty default), so the timeline@@ -384,8 +387,10 @@ export function appendTaskMessage(qc.setQueryData<TaskMessagePayload[]>(chatKeys.taskMessages(payload.task_id),(old = []) => {- if (old.some((m) => m.seq === payload.seq)) return old;- return [...old, payload].sort((a, b) => a.seq - b.seq);+ const index = old.findIndex((m) => m.seq === payload.seq);+ if (index === -1) return [...old, payload].sort((a, b) => a.seq - b.seq);+ if (!old[index]!.details_hidden || payload.details_hidden) return old;+ return old.map((m, i) => (i === index ? payload : m));},);}diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 81032fe87a..4efeeb963e 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -2595,6 +2595,20 @@ describe("TaskMessageListSchema", () => {const parsed = TaskMessageListSchema.parse([{ ...row, type: "video" }]);expect(parsed[0]?.type).toBe("text");});++ it("keeps the mark on a tool call whose details were withheld", () => {+ const parsed = TaskMessageListSchema.parse([+ { ...row, seq: 1, type: "tool_use", tool: "Bash", output: undefined, details_hidden: true },+ { ...row, seq: 2 },+ ]);+ expect(parsed.map((m) => m.details_hidden)).toEqual([true, undefined]);+ });++ it("keeps the row and forgets a malformed withheld mark", () => {+ const parsed = TaskMessageListSchema.parse([{ ...row, details_hidden: "yes" }]);+ expect(parsed).toHaveLength(1);+ expect(parsed[0]?.details_hidden).toBeUndefined();+ });});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 259bc42927..92824b657d 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -2619,6 +2619,7 @@ export const TaskMessagePayloadSchema = z.object({output: z.string().optional(),output_truncated: z.boolean().optional().catch(undefined),created_at: z.string().optional(),+ details_hidden: z.boolean().optional().catch(undefined),}).loose();export const TaskMessageListSchema = z.array(TaskMessagePayloadSchema).default([]);diff --git a/packages/core/chat/queries.test.ts b/packages/core/chat/queries.test.tsindex 27e11071cf..d8087ca502 100644--- a/packages/core/chat/queries.test.ts+++ b/packages/core/chat/queries.test.ts@@ -106,6 +106,28 @@ describe("mergeTaskMessagesBySeq", () => {expect(mergeTaskMessagesBySeq(existing, [])).toBe(existing);expect(mergeTaskMessagesBySeq(existing, [msg(1), msg(2)])).toBe(existing);});++ // A restricted agent's tool call reaches a reader twice: stripped through+ // the workspace, whole through their own scope, in either order.+ describe("a tool call sent both with and without its details", () => {+ const hidden: TaskMessagePayload = { ...msg(2), type: "tool_use", tool: "Bash", content: undefined, details_hidden: true };+ const whole: TaskMessagePayload = { ...msg(2), type: "tool_use", tool: "Bash", content: undefined, input: { command: "env" } };++ it("keeps the whole call when it arrives second", () => {+ const merged = mergeTaskMessagesBySeq([msg(1), hidden], [whole]);+ expect(merged.find((m) => m.seq === 2)).toBe(whole);+ });++ it("keeps the whole call when the stripped one arrives second", () => {+ const existing = [msg(1), whole];+ expect(mergeTaskMessagesBySeq(existing, [hidden])).toBe(existing);+ });++ it("keeps the whole call when both land in one batch", () => {+ expect(mergeTaskMessagesBySeq([msg(1)], [whole, hidden]).find((m) => m.seq === 2)).toBe(whole);+ expect(mergeTaskMessagesBySeq([msg(1)], [hidden, whole]).find((m) => m.seq === 2)).toBe(whole);+ });+ });});describe("sortChatSessions", () => {diff --git a/packages/core/chat/queries.ts b/packages/core/chat/queries.tsindex 4c8db7008b..4fdbcdd5ce 100644--- a/packages/core/chat/queries.ts+++ b/packages/core/chat/queries.ts@@ -317,6 +317,11 @@ export function useTaskMessages(taskId: string, isLive: boolean, enabled = true)* conflict, and the original array reference is preserved when nothing new* arrives so React Query observers don't re-render on duplicate events.*+ * The one exception is a tool call the server sent twice: an agent that+ * restricts its tool details streams the call to the whole workspace without+ * them, and to the people allowed them a second time whole. Whichever copy+ * lands first, the whole one is what a reader keeps.+ ** Both the realtime `task:message` handler (a single payload) and the* transcript backfill (a full refetch) write this cache. Routing both through* one helper keeps a forced backfill from blind-replacing a seq the WebSocket@@ -328,10 +333,17 @@ export function mergeTaskMessagesBySeq(incoming: readonly TaskMessagePayload[],): TaskMessagePayload[] {if (incoming.length === 0) return existing as TaskMessagePayload[];- const knownSeqs = new Set(existing.map((m) => m.seq));- const fresh = incoming.filter((m) => !knownSeqs.has(m.seq));- if (fresh.length === 0) return existing as TaskMessagePayload[];- return [...existing, ...fresh].sort((a, b) => a.seq - b.seq);+ const bySeq = new Map(existing.map((m) => [m.seq, m]));+ let changed = false;+ for (const msg of incoming) {+ const known = bySeq.get(msg.seq);+ if (!known || (known.details_hidden && !msg.details_hidden)) {+ bySeq.set(msg.seq, msg);+ changed = true;+ }+ }+ if (!changed) return existing as TaskMessagePayload[];+ return [...bySeq.values()].sort((a, b) => a.seq - b.seq);}/**diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex dff3c0193a..c23ff61a10 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -7,6 +7,13 @@ export type AgentRuntimeMode = "local" | "cloud";export type AgentVisibility = "workspace" | "private";+/**+ * Who can read the inputs and outputs of an agent's tool calls in its run+ * logs: everyone who can see the run, or only the agent's owner and workspace+ * owners/admins.+ */+export type AgentToolDetailsVisibility = "everyone" | "restricted";+// Agent invocation permissions (MUL-3963)//// `permission_mode` + `invocation_targets` are the AUTHORITATIVE gate for who@@ -666,6 +673,12 @@ export interface Agent {* field; treat `undefined` as false.*/composio_toolkit_allowlist_redacted?: boolean;+ /**+ * Who can read the inputs and outputs of the agent's tool calls in its run+ * logs. Older backends omit it; anything but "restricted" means everyone+ * who can see the run.+ */+ tool_details_visibility?: AgentToolDetailsVisibility;visibility: AgentVisibility;/*** Authoritative invocation permission mode (MUL-3963). The `visibility`@@ -851,6 +864,8 @@ export interface UpdateAgentRequest {name?: string;description?: string;instructions?: string;+ /** Agent owner or workspace owner/admin only. See `Agent.tool_details_visibility`. */+ tool_details_visibility?: AgentToolDetailsVisibility;conversation_starters?: AgentConversationStarter[];avatar_url?: string;runtime_id?: string;diff --git a/packages/core/types/events.ts b/packages/core/types/events.tsindex c0a48c8b31..a8527c1c31 100644--- a/packages/core/types/events.ts+++ b/packages/core/types/events.ts@@ -386,6 +386,12 @@ export interface TaskMessagePayload {*/output_truncated?: boolean;created_at?: string;+ /**+ * The agent restricts its tool inputs and outputs and this reader is not+ * allowed them: `input`, `output` and `content` were removed from this+ * tool_use/tool_result by the server, not empty to begin with.+ */+ details_hidden?: boolean;}export interface TaskQueuedPayload {diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 3adc81ba0b..d2cf2ee166 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -35,6 +35,7 @@ export type {AgentStatus,AgentRuntimeMode,AgentVisibility,+ AgentToolDetailsVisibility,AgentPermissionMode,AgentInvocationTarget,AgentInvocationTargetInput,diff --git a/packages/views/agents/components/agent-access-settings.test.tsx b/packages/views/agents/components/agent-access-settings.test.tsxindex 936952653e..d51a01bfe2 100644--- a/packages/views/agents/components/agent-access-settings.test.tsx+++ b/packages/views/agents/components/agent-access-settings.test.tsx@@ -1,7 +1,7 @@// @vitest-environment jsdomimport { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { cleanup, screen, waitFor } from "@testing-library/react";+import { cleanup, fireEvent, screen, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { setApiInstance } from "@multica/core/api";import type { ApiClient } from "@multica/core/api/client";@@ -40,11 +40,22 @@ function agent(overrides: Partial<Agent>): Agent {} as Agent;}-function renderSettings(value: Agent) {+type UpdateAgent = (id: string, data: Record<string, unknown>) => Promise<void>;++function renderSettings(+ value: Agent,+ { canEdit = true, onUpdate = vi.fn<UpdateAgent>() }: { canEdit?: boolean; onUpdate?: UpdateAgent } = {},+) {const qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });return renderWithI18n(<QueryClientProvider client={qc}>- <AgentAccessSettings agent={value} members={MEMBERS} currentUserId="owner" onUpdate={vi.fn()} />+ <AgentAccessSettings+ agent={value}+ members={MEMBERS}+ currentUserId="owner"+ canEdit={canEdit}+ onUpdate={onUpdate}+ /></QueryClientProvider>,);}@@ -79,3 +90,46 @@ describe("AgentAccessSettings plan access", () => {expect(screen.queryByRole("checkbox", { name: /Bob/i })).not.toBeInTheDocument();});});++describe("AgentAccessSettings run logs", () => {+ beforeEach(() => {+ setApiInstance({+ getWorkspaceFeatures: vi.fn(async () => ({ features: { agent_invocation_members: "available" } })),+ } as unknown as ApiClient);+ });+ afterEach(cleanup);++ it("restricts tool details when switched on", async () => {+ const onUpdate = vi.fn(async () => {});+ renderSettings(agent({}), { onUpdate });+ const toggle = screen.getByRole("switch", { name: "Restrict tool details" });+ expect(toggle).not.toBeChecked();++ fireEvent.click(toggle);++ expect(onUpdate).toHaveBeenCalledWith("a1", { tool_details_visibility: "restricted" });+ });++ it("lifts the restriction when switched off", () => {+ const onUpdate = vi.fn(async () => {});+ renderSettings(agent({ tool_details_visibility: "restricted" }), { onUpdate });+ const toggle = screen.getByRole("switch", { name: "Restrict tool details" });+ expect(toggle).toBeChecked();++ fireEvent.click(toggle);++ expect(onUpdate).toHaveBeenCalledWith("a1", { tool_details_visibility: "everyone" });+ });++ it("is read-only for someone who cannot manage the agent", () => {+ const onUpdate = vi.fn(async () => {});+ renderSettings(agent({ tool_details_visibility: "restricted" }), { canEdit: false, onUpdate });+ const toggle = screen.getByRole("switch", { name: "Restrict tool details" });+ expect(toggle).toBeChecked();+ expect(toggle).toHaveAttribute("data-disabled");++ fireEvent.click(toggle);++ expect(onUpdate).not.toHaveBeenCalled();+ });+});diff --git a/packages/views/agents/components/agent-access-settings.tsx b/packages/views/agents/components/agent-access-settings.tsxindex dd9d11fa2b..e7f400e70d 100644--- a/packages/views/agents/components/agent-access-settings.tsx+++ b/packages/views/agents/components/agent-access-settings.tsx@@ -4,8 +4,10 @@ import type { Agent, MemberWithUser } from "@multica/core/types";import { usesInvocationMembers } from "@multica/core/agents";import { usePaidFeatureAccess } from "@multica/core/billing";import { useWorkspaceId } from "@multica/core/hooks";+import { Switch } from "@multica/ui/components/ui/switch";import {SettingsCard,+ SettingsRow,SettingsSection,} from "../../settings/components/settings-layout";import { useT } from "../../i18n";@@ -15,12 +17,15 @@ export function AgentAccessSettings({agent,members,currentUserId,+ canEdit,onDirtyChange,onUpdate,}: {agent: Agent;members: MemberWithUser[];currentUserId: string | null;+ /** Agent owner or workspace owner/admin. */+ canEdit: boolean;onDirtyChange?: (dirty: boolean) => void;onUpdate: (id: string, data: Record<string, unknown>) => Promise<void>;}) {@@ -29,29 +34,51 @@ export function AgentAccessSettings({const membersAccess = usePaidFeatureAccess(wsId, "agent_invocation_members", {hasExistingConfig: usesInvocationMembers(agent.permission_mode, agent.invocation_targets),});+ const restrictToolDetails = agent.tool_details_visibility === "restricted";return (- <SettingsSection- title={t(($) => $.access.section_title)}- >- <SettingsCard>- <AccessPicker- permissionMode={agent.permission_mode}- invocationTargets={agent.invocation_targets}- visibility={agent.visibility}- members={members}- ownerId={agent.owner_id}- canEdit={- currentUserId !== null && agent.owner_id === currentUserId- }- hasComposioAllowlist={- (agent.composio_toolkit_allowlist ?? []).length > 0- }- onDirtyChange={onDirtyChange}- membersAccess={membersAccess}- onChange={(next) => onUpdate(agent.id, next)}- />- </SettingsCard>- </SettingsSection>+ <div className="space-y-8">+ <SettingsSection+ title={t(($) => $.access.section_title)}+ >+ <SettingsCard>+ <AccessPicker+ permissionMode={agent.permission_mode}+ invocationTargets={agent.invocation_targets}+ visibility={agent.visibility}+ members={members}+ ownerId={agent.owner_id}+ canEdit={+ currentUserId !== null && agent.owner_id === currentUserId+ }+ hasComposioAllowlist={+ (agent.composio_toolkit_allowlist ?? []).length > 0+ }+ onDirtyChange={onDirtyChange}+ membersAccess={membersAccess}+ onChange={(next) => onUpdate(agent.id, next)}+ />+ </SettingsCard>+ </SettingsSection>+ <SettingsSection title={t(($) => $.access.run_logs_title)}>+ <SettingsCard>+ <SettingsRow+ label={t(($) => $.access.restrict_tool_details_label)}+ description={t(($) => $.access.restrict_tool_details_desc)}+ >+ <Switch+ checked={restrictToolDetails}+ disabled={!canEdit}+ aria-label={t(($) => $.access.restrict_tool_details_label)}+ onCheckedChange={(checked) =>+ onUpdate(agent.id, {+ tool_details_visibility: checked ? "restricted" : "everyone",+ })+ }+ />+ </SettingsRow>+ </SettingsCard>+ </SettingsSection>+ </div>);}diff --git a/packages/views/agents/components/agent-advanced-settings.tsx b/packages/views/agents/components/agent-advanced-settings.tsxindex 6a532c386e..427a2756f2 100644--- a/packages/views/agents/components/agent-advanced-settings.tsx+++ b/packages/views/agents/components/agent-advanced-settings.tsx@@ -285,6 +285,7 @@ export function AgentAdvancedSettings({agent={agent}members={members}currentUserId={currentUserId}+ canEdit={canEdit}onDirtyChange={setDirty}onUpdate={onUpdate}/>diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsxindex 7ad32cbad9..64fcafd525 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.test.tsx@@ -1278,6 +1278,65 @@ describe("tool output completeness", () => {});});+describe("restricted tool details", () => {+ const hiddenRun: TimelineItem[] = [+ { seq: 1, type: "thinking", content: "Checking the deploy config" },+ { seq: 2, type: "tool_use", tool: "Bash", detailsHidden: true },+ { seq: 3, type: "tool_result", tool: "Bash", detailsHidden: true },+ { seq: 4, type: "text", content: "Deploy config looks right." },+ ];++ afterEach(() => {+ vi.mocked(api.getAgent).mockResolvedValue(null as never);+ });++ it("shows a withheld call as hidden, keeping its name and the reasoning around it", () => {+ renderDialog(hiddenRun);++ const row = screen.getByRole("button", { name: /Bash/ });+ expect(row).toHaveTextContent("Hidden");+ expect(screen.getByText("Tool details hidden")).toBeInTheDocument();+ expect(screen.getByRole("button", { name: /Checking the deploy config/ })).toBeInTheDocument();+ });++ it("explains in the inspector why a withheld call has nothing to show", () => {+ renderDialog(hiddenRun);+ fireEvent.click(screen.getByRole("button", { name: /Bash/ }));++ expect(screen.getByText("Tool input and output are hidden")).toBeInTheDocument();+ expect(screen.getByText("Only this agent's owner and workspace admins can see them.")).toBeInTheDocument();+ expect(screen.queryByText("Input")).not.toBeInTheDocument();+ expect(screen.queryByRole("button", { name: "Copy this step" })).not.toBeInTheDocument();+ });++ it("marks a folded group of withheld calls as hidden", () => {+ renderDialog(+ [1, 3, 5].flatMap((seq): TimelineItem[] => [+ { seq, type: "tool_use", tool: "Grep", detailsHidden: true },+ { seq: seq + 1, type: "tool_result", tool: "Grep", detailsHidden: true },+ ]),+ );++ const group = screen.getByRole("button", { name: /Grep/, expanded: false });+ expect(group).toHaveTextContent("Hidden");+ });++ it("tells someone allowed the details that others cannot see them", async () => {+ vi.mocked(api.getAgent).mockResolvedValue({ id: "agent-1", tool_details_visibility: "restricted" } as never);+ renderDialog(items, { task: { ...baseTask, agent_id: "agent-1" } });++ expect(await screen.findByText("Tool details visible to owner and admins only")).toBeInTheDocument();+ expect(screen.queryByText("Hidden")).not.toBeInTheDocument();+ });++ it("says nothing for an agent that does not restrict its tool details", () => {+ renderDialog(items);++ expect(screen.queryByText("Tool details hidden")).not.toBeInTheDocument();+ expect(screen.queryByText("Tool details visible to owner and admins only")).not.toBeInTheDocument();+ });+});+describe("clearing a run's log", () => {it("lets an admin clear a finished run after confirming", async () => {memberRole.current = "admin";diff --git a/packages/views/common/task-transcript/agent-transcript-dialog.tsx b/packages/views/common/task-transcript/agent-transcript-dialog.tsxindex 9de7f8b37d..cb4cfa1f30 100644--- a/packages/views/common/task-transcript/agent-transcript-dialog.tsx+++ b/packages/views/common/task-transcript/agent-transcript-dialog.tsx@@ -29,6 +29,7 @@ import {Coins,GitBranch,Trash2,+ Lock,} from "@multica/ui/icons";import { useQueryClient } from "@tanstack/react-query";import { toast } from "sonner";@@ -606,6 +607,10 @@ export function AgentTranscriptDialog({const lanes = useMemo(() => buildLanes(steps, runStart, runEnd), [steps, runStart, runEnd]);const toolKinds = useMemo(() => toolKindTotals(steps), [steps]);const outcome = useMemo(() => buildRunOutcome(steps), [steps]);+ // Hidden: the server withheld some of this run's tool details from the+ // viewer. Restricted alone: the viewer is one of the people allowed them.+ const toolDetailsHidden = useMemo(() => items.some((item) => item.detailsHidden), [items]);+ const toolDetailsRestricted = agentInfo?.tool_details_visibility === "restricted";const selectedStep = useMemo(() => {if (selectedSeq === null) return null;@@ -1207,7 +1212,9 @@ export function AgentTranscriptDialog({<RunTriggerRow task={task} />{/* ── What the run produced ──────────────────────────────────── */}- <RunOutcomeRow outcome={outcome} branch={task.branch_name} />+ {/* Read off the tool inputs, so it has nothing true to say when those+ were withheld. */}+ {!toolDetailsHidden && <RunOutcomeRow outcome={outcome} branch={task.branch_name} />}{/* ── Where the time went ────────────────────────────────────── */}{lanes && (@@ -1238,7 +1245,21 @@ export function AgentTranscriptDialog({className="min-w-0 flex-1 bg-transparent text-caption outline-none placeholder:text-faint-foreground"/></label>- <span className="ml-auto shrink-0 whitespace-nowrap text-caption text-muted-foreground">+ {(toolDetailsHidden || toolDetailsRestricted) && (+ <span className="ml-auto flex shrink-0 items-center gap-1 whitespace-nowrap text-caption text-muted-foreground">+ <Lock aria-hidden className="h-3 w-3" />+ {toolDetailsHidden+ ? t(($) => $.transcript.tool_details_hidden_toolbar)+ : t(($) => $.transcript.tool_details_restricted_toolbar)}+ <span aria-hidden className="text-faint-foreground">·</span>+ </span>+ )}+ <span+ className={cn(+ "shrink-0 whitespace-nowrap text-caption text-muted-foreground",+ !(toolDetailsHidden || toolDetailsRestricted) && "ml-auto",+ )}+ >{activeFilterKeys.length > 0 || trimmedQuery.length > 0? t(($) => $.transcript.steps_filtered, {shown: filteredSteps.length,@@ -1811,7 +1832,7 @@ function StepRow({call && "font-mono",)}>- {summary}+ {call && callDetailsHidden(call) ? <HiddenDetails /> : summary}</span></span><DurationCell ms={call?.durationMs} pending={pending} />@@ -1862,7 +1883,7 @@ function GroupRow({{/* Name the first thing it touched, not just how many: "Read · 4calls" hides the one detail that makes a folded group scannable. */}<span className="truncate font-mono text-micro text-muted-foreground">- {callSummary(row.steps[0]!, summaryLabels)}+ {callDetailsHidden(row.steps[0]!) ? <HiddenDetails /> : callSummary(row.steps[0]!, summaryLabels)}</span><span className="shrink-0 text-micro text-faint-foreground">{t(($) => $.transcript.group_calls, { count: row.steps.length })}@@ -1887,7 +1908,7 @@ function GroupRow({)}><span className="truncate font-mono text-muted-foreground">- {callSummary(step, summaryLabels) || step.tool}+ {callDetailsHidden(step) ? <HiddenDetails /> : callSummary(step, summaryLabels) || step.tool}</span>{step.durationMs === undefined ? (<span className="ml-auto shrink-0" />@@ -1928,6 +1949,22 @@ function firstLineOf(value: string | undefined): string {return value?.split("\n").find((line) => line.trim().length > 0) ?? "";}+/** The agent restricts its tool details and the server withheld this call's. */+function callDetailsHidden(step: TraceCallStep): boolean {+ return step.call?.detailsHidden === true || step.result?.detailsHidden === true;+}++/** Stands in for a call's argument when the viewer may not read it. */+function HiddenDetails() {+ const { t } = useT("agents");+ return (+ <span className="inline-flex items-center gap-1 font-sans text-faint-foreground">+ <Lock aria-hidden className="h-3 w-3" />+ {t(($) => $.transcript.tool_details_hidden_value)}+ </span>+ );+}+// ─── Inspector ──────────────────────────────────────────────────────────────/**@@ -1954,6 +1991,7 @@ function StepInspector({const call = isCallStep(step) ? step : null;const message = call ? null : (step as TraceMessageStep);+ const detailsHidden = call !== null && callDetailsHidden(call);const handleCopy = useCallback(() => {const parts: string[] = [];@@ -1999,16 +2037,18 @@ function StepInspector({</>)}</span>- <IconButton- variant="ghost"- size="icon-sm"- onClick={handleCopy}- label={t(($) => $.transcript.copy_step)}- tooltipSide="bottom"- className="shrink-0 text-muted-foreground"- >- <CopyCheckIcon copied={copied} />- </IconButton>+ {!detailsHidden && (+ <IconButton+ variant="ghost"+ size="icon-sm"+ onClick={handleCopy}+ label={t(($) => $.transcript.copy_step)}+ tooltipSide="bottom"+ className="shrink-0 text-muted-foreground"+ >+ <CopyCheckIcon copied={copied} />+ </IconButton>+ )}<IconButtonvariant="ghost"size="icon-sm"@@ -2027,7 +2067,17 @@ function StepInspector({animate={{ opacity: 1 }}transition={{ duration: reduceMotion ? 0 : 0.12, ease: UI_EASE_OUT }}>- {call ? (+ {detailsHidden ? (+ <div className="flex flex-col items-center gap-1.5 px-6 py-12 text-center">+ <Lock aria-hidden className="mb-1 h-4 w-4 text-faint-foreground" />+ <p className="text-caption font-medium text-foreground">+ {t(($) => $.transcript.tool_details_hidden_title)}+ </p>+ <p className="text-caption text-muted-foreground">+ {t(($) => $.transcript.tool_details_hidden_body)}+ </p>+ </div>+ ) : call ? (<>{call.call && (<InspectorSection label={t(($) => $.transcript.step_input)}>diff --git a/packages/views/common/task-transcript/build-timeline.ts b/packages/views/common/task-transcript/build-timeline.tsindex 9f70158720..3a0d1e3d0b 100644--- a/packages/views/common/task-transcript/build-timeline.ts+++ b/packages/views/common/task-transcript/build-timeline.ts@@ -18,6 +18,8 @@ export interface TimelineItem {*/output_truncated?: boolean;created_at?: string;+ /** The server withheld this tool call's input and output from the viewer. */+ detailsHidden?: boolean;}function canMergeStreamingText(prev: TimelineItem, next: TimelineItem): boolean {@@ -81,8 +83,8 @@ export function isOutputTruncated(item: TimelineItem): boolean {* what they had been on the previous pass (MUL-7227).** A message is immutable once it lands — the realtime merge appends unseen seqs- * and keeps the objects it already holds — so identity is a sound proof that a- * body has not changed. Each entry records the exact messages it was built+ * and keeps the objects it already holds, replacing one only with a new object+ * — so identity is a sound proof that a body has not changed. Each entry records the exact messages it was built* from, and is reused only when that list still matches: a coalescing run that* gained a fragment is rebuilt, which is what keeps redaction applied to merged* text rather than to the pieces.@@ -120,6 +122,7 @@ function mergeRun(run: readonly TaskMessagePayload[]): TimelineItem {output: first.output,output_truncated: first.output_truncated,created_at: createdAt,+ ...(first.details_hidden ? { detailsHidden: true } : {}),};}diff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 43d61098bb..e525b796d6 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -877,7 +877,10 @@"members_empty": "No workspace members to choose from","composio_switch_hint": "Heads up — this agent has connected apps enabled. Sharing it lets anyone with access use those apps through this agent.","trigger_members_count_one": "{{count}} person",- "trigger_members_count_other": "{{count}} people"+ "trigger_members_count_other": "{{count}} people",+ "run_logs_title": "Run logs",+ "restrict_tool_details_label": "Restrict tool details",+ "restrict_tool_details_desc": "Only the agent's owner and workspace admins can see tool inputs and outputs in its runs. Everyone else sees which tools ran and how long they took."},"profile_card": {"unavailable": "Agent unavailable",@@ -1033,7 +1036,12 @@"context_receipt_package": "Package","context_receipt_instruction_file_bytes": "Instruction files: {{size}}","context_receipt_skill_package_bytes": "Skill packages: {{size}}",- "context_receipt_other_file_bytes": "Other files: {{size}}"+ "context_receipt_other_file_bytes": "Other files: {{size}}",+ "tool_details_hidden_value": "Hidden",+ "tool_details_hidden_title": "Tool input and output are hidden",+ "tool_details_hidden_body": "Only this agent's owner and workspace admins can see them.",+ "tool_details_hidden_toolbar": "Tool details hidden",+ "tool_details_restricted_toolbar": "Tool details visible to owner and admins only"},"task_failure": {"cancelled_by_system": "Cancelled by the system",diff --git a/packages/views/locales/es/agents.json b/packages/views/locales/es/agents.jsonindex e021d84e9e..67607490eb 100644--- a/packages/views/locales/es/agents.json+++ b/packages/views/locales/es/agents.json@@ -852,7 +852,10 @@"members_empty": "No hay miembros del espacio de trabajo para elegir","composio_switch_hint": "Aviso: este agente tiene aplicaciones conectadas activadas. Al compartirlo, cualquiera con acceso podrá usar esas aplicaciones a través de este agente.","trigger_members_count_one": "{{count}} persona",- "trigger_members_count_other": "{{count}} personas"+ "trigger_members_count_other": "{{count}} personas",+ "run_logs_title": "Registros de ejecución",+ "restrict_tool_details_label": "Restringir detalles de herramientas",+ "restrict_tool_details_desc": "Solo el propietario del agente y los administradores del espacio de trabajo pueden ver las entradas y salidas de las herramientas en sus ejecuciones. Los demás ven qué herramientas se ejecutaron y cuánto tardaron."},"profile_card": {"unavailable": "Agente no disponible",@@ -1008,7 +1011,12 @@"context_receipt_package": "Paquete","context_receipt_instruction_file_bytes": "Archivos de instrucciones: {{size}}","context_receipt_skill_package_bytes": "Paquetes de skills: {{size}}",- "context_receipt_other_file_bytes": "Otros archivos: {{size}}"+ "context_receipt_other_file_bytes": "Otros archivos: {{size}}",+ "tool_details_hidden_value": "Oculto",+ "tool_details_hidden_title": "La entrada y la salida de la herramienta están ocultas",+ "tool_details_hidden_body": "Solo el propietario de este agente y los administradores del espacio de trabajo pueden verlas.",+ "tool_details_hidden_toolbar": "Detalles de herramientas ocultos",+ "tool_details_restricted_toolbar": "Detalles de herramientas visibles solo para el propietario y los administradores"},"task_failure": {"cancelled_by_system": "Cancelada por el sistema",diff --git a/packages/views/locales/fr/agents.json b/packages/views/locales/fr/agents.jsonindex 793b1a05d5..e3f1192ae1 100644--- a/packages/views/locales/fr/agents.json+++ b/packages/views/locales/fr/agents.json@@ -877,7 +877,10 @@"members_empty": "Aucun membre de l'espace de travail à choisir","composio_switch_hint": "Attention : cet agent dispose d'applications connectées activées. Le partager permet à toute personne y ayant accès d'utiliser ces applications via cet agent.","trigger_members_count_one": "{{count}} personne",- "trigger_members_count_other": "{{count}} personnes"+ "trigger_members_count_other": "{{count}} personnes",+ "run_logs_title": "Journaux d'exécution",+ "restrict_tool_details_label": "Restreindre les détails des outils",+ "restrict_tool_details_desc": "Seuls le propriétaire de l'agent et les administrateurs de l'espace de travail peuvent voir les entrées et sorties des outils dans ses exécutions. Les autres voient quels outils ont été lancés et leur durée."},"profile_card": {"unavailable": "Agent indisponible",@@ -1033,7 +1036,12 @@"context_receipt_package": "Paquet","context_receipt_instruction_file_bytes": "Fichiers d’instructions : {{size}}","context_receipt_skill_package_bytes": "Paquets de skills : {{size}}",- "context_receipt_other_file_bytes": "Autres fichiers : {{size}}"+ "context_receipt_other_file_bytes": "Autres fichiers : {{size}}",+ "tool_details_hidden_value": "Masqué",+ "tool_details_hidden_title": "L'entrée et la sortie de l'outil sont masquées",+ "tool_details_hidden_body": "Seuls le propriétaire de cet agent et les administrateurs de l'espace de travail peuvent les voir.",+ "tool_details_hidden_toolbar": "Détails des outils masqués",+ "tool_details_restricted_toolbar": "Détails des outils visibles par le propriétaire et les administrateurs uniquement"},"task_failure": {"cancelled_by_system": "Annulée par le système",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex 0989922591..70250f0b43 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -711,7 +711,10 @@"owner_only_readonly": "このエージェントを実行できる相手は、オーナーのみが変更できます。","members_empty": "選択できるワークスペースメンバーがいません","composio_switch_hint": "注意: このエージェントでは連携アプリが有効になっています。共有すると、アクセス権を持つメンバーがこのエージェント経由でそれらのアプリを利用できるようになります。",- "trigger_members_count_other": "{{count}} 人"+ "trigger_members_count_other": "{{count}} 人",+ "run_logs_title": "実行ログ",+ "restrict_tool_details_label": "ツールの詳細を制限",+ "restrict_tool_details_desc": "実行中のツールの入力と出力は、エージェントのオーナーとワークスペース管理者のみが閲覧できます。他のメンバーには、実行されたツールと所要時間のみが表示されます。"},"profile_card": {"unavailable": "エージェントを利用できません",@@ -862,7 +865,12 @@"context_receipt_package": "パッケージ","context_receipt_instruction_file_bytes": "指示ファイル:{{size}}","context_receipt_skill_package_bytes": "スキルパッケージ:{{size}}",- "context_receipt_other_file_bytes": "その他のファイル:{{size}}"+ "context_receipt_other_file_bytes": "その他のファイル:{{size}}",+ "tool_details_hidden_value": "非表示",+ "tool_details_hidden_title": "ツールの入力と出力は非表示です",+ "tool_details_hidden_body": "このエージェントのオーナーとワークスペース管理者のみが閲覧できます。",+ "tool_details_hidden_toolbar": "ツールの詳細は非表示",+ "tool_details_restricted_toolbar": "ツールの詳細はオーナーと管理者のみに表示"},"task_failure": {"cancelled_by_system": "システムによってキャンセルされました",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex e15bbc12ba..4439af448f 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -711,7 +711,10 @@"owner_only_readonly": "이 에이전트를 실행할 수 있는 대상은 소유자만 변경할 수 있습니다.","members_empty": "선택할 워크스페이스 구성원이 없습니다","composio_switch_hint": "참고: 이 에이전트에는 연결된 앱이 활성화되어 있습니다. 공유하면 접근 권한이 있는 누구나 이 에이전트를 통해 해당 앱을 사용할 수 있습니다.",- "trigger_members_count_other": "{{count}}명"+ "trigger_members_count_other": "{{count}}명",+ "run_logs_title": "실행 로그",+ "restrict_tool_details_label": "도구 세부 정보 제한",+ "restrict_tool_details_desc": "실행 중 도구의 입력과 출력은 에이전트 소유자와 워크스페이스 관리자만 볼 수 있습니다. 다른 멤버에게는 어떤 도구가 실행되었고 얼마나 걸렸는지만 표시됩니다."},"profile_card": {"unavailable": "에이전트를 사용할 수 없습니다",@@ -862,7 +865,12 @@"context_receipt_package": "패키지","context_receipt_instruction_file_bytes": "지침 파일: {{size}}","context_receipt_skill_package_bytes": "스킬 패키지: {{size}}",- "context_receipt_other_file_bytes": "기타 파일: {{size}}"+ "context_receipt_other_file_bytes": "기타 파일: {{size}}",+ "tool_details_hidden_value": "숨김",+ "tool_details_hidden_title": "도구 입력과 출력이 숨겨져 있습니다",+ "tool_details_hidden_body": "이 에이전트의 소유자와 워크스페이스 관리자만 볼 수 있습니다.",+ "tool_details_hidden_toolbar": "도구 세부 정보 숨김",+ "tool_details_restricted_toolbar": "도구 세부 정보는 소유자와 관리자에게만 표시"},"task_failure": {"cancelled_by_system": "시스템에서 취소함",diff --git a/packages/views/locales/ru/agents.json b/packages/views/locales/ru/agents.jsonindex 8a755e9965..41288fecda 100644--- a/packages/views/locales/ru/agents.json+++ b/packages/views/locales/ru/agents.json@@ -927,7 +927,10 @@"trigger_members_count_one": "{{count}} участник","trigger_members_count_few": "{{count}} участников","trigger_members_count_many": "{{count}} участников",- "trigger_members_count_other": "{{count}} участников"+ "trigger_members_count_other": "{{count}} участников",+ "run_logs_title": "Журналы запусков",+ "restrict_tool_details_label": "Ограничить сведения об инструментах",+ "restrict_tool_details_desc": "Входные и выходные данные инструментов в запусках агента видят только его владелец и администраторы рабочего пространства. Остальные видят, какие инструменты запускались и сколько это заняло."},"profile_card": {"unavailable": "Агент недоступен",@@ -1093,7 +1096,12 @@"context_receipt_package": "Пакет","context_receipt_instruction_file_bytes": "Файлы инструкций: {{size}}","context_receipt_skill_package_bytes": "Пакеты навыков: {{size}}",- "context_receipt_other_file_bytes": "Другие файлы: {{size}}"+ "context_receipt_other_file_bytes": "Другие файлы: {{size}}",+ "tool_details_hidden_value": "Скрыто",+ "tool_details_hidden_title": "Входные и выходные данные инструмента скрыты",+ "tool_details_hidden_body": "Их видят только владелец этого агента и администраторы рабочего пространства.",+ "tool_details_hidden_toolbar": "Сведения об инструментах скрыты",+ "tool_details_restricted_toolbar": "Сведения об инструментах видны только владельцу и администраторам"},"task_failure": {"cancelled_by_system": "Отменено системой",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex 644f41b725..718cbe6c36 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -852,7 +852,10 @@"owner_only_readonly": "只有该智能体的所有者可以更改谁能调用它。","members_empty": "没有可选择的工作区成员","composio_switch_hint": "注意:该智能体已启用已连接应用。共享后,所有有权限运行该智能体的成员都可以通过它使用这些应用。",- "trigger_members_count_other": "{{count}} 人"+ "trigger_members_count_other": "{{count}} 人",+ "run_logs_title": "运行日志",+ "restrict_tool_details_label": "限制查看工具详情",+ "restrict_tool_details_desc": "开启后,只有智能体的所有者和工作区管理员能查看其运行中的工具输入与输出,其他成员只能看到调用了哪些工具及耗时。"},"profile_card": {"unavailable": "智能体不可用",@@ -1003,7 +1006,12 @@"context_receipt_package": "包总量","context_receipt_instruction_file_bytes": "指令文件:{{size}}","context_receipt_skill_package_bytes": "skill 包:{{size}}",- "context_receipt_other_file_bytes": "其他文件:{{size}}"+ "context_receipt_other_file_bytes": "其他文件:{{size}}",+ "tool_details_hidden_value": "已隐藏",+ "tool_details_hidden_title": "工具输入与输出已隐藏",+ "tool_details_hidden_body": "只有该智能体的所有者和工作区管理员可以查看。",+ "tool_details_hidden_toolbar": "工具详情已隐藏",+ "tool_details_restricted_toolbar": "工具详情仅所有者和管理员可见"},"task_failure": {"cancelled_by_system": "已由系统取消",diff --git a/packages/views/locales/zh-Hant/agents.json b/packages/views/locales/zh-Hant/agents.jsonindex 78ed40b4d7..8cea97e3fd 100644--- a/packages/views/locales/zh-Hant/agents.json+++ b/packages/views/locales/zh-Hant/agents.json@@ -852,7 +852,10 @@"owner_only_readonly": "只有該 AI 代理的所有者可以更改誰能呼叫它。","members_empty": "沒有可選擇的工作區成員","composio_switch_hint": "提示:該 AI 代理已啟用已連接的應用程式。共享後,有權存取此 AI 代理的人都將可以透過它使用這些應用程式。",- "trigger_members_count_other": "{{count}} 人"+ "trigger_members_count_other": "{{count}} 人",+ "run_logs_title": "執行紀錄",+ "restrict_tool_details_label": "限制查看工具詳情",+ "restrict_tool_details_desc": "開啟後,只有 AI 代理的所有者和工作區管理員能查看其執行中的工具輸入與輸出,其他成員只能看到呼叫了哪些工具及耗時。"},"profile_card": {"unavailable": "AI 代理不可用",@@ -1003,7 +1006,12 @@"context_receipt_package": "套件總量","context_receipt_instruction_file_bytes": "執行說明檔案:{{size}}","context_receipt_skill_package_bytes": "skill 套件:{{size}}",- "context_receipt_other_file_bytes": "其他檔案:{{size}}"+ "context_receipt_other_file_bytes": "其他檔案:{{size}}",+ "tool_details_hidden_value": "已隱藏",+ "tool_details_hidden_title": "工具輸入與輸出已隱藏",+ "tool_details_hidden_body": "只有該 AI 代理的所有者和工作區管理員可以查看。",+ "tool_details_hidden_toolbar": "工具詳情已隱藏",+ "tool_details_restricted_toolbar": "工具詳情僅所有者和管理員可見"},"task_failure": {"cancelled_by_system": "已由系統取消",diff --git a/server/cmd/server/listeners.go b/server/cmd/server/listeners.goindex 80ac70eb9c..ba4f1f992d 100644--- a/server/cmd/server/listeners.go+++ b/server/cmd/server/listeners.go@@ -295,6 +295,11 @@ func registerListeners(bus *events.Bus, b realtime.Broadcaster, audience ...privreturn}+ if payload, ok := restrictedToolMessage(e); ok {+ sendRestrictedToolMessage(b, e, payload, projectAudience)+ return+ }+// A chat session is creator-private: its events and its tasks'// transcript go only to the creator's connections bound to the// session's workspace. Not the whole user scope: a connection todiff --git a/server/cmd/server/tool_details_realtime.go b/server/cmd/server/tool_details_realtime.gonew file mode 100644index 0000000000..f657429add--- /dev/null+++ b/server/cmd/server/tool_details_realtime.go@@ -0,0 +1,103 @@+package main++import (+ "context"+ "encoding/json"+ "log/slog"+ "sort"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// restrictedToolMessage returns the tool call e carries when it comes from an+// agent that restricts its tool details. Prose and reasoning from the same+// agent are not tool details and take the ordinary route.+func restrictedToolMessage(e events.Event) (protocol.TaskMessagePayload, bool) {+ if !e.ToolDetailsRestricted || e.Type != protocol.EventTaskMessage {+ return protocol.TaskMessagePayload{}, false+ }+ payload, ok := e.Payload.(protocol.TaskMessagePayload)+ if !ok || (payload.Type != "tool_use" && payload.Type != "tool_result") {+ return protocol.TaskMessagePayload{}, false+ }+ return payload, true+}++// sendRestrictedToolMessage delivers a tool call whose input and output only+// e.ToolDetailReaders may read, to the same people the ordinary route would.+// A chat's creator and a private project's audience each get the one frame+// they may read through their own member scope. A run the whole workspace+// sees goes to the workspace without its details, and its readers also get+// the whole call: their clients keep it over the stripped copy of the same+// seq, which costs a handful of extra frames rather than one per member.+func sendRestrictedToolMessage(b realtime.Broadcaster, e events.Event, payload protocol.TaskMessagePayload, audience privateProjectAudience) {+ full, err := taskMessageFrame(e, payload)+ if err != nil {+ slog.Error("failed to marshal event", "event_type", e.Type, "error", err)+ return+ }+ stripped, err := taskMessageFrame(e, payload.WithoutToolDetails())+ if err != nil {+ slog.Error("failed to marshal event", "event_type", e.Type, "error", err)+ return+ }+ frameFor := func(userID string) []byte {+ if e.ToolDetailReaders[userID] {+ return full+ }+ return stripped+ }+ toMember := func(userID string, frame []byte) {+ b.BroadcastToScope(realtime.ScopeWorkspaceMember, realtime.WorkspaceMemberScopeID(e.WorkspaceID, userID), frame)+ }++ if isChatPrivateEvent(e) {+ if e.ChatSessionOwnerID == "" || e.WorkspaceID == "" {+ slog.Warn("realtime: dropping chat event without session owner",+ "event_type", e.Type, "chat_session_id", e.ChatSessionID, "task_id", e.TaskID)+ return+ }+ realtime.M.RecordEvent(e.Type)+ toMember(e.ChatSessionOwnerID, frameFor(e.ChatSessionOwnerID))+ return+ }+ if e.WorkspaceID == "" {+ return+ }+ if audience != nil {+ ctx, cancel := context.WithTimeout(context.Background(), audienceResolveTimeout)+ recipients, private, err := audience.Audience(ctx, e)+ cancel()+ if err != nil {+ logAudienceFailure(e, err)+ return+ }+ if private {+ realtime.M.RecordEvent(e.Type)+ for _, userID := range recipients {+ toMember(userID, frameFor(userID))+ }+ return+ }+ }+ realtime.M.RecordEvent(e.Type)+ readers := make([]string, 0, len(e.ToolDetailReaders))+ for userID, ok := range e.ToolDetailReaders {+ if ok {+ readers = append(readers, userID)+ }+ }+ sort.Strings(readers)+ // The full frames go first: a client that keeps the first copy of a seq,+ // as clients built before details_hidden do, then keeps the full one.+ for _, userID := range readers {+ toMember(userID, full)+ }+ b.BroadcastToWorkspace(e.WorkspaceID, stripped)+}++func taskMessageFrame(e events.Event, payload protocol.TaskMessagePayload) ([]byte, error) {+ return json.Marshal(map[string]any{"type": e.Type, "payload": payload, "actor_id": e.ActorID, "actor_type": e.ActorType})+}diff --git a/server/cmd/server/tool_details_realtime_test.go b/server/cmd/server/tool_details_realtime_test.gonew file mode 100644index 0000000000..b6c47b33f3--- /dev/null+++ b/server/cmd/server/tool_details_realtime_test.go@@ -0,0 +1,223 @@+package main++import (+ "context"+ "encoding/json"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/realtime"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++type stubAudience struct {+ recipients []string+ private bool+}++func (s stubAudience) Audience(context.Context, events.Event) ([]string, bool, error) {+ return s.recipients, s.private, nil+}+func (stubAudience) IssueRefReaders(context.Context, events.Event) (map[string]map[string]bool, error) {+ return nil, nil+}+func (stubAudience) Members(context.Context, string) ([]string, error) { return nil, nil }++const toolDetailsWS = "ws-1"++func restrictedToolEvent(chatOwner string) events.Event {+ e := events.Event{+ Type: protocol.EventTaskMessage,+ WorkspaceID: toolDetailsWS,+ ActorType: "system",+ TaskID: "task-1",+ Payload: protocol.TaskMessagePayload{+ TaskID: "task-1", Seq: 2, Type: "tool_use", Tool: "Bash",+ Input: map[string]any{"command": "cat ~/.ssh/config"},+ },+ ToolDetailsRestricted: true,+ ToolDetailReaders: map[string]bool{"owner": true, "admin": true},+ }+ if chatOwner != "" {+ e.ChatSessionID = "chat-1"+ e.ChatSessionOwnerID = chatOwner+ }+ return e+}++// frameDetails reads what a frame says about the tool call it carries.+func frameDetails(t *testing.T, frame []byte) (hidden bool, input map[string]any) {+ t.Helper()+ var msg struct {+ Payload protocol.TaskMessagePayload `json:"payload"`+ }+ if err := json.Unmarshal(frame, &msg); err != nil {+ t.Fatalf("decode frame: %v", err)+ }+ if msg.Payload.Tool != "Bash" || msg.Payload.Seq != 2 {+ t.Fatalf("frame lost the tool call itself: %+v", msg.Payload)+ }+ return msg.Payload.DetailsHidden, msg.Payload.Input+}++func memberFrames(fb *fakeBroadcaster) map[string][]byte {+ out := map[string][]byte{}+ for _, c := range fb.scopeCalls {+ if c.scopeType == realtime.ScopeWorkspaceMember {+ out[c.scopeID] = c.msg+ }+ }+ return out+}++func wantFull(t *testing.T, who string, frame []byte) {+ t.Helper()+ if frame == nil {+ t.Fatalf("%s got no frame", who)+ }+ if hidden, input := frameDetails(t, frame); hidden || input["command"] == nil {+ t.Errorf("%s may read the tool call but got hidden=%v input=%v", who, hidden, input)+ }+}++func wantStripped(t *testing.T, who string, frame []byte) {+ t.Helper()+ if frame == nil {+ t.Fatalf("%s got no frame", who)+ }+ if hidden, input := frameDetails(t, frame); !hidden || input != nil {+ t.Errorf("%s may not read the tool call but got hidden=%v input=%v", who, hidden, input)+ }+}++func TestRestrictedToolCallReachesTheWorkspaceWithoutItsDetails(t *testing.T) {+ for _, tc := range []struct {+ name string+ audience []privateProjectAudience+ }{+ {name: "no project audience"},+ {name: "a run outside private projects", audience: []privateProjectAudience{stubAudience{}}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb, tc.audience...)++ bus.Publish(restrictedToolEvent(""))++ if len(fb.workspaceCalls) != 1 {+ t.Fatalf("workspace frames = %d, want 1", len(fb.workspaceCalls))+ }+ wantStripped(t, "the workspace", fb.workspaceCalls[0].msg)+ frames := memberFrames(fb)+ if len(frames) != 2 {+ t.Fatalf("member frames = %d, want one per reader", len(frames))+ }+ wantFull(t, "the agent owner", frames[realtime.WorkspaceMemberScopeID(toolDetailsWS, "owner")])+ wantFull(t, "an admin", frames[realtime.WorkspaceMemberScopeID(toolDetailsWS, "admin")])+ })+ }+}++// sendOrder records which kind of frame went out in what order.+type sendOrder struct {+ *fakeBroadcaster+ sent []string+}++func (s *sendOrder) BroadcastToScope(scopeType, scopeID string, message []byte) {+ s.sent = append(s.sent, scopeType)+ s.fakeBroadcaster.BroadcastToScope(scopeType, scopeID, message)+}++func (s *sendOrder) BroadcastToWorkspace(workspaceID string, message []byte) {+ s.sent = append(s.sent, "workspace")+ s.fakeBroadcaster.BroadcastToWorkspace(workspaceID, message)+}++// Clients built before details_hidden keep the first copy of a seq, so a+// reader must get the full call before the stripped one.+func TestRestrictedToolCallReachesReadersBeforeTheWorkspace(t *testing.T) {+ bus := events.New()+ b := &sendOrder{fakeBroadcaster: &fakeBroadcaster{}}+ registerListeners(bus, b)++ bus.Publish(restrictedToolEvent(""))++ want := []string{realtime.ScopeWorkspaceMember, realtime.ScopeWorkspaceMember, "workspace"}+ if len(b.sent) != len(want) {+ t.Fatalf("sent %v, want %v", b.sent, want)+ }+ for i := range want {+ if b.sent[i] != want[i] {+ t.Fatalf("sent %v, want %v", b.sent, want)+ }+ }+}++func TestRestrictedToolCallInAPrivateProjectGoesToEachMemberOnce(t *testing.T) {+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb, stubAudience{recipients: []string{"owner", "member"}, private: true})++ bus.Publish(restrictedToolEvent(""))++ if len(fb.workspaceCalls) != 0 {+ t.Fatalf("a private project's run reached the workspace %d time(s)", len(fb.workspaceCalls))+ }+ frames := memberFrames(fb)+ if len(fb.scopeCalls) != 2 {+ t.Fatalf("member frames = %d, want 2 (admin is not in the project)", len(fb.scopeCalls))+ }+ wantFull(t, "the agent owner", frames[realtime.WorkspaceMemberScopeID(toolDetailsWS, "owner")])+ wantStripped(t, "a project member", frames[realtime.WorkspaceMemberScopeID(toolDetailsWS, "member")])+}++func TestRestrictedToolCallInAChatGoesToItsCreatorAsTheyMayReadIt(t *testing.T) {+ for _, tc := range []struct {+ creator string+ full bool+ }{{"member", false}, {"admin", true}} {+ t.Run(tc.creator, func(t *testing.T) {+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb, stubAudience{})++ bus.Publish(restrictedToolEvent(tc.creator))++ if len(fb.workspaceCalls) != 0 || len(fb.scopeCalls) != 1 {+ t.Fatalf("chat frame went to workspace=%d members=%d, want only its creator",+ len(fb.workspaceCalls), len(fb.scopeCalls))+ }+ frame := memberFrames(fb)[realtime.WorkspaceMemberScopeID(toolDetailsWS, tc.creator)]+ if tc.full {+ wantFull(t, "the chat creator", frame)+ } else {+ wantStripped(t, "the chat creator", frame)+ }+ })+ }+}++func TestRestrictedAgentsProseTakesTheOrdinaryRoute(t *testing.T) {+ bus := events.New()+ fb := &fakeBroadcaster{}+ registerListeners(bus, fb)++ e := restrictedToolEvent("")+ e.Payload = protocol.TaskMessagePayload{TaskID: "task-1", Seq: 3, Type: "thinking", Content: "reading the config"}+ bus.Publish(e)++ if len(fb.workspaceCalls) != 1 || len(fb.scopeCalls) != 0 {+ t.Fatalf("workspace=%d members=%d, want one workspace frame", len(fb.workspaceCalls), len(fb.scopeCalls))+ }+ var msg struct {+ Payload protocol.TaskMessagePayload `json:"payload"`+ }+ if err := json.Unmarshal(fb.workspaceCalls[0].msg, &msg); err != nil {+ t.Fatal(err)+ }+ if msg.Payload.Content != "reading the config" || msg.Payload.DetailsHidden {+ t.Errorf("reasoning was changed: %+v", msg.Payload)+ }+}diff --git a/server/internal/events/bus.go b/server/internal/events/bus.goindex e8c7f9b5ac..ed3dab5118 100644--- a/server/internal/events/bus.go+++ b/server/internal/events/bus.go@@ -40,6 +40,13 @@ type Event struct {// realtime layer delivers it only to that user's connections bound to// WorkspaceID.MemberPrivateUserID string++ // ToolDetailsRestricted marks a task:message from an agent that restricts+ // its tool inputs and outputs to ToolDetailReaders (user ids). Every other+ // recipient, and every consumer that cannot tell recipients apart, must+ // use protocol.TaskMessagePayload.WithoutToolDetails().+ ToolDetailsRestricted bool+ ToolDetailReaders map[string]bool}// Handler is a function that processes an event.diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 74d546c9e1..0d976d3a3d 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -135,7 +135,11 @@ type AgentResponse struct {// mirroring the existing mcp_config redaction contract.ComposioToolkitAllowlist []string `json:"composio_toolkit_allowlist,omitempty"`ComposioToolkitAllowlistRedacted bool `json:"composio_toolkit_allowlist_redacted,omitempty"`- OwnerID *string `json:"owner_id"`+ // ToolDetailsVisibility is who can read the inputs and outputs of the+ // agent's tool calls in its run logs: "everyone" who can see the run, or+ // "restricted" to the agent's owner and workspace owners/admins.+ ToolDetailsVisibility string `json:"tool_details_visibility"`+ OwnerID *string `json:"owner_id"`Skills []AgentSkillSummary `json:"skills"`DisabledRuntimeSkills []DisabledRuntimeSkill `json:"disabled_runtime_skills"`CreatedAt string `json:"created_at"`@@ -236,6 +240,7 @@ func (h *Handler) agentToResponse(a db.Agent) AgentResponse {ThinkingLevel: a.ThinkingLevel.String,ServiceTier: a.ServiceTier.String,ComposioToolkitAllowlist: composioAllowlist,+ ToolDetailsVisibility: a.ToolDetailsVisibility,OwnerID: uuidToPtr(a.OwnerID),Skills: []AgentSkillSummary{},DisabledRuntimeSkills: decodeDisabledRuntimeSkills(a.DisabledRuntimeSkills),@@ -1896,6 +1901,10 @@ type UpdateAgentRequest struct {// null" (a *[]string can't, because a nil pointer is the same wire// representation as both). MUL-3869.ComposioToolkitAllowlist *[]string `json:"composio_toolkit_allowlist"`+ // ToolDetailsVisibility is "everyone" or "restricted". Only a person may+ // change it: it decides who reads the agent's tool calls, so neither the+ // agent itself nor any other machine credential gets to widen that.+ ToolDetailsVisibility *string `json:"tool_details_visibility"`}// workspaceAlwaysRedactSecrets reports whether the workspace has opted@@ -2107,6 +2116,17 @@ func (h *Handler) UpdateAgent(w http.ResponseWriter, r *http.Request) {params := db.UpdateAgentParams{ID: existing.ID,}+ if req.ToolDetailsVisibility != nil {+ if !validToolDetailsVisibility(*req.ToolDetailsVisibility) {+ writeError(w, http.StatusBadRequest, `tool_details_visibility must be "everyone" or "restricted"`)+ return+ }+ if actorType, _ := h.resolveActor(r, requestUserID(r), uuidToString(existing.WorkspaceID)); isMachineCredentialActor(r) || actorType != "member" {+ writeError(w, http.StatusForbidden, "only a person can change who sees this agent's tool details")+ return+ }+ params.ToolDetailsVisibility = pgtype.Text{String: *req.ToolDetailsVisibility, Valid: true}+ }if req.Name != nil {params.Name = pgtype.Text{String: *req.Name, Valid: true}}diff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 1111770392..2089cc158b 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -6138,6 +6138,12 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {if task.ChatSessionID.Valid {chatSessionID = uuidToString(task.ChatSessionID)}+ // One indexed read per batch. A failed read restricts the batch to+ // nobody rather than guessing the agent allows everyone.+ audience, err := h.loadToolDetailsAudience(r.Context(), task.AgentID)+ if err != nil && !isNotFound(err) {+ slog.Warn("load tool details audience failed", "task_id", taskID, "error", err)+ }for _, m := range created {// The ordered CTE makes sqlc name the row type after the query// rather than reusing the table model; the columns are the table's,@@ -6149,8 +6155,10 @@ func (h *Handler) ReportTaskMessages(w http.ResponseWriter, r *http.Request) {ActorType: "system",TaskID: taskID,ChatSessionID: chatSessionID,- ChatSessionOwnerID: scope.ChatSessionOwnerID,- Payload: taskMessageToPayload(db.TaskMessage(m), taskID, uuidToString(task.IssueID)),+ ChatSessionOwnerID: scope.ChatSessionOwnerID,+ Payload: taskMessageToPayload(db.TaskMessage(m), taskID, uuidToString(task.IssueID)),+ ToolDetailsRestricted: audience.restricted,+ ToolDetailReaders: audience.readers,})}}@@ -6926,12 +6934,21 @@ func (h *Handler) ListTaskMessagesByUser(w http.ResponseWriter, r *http.Request)writeError(w, http.StatusInternalServerError, "failed to list task messages")return}+ audience, err := h.loadToolDetailsAudience(r.Context(), task.AgentID)+ if err != nil && !isNotFound(err) {+ writeError(w, http.StatusInternalServerError, "failed to list task messages")+ return+ }+ reader := ""+ if audience.restricted {+ reader = h.toolDetailsReader(r, middleware.WorkspaceIDFromContext(r.Context()))+ }issueID := uuidToString(task.IssueID)resp := make([]protocol.TaskMessagePayload, len(messages))for i, m := range messages {- resp[i] = taskMessageToPayload(m, taskID, issueID)+ resp[i] = audience.payloadFor(reader, taskMessageToPayload(m, taskID, issueID))}writeJSON(w, http.StatusOK, resp)diff --git a/server/internal/handler/plugin_action.go b/server/internal/handler/plugin_action.goindex c5b35e590d..d94764dc7b 100644--- a/server/internal/handler/plugin_action.go+++ b/server/internal/handler/plugin_action.go@@ -537,6 +537,13 @@ func (h *Handler) ListPluginTaskMessages(w http.ResponseWriter, r *http.Request)publicapiv1.WriteProblem(w, r, http.StatusInternalServerError, "internal_error", "failed to list task messages")return}+ // A plugin is code, not one of the people an agent's tool details are+ // restricted to, even when it acts for one of them.+ audience, err := h.loadToolDetailsAudience(r.Context(), task.AgentID)+ if err != nil && !isNotFound(err) {+ publicapiv1.WriteProblem(w, r, http.StatusInternalServerError, "internal_error", "failed to list task messages")+ return+ }includeThinking := r.URL.Query().Get("include") != "thinking=false"issueID := ""@@ -548,7 +555,7 @@ func (h *Handler) ListPluginTaskMessages(w http.ResponseWriter, r *http.Request)if !includeThinking && m.Type == "thinking" {continue}- resp = append(resp, taskMessageToPayload(m, taskID, issueID))+ resp = append(resp, audience.payloadFor("", taskMessageToPayload(m, taskID, issueID)))}writeJSON(w, http.StatusOK, map[string]any{"messages": resp})}diff --git a/server/internal/handler/plugin_task_messages_test.go b/server/internal/handler/plugin_task_messages_test.goindex f2646ae617..b25c13115f 100644--- a/server/internal/handler/plugin_task_messages_test.go+++ b/server/internal/handler/plugin_task_messages_test.go@@ -155,6 +155,40 @@ func TestPluginTaskMessagesReturnsTranscriptInSeqOrder(t *testing.T) {}}+// A plugin is not one of the people an agent's tool details are restricted to.+func TestPluginTaskMessagesWithholdRestrictedToolDetails(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ withPluginsV1Flag(t, testHandler, true)+ cleanupPluginInstallations(t)+ withCallbackTokens(t)+ installationID := installTaskReaderPlugin(t)++ taskID, _ := restrictedTranscript(t, "plugin-transcript-restricted")+ recorder := httptest.NewRecorder()+ testHandler.ListPluginTaskMessages(recorder, pluginTaskMessagesRequest(taskCallbackToken(t, installationID, ""), taskID, ""))+ if recorder.Code != http.StatusOK {+ t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())+ }+ var body struct {+ Messages []map[string]any `json:"messages"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &body); err != nil {+ t.Fatal(err)+ }+ if len(body.Messages) != 3 {+ t.Fatalf("messages = %d, want 3", len(body.Messages))+ }+ tool := body.Messages[1]+ if tool["tool"] != "fs_read" || tool["details_hidden"] != true || tool["input"] != nil || tool["output"] != nil {+ t.Errorf("tool call = %v, want its name without input or output", tool)+ }+ if body.Messages[0]["content"] != "planning the run" || body.Messages[2]["content"] != "done" {+ t.Errorf("reasoning or prose was withheld: %v", body.Messages)+ }+}+func TestPluginTaskMessagesIncludeThinkingFalseDropsThinking(t *testing.T) {if testHandler == nil {t.Skip("database not available")diff --git a/server/internal/handler/tool_details.go b/server/internal/handler/tool_details.gonew file mode 100644index 0000000000..167a7198f3--- /dev/null+++ b/server/internal/handler/tool_details.go@@ -0,0 +1,77 @@+package handler++import (+ "context"+ "net/http"++ "github.com/jackc/pgx/v5/pgtype"++ "github.com/multica-ai/multica/server/pkg/protocol"+)++// An agent's tool_details_visibility: who can read the inputs and outputs of+// the tool calls in its run logs.+const (+ toolDetailsEveryone = "everyone"+ toolDetailsRestricted = "restricted"+)++func validToolDetailsVisibility(v string) bool {+ return v == toolDetailsEveryone || v == toolDetailsRestricted+}++// toolDetailsAudience is who may read an agent's tool inputs and outputs.+type toolDetailsAudience struct {+ restricted bool+ // readers are the agent's owner and the workspace's owners and admins,+ // filled only when restricted.+ readers map[string]bool+}++// closedToolDetailsAudience is the answer when the audience cannot be read:+// restricted, with nobody allowed.+var closedToolDetailsAudience = toolDetailsAudience{restricted: true}++func (a toolDetailsAudience) allows(userID string) bool {+ return !a.restricted || (userID != "" && a.readers[userID])+}++// payloadFor returns the message as userID may read it.+func (a toolDetailsAudience) payloadFor(userID string, p protocol.TaskMessagePayload) protocol.TaskMessagePayload {+ if a.allows(userID) {+ return p+ }+ return p.WithoutToolDetails()+}++func (h *Handler) loadToolDetailsAudience(ctx context.Context, agentID pgtype.UUID) (toolDetailsAudience, error) {+ row, err := h.Queries.GetAgentToolDetailsReaders(ctx, agentID)+ if err != nil {+ return closedToolDetailsAudience, err+ }+ if row.ToolDetailsVisibility != toolDetailsRestricted {+ return toolDetailsAudience{}, nil+ }+ readers := make(map[string]bool, len(row.Readers))+ for _, id := range row.Readers {+ if id.Valid {+ readers[uuidToString(id)] = true+ }+ }+ return toolDetailsAudience{restricted: true, readers: readers}, nil+}++// toolDetailsReader is the user a run-log read is for, or "" when the caller+// is not a person allowed to be a reader: a machine credential, or an agent+// acting in the workspace. Tool details are for the people accountable for the+// agent, so a script or another agent reads the restricted view.+func (h *Handler) toolDetailsReader(r *http.Request, workspaceID string) string {+ if isMachineCredentialActor(r) {+ return ""+ }+ userID := requestUserID(r)+ if actorType, _ := h.resolveActor(r, userID, workspaceID); actorType != "member" {+ return ""+ }+ return userID+}diff --git a/server/internal/handler/tool_details_test.go b/server/internal/handler/tool_details_test.gonew file mode 100644index 0000000000..92ad839bbf--- /dev/null+++ b/server/internal/handler/tool_details_test.go@@ -0,0 +1,218 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"++ "github.com/multica-ai/multica/server/internal/events"+ "github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/testutil"+ db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol"+)++// restrictedTranscript seeds a run of an agent owned by a plain member, with+// the agent's tool details restricted.+func restrictedTranscript(t *testing.T, label string) (taskID, agentOwner string) {+ t.Helper()+ taskID, _ = seedTranscript(t, label)+ agentOwner = createTestUserAndMember(t, "member")+ dbfx.Exec(t, `UPDATE agent SET owner_id = $1, tool_details_visibility = 'restricted'+ WHERE id = (SELECT agent_id FROM agent_task_queue WHERE id = $2)`, agentOwner, taskID)+ // Runs before the user is deleted, which the agent would otherwise block.+ t.Cleanup(func() {+ dbfx.Exec(t, `UPDATE agent SET owner_id = $1 WHERE owner_id = $2`, testUserID, agentOwner)+ })+ return taskID, agentOwner+}++func readTranscript(t *testing.T, taskID, userID string, headers map[string]string) map[int]protocol.TaskMessagePayload {+ t.Helper()+ req := withURLParam(asUser(newRequest(http.MethodGet, "/api/tasks/"+taskID+"/messages", nil), userID), "taskId", taskID)+ for k, v := range headers {+ req.Header.Set(k, v)+ }+ req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{}))+ rec := httptest.NewRecorder()+ testHandler.ListTaskMessagesByUser(rec, req)+ if rec.Code != http.StatusOK {+ t.Fatalf("read transcript = %d %s", rec.Code, rec.Body.String())+ }+ var msgs []protocol.TaskMessagePayload+ if err := json.Unmarshal(rec.Body.Bytes(), &msgs); err != nil {+ t.Fatal(err)+ }+ bySeq := map[int]protocol.TaskMessagePayload{}+ for _, m := range msgs {+ bySeq[m.Seq] = m+ }+ return bySeq+}++func TestTaskMessagesHideToolDetailsOutsideTheAgentsAudience(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ taskID, agentOwner := restrictedTranscript(t, "tool-details-read")+ admin := createTestUserAndMember(t, "admin")+ member := createTestUserAndMember(t, "member")++ for _, tc := range []struct {+ name string+ userID string+ headers map[string]string+ full bool+ }{+ {name: "agent owner", userID: agentOwner, full: true},+ {name: "workspace owner", userID: testUserID, full: true},+ {name: "workspace admin", userID: admin, full: true},+ {name: "plain member", userID: member},+ {name: "an agent acting for the workspace owner", userID: testUserID,+ headers: map[string]string{"X-Actor-Source": "task_token", "X-Agent-ID": "00000000-0000-0000-0000-000000000001"}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ msgs := readTranscript(t, taskID, tc.userID, tc.headers)+ tool := msgs[2]+ if tool.Tool != "fs_read" || tool.Type != "tool_use" {+ t.Fatalf("tool call lost its identity: %+v", tool)+ }+ if tc.full {+ if tool.DetailsHidden || tool.Input["path"] != "/etc/hosts" || tool.Output == "" {+ t.Errorf("reader got %+v, want the whole tool call", tool)+ }+ } else if !tool.DetailsHidden || tool.Input != nil || tool.Output != "" {+ t.Errorf("non-reader got %+v, want the tool call without input or output", tool)+ }+ if msgs[1].Content != "planning the run" || msgs[3].Content != "done" {+ t.Errorf("reasoning or prose was hidden: thinking=%q text=%q", msgs[1].Content, msgs[3].Content)+ }+ })+ }++ dbfx.Exec(t, `UPDATE agent SET tool_details_visibility = 'everyone'+ WHERE id = (SELECT agent_id FROM agent_task_queue WHERE id = $1)`, taskID)+ if tool := readTranscript(t, taskID, member, nil)[2]; tool.DetailsHidden || tool.Input == nil {+ t.Errorf("an unrestricted agent hid its tool call from a member: %+v", tool)+ }+}++func TestReportTaskMessagesMarksRestrictedToolDetails(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ taskID, agentOwner := restrictedTranscript(t, "tool-details-event")+ admin := createTestUserAndMember(t, "admin")+ member := createTestUserAndMember(t, "member")++ var mu sync.Mutex+ var got []events.Event+ testHandler.Bus.Subscribe(protocol.EventTaskMessage, func(e events.Event) {+ if e.TaskID == taskID {+ mu.Lock()+ got = append(got, e)+ mu.Unlock()+ }+ })+ testutil.Call(t, testHandler.ReportTaskMessages, batchMessagesRequest(t, taskID, []any{+ map[string]any{"seq": 10, "type": "tool_use", "tool": "Bash", "input": map[string]any{"command": "env"}},+ })).Want(http.StatusOK)++ mu.Lock()+ defer mu.Unlock()+ if len(got) != 1 {+ t.Fatalf("published %d events, want 1", len(got))+ }+ e := got[0]+ if !e.ToolDetailsRestricted {+ t.Fatal("event from a restricted agent is not marked restricted")+ }+ for _, reader := range []string{agentOwner, testUserID, admin} {+ if !e.ToolDetailReaders[reader] {+ t.Errorf("reader %s missing from %v", reader, e.ToolDetailReaders)+ }+ }+ if e.ToolDetailReaders[member] {+ t.Errorf("plain member %s listed as a reader", member)+ }+ if p := e.Payload.(protocol.TaskMessagePayload); p.Input["command"] != "env" {+ t.Errorf("the event must carry the whole call for readers, got %+v", p)+ }+}++func updateToolDetails(t *testing.T, agentID, userID string, body any, headers map[string]string) *httptest.ResponseRecorder {+ t.Helper()+ req := withURLParam(asUser(newRequest(http.MethodPut, "/api/agents/"+agentID, body), userID), "id", agentID)+ for k, v := range headers {+ req.Header.Set(k, v)+ }+ req = req.WithContext(middleware.SetMemberContext(req.Context(), testWorkspaceID, db.Member{}))+ rec := httptest.NewRecorder()+ testHandler.UpdateAgent(rec, req)+ return rec+}++func TestUpdateAgentToolDetailsVisibility(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ agentOwner := createTestUserAndMember(t, "member")+ agentID := dbfx.Agent(t, "tool-details-settings agent", handlerTestRuntimeID(t), testutil.Cols{+ "owner_id": agentOwner, "custom_env": testutil.Raw("'{}'::jsonb"), "custom_args": testutil.Raw("'[]'::jsonb"),+ })+ t.Cleanup(func() {+ dbfx.Exec(t, `UPDATE agent SET owner_id = $1 WHERE owner_id = $2`, testUserID, agentOwner)+ })+ visibility := func() string {+ a, err := testHandler.Queries.GetAgent(context.Background(), parseUUID(agentID))+ if err != nil {+ t.Fatal(err)+ }+ return a.ToolDetailsVisibility+ }+ if v := visibility(); v != "everyone" {+ t.Fatalf("new agent tool_details_visibility = %q, want everyone", v)+ }++ rec := updateToolDetails(t, agentID, agentOwner, map[string]any{"tool_details_visibility": "restricted"}, nil)+ if rec.Code != http.StatusOK {+ t.Fatalf("owner update = %d %s", rec.Code, rec.Body.String())+ }+ var resp AgentResponse+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {+ t.Fatal(err)+ }+ if resp.ToolDetailsVisibility != "restricted" || visibility() != "restricted" {+ t.Fatalf("response=%q stored=%q, want restricted", resp.ToolDetailsVisibility, visibility())+ }++ admin := createTestUserAndMember(t, "admin")+ if rec := updateToolDetails(t, agentID, admin, map[string]any{"tool_details_visibility": "everyone"}, nil); rec.Code != http.StatusOK {+ t.Fatalf("admin update = %d %s", rec.Code, rec.Body.String())+ }++ for _, tc := range []struct {+ name string+ userID string+ value string+ headers map[string]string+ want int+ }{+ {name: "unknown value", userID: agentOwner, value: "owner_only", want: http.StatusBadRequest},+ {name: "plain member", userID: createTestUserAndMember(t, "member"), value: "restricted", want: http.StatusForbidden},+ {name: "agent credential", userID: agentOwner, value: "restricted", want: http.StatusForbidden,+ headers: map[string]string{"X-Actor-Source": "task_token", "X-Agent-ID": agentID}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ if rec := updateToolDetails(t, agentID, tc.userID, map[string]any{"tool_details_visibility": tc.value}, tc.headers); rec.Code != tc.want {+ t.Fatalf("update = %d %s, want %d", rec.Code, rec.Body.String(), tc.want)+ }+ if v := visibility(); v != "everyone" {+ t.Fatalf("refused update changed the setting to %q", v)+ }+ })+ }+}diff --git a/server/internal/integrations/telegram/outbound.go b/server/internal/integrations/telegram/outbound.goindex 1479688669..66742eb103 100644--- a/server/internal/integrations/telegram/outbound.go+++ b/server/internal/integrations/telegram/outbound.go@@ -407,6 +407,11 @@ func (o *Outbound) handleTaskMessage(e events.Event) {if !ok {return}+ // A chat is not one of the people the agent shows its tool details to,+ // whoever is in it: a step names the tool and nothing it was given.+ if e.ToolDetailsRestricted {+ payload = payload.WithoutToolDetails()+ }switch payload.Type {case "text":if payload.Content == "" {diff --git a/server/internal/integrations/telegram/outbound_progress_test.go b/server/internal/integrations/telegram/outbound_progress_test.goindex 6fa8b0fc74..82882b2d9f 100644--- a/server/internal/integrations/telegram/outbound_progress_test.go+++ b/server/internal/integrations/telegram/outbound_progress_test.go@@ -415,6 +415,23 @@ func TestStepForShowsArgumentsByModeAndChat(t *testing.T) {}}+// An agent that restricts its tool details shows a chat which tools ran and+// nothing they were given, even in the private chat that would show more.+func TestOutboundStepsOmitRestrictedToolDetails(t *testing.T) {+ h := newProgressHarness(t, channel.ChatTypeP2P)+ h.text("I will check the deploy config.")++ h.openEditSlot()+ frame := toolFrame(h.taskID, "exec_command", map[string]any{"command": "cat ~/.ssh/config"})+ frame.ToolDetailsRestricted = true+ h.o.handleTaskMessage(frame)++ want := "I will check the deploy config.\n\n<blockquote>💻 Running a command</blockquote>"+ if got := h.last(2); clockless(got.text) != want {+ t.Fatalf("step = %q\nwant %q", got.text, want)+ }+}+// A long command keeps both ends: what it is, and what it is aimed at.func TestStepForClipsALongCommandInTheMiddle(t *testing.T) {command := "go test -race -count=1 " + strings.Repeat("-tags=integration ", 5) + "./internal/integrations/telegram/..."diff --git a/server/internal/integrations/wecom/progress_rounds_test.go b/server/internal/integrations/wecom/progress_rounds_test.goindex c16d95d79f..fd265f3ff0 100644--- a/server/internal/integrations/wecom/progress_rounds_test.go+++ b/server/internal/integrations/wecom/progress_rounds_test.go@@ -48,6 +48,13 @@ import (type fakeIdentityLookup struct {bindings map[identityKey]db.ChannelUserBindingcalls int+ // toolDetails is what the agent says about its tool details; the zero+ // value is an agent that does not restrict them.+ toolDetails db.GetAgentToolDetailsReadersRow+}++func (f *fakeIdentityLookup) GetAgentToolDetailsReaders(context.Context, pgtype.UUID) (db.GetAgentToolDetailsReadersRow, error) {+ return f.toolDetails, nil}type identityKey struct {@@ -676,6 +683,16 @@ func TestAChatThatIsNotThePrincipalsShowsNoSteps(t *testing.T) {who: "an unknown sender",setUp: func(rig *progressRig) { delete(rig.identities.bindings, identityKey{rig.instID, bubbleSender}) },},+ {+ name: "the principal, for an agent that keeps its tool details from them",+ who: "a principal outside the agent's tool details audience",+ setUp: func(rig *progressRig) {+ rig.identities.toolDetails = db.GetAgentToolDetailsReadersRow{+ ToolDetailsVisibility: "restricted",+ Readers: []pgtype.UUID{{Bytes: [16]byte{9, 9, 9}, Valid: true}},+ }+ },+ },} {t.Run(tc.name, func(t *testing.T) {t.Parallel()@@ -694,6 +711,24 @@ func TestAChatThatIsNotThePrincipalsShowsNoSteps(t *testing.T) {}}+// An agent that restricts its tool details still shows them to the people it+// restricts them to, and a principal who is one of them keeps their steps.+func TestAPrincipalAllowedTheAgentsToolDetailsSeesSteps(t *testing.T) {+ t.Parallel()+ rig := newProgressRig(t)+ rig.identities.toolDetails = db.GetAgentToolDetailsReadersRow{+ ToolDetailsVisibility: "restricted",+ Readers: []pgtype.UUID{rig.installer},+ }+ rig.running(t, "REQ-A", "task-1")++ rig.toolCall(t, "task-1", "Read", map[string]any{"file_path": "/srv/app/handler.go"})++ if got := len(rig.refreshes(t)); got != 1 {+ t.Fatalf("a principal who may read the agent's tool details was shown %d step frames, want 1", got)+ }+}+// ---- decision 3: the audience is decided again for every round ----// levelFor's inputs can change between two questions in the same chat: adiff --git a/server/internal/integrations/wecom/progress_two_replica_db_test.go b/server/internal/integrations/wecom/progress_two_replica_db_test.goindex 5115db1e44..750daece2b 100644--- a/server/internal/integrations/wecom/progress_two_replica_db_test.go+++ b/server/internal/integrations/wecom/progress_two_replica_db_test.go@@ -37,6 +37,7 @@ import (type progressTurn struct {boundTurninstaller pgtype.UUID+ agent pgtype.UUIDsender stringpool *pgxpool.Pool@@ -50,8 +51,8 @@ func seedProgressTurn(t *testing.T, pool *pgxpool.Pool) *progressTurn {turn := &progressTurn{boundTurn: seedBoundTurn(t, pool), pool: pool}var workspaceID stringif err := pool.QueryRow(ctx,- `SELECT installer_user_id, workspace_id::text FROM channel_installation WHERE id = $1`,- turn.instID).Scan(&turn.installer, &workspaceID); err != nil {+ `SELECT installer_user_id, agent_id, workspace_id::text FROM channel_installation WHERE id = $1`,+ turn.instID).Scan(&turn.installer, &turn.agent, &workspaceID); err != nil {t.Fatalf("seed: read installation: %v", err)}turn.sender = "SENDER_" + strings.ReplaceAll(turn.chatID, "CHAT_", "")@@ -145,7 +146,7 @@ func (r *progressReplica) ask(t *testing.T, turn *progressTurn) {t.Fatalf("parse session: %v", err)}r.typing.OnIngested(context.Background(),- engine.ResolvedInstallation{ID: r.instID, InstallerUserID: turn.installer},+ engine.ResolvedInstallation{ID: r.instID, AgentID: turn.agent, InstallerUserID: turn.installer},channel.InboundMessage{Text: "S270 的价格",Source: channel.Source{ChannelType: TypeWecom, ChatID: turn.chatID, ChatType: channel.ChatTypeP2P, SenderID: turn.sender},diff --git a/server/internal/integrations/wecom/typing_indicator.go b/server/internal/integrations/wecom/typing_indicator.goindex 309a26897f..b07d0134ed 100644--- a/server/internal/integrations/wecom/typing_indicator.go+++ b/server/internal/integrations/wecom/typing_indicator.go@@ -14,6 +14,7 @@ import ("context""errors""log/slog"+ "slices""strings""time"@@ -78,11 +79,13 @@ type taskOrigin interface {}// identityLookup resolves the WeCom sender on an inbound message to the-// Multica user behind them. It answers the only question the step list's-// audience gate asks — is this person the bot's principal — and *db.Queries-// satisfies it with the row the identity resolver already reads.+// Multica user behind them, and says who the agent shows its tool details to.+// Those are the step list's audience gate — is this person the bot's+// principal, and may they read the agent's tool calls — and *db.Queries+// satisfies both.type identityLookup interface {GetChannelUserBindingByUserID(ctx context.Context, arg db.GetChannelUserBindingByUserIDParams) (db.ChannelUserBinding, error)+ GetAgentToolDetailsReaders(ctx context.Context, id pgtype.UUID) (db.GetAgentToolDetailsReadersRow, error)}// TypingIndicatorManager opens a streaming bubble per round when messages are@@ -365,6 +368,18 @@ func (m *TypingIndicatorManager) levelFor(ctx context.Context, inst engine.Resolif binding.MulticaUserID != inst.InstallerUserID {return progressLevelNone}+ // An agent that restricts its tool details shows them only to its owner+ // and the workspace's admins, and every step here is a tool call with its+ // argument, so the installer sees the steps only as one of those.+ audience, err := m.identities.GetAgentToolDetailsReaders(ctx, inst.AgentID)+ if err != nil {+ m.log.WarnContext(ctx, "wecom typing: cannot tell whether the agent restricts its tool details, showing no steps",+ "installation_id", util.UUIDToString(inst.ID), "error", err)+ return progressLevelNone+ }+ if audience.ToolDetailsVisibility == "restricted" && !slices.Contains(audience.Readers, inst.InstallerUserID) {+ return progressLevelNone+ }return progressLevelDetail}diff --git a/server/migrations/757_agent_tool_details_visibility.down.sql b/server/migrations/757_agent_tool_details_visibility.down.sqlnew file mode 100644index 0000000000..50f2acb66f--- /dev/null+++ b/server/migrations/757_agent_tool_details_visibility.down.sql@@ -0,0 +1 @@+ALTER TABLE agent DROP COLUMN IF EXISTS tool_details_visibility;diff --git a/server/migrations/757_agent_tool_details_visibility.up.sql b/server/migrations/757_agent_tool_details_visibility.up.sqlnew file mode 100644index 0000000000..3ec4e6dde0--- /dev/null+++ b/server/migrations/757_agent_tool_details_visibility.up.sql@@ -0,0 +1,7 @@+-- Who can read the inputs and outputs of an agent's tool calls in its run logs+-- (MUL-10284). 'everyone' is every member who can see the run, as before.+-- 'restricted' is the agent's owner and workspace owners/admins only; everyone+-- else still sees which tools ran and for how long. Values are checked by the+-- API, not a constraint, so a later value needs no table rewrite.+ALTER TABLE agent+ ADD COLUMN IF NOT EXISTS tool_details_visibility TEXT NOT NULL DEFAULT 'everyone';diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 8579b938b2..9132276391 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -122,7 +122,7 @@ func (q *Queries) AcknowledgeExhaustedDelegatedFailureRecovery(ctx context.Conteconst archiveAgent = `-- name: ArchiveAgent :oneUPDATE agent SET archived_at = now(), archived_by = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type ArchiveAgentParams struct {@@ -163,6 +163,7 @@ func (q *Queries) ArchiveAgent(ctx context.Context, arg ArchiveAgentParams) (Age&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -171,7 +172,7 @@ const archiveAgentsByIDs = `-- name: ArchiveAgentsByIDs :manyUPDATE agentSET archived_at = now(), archived_by = $1, updated_at = now()WHERE id = ANY($2::uuid[]) AND archived_at IS NULL-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type ArchiveAgentsByIDsParams struct {@@ -226,6 +227,7 @@ func (q *Queries) ArchiveAgentsByIDs(ctx context.Context, arg ArchiveAgentsByIDs&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -242,7 +244,7 @@ UPDATE agentSET archived_at = now(), archived_by = $1, updated_at = now()WHERE workspace_id = $2 AND owner_id = $3 AND archived_at IS NULLAND (system_key IS NULL OR system_key = '')-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type ArchiveAgentsByOwnerParams struct {@@ -296,6 +298,7 @@ func (q *Queries) ArchiveAgentsByOwner(ctx context.Context, arg ArchiveAgentsByO&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -312,7 +315,7 @@ UPDATE agentSET archived_at = now(), archived_by = $1, updated_at = now()WHERE runtime_id = ANY($2::uuid[]) AND archived_at IS NULLAND (system_key IS NULL OR system_key = '')-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type ArchiveAgentsByRuntimeParams struct {@@ -370,6 +373,7 @@ func (q *Queries) ArchiveAgentsByRuntime(ctx context.Context, arg ArchiveAgentsB&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -1928,7 +1932,7 @@ func (q *Queries) ClaimChatFinalizeDeferred(ctx context.Context, id pgtype.UUID)const clearAgentComposioToolkitAllowlist = `-- name: ClearAgentComposioToolkitAllowlist :oneUPDATE agent SET composio_toolkit_allowlist = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`// Explicit NULL-clear for composio_toolkit_allowlist. The COALESCE-based@@ -1970,6 +1974,7 @@ func (q *Queries) ClearAgentComposioToolkitAllowlist(ctx context.Context, id pgt&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -1977,7 +1982,7 @@ func (q *Queries) ClearAgentComposioToolkitAllowlist(ctx context.Context, id pgtconst clearAgentMcpConfig = `-- name: ClearAgentMcpConfig :oneUPDATE agent SET mcp_config = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agent, error) {@@ -2013,6 +2018,7 @@ func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agen&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -2020,7 +2026,7 @@ func (q *Queries) ClearAgentMcpConfig(ctx context.Context, id pgtype.UUID) (Agenconst clearAgentServiceTier = `-- name: ClearAgentServiceTier :oneUPDATE agent SET service_tier = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`// Explicit NULL-clear for service_tier. COALESCE-based UpdateAgent cannot@@ -2058,6 +2064,7 @@ func (q *Queries) ClearAgentServiceTier(ctx context.Context, id pgtype.UUID) (Ag&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -2065,7 +2072,7 @@ func (q *Queries) ClearAgentServiceTier(ctx context.Context, id pgtype.UUID) (Agconst clearAgentThinkingLevel = `-- name: ClearAgentThinkingLevel :oneUPDATE agent SET thinking_level = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`// Explicit NULL-clear for thinking_level. COALESCE-based UpdateAgent cannot@@ -2104,6 +2111,7 @@ func (q *Queries) ClearAgentThinkingLevel(ctx context.Context, id pgtype.UUID) (&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -2275,7 +2283,7 @@ INSERT INTO agent ($19::text[],COALESCE($20, 'private'))-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type CreateAgentParams struct {@@ -2355,6 +2363,7 @@ func (q *Queries) CreateAgent(ctx context.Context, arg CreateAgentParams) (Agent&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -2369,7 +2378,7 @@ INSERT INTO agent ('private', 'private', 1, $5, $6,'{}'::jsonb, '[]'::jsonb, $7, 'system', $8)-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type CreateAgentBuilderParams struct {@@ -2429,6 +2438,7 @@ func (q *Queries) CreateAgentBuilder(ctx context.Context, arg CreateAgentBuilder&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -3274,7 +3284,7 @@ INSERT INTO agent ($6, $7, $8, $9, $10,$11, '', '{}'::jsonb, '[]'::jsonb, 'user', $12)-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type CreateSystemUserAgentParams struct {@@ -3350,6 +3360,7 @@ func (q *Queries) CreateSystemUserAgent(ctx context.Context, arg CreateSystemUse&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -4088,7 +4099,7 @@ func (q *Queries) FailStaleTasks(ctx context.Context, arg FailStaleTasksParams)}const getAgent = `-- name: GetAgent :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE id = $1`@@ -4125,12 +4136,13 @@ func (q *Queries) GetAgent(ctx context.Context, id pgtype.UUID) (Agent, error) {&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}const getAgentBySystemKey = `-- name: GetAgentBySystemKey :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE workspace_id = $1 AND system_key = $2ORDER BY (archived_at IS NOT NULL) ASC, created_at ASC, id ASCLIMIT 1@@ -4181,12 +4193,13 @@ func (q *Queries) GetAgentBySystemKey(ctx context.Context, arg GetAgentBySystemK&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}const getAgentForClaimUpdate = `-- name: GetAgentForClaimUpdate :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE id = $1FOR UPDATE`@@ -4224,12 +4237,13 @@ func (q *Queries) GetAgentForClaimUpdate(ctx context.Context, id pgtype.UUID) (A&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}const getAgentForUpdate = `-- name: GetAgentForUpdate :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE id = $1FOR UPDATE`@@ -4269,12 +4283,13 @@ func (q *Queries) GetAgentForUpdate(ctx context.Context, id pgtype.UUID) (Agent,&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}const getAgentInWorkspace = `-- name: GetAgentInWorkspace :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE id = $1 AND workspace_id = $2 AND kind = 'user'`@@ -4316,6 +4331,7 @@ func (q *Queries) GetAgentInWorkspace(ctx context.Context, arg GetAgentInWorkspa&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -4614,6 +4630,37 @@ func (q *Queries) GetAgentTaskStatus(ctx context.Context, id pgtype.UUID) (GetAgreturn i, err}+const getAgentToolDetailsReaders = `-- name: GetAgentToolDetailsReaders :one+SELECT+ a.tool_details_visibility,+ CASE WHEN a.tool_details_visibility = 'restricted' THEN+ ARRAY(+ SELECT m.user_id FROM member m+ WHERE m.workspace_id = a.workspace_id AND m.role IN ('owner', 'admin')+ UNION+ SELECT a.owner_id WHERE a.owner_id IS NOT NULL+ )+ ELSE '{}'::uuid[] END::uuid[] AS readers+FROM agent a+WHERE a.id = $1+`++type GetAgentToolDetailsReadersRow struct {+ ToolDetailsVisibility string `json:"tool_details_visibility"`+ Readers []pgtype.UUID `json:"readers"`+}++// Who may read the inputs and outputs of the agent's tool calls. Readers is+// only filled when the agent restricts them: the agent's owner and the+// workspace's owners and admins. Read on every message batch a run reports,+// so it is one indexed lookup and costs nothing more for unrestricted agents.+func (q *Queries) GetAgentToolDetailsReaders(ctx context.Context, id pgtype.UUID) (GetAgentToolDetailsReadersRow, error) {+ row := q.db.QueryRow(ctx, getAgentToolDetailsReaders, id)+ var i GetAgentToolDetailsReadersRow+ err := row.Scan(&i.ToolDetailsVisibility, &i.Readers)+ return i, err+}+const getCommentThreadRootID = `-- name: GetCommentThreadRootID :oneSELECT comment_thread_root_id($1::uuid)::uuid AS id`@@ -5319,7 +5366,7 @@ func (q *Queries) LinkTaskToIssue(ctx context.Context, arg LinkTaskToIssueParams}const listActiveAgentsByRuntime = `-- name: ListActiveAgentsByRuntime :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE runtime_id = $1 AND archived_at IS NULL AND kind = 'user'ORDER BY name ASC`@@ -5369,6 +5416,7 @@ func (q *Queries) ListActiveAgentsByRuntime(ctx context.Context, runtimeID pgtyp&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -5381,7 +5429,7 @@ func (q *Queries) ListActiveAgentsByRuntime(ctx context.Context, runtimeID pgtyp}const listActiveAgentsByRuntimeForUpdate = `-- name: ListActiveAgentsByRuntimeForUpdate :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE runtime_id = $1 AND archived_at IS NULL AND kind = 'user'ORDER BY name ASCFOR UPDATE@@ -5433,6 +5481,7 @@ func (q *Queries) ListActiveAgentsByRuntimeForUpdate(ctx context.Context, runtim&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -5756,7 +5805,7 @@ func (q *Queries) ListAgentTasks(ctx context.Context, arg ListAgentTasksParams)}const listAgents = `-- name: ListAgents :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE workspace_id = $1 AND archived_at IS NULL AND kind = 'user'ORDER BY created_at ASC`@@ -5800,6 +5849,7 @@ func (q *Queries) ListAgents(ctx context.Context, workspaceID pgtype.UUID) ([]Ag&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -5812,7 +5862,7 @@ func (q *Queries) ListAgents(ctx context.Context, workspaceID pgtype.UUID) ([]Ag}const listAllAgents = `-- name: ListAllAgents :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE workspace_id = $1 AND kind = 'user'ORDER BY created_at ASC`@@ -5856,6 +5906,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -5868,7 +5919,7 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([}const listAllAgentsAnyKind = `-- name: ListAllAgentsAnyKind :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE workspace_id = $1ORDER BY created_at ASC`@@ -5922,6 +5973,7 @@ func (q *Queries) ListAllAgentsAnyKind(ctx context.Context, workspaceID pgtype.U&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -6037,7 +6089,7 @@ func (q *Queries) ListChatFinalizeDeferredExpired(ctx context.Context, arg ListC}const listNonOwnerAgentsByRuntime = `-- name: ListNonOwnerAgentsByRuntime :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE runtime_id = $1AND owner_id IS DISTINCT FROM $2AND NOT COALESCE(owner_id = ANY($3::uuid[]), false)@@ -6092,6 +6144,7 @@ func (q *Queries) ListNonOwnerAgentsByRuntime(ctx context.Context, arg ListNonOw&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -6104,7 +6157,7 @@ func (q *Queries) ListNonOwnerAgentsByRuntime(ctx context.Context, arg ListNonOw}const listNonOwnerAgentsByRuntimeForUpdate = `-- name: ListNonOwnerAgentsByRuntimeForUpdate :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE runtime_id = $1AND owner_id IS DISTINCT FROM $2AND NOT COALESCE(owner_id = ANY($3::uuid[]), false)@@ -6159,6 +6212,7 @@ func (q *Queries) ListNonOwnerAgentsByRuntimeForUpdate(ctx context.Context, arg&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -6898,7 +6952,7 @@ func (q *Queries) ListUserAgentIDsByRuntime(ctx context.Context, runtimeID pgtyp}const listUserAgentsByRuntimeForUpdate = `-- name: ListUserAgentsByRuntimeForUpdate :many-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE runtime_id = $1 AND kind = 'user'ORDER BY idFOR UPDATE@@ -6948,6 +7002,7 @@ func (q *Queries) ListUserAgentsByRuntimeForUpdate(ctx context.Context, runtimeI&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -7261,7 +7316,7 @@ func (q *Queries) ListWorkspaceWorkingAgents(ctx context.Context, arg ListWorksp}const lockAgentForAutopilotAssignment = `-- name: LockAgentForAutopilotAssignment :one-SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters FROM agent+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility FROM agentWHERE id = $1 AND workspace_id = $2 AND kind = 'user'FOR SHARE`@@ -7313,6 +7368,7 @@ func (q *Queries) LockAgentForAutopilotAssignment(ctx context.Context, arg LockA&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -8391,7 +8447,7 @@ SET runtime_id = $1,model = $3,updated_at = now()WHERE id = $4 AND kind = 'system' AND system_key LIKE 'agent_builder:%'-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type RebindAgentBuilderRuntimeParams struct {@@ -8455,6 +8511,7 @@ func (q *Queries) RebindAgentBuilderRuntime(ctx context.Context, arg RebindAgent&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -8862,7 +8919,7 @@ SET status = desired.status,updated_at = now()FROM desiredWHERE a.id = $1 AND a.status IS DISTINCT FROM desired.status-RETURNING a.id, a.workspace_id, a.name, a.avatar_url, a.runtime_mode, a.runtime_config, a.visibility, a.status, a.max_concurrent_tasks, a.owner_id, a.created_at, a.updated_at, a.description, a.runtime_id, a.instructions, a.archived_at, a.archived_by, a.custom_env, a.custom_args, a.mcp_config, a.model, a.thinking_level, a.composio_toolkit_allowlist, a.permission_mode, a.kind, a.system_key, a.disabled_runtime_skills, a.service_tier, a.conversation_starters+RETURNING a.id, a.workspace_id, a.name, a.avatar_url, a.runtime_mode, a.runtime_config, a.visibility, a.status, a.max_concurrent_tasks, a.owner_id, a.created_at, a.updated_at, a.description, a.runtime_id, a.instructions, a.archived_at, a.archived_by, a.custom_env, a.custom_args, a.mcp_config, a.model, a.thinking_level, a.composio_toolkit_allowlist, a.permission_mode, a.kind, a.system_key, a.disabled_runtime_skills, a.service_tier, a.conversation_starters, a.tool_details_visibility`// Persisted agent.status has no queued/resource-wait bucket. Keep dispatched@@ -8903,6 +8960,7 @@ func (q *Queries) RefreshAgentStatusFromTasks(ctx context.Context, id pgtype.UUI&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -9095,7 +9153,7 @@ func (q *Queries) RequeueAgentTaskAfterClaimFailure(ctx context.Context, arg Reqconst restoreAgent = `-- name: RestoreAgent :oneUPDATE agent SET archived_at = NULL, archived_by = NULL, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, error) {@@ -9131,6 +9189,7 @@ func (q *Queries) RestoreAgent(ctx context.Context, id pgtype.UUID) (Agent, erro&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -9465,7 +9524,7 @@ UPDATE agentSET owner_id = $1, updated_at = now()WHERE workspace_id = $2 AND owner_id = $3AND kind = 'user' AND system_key IS NOT NULL AND system_key <> ''-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type TransferProductAgentsOwnerParams struct {@@ -9518,6 +9577,7 @@ func (q *Queries) TransferProductAgentsOwner(ctx context.Context, arg TransferPr&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -9550,9 +9610,10 @@ UPDATE agent SETservice_tier = COALESCE($18, service_tier),conversation_starters = COALESCE($19, conversation_starters),composio_toolkit_allowlist = COALESCE($20::text[], composio_toolkit_allowlist),+ tool_details_visibility = COALESCE($21, tool_details_visibility),updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type UpdateAgentParams struct {@@ -9576,6 +9637,7 @@ type UpdateAgentParams struct {ServiceTier pgtype.Text `json:"service_tier"`ConversationStarters []byte `json:"conversation_starters"`ComposioToolkitAllowlist []string `json:"composio_toolkit_allowlist"`+ ToolDetailsVisibility pgtype.Text `json:"tool_details_visibility"`}// composio_toolkit_allowlist is set wholesale: the API layer is responsible@@ -9606,6 +9668,7 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agentarg.ServiceTier,arg.ConversationStarters,arg.ComposioToolkitAllowlist,+ arg.ToolDetailsVisibility,)var i Agenterr := row.Scan(@@ -9638,6 +9701,7 @@ func (q *Queries) UpdateAgent(ctx context.Context, arg UpdateAgentParams) (Agent&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -9646,7 +9710,7 @@ const updateAgentCustomEnv = `-- name: UpdateAgentCustomEnv :oneUPDATE agentSET custom_env = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type UpdateAgentCustomEnvParams struct {@@ -9692,6 +9756,7 @@ func (q *Queries) UpdateAgentCustomEnv(ctx context.Context, arg UpdateAgentCusto&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -9700,7 +9765,7 @@ const updateAgentDisabledRuntimeSkills = `-- name: UpdateAgentDisabledRuntimeSkiUPDATE agentSET disabled_runtime_skills = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type UpdateAgentDisabledRuntimeSkillsParams struct {@@ -9741,6 +9806,7 @@ func (q *Queries) UpdateAgentDisabledRuntimeSkills(ctx context.Context, arg Upda&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}@@ -9748,7 +9814,7 @@ func (q *Queries) UpdateAgentDisabledRuntimeSkills(ctx context.Context, arg Updaconst updateAgentStatus = `-- name: UpdateAgentStatus :oneUPDATE agent SET status = $2, updated_at = now()WHERE id = $1-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type UpdateAgentStatusParams struct {@@ -9789,6 +9855,7 @@ func (q *Queries) UpdateAgentStatus(ctx context.Context, arg UpdateAgentStatusPa&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,)return i, err}diff --git a/server/pkg/db/generated/models.go b/server/pkg/db/generated/models.goindex 2d2a2fc715..7301510bff 100644--- a/server/pkg/db/generated/models.go+++ b/server/pkg/db/generated/models.go@@ -54,6 +54,7 @@ type Agent struct {DisabledRuntimeSkills []byte `json:"disabled_runtime_skills"`ServiceTier pgtype.Text `json:"service_tier"`ConversationStarters []byte `json:"conversation_starters"`+ ToolDetailsVisibility string `json:"tool_details_visibility"`}type AgentApp struct {diff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 855bddaa5f..31cb3bc9ea 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -2149,7 +2149,7 @@ SET runtime_id = NULL, updated_at = now()WHERE runtime_id = $1AND owner_id IS DISTINCT FROM $2AND NOT COALESCE(owner_id = ANY($3::uuid[]), false)-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`type UnbindNonOwnerAgentsFromRuntimeParams struct {@@ -2199,6 +2199,7 @@ func (q *Queries) UnbindNonOwnerAgentsFromRuntime(ctx context.Context, arg Unbin&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}@@ -2236,7 +2237,7 @@ const unbindUserAgentsFromRuntime = `-- name: UnbindUserAgentsFromRuntime :manyUPDATE agentSET runtime_id = NULL, updated_at = now()WHERE runtime_id = $1 AND kind = 'user'-RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters+RETURNING id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier, conversation_starters, tool_details_visibility`// MUL-5559: the runtime-delete replacement for archive-then-hard-delete. Every@@ -2288,6 +2289,7 @@ func (q *Queries) UnbindUserAgentsFromRuntime(ctx context.Context, runtimeID pgt&i.DisabledRuntimeSkills,&i.ServiceTier,&i.ConversationStarters,+ &i.ToolDetailsVisibility,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 2f37ad68fe..5221aeba21 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -153,10 +153,29 @@ UPDATE agent SETservice_tier = COALESCE(sqlc.narg('service_tier'), service_tier),conversation_starters = COALESCE(sqlc.narg('conversation_starters'), conversation_starters),composio_toolkit_allowlist = COALESCE(sqlc.narg('composio_toolkit_allowlist')::text[], composio_toolkit_allowlist),+ tool_details_visibility = COALESCE(sqlc.narg('tool_details_visibility'), tool_details_visibility),updated_at = now()WHERE id = $1RETURNING *;+-- name: GetAgentToolDetailsReaders :one+-- Who may read the inputs and outputs of the agent's tool calls. Readers is+-- only filled when the agent restricts them: the agent's owner and the+-- workspace's owners and admins. Read on every message batch a run reports,+-- so it is one indexed lookup and costs nothing more for unrestricted agents.+SELECT+ a.tool_details_visibility,+ CASE WHEN a.tool_details_visibility = 'restricted' THEN+ ARRAY(+ SELECT m.user_id FROM member m+ WHERE m.workspace_id = a.workspace_id AND m.role IN ('owner', 'admin')+ UNION+ SELECT a.owner_id WHERE a.owner_id IS NOT NULL+ )+ ELSE '{}'::uuid[] END::uuid[] AS readers+FROM agent a+WHERE a.id = $1;+-- name: ClearAgentComposioToolkitAllowlist :one-- Explicit NULL-clear for composio_toolkit_allowlist. The COALESCE-based-- UpdateAgent cannot set the column back to NULL — sending an empty arraydiff --git a/server/pkg/protocol/messages.go b/server/pkg/protocol/messages.goindex 7e639fc329..110aba2506 100644--- a/server/pkg/protocol/messages.go+++ b/server/pkg/protocol/messages.go@@ -297,6 +297,26 @@ type TaskMessagePayload struct {// present as unknown rather than as complete.OutputTruncated *bool `json:"output_truncated,omitempty"`CreatedAt string `json:"created_at,omitempty"`+ // DetailsHidden reports that the agent restricts its tool inputs and+ // outputs and this reader is not allowed them: Input, Output and Content+ // were removed from this tool_use/tool_result, not empty to begin with.+ DetailsHidden bool `json:"details_hidden,omitempty"`+}++// WithoutToolDetails returns the message as a reader outside an agent's tool+// details audience gets it. A tool call keeps its name, identity and timing;+// its input, output and any text it carried are dropped. Prose, reasoning and+// errors are not tool details and pass through unchanged.+func (p TaskMessagePayload) WithoutToolDetails() TaskMessagePayload {+ if p.Type != "tool_use" && p.Type != "tool_result" {+ return p+ }+ p.Input = nil+ p.Output = ""+ p.Content = ""+ p.OutputTruncated = nil+ p.DetailsHidden = true+ return p}// DaemonRegisterPayload is sent from daemon to server on connection.diff --git a/server/pkg/publicapi/v1/openapi.yaml b/server/pkg/publicapi/v1/openapi.yamlindex 8aaf1df1df..7a534a54cc 100644--- a/server/pkg/publicapi/v1/openapi.yaml+++ b/server/pkg/publicapi/v1/openapi.yaml@@ -435,6 +435,12 @@ components:output: { type: string }output_truncated: { type: boolean }created_at: { type: string, format: date-time }+ details_hidden:+ type: boolean+ description: >-+ The agent restricts the inputs and outputs of its tool calls to its+ owner and workspace admins, so input, output and content were+ removed from this tool_use or tool_result.TaskMessageListResponse:type: objectrequired: [messages]