The all-in-one local AI studio for your desktop: chat, image and video generation and a coding agent in one free, open source app. Windows and Linux. No Docker, no terminal, no cloud required.
TypeScript agentai-chatai-studioall-in-onecoding-agentdesktop-appfluximage-generationlinuxllmlocal-ailocal-llmopen-sourceprivacyself-hostedstable-diffusionuncensoreduncensored-aivideo-generationwindows
feat(commands): /goal keeps the objective, /loop keeps going until it is proven
purpled8d460419a45
diff --git a/src/components/chat/ChatInput.tsx b/src/components/chat/ChatInput.tsxindex 6a59411b..c8e669b4 100644--- a/src/components/chat/ChatInput.tsx+++ b/src/components/chat/ChatInput.tsx@@ -36,6 +36,8 @@ interface Props {* ModelSelector so the prompt window owns the model choice (web parity).*/composerModel?: ReactNode+ /** Rendered directly above the prompt box (the standing-goal bar). */+ composerAbove?: ReactNode/*** View-specific action buttons (Docs · Plugins · Tools) shown in the action* bar between Think and the model picker. Chat and Code pass different sets.@@ -56,7 +58,7 @@ function fileToImageAttachment(file: File): Promise<ImageAttachment> {})}-export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApprove, onReject, disabled, slashCommands, onAttachDocs, composerModel, composerActions }: Props) {+export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApprove, onReject, disabled, slashCommands, onAttachDocs, composerModel, composerActions, composerAbove }: Props) {const [input, setInput] = useState('')const [images, setImages] = useState<ImageAttachment[]>([])const [isDragOver, setIsDragOver] = useState(false)@@ -280,6 +282,10 @@ export function ChatInput({ onSend, onStop, isGenerating, pendingApproval, onApp</div>)}+ {/* The standing goal sits above everything else in the composer, so an+ instruction that steers every turn is never invisible. */}+ {composerAbove}+{/* Prompt area — hints, image previews, then the textarea (buttons livein the action bar below, web-parity two-row composer). */}<div className="px-3 pt-2.5">diff --git a/src/components/chat/ChatView.tsx b/src/components/chat/ChatView.tsxindex ebee4d04..7456f9eb 100644--- a/src/components/chat/ChatView.tsx+++ b/src/components/chat/ChatView.tsx@@ -15,6 +15,7 @@ import { useSettingsStore } from '../../stores/settingsStore'import { FileText, ChevronDown, Download, Wrench, Radio, RefreshCw, X } from 'lucide-react'import { PluginsDropdown } from './PluginsDropdown'import { ModelSelector } from '../models/ModelSelector'+import { GoalBar } from './GoalBar'import { MemoryDebugToggle } from './MemoryDebugPanel'import { TokenCounter } from './TokenCounter'import { ContextDropdown } from './ContextDropdown'@@ -338,6 +339,7 @@ export function ChatView() {slashCommands={isAgentActive}onAttachDocs={appMode !== 'cloud' ? () => setRagPanelOpen(true) : undefined}composerModel={<ModelSelector openUpward />}+ composerAbove={<GoalBar />}composerActions={<>{/* Documents (RAG) — local-embeddings only, so hide indiff --git a/src/components/chat/CodexView.tsx b/src/components/chat/CodexView.tsxindex 9abdf3aa..786c510c 100644--- a/src/components/chat/CodexView.tsx+++ b/src/components/chat/CodexView.tsx@@ -12,6 +12,7 @@ import { SmallModelModeToggle } from './SmallModelModeToggle'import { RealtimeCounter } from './RealtimeCounter'import { PluginsDropdown } from './PluginsDropdown'import { ModelSelector } from '../models/ModelSelector'+import { GoalBar } from './GoalBar'import { TypingIndicator } from './TypingIndicator'import { useSettingsStore } from '../../stores/settingsStore'import { useModelStore } from '../../stores/modelStore'@@ -490,6 +491,7 @@ export function CodexView() {isGenerating={isRunning}slashCommandscomposerModel={<ModelSelector openUpward surface="code" />}+ composerAbove={<GoalBar />}composerActions={<PluginsDropdown openUpward />}/></div>diff --git a/src/components/chat/GoalBar.tsx b/src/components/chat/GoalBar.tsxnew file mode 100644index 00000000..58805f2a--- /dev/null+++ b/src/components/chat/GoalBar.tsx@@ -0,0 +1,40 @@+// The standing goal (/goal), shown above the composer in Code and in Agent.+//+// A persisted instruction that silently steers every turn is a trap: three days+// later nobody remembers why the agent keeps circling back to the same thing.+// So it is always on screen while it is in force, and always one click from+// gone.++import { X, Target } from 'lucide-react'+import { useAgentGoalStore } from '../../stores/agentGoalStore'+import { useChatStore } from '../../stores/chatStore'++export function GoalBar() {+ const activeConversationId = useChatStore((s) => s.activeConversationId)+ const goal = useAgentGoalStore((s) => (activeConversationId ? s.goals[activeConversationId] : undefined))+ const clearGoal = useAgentGoalStore((s) => s.clearGoal)++ if (!activeConversationId || !goal?.text) return null++ return (+ <div className="w-full max-w-[70%] mx-auto px-3 pb-1 flex justify-center">+ <div className="w-full flex items-center gap-1.5 px-2 py-1 rounded-md border border-purple-500/20 bg-purple-500/[0.04]">+ <Target size={9} className="text-purple-400 shrink-0" />+ <span className="text-[0.55rem] uppercase tracking-wider text-gray-500 shrink-0">goal</span>+ <span+ className="flex-1 min-w-0 truncate text-[0.6rem] text-gray-700 dark:text-gray-300"+ title={goal.text}+ >+ {goal.text}+ </span>+ <button+ onClick={() => clearGoal(activeConversationId)}+ title="Clear the goal for this session"+ className="flex items-center justify-center w-4 h-4 rounded text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-white/5 transition-colors shrink-0"+ >+ <X size={10} />+ </button>+ </div>+ </div>+ )+}diff --git a/src/components/layout/AppShell.tsx b/src/components/layout/AppShell.tsxindex 5750dd06..7b9f5557 100644--- a/src/components/layout/AppShell.tsx+++ b/src/components/layout/AppShell.tsx@@ -161,6 +161,8 @@ export function AppShell() {// retention line) claimed in its own comment that it survived an update// and did not, because it was never listed here.'lu_cloud_notice', 'locally-uncensored-model-health',+ // The standing goal (/goal) is per conversation and outlives a session.+ 'locally-uncensored-agent-goal',]const STORE_KEYS_SET = new Set(STORE_KEYS)// These two persist via idbStorage (IndexedDB) since v2.5.0 — the backupdiff --git a/src/hooks/useAgentChat.ts b/src/hooks/useAgentChat.tsindex 1690e0be..a0ead42b 100644--- a/src/hooks/useAgentChat.ts+++ b/src/hooks/useAgentChat.ts@@ -39,6 +39,7 @@ import { WorkflowEngine } from '../lib/workflow-engine'import type { AgentBlock, AgentToolCall, OllamaChatMessage } from '../types/agent-mode'import { selectRelevantToolsAsync } from '../lib/tool-selection'import { MUTATING_TOOLS } from '../lib/mutating-tools'+import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'import { generateEmbeddings } from '../api/rag'import { truncateToolResult } from '../lib/truncate-tool-result'import { budgetFromSettings } from '../api/agents/budget'@@ -459,6 +460,9 @@ export function useAgentChat() {: settings.smallModelMode? buildAgentSystemPromptLean(systemPrompt): buildAgentSystemPrompt(systemPrompt)+ // Standing goal (/goal) — same section Code injects, so the objective+ // survives a switch between the two surfaces.+ agentSystemPrompt += renderGoalSection(useAgentGoalStore.getState().getGoal(convId))// Multi-Repo (Sprint C #8): when the agent workspace has extra paths,// append a "Workspaces" section so the model can reference them bydiff --git a/src/hooks/useChat.ts b/src/hooks/useChat.tsindex 58bfb630..87f92701 100644--- a/src/hooks/useChat.ts+++ b/src/hooks/useChat.ts@@ -14,6 +14,7 @@ import { requestGenerationCancel } from "../api/vram-handoff"import { effectiveContextWindow } from "../lib/context-window"import { useAgentChat } from "./useAgentChat"import { parseAgentCommand } from '../lib/agent-commands'+import { applyGoalCommand } from '../lib/goal-command'import { useMemory } from "./useMemory"import { useAgentModeStore } from "../stores/agentModeStore"import { useGenerationStore } from "../stores/generationStore"@@ -77,6 +78,14 @@ export function useChat() {// text: there is no tool catalog there for the templates to drive.if (store.activeConversationId && useAgentModeStore.getState().isActive(store.activeConversationId)) {const slash = parseAgentCommand(content)+ if (slash?.command.handledLocally && slash.command.name === 'goal') {+ // Bookkeeping, not a prompt — never spend a round-trip on it.+ const convId = store.activeConversationId+ const res = applyGoalCommand(convId, slash.args)+ store.addMessage(convId, { id: uuid(), role: 'user', content, timestamp: Date.now() })+ store.addMessage(convId, { id: uuid(), role: 'assistant', content: res.message, timestamp: Date.now() })+ return+ }if (slash) {return agentChat.sendAgentMessage(slash.expanded, images, {displayContent: content,diff --git a/src/hooks/useCodex.ts b/src/hooks/useCodex.tsindex 1d8d2a57..5d98b6ef 100644--- a/src/hooks/useCodex.ts+++ b/src/hooks/useCodex.ts@@ -10,6 +10,8 @@ import { toolRegistry } from '../api/mcp'import { usePermissionStore } from '../stores/permissionStore'import { toolStrategyFor } from '../lib/tool-support'import { MUTATING_TOOLS } from '../lib/mutating-tools'+import { applyGoalCommand } from '../lib/goal-command'+import { useAgentGoalStore, renderGoalSection } from '../stores/agentGoalStore'import { CODEX_CONFIRM_TOOLS, codexConfirmEnabled } from './codexShellGate'import { buildHermesToolPrompt, buildHermesToolResult, parseHermesToolCalls, stripToolCallTags, hasToolCallTags } from '../api/hermes-tool-calling'import { chatNonStreaming } from '../api/agents'@@ -277,6 +279,19 @@ export function useCodex() {})}+ // `/goal` is bookkeeping, not a prompt. Handle it here and show the result;+ // every LATER turn picks the goal up from the system prompt below.+ if (slash?.command.handledLocally && slash.command.name === 'goal') {+ const res = applyGoalCommand(convId, slash.args)+ useChatStore.getState().addMessage(convId, {+ id: uuid(), role: 'user', content: rawInstruction, timestamp: Date.now(),+ })+ useChatStore.getState().addMessage(convId, {+ id: uuid(), role: 'assistant', content: res.message, timestamp: Date.now(),+ })+ return+ }+// Review Mode strips every mutating tool. A command whose whole job is to// change something would then run to completion narrating work it could not// do, with nothing on screen explaining why. Say it and stop.@@ -374,6 +389,9 @@ export function useCodex() {? `Working directory: ${workDir}\nUse paths relative to it (e.g. \`package.json\`); do not prefix with \`/\` or a drive letter.`: 'Working directory: your private sandbox folder. Use relative paths only (e.g. `package.json`, `.`); never a leading `/` or a drive letter like `C:\\`.'let systemPrompt = `${baseCodexPrompt}\n\n${workDirLine}`+ // Standing goal (/goal) — ahead of the rules and the repo map so it frames+ // everything that follows instead of reading as an afterthought.+ systemPrompt += renderGoalSection(useAgentGoalStore.getState().getGoal(convId))// Memory injection — parity with Chat + Agent. Codex was the only// surface that ignored the memory system; now it sees remembereddiff --git a/src/lib/__tests__/agent-commands.test.ts b/src/lib/__tests__/agent-commands.test.tsindex bb2beeee..f0d194e2 100644--- a/src/lib/__tests__/agent-commands.test.ts+++ b/src/lib/__tests__/agent-commands.test.ts@@ -10,6 +10,8 @@ import { MUTATING_TOOLS } from '../mutating-tools'// The 2.5.9 set. Kept as an explicit list rather than a count so a rename or an// accidental drop fails loudly instead of quietly changing a number.const EXPECTED = [+ // steer+ 'goal', 'loop',// understand'plan', 'explain', 'find', 'diff', 'log', 'todo',// change@@ -28,8 +30,11 @@ describe('AGENT_COMMANDS registry', () => {it('every command has a summary and a non-empty expansion', () => {for (const c of AGENT_COMMANDS) {expect(c.summary.length).toBeGreaterThan(5)- expect(c.build('').length).toBeGreaterThan(40)- expect(c.build('src/app.ts').length).toBeGreaterThan(40)+ // A locally-handled command's build() is a short marker the hook reads,+ // not a prompt, so it is exempt from the length floor.+ const floor = c.handledLocally ? 4 : 40+ expect(c.build('').length, c.name).toBeGreaterThan(floor)+ expect(c.build('src/app.ts').length, c.name).toBeGreaterThan(floor)}})@@ -38,12 +43,29 @@ describe('AGENT_COMMANDS registry', () => {expect(new Set(names).size).toBe(names.length)})- it('every command tells the model to act via tools', () => {+ it('every command that reaches a model tells it to act via tools', () => {for (const c of AGENT_COMMANDS) {- expect(c.build('')).toContain('Use your tools')+ if (c.handledLocally) continue+ expect(c.build(''), c.name).toContain('Use your tools')}})+ it('marks only /goal as handled locally', () => {+ // Everything else must reach a model; a second locally-handled command+ // would need its own branch in three hooks and would silently no-op if it+ // did not get one.+ expect(AGENT_COMMANDS.filter((c) => c.handledLocally).map((c) => c.name)).toEqual(['goal'])+ })++ it('/loop refuses to fake a green result', () => {+ const t = getAgentCommand('loop')!.build('make the tests pass')+ expect(t).toContain('Never loosen the check to make it pass')+ expect(t).toContain('never delete or skip a test to go green')+ // And it has to stop rather than spin: a loop with no exit burns a cloud+ // budget until the iteration cap saves it.+ expect(t).toContain('Stop EARLY')+ })+it('an argument the user typed always reaches the expansion', () => {// A template that silently drops its args looks like it worked and does the// wrong thing, which is worse than refusing.diff --git a/src/lib/__tests__/goal-command.test.ts b/src/lib/__tests__/goal-command.test.tsnew file mode 100644index 00000000..22bfff19--- /dev/null+++ b/src/lib/__tests__/goal-command.test.ts@@ -0,0 +1,95 @@+import { describe, it, expect, beforeEach, vi } from 'vitest'++// zustand/persist needs storage; vitest runs on `node`.+const store = new Map<string, string>()+vi.stubGlobal('localStorage', {+ getItem: (k: string) => store.get(k) ?? null,+ setItem: (k: string, v: string) => { store.set(k, v) },+ removeItem: (k: string) => { store.delete(k) },+ clear: () => { store.clear() },+})++import { applyGoalCommand } from '../goal-command'+import { useAgentGoalStore, renderGoalSection, MAX_GOAL_LENGTH } from '../../stores/agentGoalStore'++const CONV = 'conv-1'++beforeEach(() => {+ store.clear()+ useAgentGoalStore.setState({ goals: {} })+})++describe('/goal', () => {+ it('sets an objective and confirms it', () => {+ const r = applyGoalCommand(CONV, 'ship 2.5.9 with no regressions')+ expect(r.action).toBe('set')+ expect(r.message).toContain('ship 2.5.9 with no regressions')+ expect(useAgentGoalStore.getState().getGoal(CONV)?.text).toBe('ship 2.5.9 with no regressions')+ })++ it('reads the current goal back with no arguments', () => {+ applyGoalCommand(CONV, 'fix the flaky test')+ const r = applyGoalCommand(CONV, '')+ expect(r.action).toBe('read')+ expect(r.message).toContain('fix the flaky test')+ })++ it('says so when there is nothing to read', () => {+ const r = applyGoalCommand(CONV, '')+ expect(r.action).toBe('read')+ expect(r.message).toContain('No goal set')+ })++ it('clears on clear / off / none / reset', () => {+ for (const word of ['clear', 'off', 'none', 'reset']) {+ applyGoalCommand(CONV, 'something')+ const r = applyGoalCommand(CONV, word)+ expect(r.action, word).toBe('clear')+ expect(useAgentGoalStore.getState().getGoal(CONV)).toBeNull()+ }+ })++ it('clearing nothing is not reported as a change', () => {+ expect(applyGoalCommand(CONV, 'clear').action).toBe('noop')+ })++ it('replaces rather than appends', () => {+ applyGoalCommand(CONV, 'first')+ applyGoalCommand(CONV, 'second')+ expect(useAgentGoalStore.getState().getGoal(CONV)?.text).toBe('second')+ })++ it('keeps goals separate per conversation', () => {+ applyGoalCommand('a', 'goal A')+ applyGoalCommand('b', 'goal B')+ expect(useAgentGoalStore.getState().getGoal('a')?.text).toBe('goal A')+ expect(useAgentGoalStore.getState().getGoal('b')?.text).toBe('goal B')+ })++ it('truncates a runaway goal and says it did', () => {+ // A goal rides in EVERY later prompt, so an unbounded one quietly eats the+ // context window it was meant to help focus.+ const long = 'x'.repeat(MAX_GOAL_LENGTH + 200)+ const r = applyGoalCommand(CONV, long)+ expect(useAgentGoalStore.getState().getGoal(CONV)!.text.length).toBe(MAX_GOAL_LENGTH)+ expect(r.message).toContain('Trimmed')+ })+})++describe('renderGoalSection', () => {+ it('is empty when nothing is set, so callers can concatenate blindly', () => {+ expect(renderGoalSection(null)).toBe('')+ expect(renderGoalSection({ text: '', setAt: 0 })).toBe('')+ })++ it('carries the goal text and tells the model not to parrot it', () => {+ const out = renderGoalSection({ text: 'keep the build green', setAt: 0 })+ expect(out).toContain('keep the build green')+ expect(out).toContain('Do not announce the goal back to the user every turn')+ })++ it('lets an off-goal request through instead of redirecting it', () => {+ // A north star that hijacks unrelated questions is worse than no north star.+ expect(renderGoalSection({ text: 'g', setAt: 0 })).toContain('do the request anyway')+ })+})diff --git a/src/lib/agent-commands.ts b/src/lib/agent-commands.tsindex 48ca9460..bb556dab 100644--- a/src/lib/agent-commands.ts+++ b/src/lib/agent-commands.ts@@ -27,6 +27,14 @@ export interface AgentCommand {summary: string/** Argument hint shown after the name, e.g. "[file | \"changes\"]". */argHint?: string+ /**+ * True when the hook handles the command itself and never calls the model.+ * `/goal` is the only one: setting an objective is bookkeeping, and spending+ * a cloud round-trip to have a model acknowledge it would be theatre.+ * `build()` still returns text for these, used as the confirmation shown in+ * the transcript.+ */+ handledLocally?: true/*** True when the command must not touch anything. Enforced by the runner:* file_write / file_edit / shell_execute / code_execute / run_tests /@@ -46,6 +54,41 @@ const ACT = 'Use your tools to do this for real — do not just describe the steconst LOOK = 'Read the real code with file_read / file_list / file_search first — never answer from memory. You have no write or shell tools on this turn, so do not plan to use them.'export const AGENT_COMMANDS: AgentCommand[] = [+ // ── Steer ─────────────────────────────────────────────────────────────+ {+ name: 'goal',+ summary: 'Set the standing objective for this session',+ argHint: '[objective | "clear"]',+ handledLocally: true,+ // Never reaches a model. The hook writes agentGoalStore and prints this+ // confirmation; every later turn gets the goal in its system prompt.+ // build() is only the transcript line, so it is written for the USER.+ build: (a) => {+ const arg = a.trim()+ if (!arg) return 'goal: read'+ if (/^(clear|off|none|reset)$/i.test(arg)) return 'goal: clear'+ return `goal: set ${arg}`+ },+ },+ {+ name: 'loop',+ summary: 'Keep working until a finish condition is met',+ argHint: '<task, and how you will know it is done>',+ build: (a) => {+ const task = a.trim() || 'the task the user just described'+ return `Work on this until it is genuinely finished: ${task}++Run it as a loop, not a single pass:+1) Do the next concrete step.+2) VERIFY it — run the tests, the build, the command, whatever actually proves it. Reading your own change back is not verification.+3) If the check fails, fix the cause and go back to step 2.++Stop when the finish condition is met, and say which check proved it.++Stop EARLY and say so plainly if: the same fix fails twice in a row, the next step needs a decision only the user can make, or you would have to guess at something you cannot look up. A loop that reports honest failure after three rounds is worth more than one that keeps going and reports success it did not earn. Never loosen the check to make it pass, and never delete or skip a test to go green. ${ACT}`+ },+ },+// ── Understand ────────────────────────────────────────────────────────{name: 'plan',diff --git a/src/lib/goal-command.ts b/src/lib/goal-command.tsnew file mode 100644index 00000000..8b267231--- /dev/null+++ b/src/lib/goal-command.ts@@ -0,0 +1,53 @@+/**+ * `/goal` handling, shared by Code and Agent so the command behaves identically+ * in both. Kept out of agent-commands.ts, which is pure data by contract.+ *+ * Three shapes:+ * /goal <text> set it+ * /goal read it back+ * /goal clear drop it+ *+ * None of them call a model. Spending a cloud round-trip to have an LLM say+ * "ok, noted" would be theatre, and on a slow local model it would also be the+ * slowest possible way to write one string to a store.+ */++import { useAgentGoalStore, MAX_GOAL_LENGTH } from '../stores/agentGoalStore'++const CLEAR_WORDS = /^(clear|off|none|reset)$/i++export interface GoalCommandResult {+ /** What to show the user in the transcript. */+ message: string+ action: 'set' | 'read' | 'clear' | 'noop'+}++export function applyGoalCommand(conversationId: string, rawArgs: string): GoalCommandResult {+ const store = useAgentGoalStore.getState()+ const args = rawArgs.trim()++ if (!args) {+ const current = store.getGoal(conversationId)+ return current+ ? { action: 'read', message: `Current goal:\n\n${current.text}\n\nUse /goal clear to drop it, or /goal <new objective> to replace it.` }+ : { action: 'read', message: 'No goal set for this session. Use /goal <objective> to set one and it will steer every following turn.' }+ }++ if (CLEAR_WORDS.test(args)) {+ const had = store.getGoal(conversationId)+ if (!had) return { action: 'noop', message: 'There was no goal to clear.' }+ store.clearGoal(conversationId)+ return { action: 'clear', message: 'Goal cleared. Following turns go back to taking each request on its own.' }+ }++ store.setGoal(conversationId, args)+ const saved = store.getGoal(conversationId)+ const truncated = args.length > MAX_GOAL_LENGTH+ return {+ action: 'set',+ message:+ `Goal set:\n\n${saved?.text ?? args}\n\n` ++ (truncated ? `Trimmed to ${MAX_GOAL_LENGTH} characters so it fits in every prompt. ` : '') ++ 'Every following turn in this session will see it. /goal clear drops it.',+ }+}diff --git a/src/stores/agentGoalStore.ts b/src/stores/agentGoalStore.tsnew file mode 100644index 00000000..2472e103--- /dev/null+++ b/src/stores/agentGoalStore.ts@@ -0,0 +1,79 @@+/**+ * The standing objective for a conversation (2.5.9, `/goal`).+ *+ * A slash command is normally one prompt expansion and then it is gone, which+ * is fine for `/commit` and useless for "here is what we are actually trying to+ * achieve". Long agent runs drift: the model fixes the thing in front of it and+ * forgets what the work was for. A goal is stored per conversation, injected+ * into the system prompt on EVERY later turn in both Code and Agent, and shown+ * above the composer so it is never a hidden instruction the user forgot about.+ *+ * Persisted, because the drift it exists to stop happens across sessions too.+ */++import { create } from 'zustand'+import { persist } from 'zustand/middleware'++export interface AgentGoal {+ text: string+ setAt: number+}++interface AgentGoalState {+ goals: Record<string, AgentGoal>+ getGoal: (conversationId: string | null | undefined) => AgentGoal | null+ setGoal: (conversationId: string, text: string) => void+ clearGoal: (conversationId: string) => void+}++/** Keep a goal short enough to sit in every prompt without eating the budget. */+export const MAX_GOAL_LENGTH = 500++export const useAgentGoalStore = create<AgentGoalState>()(+ persist(+ (set, get) => ({+ goals: {},++ getGoal: (conversationId) => {+ if (!conversationId) return null+ return get().goals[conversationId] ?? null+ },++ setGoal: (conversationId, text) => {+ const trimmed = text.trim().slice(0, MAX_GOAL_LENGTH)+ if (!trimmed) return+ set((state) => ({+ goals: { ...state.goals, [conversationId]: { text: trimmed, setAt: Date.now() } },+ }))+ },++ clearGoal: (conversationId) =>+ set((state) => {+ if (!(conversationId in state.goals)) return state+ const next = { ...state.goals }+ delete next[conversationId]+ return { goals: next }+ }),+ }),+ { name: 'locally-uncensored-agent-goal' },+ ),+)++/**+ * The section appended to the system prompt. Empty string when no goal is set,+ * so callers can concatenate unconditionally.+ *+ * Worded so the goal STEERS without overriding the current instruction: a user+ * who asks something off-goal still gets an answer, they just get told it is+ * off-goal rather than silently redirected.+ */+export function renderGoalSection(goal: AgentGoal | null): string {+ if (!goal?.text) return ''+ return (+ `\n\n## Standing goal\n` ++ `The user set this objective for this session:\n\n${goal.text}\n\n` ++ `Keep it in view. When a step moves toward it, say which part it moved. ` ++ `If the current request pulls away from it, do the request anyway and note the tension in one line. ` ++ `Do not announce the goal back to the user every turn.`+ )+}