feat: add request-scoped context policies (#2914)

* feat: add request-scoped context policies

Add named turn profiles under agents.defaults so callers can opt into
per-request context and tool policies without changing default chat behavior.

Profiles can disable history, system context, skill prompts, or tools, and can
limit skills/tools with allow lists. Wire profile selection through Pico message
payloads, agent turn execution, Web chat selection, and Web visual config.

Reject invalid turn profiles before saving config through Web APIs and document
the new request context policy behavior.

* fix: address turn profile review blockers

* feat: simplify request context policy config

* fix: suppress tool prompt when turn tools are disabled

* fix: enforce turn profile tool restrictions
This commit is contained in:
lxowalle authored and GitHub committed 2026-05-22 10:06:40 +08:00
1 parent 5bbebb5fc8
commit 2992eccbf0
39 files changed
+3150 -162

No files matched your search

@@ -1,5 +1,5 @@
import { IconArrowUp, IconPhotoPlus, IconX } from "@tabler/icons-react"
import type { KeyboardEvent } from "react"
import { useRef, type KeyboardEvent as ReactKeyboardEvent } from "react"
import { useTranslation } from "react-i18next"
import TextareaAutosize from "react-textarea-autosize"
@@ -52,14 +52,25 @@ export function ChatComposer({
}: ChatComposerProps) {
const { t } = useTranslation()
const canInput = inputDisabledReason === null
const composingRef = useRef(false)
const disabledMessage =
inputDisabledReason === null
? null
: t(`chat.disabledPlaceholder.${inputDisabledReason}`)
const placeholder = disabledMessage ?? t("chat.placeholder")
const handleKeyDown = (e: KeyboardEvent<HTMLTextAreaElement>) => {
if (e.nativeEvent.isComposing) return
const handleKeyDown = (e: ReactKeyboardEvent<HTMLTextAreaElement>) => {
const nativeEvent = e.nativeEvent as Event & {
isComposing?: boolean
keyCode?: number
}
if (
composingRef.current ||
nativeEvent.isComposing ||
nativeEvent.keyCode === 229
) {
return
}
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault()
onSend()
@@ -98,6 +109,12 @@ export function ChatComposer({
<TextareaAutosize
value={input}
onChange={(e) => onInputChange(e.target.value)}
onCompositionStart={() => {
composingRef.current = true
}}
onCompositionEnd={() => {
composingRef.current = false
}}
onKeyDown={handleKeyDown}
placeholder={placeholder}
disabled={!canInput}
@@ -351,7 +351,7 @@ export function ChatPage() {
<div
ref={scrollRef}
onScroll={handleScroll}
className="min-h-0 flex-1 overflow-y-auto px-4 py-6 [scrollbar-gutter:stable] md:px-8 lg:px-24 xl:px-48"
className="min-h-0 flex-1 [scrollbar-gutter:stable] overflow-y-auto px-4 py-6 md:px-8 lg:px-24 xl:px-48"
>
<div className="mx-auto flex w-full max-w-250 flex-col gap-8 pb-8">
{messages.length === 0 && !isTyping && (
@@ -32,6 +32,7 @@ import {
EMPTY_LAUNCHER_FORM,
type LauncherForm,
type MCPServerForm,
type TurnProfileForm,
buildFormFromConfig,
parseCIDRText,
parseFloatField,
@@ -40,7 +41,6 @@ import {
parseMultilineList,
} from "@/components/config/form-model"
import { PageHeader } from "@/components/page-header"
import { Badge } from "@/components/ui/badge"
import {
AlertDialog,
AlertDialogAction,
@@ -52,6 +52,7 @@ import {
AlertDialogTitle,
AlertDialogTrigger,
} from "@/components/ui/alert-dialog"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { showSaveSuccessOrRestartToast } from "@/lib/restart-required"
import { refreshGatewayState } from "@/store/gateway"
@@ -71,6 +72,33 @@ function buildStringMapMergePatch(
return patch
}
function buildTurnProfilePatch(
profile: TurnProfileForm,
): Record<string, unknown> {
const result: Record<string, unknown> = {
enabled: profile.enabled,
history: { mode: profile.historyMode },
system_prompt: { mode: profile.systemPromptMode },
skills: { mode: profile.skillsMode },
tools: { mode: profile.toolsMode },
}
if (profile.skillsMode === "custom") {
result.skills = {
mode: "custom",
allow: parseMultilineList(profile.skillsAllowText),
}
}
if (profile.toolsMode === "custom") {
result.tools = {
mode: "custom",
allow: parseMultilineList(profile.toolsAllowText),
}
}
return result
}
export function ConfigPage() {
const { t } = useTranslation()
const queryClient = useQueryClient()
@@ -221,6 +249,13 @@ export function ConfigPage() {
)
}
const handleTurnProfileFieldChange = <K extends keyof TurnProfileForm>(
key: K,
value: TurnProfileForm[K],
) => {
updateField("turnProfile", { ...form.turnProfile, [key]: value })
}
const handleReset = () => {
setForm(baseline)
setLauncherForm(launcherBaseline)
@@ -314,6 +349,7 @@ export function ConfigPage() {
"Summarize token percent",
{ min: 1, max: 100 },
)
const turnProfile = buildTurnProfilePatch(form.turnProfile)
const heartbeatInterval = parseIntField(
form.heartbeatInterval,
"Heartbeat interval",
@@ -548,6 +584,7 @@ export function ConfigPage() {
max_tool_iterations: maxToolIterations,
summarize_message_threshold: summarizeMessageThreshold,
summarize_token_percent: summarizeTokenPercent,
turn_profile: turnProfile,
},
},
session: {
@@ -757,7 +794,11 @@ export function ConfigPage() {
disabled={saving || isLauncherLoading}
/>
<AgentDefaultsSection form={form} onFieldChange={updateField} />
<AgentDefaultsSection
form={form}
onFieldChange={updateField}
onTurnProfileFieldChange={handleTurnProfileFieldChange}
/>
<RuntimeSection form={form} onFieldChange={updateField} />
@@ -9,6 +9,8 @@ import {
type LauncherForm,
type MCPServerForm,
type MCPServerType,
type TurnProfileForm,
type TurnProfileMode,
} from "@/components/config/form-model"
import { Field, SwitchCardField } from "@/components/shared-form"
import { Button } from "@/components/ui/button"
@@ -66,13 +68,49 @@ function ConfigSectionCard({
interface AgentDefaultsSectionProps {
form: CoreConfigForm
onFieldChange: UpdateCoreField
onTurnProfileFieldChange: <K extends keyof TurnProfileForm>(
key: K,
value: TurnProfileForm[K],
) => void
}
export function AgentDefaultsSection({
form,
onFieldChange,
onTurnProfileFieldChange,
}: AgentDefaultsSectionProps) {
const { t } = useTranslation()
const renderModeSelect = ({
value,
onValueChange,
allowCustom,
}: {
value: TurnProfileMode
onValueChange: (mode: TurnProfileMode) => void
allowCustom: boolean
}) => (
<Select
value={value}
onValueChange={(next) => onValueChange(next as TurnProfileMode)}
>
<SelectTrigger className="h-9">
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="default">
{t("pages.config.turn_profile_mode_default")}
</SelectItem>
<SelectItem value="off">
{t("pages.config.turn_profile_mode_off")}
</SelectItem>
{allowCustom && (
<SelectItem value="custom">
{t("pages.config.turn_profile_mode_custom")}
</SelectItem>
)}
</SelectContent>
</Select>
)
return (
<ConfigSectionCard title={t("pages.config.sections.agent")}>
@@ -215,6 +253,116 @@ export function AgentDefaultsSection({
}
/>
</Field>
<Field
label={t("pages.config.turn_profile")}
hint={t("pages.config.turn_profile_hint")}
layout="setting-row"
controlClassName="md:max-w-[42rem]"
>
<div className="space-y-3">
<SwitchCardField
label={t("pages.config.turn_profile_enabled")}
hint={t("pages.config.turn_profile_enabled_hint")}
checked={form.turnProfile.enabled}
onCheckedChange={(checked) =>
onTurnProfileFieldChange("enabled", checked)
}
/>
<div className="grid gap-3 lg:grid-cols-2">
<div className="space-y-2">
<label className="text-sm font-medium">
{t("pages.config.turn_profile_history")}
</label>
{renderModeSelect({
value: form.turnProfile.historyMode,
onValueChange: (mode) =>
onTurnProfileFieldChange(
"historyMode",
mode === "off" ? "off" : "default",
),
allowCustom: false,
})}
<p className="text-muted-foreground text-xs leading-relaxed">
{t("pages.config.turn_profile_history_hint")}
</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">
{t("pages.config.turn_profile_system_prompt")}
</label>
{renderModeSelect({
value: form.turnProfile.systemPromptMode,
onValueChange: (mode) =>
onTurnProfileFieldChange(
"systemPromptMode",
mode === "off" ? "off" : "default",
),
allowCustom: false,
})}
<p className="text-muted-foreground text-xs leading-relaxed">
{t("pages.config.turn_profile_system_prompt_hint")}
</p>
</div>
<div className="space-y-2">
<label className="text-sm font-medium">
{t("pages.config.turn_profile_skills")}
</label>
{renderModeSelect({
value: form.turnProfile.skillsMode,
onValueChange: (mode) =>
onTurnProfileFieldChange("skillsMode", mode),
allowCustom: true,
})}
<p className="text-muted-foreground text-xs leading-relaxed">
{t("pages.config.turn_profile_skills_hint")}
</p>
{form.turnProfile.skillsMode === "custom" && (
<Textarea
value={form.turnProfile.skillsAllowText}
onChange={(e) =>
onTurnProfileFieldChange("skillsAllowText", e.target.value)
}
placeholder={t(
"pages.config.turn_profile_skills_allow_placeholder",
)}
className="min-h-20 font-mono text-xs"
/>
)}
</div>
<div className="space-y-2">
<label className="text-sm font-medium">
{t("pages.config.turn_profile_tools")}
</label>
{renderModeSelect({
value: form.turnProfile.toolsMode,
onValueChange: (mode) =>
onTurnProfileFieldChange("toolsMode", mode),
allowCustom: true,
})}
<p className="text-muted-foreground text-xs leading-relaxed">
{t("pages.config.turn_profile_tools_hint")}
</p>
{form.turnProfile.toolsMode === "custom" && (
<Textarea
value={form.turnProfile.toolsAllowText}
onChange={(e) =>
onTurnProfileFieldChange("toolsAllowText", e.target.value)
}
placeholder={t(
"pages.config.turn_profile_tools_allow_placeholder",
)}
className="min-h-20 font-mono text-xs"
/>
)}
</div>
</div>
</div>
</Field>
</ConfigSectionCard>
)
}
@@ -20,6 +20,7 @@ export interface CoreConfigForm {
maxToolIterations: string
summarizeMessageThreshold: string
summarizeTokenPercent: string
turnProfile: TurnProfileForm
dmScope: string
heartbeatEnabled: boolean
heartbeatInterval: string
@@ -43,6 +44,18 @@ export interface CoreConfigForm {
export type MCPServerType = "http" | "sse" | "stdio"
export type TurnProfileMode = "default" | "off" | "custom"
export interface TurnProfileForm {
enabled: boolean
historyMode: Exclude<TurnProfileMode, "custom">
systemPromptMode: Exclude<TurnProfileMode, "custom">
skillsMode: TurnProfileMode
skillsAllowText: string
toolsMode: TurnProfileMode
toolsAllowText: string
}
export interface MCPServerForm {
id: string
name: string
@@ -116,6 +129,15 @@ export const EMPTY_FORM: CoreConfigForm = {
maxToolIterations: "50",
summarizeMessageThreshold: "20",
summarizeTokenPercent: "75",
turnProfile: {
enabled: false,
historyMode: "default",
systemPromptMode: "default",
skillsMode: "default",
skillsAllowText: "",
toolsMode: "default",
toolsAllowText: "",
},
dmScope: "per-channel-peer",
heartbeatEnabled: true,
heartbeatInterval: "30",
@@ -222,6 +244,46 @@ function mapMCPServers(value: unknown): MCPServerForm[] {
})
}
function toTurnProfileMode(value: unknown): TurnProfileMode {
if (value === "off" || value === "custom") {
return value
}
return "default"
}
function toBasicTurnProfileMode(
value: unknown,
): Exclude<TurnProfileMode, "custom"> {
return value === "off" ? "off" : "default"
}
function allowListText(value: unknown): string {
if (!Array.isArray(value)) {
return ""
}
return value
.filter((item): item is string => typeof item === "string")
.join("\n")
}
function mapTurnProfile(value: unknown): TurnProfileForm {
const profile = asRecord(value)
const history = asRecord(profile.history)
const systemPrompt = asRecord(profile.system_prompt)
const skills = asRecord(profile.skills)
const tools = asRecord(profile.tools)
return {
enabled: asBool(profile.enabled),
historyMode: toBasicTurnProfileMode(history.mode),
systemPromptMode: toBasicTurnProfileMode(systemPrompt.mode),
skillsMode: toTurnProfileMode(skills.mode),
skillsAllowText: allowListText(skills.allow),
toolsMode: toTurnProfileMode(tools.mode),
toolsAllowText: allowListText(tools.allow),
}
}
export function buildFormFromConfig(config: unknown): CoreConfigForm {
const root = asRecord(config)
const agents = asRecord(root.agents)
@@ -310,6 +372,7 @@ export function buildFormFromConfig(config: unknown): CoreConfigForm {
defaults.summarize_token_percent,
EMPTY_FORM.summarizeTokenPercent,
),
turnProfile: mapTurnProfile(defaults.turn_profile),
dmScope: asString(session.dm_scope) || EMPTY_FORM.dmScope,
heartbeatEnabled:
heartbeat.enabled === undefined