mirror of
https://github.com/hanzoai/skills.git
synced 2026-11-19 00:47:36 +00:00
592 lines
48 KiB
HTML
592 lines
48 KiB
HTML
<!doctype html>
|
|
<html lang="en"><head>
|
|
<meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
<title>hip-0301</title>
|
|
<meta name="color-scheme" content="dark">
|
|
<style>
|
|
/* Committed to one visual world: a dark instrument panel. No light variant —
|
|
the dot field and the hairline rules only read on black, and a naive
|
|
inversion would wash both out. Every colour is painted explicitly so the page
|
|
never borrows a host background. */
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen';src:url('/fonts/Zen-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Variable.woff2') format('woff2');font-weight:100 900;font-style:normal;font-display:swap}
|
|
@font-face{font-family:'Zen Mono';src:url('/fonts/ZenMono-Italic-Variable.woff2') format('woff2');font-weight:100 900;font-style:italic;font-display:swap}
|
|
@font-face{font-family:'Zen Pixel Square';src:url('/fonts/ZenPixel-Square.woff2') format('woff2');font-style:normal;font-display:swap}
|
|
|
|
:root{
|
|
--ink:#f4f4f2; --soft:#9c9c98; --faint:#6a6a66; --ground:#000; --panel:#0a0a0a;
|
|
--line:#232323; --line-hi:#3a3a3a; --accent:#f4f4f2;
|
|
--font-zen-sans:'Zen',-apple-system,BlinkMacSystemFont,"Segoe UI",Helvetica,Arial,sans-serif;
|
|
--font-zen-mono:'Zen Mono',ui-monospace,"SF Mono",SFMono-Regular,Menlo,Consolas,monospace;
|
|
--font-zen-pixel-square:'Zen Pixel Square',monospace;
|
|
--mono:var(--font-zen-mono);
|
|
--sans:var(--font-zen-sans);
|
|
/* Controls are pills and surfaces are soft, as on hanzo.ai. */
|
|
--r:999px; --r-soft:14px;
|
|
}
|
|
*{box-sizing:border-box}
|
|
html{-webkit-text-size-adjust:100%}
|
|
body{margin:0;background:var(--ground);color:var(--ink);font-family:var(--sans);
|
|
font-size:16px;line-height:1.65;-webkit-font-smoothing:antialiased}
|
|
.wrap{max-width:60rem;margin:0 auto;padding:0 1.75rem}
|
|
|
|
/* The dot field. A halftone made of one repeating radial-gradient, faded out
|
|
along the diagonal by a mask so it reads as a wave rather than wallpaper. */
|
|
/* No overflow clip here: the dot field is inset to the box already, and a clip
|
|
would cut off the copy-prompt menu. */
|
|
.hero{position:relative;border-bottom:1px solid var(--line)}
|
|
.hero::before{content:"";position:absolute;inset:0;
|
|
background-image:radial-gradient(var(--line-hi) 1px, transparent 1px);
|
|
background-size:7px 7px;
|
|
-webkit-mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
mask-image:linear-gradient(115deg,#000 0%,rgba(0,0,0,.55) 38%,transparent 72%);
|
|
pointer-events:none}
|
|
.hero .wrap{position:relative;padding-top:5.5rem;padding-bottom:4rem}
|
|
|
|
nav{border-bottom:1px solid var(--line)}
|
|
nav .in{max-width:60rem;margin:0 auto;padding:1.1rem 1.75rem;display:flex;
|
|
justify-content:space-between;align-items:center;gap:1rem}
|
|
.brand{font-family:var(--mono);font-size:.85rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--ink);text-decoration:none;
|
|
display:inline-flex;align-items:center;gap:.6rem}
|
|
.brand i{font-style:normal;color:var(--faint)}
|
|
.mark{width:1.15em;height:1.15em;display:block;flex:0 0 auto}
|
|
nav a.up{font-family:var(--mono);font-size:.72rem;letter-spacing:.14em;
|
|
text-transform:uppercase;color:var(--soft);text-decoration:none}
|
|
nav a.up:hover{color:var(--ink)}
|
|
|
|
h1{font-family:var(--mono);font-size:clamp(2rem,5.4vw,3.4rem);line-height:1.12;
|
|
letter-spacing:-.02em;margin:0 0 1.1rem;font-weight:500;text-wrap:balance}
|
|
h1 em{font-style:normal;color:var(--faint)}
|
|
.lede{color:var(--soft);font-size:1.05rem;max-width:52ch;margin:0 0 2.25rem}
|
|
|
|
.btns{display:flex;flex-wrap:wrap;gap:.7rem;margin:0 0 .5rem;align-items:center}
|
|
.btn{display:inline-flex;align-items:center;gap:.5rem;font-family:var(--mono);
|
|
font-size:.72rem;letter-spacing:.14em;text-transform:uppercase;
|
|
padding:.8rem 1.4rem;border:1px solid var(--line-hi);border-radius:var(--r);
|
|
color:var(--ink);text-decoration:none;background:transparent;cursor:pointer;
|
|
line-height:1.2;font-weight:400}
|
|
.btn:hover{background:#141414;text-decoration:none;border-color:var(--soft)}
|
|
.btn.solid{background:var(--ink);color:#000;border-color:var(--ink)}
|
|
.btn.solid:hover{background:#d8d8d4}
|
|
.btn .chev{width:.7em;height:.7em;flex:0 0 auto;transition:transform .15s ease}
|
|
.btn[aria-expanded="true"] .chev{transform:rotate(180deg)}
|
|
|
|
/* Copy-prompt selector. Each row copies the prompt for its own target. */
|
|
.copy{position:relative;display:inline-flex}
|
|
.menu{position:absolute;top:calc(100% + .5rem);left:0;z-index:20;min-width:21rem;
|
|
background:var(--panel);border:1px solid var(--line-hi);border-radius:var(--r-soft);
|
|
padding:.4rem;display:flex;flex-direction:column;
|
|
box-shadow:0 12px 32px rgba(0,0,0,.75)}
|
|
.menu[hidden]{display:none}
|
|
.mi{display:flex;align-items:center;gap:.7rem;width:100%;text-align:left;
|
|
padding:.62rem .8rem;border:0;border-radius:calc(var(--r-soft) - .35rem);
|
|
background:transparent;color:var(--ink);font-family:var(--mono);font-size:.76rem;
|
|
letter-spacing:.04em;text-decoration:none;cursor:pointer;line-height:1.3;
|
|
white-space:nowrap}
|
|
.mi:hover,.mi:focus-visible{background:#181818;outline:none}
|
|
.mi .mark{width:1.05rem;height:1.05rem;color:var(--soft)}
|
|
.mi:hover .mark{color:var(--ink)}
|
|
.mi u{margin-left:auto;color:var(--faint);text-decoration:none;font-size:.68rem;
|
|
letter-spacing:.1em;text-transform:uppercase}
|
|
|
|
/* Works-with bar: one scrolling row, name and mark per agent. */
|
|
.strip{border-bottom:1px solid var(--line);background:var(--panel)}
|
|
.strip .in{max-width:60rem;margin:0 auto;padding:.9rem 1.75rem;display:flex;
|
|
align-items:center;gap:1.25rem;font-family:var(--mono);font-size:.72rem;
|
|
letter-spacing:.1em;text-transform:uppercase;color:var(--faint)}
|
|
.strip b{color:var(--soft);font-weight:400;flex:0 0 auto;
|
|
border-right:1px solid var(--line);padding-right:1.25rem;align-self:stretch;
|
|
display:flex;align-items:center}
|
|
.bar{display:flex;align-items:center;gap:.5rem;flex:1 1 auto;min-width:0;
|
|
overflow-x:auto;scrollbar-width:none;scroll-snap-type:x proximity;
|
|
-webkit-overflow-scrolling:touch;
|
|
-webkit-mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent);
|
|
mask-image:linear-gradient(90deg,#000 calc(100% - 3rem),transparent)}
|
|
.bar::-webkit-scrollbar{display:none}
|
|
.agent{display:inline-flex;align-items:center;gap:.45rem;flex:0 0 auto;
|
|
padding:.4rem .85rem;border:1px solid var(--line);border-radius:var(--r);
|
|
color:var(--soft);white-space:nowrap;scroll-snap-align:start;
|
|
text-decoration:none;background:var(--ground)}
|
|
.agent:hover{color:var(--ink);border-color:var(--line-hi);text-decoration:none}
|
|
.agent .mark{width:.95rem;height:.95rem}
|
|
|
|
h2{font-family:var(--mono);font-size:1.1rem;letter-spacing:-.01em;margin:2.75rem 0 .75rem;font-weight:500}
|
|
h3{font-size:1rem;margin:2rem 0 .5rem;font-weight:600}
|
|
h4,h5,h6{font-size:.94rem;margin:1.5rem 0 .5rem;font-weight:600}
|
|
p{margin:0 0 1rem;max-width:70ch}
|
|
ul,ol{margin:0 0 1rem;padding-left:1.35rem;max-width:70ch}
|
|
li{margin:.22rem 0}
|
|
a{color:var(--ink);text-decoration:underline;text-underline-offset:3px;
|
|
text-decoration-color:var(--line-hi)}
|
|
a:hover{text-decoration-color:var(--ink)}
|
|
a:focus-visible{outline:1px solid var(--ink);outline-offset:3px}
|
|
code{font-family:var(--mono);font-size:.85em;background:var(--panel);
|
|
border:1px solid var(--line);border-radius:5px;padding:.1em .36em}
|
|
pre{background:var(--panel);border:1px solid var(--line);padding:1rem 1.1rem;
|
|
border-radius:var(--r-soft);overflow-x:auto;margin:0 0 1.25rem}
|
|
pre code{background:none;border:0;padding:0;font-size:.82rem;line-height:1.7}
|
|
blockquote{margin:0 0 1rem;padding-left:1rem;border-left:1px solid var(--line-hi);color:var(--soft)}
|
|
hr{border:0;border-top:1px solid var(--line);margin:2.5rem 0}
|
|
table{border-collapse:collapse;width:100%;margin:0 0 1.25rem;font-size:.92rem;
|
|
display:block;overflow-x:auto}
|
|
th,td{border:1px solid var(--line);padding:.5rem .7rem;text-align:left}
|
|
|
|
.curl{display:block;background:var(--panel);border:1px solid var(--line);
|
|
border-radius:var(--r-soft);padding:.95rem 1.1rem;font-family:var(--mono);
|
|
font-size:.8rem;color:var(--soft);overflow-x:auto;margin:0 0 2.5rem;
|
|
white-space:pre;line-height:1.9}
|
|
.curl b{color:var(--ink);font-weight:400}
|
|
.curl i{font-style:normal;color:var(--faint)}
|
|
|
|
/* index */
|
|
#q{width:100%;padding:.85rem 1.2rem;font-family:var(--mono);font-size:.85rem;color:var(--ink);
|
|
background:var(--panel);border:1px solid var(--line);border-radius:var(--r);margin:0 0 .6rem}
|
|
#q::placeholder{color:var(--faint);text-transform:uppercase;letter-spacing:.1em;font-size:.72rem}
|
|
#q:focus{outline:none;border-color:var(--soft)}
|
|
#count{color:var(--faint);font-family:var(--mono);font-size:.72rem;letter-spacing:.1em;
|
|
text-transform:uppercase;margin:0 0 2rem}
|
|
.cat{margin:2.5rem 0 .5rem;font-family:var(--mono);font-size:.7rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);border-bottom:1px solid var(--line);
|
|
padding-bottom:.45rem}
|
|
.row{display:block;padding:.6rem .9rem;margin:0 -.9rem;border-bottom:1px solid var(--line);
|
|
border-radius:var(--r-soft);text-decoration:none}
|
|
.row:hover{background:#0a0a0a}
|
|
.nm{font-family:var(--mono);font-size:.84rem;color:var(--ink);display:block}
|
|
.ds{color:var(--soft);font-size:.9rem;display:block;margin-top:.12rem}
|
|
footer{margin-top:4rem;padding:2rem 0 4rem;border-top:1px solid var(--line);
|
|
color:var(--faint);font-size:.85rem}
|
|
footer a{color:var(--soft)}
|
|
.fmap{display:grid;gap:1.75rem;grid-template-columns:repeat(auto-fit,minmax(11rem,1fr));
|
|
margin:0 0 2rem;font-size:.85rem}
|
|
.fmap b{display:block;font-family:var(--mono);font-size:.68rem;letter-spacing:.16em;
|
|
text-transform:uppercase;color:var(--faint);font-weight:400;margin:0 0 .6rem;
|
|
border-bottom:1px solid var(--line);padding-bottom:.4rem}
|
|
.fmap a{display:inline-block;color:var(--ink);text-decoration:none;margin:.3rem .35rem 0 0}
|
|
.fmap a:hover{text-decoration:underline}
|
|
.fmap div{color:var(--faint);line-height:1.5}
|
|
.fend{border-top:1px solid var(--line);padding-top:1.25rem;font-size:.82rem}
|
|
|
|
@media (max-width:640px){
|
|
.hero .wrap{padding-top:3.25rem;padding-bottom:2.75rem}
|
|
.btns{gap:.5rem}
|
|
.btn{padding:.75rem 1.15rem;font-size:.68rem}
|
|
.copy,.copy .btn{width:100%;justify-content:center}
|
|
.menu{left:0;right:0;min-width:0}
|
|
.strip .in{flex-direction:column;align-items:flex-start;gap:.6rem;padding:.9rem 1.75rem}
|
|
.strip b{border-right:0;padding-right:0}
|
|
.bar{width:100%}
|
|
}
|
|
</style>
|
|
<link rel="alternate" type="text/markdown" href="/hip-0301.md">
|
|
|
|
<link rel="icon" href="/favicon.svg">
|
|
<link rel="canonical" href="https://hanzoskills.com/hip-0301">
|
|
</head>
|
|
<!-- Reading this with a machine? Every page here is also plain markdown.
|
|
This one: https://hanzoskills.com/hip-0301.md
|
|
Index: https://hanzoskills.com/llms.txt
|
|
Corpus: https://hanzoskills.com/all.md
|
|
Append .md to any path for the markdown twin. -->
|
|
<body>
|
|
<nav><div class="in">
|
|
<a class="brand" href="/"><svg class="mark" viewBox="0 0 67 67" fill="currentColor" aria-hidden="true"><path d="M22.21 67V44.6369H0V67H22.21Z"/><path d="M66.7038 22.3184H22.2534L0.0878906 44.6367H44.4634L66.7038 22.3184Z"/><path d="M22.21 0H0V22.3184H22.21V0Z"/><path d="M66.7198 0H44.5098V22.3184H66.7198V0Z"/><path d="M66.7198 67V44.6369H44.5098V67H66.7198Z"/></svg> HANZO<i>SKILLS</i></a>
|
|
<a class="up" href="/">All skills</a>
|
|
</div></nav>
|
|
|
|
<div class="wrap">
|
|
<h1>hip-0301</h1><p class="lede">HIP-301: Agent Runtime Protocols & Cross-Platform Parity. Status Final. Hanzo architectural specification.</p><h1>HIP-0301: Agent Runtime Protocols & Cross-Platform Parity</h1>
|
|
<h2>Abstract</h2>
|
|
<p>Standardize the agent runtime layer across all Hanzo platforms (Rust CLI/TUI, Python CLI/TUI, JS/TS CLI, Web UI, multi-channel bot). Covers protocol abstractions, MCP client transport, SSE parsing, hierarchical configuration, session compaction, OAuth PKCE, permission management, LSP integration, hook execution, sandboxing, input modes, git operations, multi-provider auth, agent subcommands, WebSocket bridging, Rust utility crates, package naming, and a cross-platform conformance test suite ensuring identical behavior across Python, Rust, and JS.</p>
|
|
<h2>Platforms</h2>
|
|
<p>| Platform | Package | Role | |----------|---------|------| | Rust CLI/TUI | @hanzo/dev (hanzo-dev crate) | Dev tool (native) | | Python CLI/TUI | hanzo-dev (PyPI) | Dev tool (Python) | | JS/TS CLI | @hanzo/dev (npm) | Dev tool (JS wrapper → Rust binary) | | LLM API Gateway | hanzo/cloud (Go, ZAP) | Model routing, IAM, billing, KMS | | PaaS | hanzo/platform | Deploy apps, databases, Docker | | Chat Web UI | hanzo/chat (React) | Browser chat interface | | Desktop App | hanzo/app (macOS) | AI command palette + local AI | | Component Lib | @hanzo/ui (React/Vue/Svelte) | 161+ UI components | | Multi-channel Bot | @hanzo/bot (Node.js) | 22 channels (WhatsApp, Slack, Discord, etc.) | | Python SDK | hanzoai (PyPI) | Core runtime, protocols, auth | | MCP Server | @hanzo/mcp (npm) + hanzo-mcp (PyPI) | Tool surface for AI assistants |</p>
|
|
<h2>Motivation</h2>
|
|
<p>Analysis of clean-room agent harness implementations revealed architectural patterns that improve testability, security, and extensibility of the SDK's agent runtime. These patterns address concrete gaps:</p>
|
|
<ol><li><strong>Stubbed MCP client</strong> - No JSON-RPC transport; tool listing returns empty</li><li><strong>Missing permission data model</strong> - No structured representation of allow/deny/prompt decisions</li><li><strong>No session compaction</strong> - Long-running agents hit context limits with no recovery</li><li><strong>Flat configuration</strong> - Single config source, no project-level overrides or MCP server discovery</li><li><strong>Basic SSE parsing</strong> - Frame boundaries split across chunk boundaries cause dropped events</li><li><strong>No PKCE</strong> - OAuth flow uses plain challenge method, violating OAuth 2.1</li><li><strong>No LSP integration</strong> - Agents lack IDE-quality code intelligence</li><li><strong>No hook system</strong> - No way to run pre/post checks on tool execution</li><li><strong>No sandboxing</strong> - Filesystem access is unrestricted</li><li><strong>No cross-platform conformance</strong> - Python, Rust, and JS implementations diverge silently</li></ol>
|
|
<h2>Specification</h2>
|
|
<h3>1. MCP Client Protocol</h3>
|
|
<p>JSON-RPC 2.0 client supporting stdio and HTTP transports for connecting to MCP tool servers.</p>
|
|
<pre><code class="lang-python">class McpConnection(Protocol):
|
|
"""Transport-agnostic MCP connection."""
|
|
|
|
async def send(self, request: JsonRpcRequest) -> JsonRpcResponse: ...
|
|
async def close(self) -> None: ...
|
|
|
|
class StdioMcpTransport:
|
|
"""Spawns MCP server as subprocess, communicates over stdin/stdout."""
|
|
|
|
def __init__(self, command: list[str], env: dict[str, str] | None = None): ...
|
|
async def connect(self) -> McpConnection: ...
|
|
|
|
class HttpMcpTransport:
|
|
"""Connects to MCP server over HTTP+SSE."""
|
|
|
|
def __init__(self, url: str, headers: dict[str, str] | None = None): ...
|
|
async def connect(self) -> McpConnection: ...</code></pre>
|
|
<p>Tool names from MCP servers are normalized to <code>mcp__<server>__<tool></code> to prevent collisions across servers. The client maintains a tool cache refreshed on <code>tools/list</code> responses, with cache invalidation on <code>notifications/tools/list_changed</code>.</p>
|
|
<p><strong>Key types:</strong></p>
|
|
<p>| Type | Description | |------|-------------| | <code>JsonRpcRequest</code> | <code>{jsonrpc: "2.0", method: str, params: dict, id: str}</code> | | <code>JsonRpcResponse</code> | <code>{jsonrpc: "2.0", result: Any, id: str}</code> or error variant | | <code>McpToolDefinition</code> | <code>{name: str, description: str, input_schema: dict}</code> | | <code>McpServerConfig</code> | <code>{command: list[str], env: dict, args: list[str]}</code> |</p>
|
|
<p><strong>Integration:</strong> The <code>McpConnection</code> protocol replaces the current stubbed <code>_mcp_client</code> attribute on <code>ApiClient</code>. Existing <code>tools/execute</code> calls route through the connection when the tool name matches the <code>mcp__</code> prefix pattern.</p>
|
|
<p><strong>Backwards compatibility:</strong> Tools without the <code>mcp__</code> prefix continue routing to the Hanzo API as before. The <code>McpConnection</code> protocol is optional; agents function without MCP servers configured.</p>
|
|
<h3>2. Protocol Abstractions</h3>
|
|
<p>Three core protocols enabling dependency injection and mock-based testing.</p>
|
|
<pre><code class="lang-python">class ToolExecutor(Protocol):
|
|
"""Executes a tool by name with given input."""
|
|
|
|
async def execute(
|
|
self, name: str, input: dict, session_id: str
|
|
) -> ToolResult: ...
|
|
|
|
class PermissionPrompter(Protocol):
|
|
"""Asks the user (or policy engine) for tool execution permission."""
|
|
|
|
async def request_permission(
|
|
self, tool_name: str, input: dict
|
|
) -> PermissionDecision: ...
|
|
|
|
class ApiClient(Protocol):
|
|
"""Sends messages to the model API and yields streaming responses."""
|
|
|
|
async def send_message(
|
|
self, messages: list[Message], tools: list[ToolDef]
|
|
) -> AsyncIterator[StreamEvent]: ...</code></pre>
|
|
<p><strong>Key types:</strong></p>
|
|
<p>| Type | Fields | |------|--------| | <code>ToolResult</code> | <code>{output: str, error: str \| None, is_error: bool}</code> | | <code>PermissionDecision</code> | <code>Allow \| Deny(reason: str) \| Escalate</code> | | <code>StreamEvent</code> | <code>ContentDelta \| ToolUse \| MessageStop \| Error</code> |</p>
|
|
<p><strong>Integration:</strong> The agent runtime loop accepts these protocols as constructor arguments instead of concrete implementations. Production code passes the real implementations; tests pass mocks.</p>
|
|
<p><strong>Backwards compatibility:</strong> Existing concrete classes implement these protocols implicitly via structural subtyping. No existing call sites change.</p>
|
|
<h3>3. SSE Parser Hardening</h3>
|
|
<p>Replace the current line-by-line SSE parser with a stateful frame buffer that handles chunk boundaries correctly.</p>
|
|
<pre><code class="lang-python">class SseFrameBuffer:
|
|
"""Accumulates raw bytes and yields complete SSE frames."""
|
|
|
|
def __init__(self) -> None:
|
|
self._buffer: str = ""
|
|
|
|
def feed(self, chunk: str) -> list[SseFrame]:
|
|
"""Feed a chunk of data, return any complete frames."""
|
|
self._buffer += chunk
|
|
frames: list[SseFrame] = []
|
|
while "\n\n" in self._buffer:
|
|
raw_frame, self._buffer = self._buffer.split("\n\n", 1)
|
|
frames.append(self._parse_frame(raw_frame))
|
|
return frames
|
|
|
|
@staticmethod
|
|
def _parse_frame(raw: str) -> SseFrame: ...</code></pre>
|
|
<p><strong>Key types:</strong></p>
|
|
<p>| Type | Fields | |------|--------| | <code>SseFrame</code> | <code>{event: str \| None, data: str, id: str \| None, retry: int \| None}</code> |</p>
|
|
<p><strong>Integration:</strong> Replaces the existing <code>_process_sse_line</code> method in <code>_streaming.py</code>. The <code>SseFrameBuffer</code> is instantiated per-request and fed raw chunks from the HTTP response body.</p>
|
|
<p><strong>Backwards compatibility:</strong> The public <code>Stream</code> and <code>AsyncStream</code> interfaces are unchanged. Only the internal parsing strategy changes.</p>
|
|
<h3>4. Hierarchical Configuration</h3>
|
|
<p>Three-tier configuration: User (<code>~/.config/hanzo/settings.json</code>) > Project (<code>.hanzo/settings.json</code>) > Local (<code>.hanzo/settings.local.json</code>). Lower tiers override higher. Local tier is gitignored.</p>
|
|
<pre><code class="lang-python">@dataclass(frozen=True)
|
|
class HanzoConfig:
|
|
"""Merged configuration from all tiers."""
|
|
|
|
api_key: str | None = None
|
|
model: str = "claude-sonnet-4-20250514"
|
|
mcp_servers: dict[str, McpServerConfig] = field(default_factory=dict)
|
|
permissions: dict[str, PermissionMode] = field(default_factory=dict)
|
|
custom_instructions: str = ""
|
|
|
|
def load_config(project_root: Path | None = None) -> HanzoConfig:
|
|
"""Load and merge configs: user < project < local."""
|
|
...</code></pre>
|
|
<p><strong>MCP server discovery:</strong> The <code>mcp_servers</code> field at each tier is merged by server name. A server defined in the project tier can be disabled in the local tier by setting <code>"disabled": true</code>.</p>
|
|
<p><strong>Sensitive fields:</strong> <code>api_key</code> and <code>oauth_credentials</code> can only be set in the user tier. Project and local tiers attempting to set these fields are ignored with a warning logged.</p>
|
|
<p><strong>Integration:</strong> <code>load_config()</code> is called once at agent startup. The resulting <code>HanzoConfig</code> is passed to the agent runtime constructor, replacing the current flat <code>os.environ</code>-based configuration.</p>
|
|
<p><strong>Backwards compatibility:</strong> Environment variables (<code>HANZO_API_KEY</code>, <code>HANZO_MODEL</code>) continue to work and take highest precedence. The config file tiers fill in values not set via environment.</p>
|
|
<h3>5. Session Compaction</h3>
|
|
<p>Token-budget-aware compaction that preserves the system prompt, recent messages, and a summary of compacted history.</p>
|
|
<pre><code class="lang-python">class SessionCompactor:
|
|
"""Compacts conversation history to fit within token budget."""
|
|
|
|
def __init__(self, max_tokens: int, reserve_recent: int = 3): ...
|
|
|
|
def compact(self, messages: list[Message]) -> list[Message]:
|
|
"""Return compacted message list fitting within max_tokens.
|
|
|
|
Strategy:
|
|
1. System prompt always preserved (index 0)
|
|
2. Last `reserve_recent` turns always preserved
|
|
3. Middle messages summarized into a single assistant message
|
|
4. Tool results in compacted range replaced with "[compacted]"
|
|
"""
|
|
...</code></pre>
|
|
<p><strong>Key types:</strong></p>
|
|
<p>| Type | Description | |------|-------------| | <code>Message</code> | Existing SDK message type with <code>role</code>, <code>content</code>, <code>token_count</code> | | <code>CompactionResult</code> | <code>{messages: list[Message], compacted_count: int, tokens_saved: int}</code> |</p>
|
|
<p><strong>Integration:</strong> The agent loop calls <code>compact()</code> before each API request when the total token count exceeds <code>max_tokens * 0.9</code>. The compaction summary is generated by the model itself via a dedicated summarization call, or falls back to truncation if the summarization call fails.</p>
|
|
<p><strong>Backwards compatibility:</strong> Compaction is opt-in. When <code>max_tokens</code> is not configured, the agent loop behaves as before with no compaction.</p>
|
|
<h3>6. OAuth PKCE</h3>
|
|
<p>S256 challenge method for the authorization code flow, with atomic credential persistence.</p>
|
|
<pre><code class="lang-python">class PkceChallenge:
|
|
"""PKCE S256 challenge for OAuth 2.1 compliance."""
|
|
|
|
verifier: str # 43-128 char random string, base64url-encoded
|
|
challenge: str # SHA-256 hash of verifier, base64url-encoded
|
|
|
|
@classmethod
|
|
def generate(cls) -> PkceChallenge:
|
|
"""Generate a new PKCE verifier/challenge pair."""
|
|
...
|
|
|
|
class OAuthFlow:
|
|
"""OAuth 2.1 authorization code flow with PKCE."""
|
|
|
|
def __init__(self, client_id: str, redirect_uri: str, token_url: str): ...
|
|
|
|
async def authorize(self, auth_url: str, scopes: list[str]) -> TokenResponse:
|
|
"""Run the full PKCE flow: generate challenge, open browser,
|
|
listen for callback, exchange code."""
|
|
...</code></pre>
|
|
<p><strong>Credential persistence:</strong> Tokens are written atomically (write to temp file, then <code>os.rename</code>) to <code>~/.config/hanzo/credentials.json</code> with <code>0600</code> permissions. Refresh token rotation is handled transparently.</p>
|
|
<p><strong>Integration:</strong> Replaces the plain challenge method in the existing <code>auth.py</code> module. The <code>OAuthFlow</code> class is used by <code>load_config()</code> when no API key is configured and interactive auth is available.</p>
|
|
<p><strong>Backwards compatibility:</strong> API key authentication continues to work and takes precedence. PKCE is only used for interactive OAuth flows.</p>
|
|
<h3>7. Permission Data Model</h3>
|
|
<p>Structured tracking of tool permission decisions with per-tool and per-server granularity.</p>
|
|
<pre><code class="lang-python">class PermissionMode(Enum):
|
|
ALLOW = "allow" # Execute without prompting
|
|
DENY = "deny" # Block execution, return denial message
|
|
PROMPT = "prompt" # Ask PermissionPrompter before execution
|
|
|
|
@dataclass
|
|
class PermissionRule:
|
|
tool_pattern: str # Glob pattern: "mcp__*", "fs.write", etc.
|
|
mode: PermissionMode
|
|
reason: str | None = None
|
|
|
|
class PermissionPolicy:
|
|
"""Evaluates permission rules for tool execution requests."""
|
|
|
|
def __init__(self, rules: list[PermissionRule]) -> None: ...
|
|
|
|
def evaluate(self, tool_name: str) -> PermissionMode:
|
|
"""Return the mode for a tool. First matching rule wins.
|
|
Default is PROMPT if no rules match."""
|
|
...</code></pre>
|
|
<p><strong>Audit trail:</strong> Every permission evaluation is logged as a structured record: <code>{timestamp, tool_name, mode, rule_matched, session_id}</code>. Denials include the denial reason.</p>
|
|
<p><strong>Integration:</strong> <code>PermissionPolicy</code> is constructed from the <code>permissions</code> field in <code>HanzoConfig</code> (Section 4). The agent loop calls <code>policy.evaluate(tool_name)</code> before executing any tool. When the result is <code>PROMPT</code>, the <code>PermissionPrompter</code> protocol (Section 2) is invoked.</p>
|
|
<p><strong>Backwards compatibility:</strong> When no permission rules are configured, all tools default to <code>PROMPT</code> mode, matching current behavior where the agent prompts before every tool execution.</p>
|
|
<h3>8. LSP Client</h3>
|
|
<p>Package: <code>hanzo-lsp</code>. Subprocess-based Language Server Protocol client providing code intelligence to the agent runtime.</p>
|
|
<pre><code class="lang-python">class LspClient:
|
|
"""Manages an LSP server subprocess and dispatches requests."""
|
|
|
|
def __init__(self, command: list[str], root_uri: str): ...
|
|
|
|
async def start(self) -> None:
|
|
"""Spawn the LSP server, send initialize/initialized."""
|
|
...
|
|
|
|
async def diagnostics(self, uri: str) -> list[Diagnostic]: ...
|
|
async def goto_definition(self, uri: str, line: int, col: int) -> Location | None: ...
|
|
async def find_references(self, uri: str, line: int, col: int) -> list[Location]: ...
|
|
async def hover(self, uri: str, line: int, col: int) -> str | None: ...
|
|
async def shutdown(self) -> None: ...</code></pre>
|
|
<p><strong>Key types:</strong></p>
|
|
<p>| Type | Fields | |------|--------| | <code>Diagnostic</code> | <code>{uri: str, range: Range, severity: int, message: str, source: str}</code> | | <code>Location</code> | <code>{uri: str, range: Range}</code> | | <code>Range</code> | <code>{start: Position, end: Position}</code> | | <code>Position</code> | <code>{line: int, character: int}</code> |</p>
|
|
<p><strong>Context enrichment:</strong> Diagnostics and hover info are injected into the system prompt as structured context before tool calls that read or edit files. This gives the agent IDE-quality awareness of type errors, unused imports, and symbol locations without requiring the user to paste compiler output.</p>
|
|
<p><strong>Integration:</strong> The <code>LspClient</code> is started lazily on first file-related tool use. The agent runtime detects the project language and spawns the appropriate server (e.g., <code>pyright</code> for Python, <code>rust-analyzer</code> for Rust, <code>typescript-language-server</code> for TS).</p>
|
|
<h3>9. Hook Runner</h3>
|
|
<p>Package: <code>hanzo-hooks</code>. Pre/post tool use hooks executed as shell scripts, enabling policy enforcement and side effects outside the agent loop.</p>
|
|
<pre><code class="lang-python">@dataclass
|
|
class HookConfig:
|
|
event: str # "pre_tool_use" | "post_tool_use"
|
|
command: str # Shell command to execute
|
|
tool_pattern: str # Glob pattern matching tool names
|
|
timeout_ms: int = 5000
|
|
|
|
class HookRunner:
|
|
"""Executes hooks before/after tool invocations."""
|
|
|
|
def __init__(self, hooks: list[HookConfig]): ...
|
|
|
|
async def run_pre(self, tool_name: str, input: dict) -> HookResult:
|
|
"""Run matching pre-hooks. Exit code semantics:
|
|
0 = allow, 2 = deny. Any other code = error (deny + log)."""
|
|
...
|
|
|
|
async def run_post(self, tool_name: str, input: dict, result: ToolResult) -> None:
|
|
"""Run matching post-hooks. Failures are logged, never block."""
|
|
...</code></pre>
|
|
<p><strong>Exit code semantics:</strong></p>
|
|
<p>| Exit Code | Meaning | |-----------|---------| | 0 | Allow - tool execution proceeds | | 2 | Deny - tool execution blocked, denial reason from stderr | | Other | Error - tool execution blocked, error logged |</p>
|
|
<p><strong>Environment:</strong> Hook scripts receive <code>HANZO_TOOL_NAME</code>, <code>HANZO_TOOL_INPUT</code> (JSON), and <code>HANZO_SESSION_ID</code> as environment variables. Post-hooks additionally receive <code>HANZO_TOOL_OUTPUT</code>.</p>
|
|
<p><strong>Integration:</strong> <code>HookRunner</code> is invoked by the agent loop between permission evaluation (Section 7) and actual tool execution. Pre-hook denial overrides an <code>ALLOW</code> permission decision. Hook configs are defined in <code>HanzoConfig.hooks</code> (Section 4).</p>
|
|
<h3>10. Sandbox</h3>
|
|
<p>Package: <code>hanzo-sandbox</code>. Container detection and filesystem isolation for tool execution.</p>
|
|
<pre><code class="lang-python">class IsolationMode(Enum):
|
|
OFF = "off" # No filesystem restrictions
|
|
WORKSPACE_ONLY = "workspace" # Restrict to project root
|
|
ALLOW_LIST = "allowlist" # Restrict to explicit paths
|
|
|
|
@dataclass
|
|
class SandboxConfig:
|
|
mode: IsolationMode = IsolationMode.WORKSPACE_ONLY
|
|
allowed_paths: list[str] = field(default_factory=list)
|
|
|
|
class Sandbox:
|
|
"""Filesystem isolation and container detection."""
|
|
|
|
def __init__(self, config: SandboxConfig, workspace: Path): ...
|
|
|
|
def check_path(self, path: Path) -> bool:
|
|
"""Return True if the path is allowed under current isolation mode."""
|
|
...
|
|
|
|
@staticmethod
|
|
def detect_container() -> str | None:
|
|
"""Detect container runtime. Returns 'docker', 'podman', 'k8s', or None."""
|
|
...</code></pre>
|
|
<p><strong>Container detection:</strong> Checks <code>/proc/1/cgroup</code>, <code>/.dockerenv</code>, <code>/run/.containerenv</code>, and <code>KUBERNETES_SERVICE_HOST</code> in order. When running inside a container, the default isolation mode is <code>OFF</code> (the container itself is the sandbox).</p>
|
|
<p><strong>Linux unshare:</strong> On Linux hosts (not in containers), <code>WORKSPACE_ONLY</code> mode uses <code>unshare(2)</code> to create a mount namespace with a read-only bind mount of <code>/</code> and a read-write bind mount of the workspace. This is a best-effort enhancement; the mode falls back to path checking when unshare is unavailable.</p>
|
|
<p><strong>Integration:</strong> <code>Sandbox.check_path()</code> is called by <code>ToolExecutor</code> before any filesystem operation. Path violations return a <code>ToolResult</code> with <code>is_error=True</code> and a message describing the denied path.</p>
|
|
<h3>11. Vim Keybindings</h3>
|
|
<p>Input mode system for the TUI, implementing a subset of Vim motions sufficient for efficient command-line editing.</p>
|
|
<p><strong>Modes:</strong></p>
|
|
<p>| Mode | Entry | Behavior | |------|-------|----------| | Insert | <code>i</code>, <code>a</code>, <code>o</code>, <code>A</code>, <code>I</code> from Normal | Characters inserted at cursor | | Normal | <code>Esc</code> from Insert | Motions and operators apply to buffer | | Visual | <code>v</code> from Normal | Selection between anchor and cursor | | Command | <code>:</code> from Normal | Ex-style commands (<code>:w</code>, <code>:q</code>, <code>:set</code>) |</p>
|
|
<p><strong>Supported motions:</strong> <code>h</code>, <code>j</code>, <code>k</code>, <code>l</code>, <code>w</code>, <code>b</code>, <code>e</code>, <code>0</code>, <code>$</code>, <code>^</code>, <code>gg</code>, <code>G</code>, <code>f<char></code>, <code>t<char></code>.</p>
|
|
<p><strong>Supported operators:</strong> <code>d</code> (delete), <code>c</code> (change), <code>y</code> (yank), <code>p</code>/<code>P</code> (paste). Operators compose with motions: <code>dw</code>, <code>ci"</code>, <code>yy</code>.</p>
|
|
<p><strong>Two-char sequences:</strong> <code>dd</code> (delete line), <code>yy</code> (yank line), <code>cc</code> (change line), <code>gg</code> (go to top). Handled via a pending-operator state machine with a 500ms timeout.</p>
|
|
<p><strong>Integration:</strong> The keybinding mode is configured in <code>HanzoConfig</code> as <code>input_mode: "vim" | "emacs" | "default"</code>. The TUI input handler dispatches to the appropriate mode handler. Vim mode state (current mode, register, pending operator) is per-input-widget.</p>
|
|
<h3>12. Git Slash Commands</h3>
|
|
<p>Built-in slash commands for common git workflows, executed as subprocess calls to <code>git</code>.</p>
|
|
<p>| Command | Behavior | |---------|----------| | <code>/branch <name></code> | <code>git checkout -b <name></code> from current HEAD | | <code>/commit</code> | Stage tracked changes, generate commit message from diff, <code>git commit</code> | | <code>/commit-push-pr</code> | <code>/commit</code> + <code>git push -u origin HEAD</code> + <code>gh pr create</code> | | <code>/worktree <name></code> | <code>git worktree add ../<repo>-<name> -b <name></code> | | <code>/diff</code> | <code>git diff</code> of staged + unstaged, injected as context | | <code>/stash</code> | <code>git stash push -m "hanzo: <timestamp>"</code> |</p>
|
|
<p><strong>Commit message generation:</strong> The diff output is sent to the model with a system prompt requesting a conventional-commit-formatted message. The user is shown the proposed message and can accept or edit before commit.</p>
|
|
<p><strong>Integration:</strong> Slash commands are registered in the agent's command table alongside tool-based commands. They do not go through the permission system (they are user-initiated, not agent-initiated).</p>
|
|
<h3>13. Multi-Provider Auth</h3>
|
|
<p>Unified authentication supporting multiple LLM providers with provider-specific OAuth flows.</p>
|
|
<pre><code class="lang-python">class AuthProvider(Enum):
|
|
ANTHROPIC = "anthropic" # PKCE authorization code
|
|
OPENAI = "openai" # Device code flow
|
|
HANZO = "hanzo" # PKCE authorization code via hanzo.id
|
|
|
|
@dataclass
|
|
class ProviderCredential:
|
|
provider: AuthProvider
|
|
access_token: str
|
|
refresh_token: str | None
|
|
expires_at: float
|
|
|
|
class CredentialStore:
|
|
"""Manages credentials for multiple providers."""
|
|
|
|
def __init__(self, path: Path = DEFAULT_CREDENTIALS_PATH): ...
|
|
|
|
def get(self, provider: AuthProvider) -> ProviderCredential | None: ...
|
|
def store(self, cred: ProviderCredential) -> None: ...
|
|
def refresh(self, provider: AuthProvider) -> ProviderCredential: ...</code></pre>
|
|
<p><strong>Auto-detect:</strong> When no explicit provider is configured, the auth system checks for credentials in order: Hanzo, Anthropic, OpenAI. The first valid credential wins.</p>
|
|
<p><strong>Credential storage:</strong> All credentials stored in <code>~/.config/hanzo/credentials.json</code> with <code>0600</code> permissions. Keyed by provider name. Atomic writes via temp file + <code>os.rename</code>.</p>
|
|
<p><strong>Integration:</strong> Extends the <code>OAuthFlow</code> from Section 6 with provider-specific endpoints and flow types. The <code>CredentialStore</code> replaces direct file reads in the current auth module.</p>
|
|
<h3>14. Agent Commands</h3>
|
|
<p>Slash commands that delegate to subagent instances with role-specific system prompts.</p>
|
|
<p>| Command | System Prompt Prefix | Behavior | |---------|---------------------|----------| | <code>/plan</code> | "You are a planning agent..." | Analyze task, produce step-by-step plan. No tool use. | | <code>/solve</code> | "You are a problem-solving agent..." | Reason through a problem. Read-only tool access. | | <code>/code</code> | "You are a coding agent..." | Implement changes. Full tool access. | | <code>/auto</code> | "You are an autonomous agent..." | Execute plan end-to-end. Full tool access + self-review. |</p>
|
|
<p><strong>Subagent lifecycle:</strong> Each command spawns a new agent loop with the specified system prompt prepended to the user's instruction. The subagent shares the parent's <code>HanzoConfig</code>, <code>PermissionPolicy</code>, and <code>HookRunner</code>. Conversation history is isolated; the subagent receives only the user's instruction and the current file context.</p>
|
|
<p><strong>Integration:</strong> Agent commands are registered as slash commands. The <code>/auto</code> command chains <code>/plan</code> then <code>/code</code> then <code>/solve</code> (for review) in sequence, passing each stage's output as context to the next.</p>
|
|
<h3>15. WebSocket DevBridge</h3>
|
|
<p>Go controller that bridges the hanzo/cloud web UI to the <code>hanzo-app-server</code> backend via WebSocket.</p>
|
|
<pre><code class="lang-go">type DevBridge struct {
|
|
Server *http.Server
|
|
AppAddr string // hanzo-app-server address
|
|
AllowOrigin []string // validated origins
|
|
}
|
|
|
|
func (b *DevBridge) HandleWS(w http.ResponseWriter, r *http.Request) {
|
|
// 1. Validate Origin header against AllowOrigin
|
|
// 2. Extract and verify JWT from Hanzo IAM
|
|
// 3. Upgrade to WebSocket
|
|
// 4. Bidirectional proxy: WS frames <-> app-server JSON-RPC
|
|
}</code></pre>
|
|
<p><strong>Auth:</strong> Every WebSocket connection requires a valid Hanzo IAM JWT. The <code>owner</code> claim scopes all downstream requests to the user's organization.</p>
|
|
<p><strong>Origin validation:</strong> The <code>Origin</code> header is checked against an explicit allow-list. Connections from unrecognized origins are rejected with 403.</p>
|
|
<p><strong>Protocol:</strong> Client sends JSON-RPC requests as WebSocket text frames. The bridge forwards to <code>hanzo-app-server</code> over HTTP, streams SSE responses back as WebSocket text frames. Binary frames are rejected.</p>
|
|
<p><strong>Integration:</strong> Deployed as a sidecar in the hanzo/cloud K8s pod. The web UI connects to the bridge instead of directly to the app server, gaining auth enforcement and origin validation.</p>
|
|
<h3>16. Rust Utility Crates</h3>
|
|
<p>Standalone Rust crates extracted from the hanzo-dev runtime for reuse across the ecosystem.</p>
|
|
<h4>hanzo-sse</h4>
|
|
<p>Zero-dependency SSE frame parser. Rust equivalent of Section 3.</p>
|
|
<pre><code class="lang-rust">pub struct SseFrameBuffer {
|
|
buffer: String,
|
|
}
|
|
|
|
impl SseFrameBuffer {
|
|
pub fn feed(&mut self, chunk: &str) -> Vec<SseFrame>;
|
|
}
|
|
|
|
pub struct SseFrame {
|
|
pub event: Option<String>,
|
|
pub data: String,
|
|
pub id: Option<String>,
|
|
pub retry: Option<u64>,
|
|
}</code></pre>
|
|
<h4>hanzo-backoff</h4>
|
|
<p>Overflow-safe exponential retry with jitter.</p>
|
|
<pre><code class="lang-rust">pub struct Backoff {
|
|
base_ms: u64,
|
|
max_ms: u64,
|
|
attempt: u32,
|
|
}
|
|
|
|
impl Backoff {
|
|
pub fn next_delay(&mut self) -> Duration;
|
|
pub fn reset(&mut self);
|
|
}</code></pre>
|
|
<p>Uses <code>saturating_mul</code> and <code>saturating_pow</code> to prevent overflow at high attempt counts. Jitter is full-jitter (uniform random in <code>[0, delay]</code>).</p>
|
|
<h4>hanzo-md-render</h4>
|
|
<p>Streaming Markdown renderer with syntax highlighting for TUI output.</p>
|
|
<pre><code class="lang-rust">pub struct MdRenderer {
|
|
theme: Theme,
|
|
}
|
|
|
|
impl MdRenderer {
|
|
pub fn render_chunk(&mut self, chunk: &str) -> Vec<StyledSpan>;
|
|
pub fn flush(&mut self) -> Vec<StyledSpan>;
|
|
}</code></pre>
|
|
<p>Handles incremental input: code fences are buffered until closed, then syntax-highlighted in a single pass. Inline formatting (bold, italic, code) is applied per-chunk.</p>
|
|
<h3>17. hanzo-dev Package Rename</h3>
|
|
<p>The <code>hanzo-repl</code> crate/package is renamed to <code>hanzo-dev</code> across all platforms to align with the <code>@hanzo/dev</code> naming convention.</p>
|
|
<p>| Before | After | |--------|-------| | <code>hanzo-repl</code> (crate) | <code>hanzo-dev</code> (crate) | | <code>hanzo-repl</code> (PyPI) | <code>hanzo-dev</code> (PyPI) | | <code>@hanzo/repl</code> (npm) | <code>@hanzo/dev</code> (npm) |</p>
|
|
<p><strong>Migration:</strong> The old package names are reserved and publish a single version that re-exports from the new name with a deprecation warning. The old names will be yanked after 90 days.</p>
|
|
<h3>18. Cross-Platform Parity</h3>
|
|
<p>Unified conformance test suite verifying that Python, Rust, and JS implementations produce identical results for core behaviors.</p>
|
|
<p><strong>Test domains:</strong></p>
|
|
<p>| Domain | What is verified | |--------|-----------------| | SSE parsing | Identical frame output for 50+ edge-case inputs (split chunks, empty data, multi-line data, BOM, retry fields) | | MCP normalization | Tool name <code>mcp__<server>__<tool></code> produced identically across platforms for the same server/tool input | | Permission policy | Same rule set produces same <code>evaluate()</code> result for same tool name across platforms | | Session compaction | Same message list + token budget produces same compacted output (modulo summary text) | | OAuth PKCE | Same verifier produces same S256 challenge across platforms | | Config loading | Same file hierarchy produces same merged <code>HanzoConfig</code> across platforms | | Backoff timing | Same attempt sequence produces same delay sequence (within jitter bounds) |</p>
|
|
<p><strong>Test format:</strong> Test vectors are stored as JSON files in <code>test-vectors/</code>. Each platform's test runner loads the same vectors and asserts identical output. The vectors are the source of truth; platform implementations conform to them.</p>
|
|
<p><strong>CI:</strong> A single CI job runs all three platform test suites against the shared vectors. A platform cannot merge if its output diverges from the vectors.</p>
|
|
<h2>Reference Implementation</h2>
|
|
<h3>Python SDK (<code>hanzoai</code> package, <code>python-sdk/pkg/hanzoai/</code>)</h3>
|
|
<p>| File | Component | |------|-----------| | <code>protocols.py</code> | <code>ToolExecutor</code>, <code>PermissionPrompter</code>, <code>ApiClient</code> protocols | | <code>mcp.py</code> | <code>McpConnection</code>, <code>StdioMcpTransport</code>, <code>HttpMcpTransport</code> | | <code>config.py</code> | <code>HanzoConfig</code>, <code>load_config()</code>, hierarchical merging | | <code>session.py</code> | <code>SessionCompactor</code>, compaction strategy | | <code>auth.py</code> | <code>PkceChallenge</code>, <code>OAuthFlow</code>, <code>CredentialStore</code> | | <code>_streaming.py</code> | <code>SseFrameBuffer</code> | | <code>permissions.py</code> | <code>PermissionMode</code>, <code>PermissionRule</code>, <code>PermissionPolicy</code> | | <code>lsp.py</code> | <code>LspClient</code> | | <code>hooks.py</code> | <code>HookRunner</code>, <code>HookConfig</code> | | <code>sandbox.py</code> | <code>Sandbox</code>, <code>SandboxConfig</code>, <code>IsolationMode</code> |</p>
|
|
<h3>Rust crates (<code>hanzo-dev</code> workspace)</h3>
|
|
<p>| Crate | Component | |-------|-----------| | <code>hanzo-dev</code> | TUI runtime, vim keybindings, slash commands, agent commands | | <code>hanzo-sse</code> | <code>SseFrameBuffer</code> | | <code>hanzo-backoff</code> | <code>Backoff</code> | | <code>hanzo-md-render</code> | <code>MdRenderer</code> | | <code>hanzo-lsp</code> | <code>LspClient</code> | | <code>hanzo-hooks</code> | <code>HookRunner</code> | | <code>hanzo-sandbox</code> | <code>Sandbox</code> |</p>
|
|
<h3>Go services</h3>
|
|
<p>| Package | Component | |---------|-----------| | <code>devbridge</code> | WebSocket DevBridge controller |</p>
|
|
<h3>Cross-platform test vectors (<code>test-vectors/</code>)</h3>
|
|
<p>| File | Domain | |------|--------| | <code>sse-frames.json</code> | SSE parsing edge cases | | <code>mcp-normalization.json</code> | Tool name normalization | | <code>permission-policy.json</code> | Rule evaluation | | <code>session-compaction.json</code> | Compaction output | | <code>oauth-pkce.json</code> | PKCE challenge generation | | <code>config-merge.json</code> | Hierarchical config merging | | <code>backoff-timing.json</code> | Retry delay sequences |</p>
|
|
<h2>Security Considerations</h2>
|
|
<ul><li><strong>PKCE</strong> prevents authorization code interception attacks by binding the authorization request to the token exchange via a cryptographic verifier</li><li><strong>Permission data model</strong> enables audit trails for every tool execution decision, supporting compliance requirements</li><li><strong>Credential storage</strong> uses atomic writes (<code>write</code> + <code>os.rename</code>) to prevent partial/corrupt credential files, with <code>0600</code> permissions</li><li><strong>Hierarchical config scoping</strong> prevents project configs from setting <code>api_key</code> or <code>oauth_credentials</code></li><li><strong>MCP tool name normalization</strong> prevents tool name collisions that could cause one MCP server's tool to shadow another's</li><li><strong>Hook runner</strong> exit code 2 (deny) cannot be overridden by the agent; only the user can modify hook configs</li><li><strong>Sandbox</strong> path traversal attacks (e.g., <code>../../etc/passwd</code>) are caught by canonicalizing paths before checking against the allow list</li><li><strong>WebSocket DevBridge</strong> validates both JWT and Origin header, preventing CSRF-style WebSocket hijacking</li><li><strong>Multi-provider credentials</strong> are stored with <code>0600</code> permissions and never logged or included in error messages</li></ul>
|
|
<h2>References</h2>
|
|
<ol><li><a href="./hip-0009-agent-sdk-multi-agent-orchestration-framework.md">HIP-9: Agent SDK</a></li><li><a href="./hip-0010-model-context-protocol-mcp-integration-standards.md">HIP-10: MCP Integration Standards</a></li><li><a href="./hip-0010-model-context-protocol-mcp-integration-standards.md">HIP-0010: Model Context Protocol Integration Standards</a></li><li><a href="https://datatracker.ietf.org/doc/html/rfc7636">RFC 7636: PKCE for OAuth</a></li><li><a href="https://datatracker.ietf.org/doc/html/rfc9126">RFC 9126: OAuth 2.0 Pushed Authorization Requests</a></li><li><a href="https://www.jsonrpc.org/specification">JSON-RPC 2.0 Specification</a></li><li><a href="https://html.spec.whatwg.org/multipage/server-sent-events.html">Server-Sent Events (W3C)</a></li><li><a href="https://microsoft.github.io/language-server-protocol/specifications/lsp/3.17/specification/">Language Server Protocol Specification</a></li><li><a href="https://datatracker.ietf.org/doc/html/rfc8628">RFC 8628: OAuth 2.0 Device Authorization Grant</a></li></ol>
|
|
<h2>Copyright</h2>
|
|
<p>Copyright and related rights waived via <a href="https://creativecommons.org/publicdomain/zero/1.0/">CC0</a>.</p>
|
|
<footer>
|
|
<div class="fmap">
|
|
<div><b>Build</b>
|
|
<a href="https://hanzo.app">hanzo.app</a> app builder
|
|
<a href="https://hanzo.codes">hanzo.codes</a> code with an agent
|
|
<a href="https://hanzoskills.com">hanzoskills.com</a> what an agent reads</div>
|
|
<div><b>Run</b>
|
|
<a href="https://console.hanzo.ai">console.hanzo.ai</a> cloud console
|
|
<a href="https://api.hanzo.ai">api.hanzo.ai</a> the API</div>
|
|
<div><b>Account</b>
|
|
<a href="https://hanzo.id">hanzo.id</a> sign in
|
|
<a href="https://pay.hanzo.ai">pay.hanzo.ai</a> top up
|
|
<a href="https://billing.hanzo.ai">billing.hanzo.ai</a> invoices and usage</div>
|
|
<div><b>Company</b>
|
|
<a href="https://hanzo.ai">hanzo.ai</a> canonical
|
|
<a href="https://hanzo.ventures">hanzo.ventures</a> ventures</div>
|
|
</div>
|
|
<div class="fend"><a href="/hip-0301.md">This page as plain text</a> · <a href="/llms.txt">Index for agents</a></div>
|
|
</footer>
|
|
</div></body></html> |