docs/internal/webfetch.md
internal/webfetch: operation engines
WebFetch is a standalone outbound HTTP, WebSocket, and MCP client. The CLI parses and dispatches locally; MCP requests pass through a separate retained-session daemon. It does not register EzAgent tools, inject server schemas, or change the agent JSONL API or session database.
Command flags and exits belong to the command guide.
Exact flags, input shapes, limits, and local framing belong to the canonical
webfetchhelp/text assets, shared with
builtin buffers by webfetchhelp. The
Ruby adapter invokes the same executable.
Structural model
| 1 | validated operation |
| 2 | -> HTTP request -> optional HTML/Markdown transform -> output |
| 3 | OR |
| 4 | -> WebSocket connection -> stream/framed adapter -> stdin/stdout |
| 5 | OR |
| 6 | -> retained MCP daemon -> authorized client/transport -> operation result |
Option parsing selects exactly one operation. HTTP owns redirects and response
metadata. Transforms consume a completed HTTP representation. WebSocket mode
owns a bidirectional connection and adapts it to a local terminal protocol.
Information requests do not select a runner. The CLI installs signal handling
before calling Run; ordinary HTTP/WebSocket operations execute in the foreground.
Organization
| Responsibility | Owner |
|---|---|
| CLI parsing, dispatch, diagnostics | options.go, run.go, errors.go |
| HTTP and output | http.go, headers.go, output.go |
| HTML/Markdown extraction and indexes | html*.go, markdown.go, index.go |
| WebSocket streams and local records | websocket*.go |
| MCP CLI input and platform wiring | mcp_*.go |
| Foreground OAuth permission review and private callback prompt | mcp_login*.go |
| MCP operation/result types and private daemon frames | mcp/contract |
| MCP negotiation and HTTP/stream transports | mcp/protocol, mcp/httptransport, mcp/stream |
| OAuth and credential persistence | mcp/auth, mcp/authstore |
| Per-caller proxy and trust configuration | mcp/netpolicy |
| Connected peer identity, separate from caller policy | mcp/peercred |
| Windows protected filesystem operations | mcp/winfs |
| Retained clients, daemon lifecycle and executable handoff | mcp/daemon |
MCP platform files supply filesystem, peer-identity, and process mechanisms; the protocol, pool, and server remain shared. The daemon and external Unix MCP transport share peer-identity lookup, but each caller decides which identity to accept.
Design constraints
- HTTP and WebSocket clients retain system TLS verification and proxy behavior; there is no insecure TLS mode. Sensitive headers may not cross an origin change.
- Diagnostics must not expose secrets or raw provider errors. Only explicitly safe errors may publish operation-specific text. MCP HTTP authentication challenges report the HTTP status and whether credentials were attached to the rejected request, without printing headers, tokens or provider prose. A configured OAuth grant is not proof that the server accepts its credentials.
- Terminal
--mcp-loginreviews permissions before setup, owns a cancellable private callback reader, and waits for saved credentials. Unix callback input is noncanonical; restoration discards queued private bytes, including through the synchronous signal path. Windows consumes console input events rather than using potentially blocking line reads after readiness checks.--mcp-authand redirected output preserve the structured machine interface. The foreground never redeems codes itself or replays an uncertain completion. Interactive failures report the failed step and the daemon's safe, client-authored error directly rather than replacing it with a request to run an auth-status command. Safe local terminal errors also remain visible; confirmation-read failures are not treated as declines, and output failures report on stderr. Callback validation rejections and drained oversized pastes return to the private prompt. Transient status transport failures keep polling with one warning per outage. Token exchange, storage and uncertain completion failures are never retried. Scope display is provider-neutral. Hidden typing gives a constant input indicator without echoing commands or callback characters. Cancellation and expiry retain auth-status recovery guidance. Raw executor errors, provider bodies and callback values are not diagnostics. - WebSocket EOF-idle close preserves a peer status published by the concurrent application reader, even if the local close call returns a generic transport error first. Reader settlement uses the existing bounded grace period so blocked stdout cannot hold shutdown indefinitely. Without a peer result, transport close errors remain failures.
- Raw HTTP and file output stream directly and may leave partial output. Transforms are bounded and materialized before output; transformation failures emit no body prefix. HTML extraction is neither browser rendering nor security sanitization.
- Framed WebSocket records and MCP control/event envelopes are local executable
interfaces, not EzAgent JSONL or raw WebSocket frames. Framed grammar and
close/error records belong to
framed.txtandwebsocket_framed.go, not an RFC 6455 wire dump. - Unix resolves symlinks in the configured
XDG_RUNTIME_DIRbase and its ancestors, then validates the resolved target path. User/root-owned ancestors may be group-writable; other-writable ancestors require root-owned sticky system directories. The base must be user-owned and not group/other-writable. Missing base directories are created privately; dangling links and loops fail. Managed runtime directories and reexec stages still reject symlinks, and private leaves require mode 0700. Locks and sockets retain nofollow checks. Relative bases fail; long socket paths use the short fallback only after base validation. Permission diagnostics name the failing path. - Windows directory traversal expands supported directory symlinks and junctions, validates target ownership and ACLs, and pins the resolved chains. Operations use resolved paths; link entries also remain pinned against writes and rename. Configured runtime bases may themselves be links. Managed credential/runtime leaf directories, executable leaf files, and other managed files still reject links, and unsupported reparse tags fail closed.
- Retained MCP clients are separated by endpoint, auth, launch, and network identity. Blocked work and caller cancellation must not affect unrelated work. Shared startup continues while another caller needs it. A session-bearing HTTP 404 clears the session ID and publishes disconnected state before returning session expiry to its caller; subsequent calls cannot reuse that session.
- Application calls with uncertain dispatch are never replayed. Credential-commit uncertainty before application dispatch is a separate failure, not evidence that the application ran.
- Stdio executes authorized paths with normal symlink/workspace semantics. Its executable hash is not a sandbox or an atomic snapshot. The daemon's own executable handoff has separate identity and lifetime-ownership requirements.
- HTTP policy belongs to each foreground caller, not the first daemon launcher. Stdio receives a complete explicit environment. The daemon excludes ambient credentials and loader settings.
- Credential encoding obscures casual viewing; it is not encryption. Protected storage, exact credential binding, and refresh serialization remain necessary. On Unix, credential-store traversal resolves ancestor symlinks using directory descriptors and validates every expanded target ancestor. Missing directories are created privately. The final credential directory and credential/lock files still reject symlinks. Directory failures report safe path/reason diagnostics, not raw filesystem errors or credential contents. Definite pre-mutation auth rejection preserves retained clients and pending logins; consumed or uncertain completion does not. Setup/logout affects the selected credential record, not other records' logins on the same endpoint. Local operations must not depend on successful remote CA initialization.
Platform boundary and validation
Windows uses the shared transports with SID/ACL checks, native file locks, and platform-specific daemon launch and child cleanup. Absolute XDG overrides are honored; default state lives under LOCALAPPDATA. Its AF_UNIX peer check authenticates the process's primary-token user, not an impersonating thread. Numeric Unix UID overrides have no Windows mapping. Windows pins the daemon image while running, so replacing that same executable path requires stopping the daemon first. Native Windows execution and storage power-loss durability remain unvalidated.
Behavior tests live beside their owners, including option, HTTP, transform,
WebSocket, output, and runner tests. CLI lifecycle coverage is in
cmd/ez-agent-webfetch. Help identity and assembly
are tested in webfetchhelp and the builtin buffer
package. Use the test guide for commands and isolated daemon fixtures.