% Agent loop flowchart
% Requires: \usepackage{tikz}
% Requires: \usetikzlibrary{shapes.geometric, arrows.meta, positioning, calc}
\begin{tikzpicture}[
    >=Stealth,
    node distance=0.9cm and 1.2cm,
    process/.style={
        draw=blue!50,
        fill=blue!6,
        rounded corners=3pt,
        minimum width=2.6cm,
        minimum height=0.7cm,
        text centered,
        font=\small,
    },
    decision/.style={
        draw=blue!50,
        fill=blue!10,
        diamond,
        aspect=2.2,
        minimum width=2.0cm,
        minimum height=0.8cm,
        text centered,
        font=\small,
        inner sep=1pt,
    },
    startstop/.style={
        draw=gray!60,
        fill=gray!10,
        rounded corners=8pt,
        minimum width=2.2cm,
        minimum height=0.7cm,
        text centered,
        font=\small\bfseries,
    },
    arrow/.style={
        ->,
        thick,
        color=blue!50!black,
    },
    lbl/.style={
        font=\scriptsize,
        color=blue!60!black,
    },
]

% Nodes — top to bottom
\node[startstop] (start) {User Prompt};

\node[process, below=of start] (steering) {Check Steering};

\node[decision, below=of steering] (compact) {\shortstack{Compaction\\needed?}};

\node[process, below left=0.7cm and 1.5cm of compact] (docompact) {\shortstack{Safe-Boundary\\Compaction}};

\node[process, below=1.4cm of compact] (stream) {Provider Stream};

\node[process, below=of stream] (parse) {Parse Response};

\node[decision, below=of parse] (toolq) {Tool calls?};

\node[process, below=of toolq] (perm) {Permission Check};

\node[process, below=of perm] (exec) {Execute Tools};

\node[process, below=of exec] (hooks) {Fire Hooks};

\node[startstop, right=2.5cm of toolq] (result) {Yield Result};

% Arrows
\draw[arrow] (start) -- (steering);
\draw[arrow] (steering) -- (compact);

% Compaction branch
\draw[arrow] (compact) -- node[lbl, above] {yes} (docompact);
\draw[arrow] (docompact) |- (stream);
\draw[arrow] (compact) -- node[lbl, right] {no} (stream);

\draw[arrow] (stream) -- (parse);
\draw[arrow] (parse) -- (toolq);

% No tools -> yield result
\draw[arrow] (toolq) -- node[lbl, above] {no} (result);

% Yes tools -> permission check -> execute -> hooks
\draw[arrow] (toolq) -- node[lbl, right] {yes} (perm);
\draw[arrow] (perm) -- (exec);
\draw[arrow] (exec) -- (hooks);

% Loop back from hooks to stream
\draw[arrow] (hooks.west) -- ++(-1.8,0) |- (stream.west)
    node[lbl, pos=0.25, below] {next iteration};

\end{tikzpicture}
