minimal agent cli memoria.tools
README.md

HTTP and SSE (WP5) #

Actual headless vendor:curl transport and standalone incremental SSE framing. No provider/model semantics, authentication, request IDs, retries, backoff, or tool execution. H01-H04/H06 are implemented; HTTP 200 / Error.None is only transport/framing success, not H05/H07 protocol completion. WP6 must validate terminal events and in-200 provider errors. H08-H09 belong to later explicit request execution, never this package.

Supported exports and ownership #

  • init_service(^Service) -> Error, close_service(^Service): address-stable root lifetime; no allocator or native mutex destruction required. Empty/repeated close is safe. Initialize before publishing; reuse after close only when prior callers have joined. Never copy a used service or call close from its callback.
  • init_request(^Request, Request_Input, allocator) -> Error clones every URL, method, header string/array and body. Checked partial failure releases all acquired owners. destroy_request releases the allocator-owned snapshot; empty/repeated destruction is safe. Request fields are internal by convention: do not mutate them or destroy the request until all borrowing runs return. Different runs may concurrently borrow the same immutable request.
  • run(^Service, ^Request, Control, Sink={}) -> Result is a blocking worker call with isolated easy/multi/parser state. Service/request/control callback data and sink state are borrowed through return, never retained afterward. Control.allocator is mandatory; it becomes the run/callback context allocator and owns scratch and returned body. It must survive result destruction, and support allocation/free on every caller/worker involved. No temporary root arena may expire before joined workers/results. Request clone/destroy uses its own retained allocator, not necessarily the output allocator.
  • Result transfers ordinary body ownership, including bounded partial bytes on failure, to the caller. destroy_result frees it using the retained allocator; empty/repeated destruction is safe. SSE results retain no raw response body. Do not interpret a failed result's partial body as a complete response.
  • init_parser(^Parser, Limits, Sink, allocator), feed(^Parser, []byte), finish(^Parser), destroy_parser are the independent framing API. feed borrows arbitrary bytes only during the call; the parser owns all retained pending bytes. Parser address/context must remain stable until destruction. A parser is serial, not thread-shared; feed/finish reentry is refused.
  • Sink.event(data, Event) -> Error is serial on the run/feed thread; name/data/id strings are callback-borrowed, invalid after return. Clone before mailbox transfer. Sinks cannot escape the run, reenter their parser or the coordinator, or close their active service. WP3 owner APIs enforce coordinator reentry refusal; adapters must publish through its cancellation-aware mailbox instead. A blocking sink must observe its own cancellation/backpressure contract: HTTP cannot preempt arbitrary user callback code. Sink refusal becomes Sink_Failed, except explicit Cancelled; cancellation intent beats late successful output.
  • control_limits, catalog_limits, model_limits, default_timeouts provide explicit endpoint configuration. Zero/default-uninitialized limits are not silently replaced. diagnostic(Error) returns a static borrowed safe string. Other helpers and Transfer fields are implementation machinery, not owner APIs.

Process and shutdown lifecycle #

A package mutex protects libcurl global init/cleanup and root-service references. The first service initializes; the last drained service cleans up. Each service mutex serializes admission with close. Close stops admissions, waits for admitted runs (including every callback and native handle destructor), then drops its process reference exactly once. Concurrent closes are safe. Another service may start/run while one drains; its reference prevents cleanup. No handle sharing, global request scratch, coordinator pointer, worker stdout or curl debug logging.

Root sequencing is initialize -> publish to workers -> stop job admission -> cancel active jobs -> drain/join -> close service -> free root allocators/data. Close drains; it does not itself invent cancellation tokens for callers. The status-only CLI constructs transport before application state and closes it last; future adapters must borrow that root service. Full frontend/signal shutdown is not implemented by WP5.

macOS links system /usr/lib/libcurl.4.dylib via Odin's vendor:curl (also system zlib/SystemConfiguration per that binding); no external curl executable or extra HTTP/TLS dependency. Toolchain: Odin dev-2026-09:a2fb372b7. Init rejects a libcurl without asynchronous DNS and thread-safe global lifecycle features. Multi poll requires libcurl >=7.66; thread-safe global lifecycle requires >=7.84. The binding is newer than system curl, so the stable numeric CURLOPT_PROTOCOLS=181 restricts HTTP/HTTPS without requiring newer string options.

Wire, security and timeouts #

GET/POST only; request bodies are bytes, not implicitly UTF-8. Reject URL userinfo, control/space/NUL bytes and other schemes; header names must be HTTP tokens, values cannot contain CR/LF/NUL/control injection, duplicates are rejected. Caller Host, Content-Length, Transfer-Encoding, Connection, Proxy-Authorization and Expect are rejected; libcurl owns routing/framing. Redirect following is always off (3xx is HTTP_Status), environment proxy use is off, and automatic content decompression is off. Non-identity Content-Encoding is Malformed. HTTP/1.1 is pinned to avoid libcurl's transparent HTTP/2 refused-stream replay; POST suppresses implicit Expect/417 negotiation. Request execution owns retries. Transfer-Encoding chunk framing is removed by curl before body/SSE callbacks. Provider endpoints must select HTTPS; plain HTTP remains available for explicit endpoint use and offline loopback fixtures. HTTP is not a TLS-disable toggle.

HTTPS always sets peer verification 1 and host verification 2, using system trust. There is no insecure setting, alternate CA injection, debug/error buffer dump, raw-header retention or body logging.

Default connect / first-response-byte / idle budgets are 5s / 60s / 90s. Connect includes DNS/TCP/TLS. PRETRANSFER identifies connection readiness (at most one poll's observation delay); upload time counts toward first-byte. Any response header byte is a first byte; subsequent headers/body/comments reset idle. These are intentionally distinct from first-model-output semantics. Positive endpoint timeout overrides up to 24h are accepted. Control.deadline is an optional absolute injected-monotonic deadline (zero disables); a nonzero deadline requires its clock. Monotonic values must be nonnegative/nonregressing. Real monotonic phase caps supplement injected clocks so a frozen test clock cannot turn network waits infinite. Curl connect timeout also protects setup.

Multi perform/poll checks cancellation and deadlines between waits and callbacks, and before each framed event; poll waits are <=50ms. Cancellation wins a late HTTP completion. Native OS/library operations and user callbacks are cooperative, not forcibly preemptible. No background HTTP thread or retry/attempt is hidden here.

Budgets (checked before owned large allocation) #

Resource Limit
Request URL / headers / body 8192 bytes / 64 headers and 32 KiB total framed bytes / 32 MiB
Ordinary control / catalog body 1 MiB / explicitly selected 32 MiB
All response headers, including interim/trailers 64 KiB; retained only as fixed metadata
SSE line / pending event / expanded emitted event <=1 MiB each; line <= event
SSE event name / persistent ID <=4096 bytes each and within pending event budget
SSE total source / expanded emitted material <=4 MiB each
SSE lines / framed events <=65536 each

All limits may be lowered explicitly. Ordinary buffers allocate the full selected cap before network IO. SSE allocates line + event + name + ID buffers once: at most 2 MiB + 8192 bytes per parser, reclaimed after run, not accumulated between requests. Pending event budget includes data-field newline separators, name and persistent ID; expanded emitted budget includes data, effective name (default message) and ID on every event. Low-value comments/empty lines still consume source/line quotas. Request structural header arrays are separately bounded by count; per-run URL/header scratch is <=8193 bytes / one <=32 KiB line. Curl's own bounded native receive/header/TLS allocations are library-owned, outside Odin allocator tracking; all slists/easy/multi handles are destroyed before service admission is released. The transport does not own global job/child count policy; execution/root/subagent admission remains separately bounded by its owners.

Metadata holds final HTTP status, safe integer curl completion code, header/body byte counts, typed Retry-After delta-seconds or IMF-fixdate Unix seconds. Invalid Retry-After is unknown; raw values are never retained. Execution must clamp delays and convert dates using wall time, not HTTP's monotonic clock. SSE parser totals are source_bytes, expanded_bytes, lines, events: source includes the whole accepted feed chunk even if later framing fails; events/expanded count framed delivery attempts, including a refused sink. body_bytes is accepted transfer body bytes; non-2xx SSE bodies are bounded/discarded, never delivered to a sink. Interim responses reset status/retry/type metadata; trailers cannot rewrite it.

Error is the authoritative outcome (curl code zero can mean no native completion). It distinguishes Invalid_Request (bad configuration/wire input), Closed, Allocation, Setup, Connect_Timeout, First_Byte_Timeout, Idle_Timeout, Deadline, Cancelled, HTTP_Status, Transport (including verified TLS failure), Limit (including request preflight), Malformed, Truncated, Sink_Failed. Status is final on completed HTTP or last-observed on early failure; no retryability or auth/model-error classification is inferred here.

Exact SSE framing and EOF #

LF, CRLF and CR delimit lines; a split CRLF counts once. An initial UTF-8 BOM is ignored, only at source start. Validate UTF-8 after each complete line, so reads may split code points. Invalid complete-line UTF-8 is Malformed, not replacement or silent loss. Comments (:) and unknown fields are ignored but bounded/countable. Split the first colon, remove one optional leading value space. data fields append value + LF; dispatch at an empty separator with only the last LF removed. An empty data field dispatches empty data; no data fields dispatch nothing. Event name resets at every separator; absent/empty name becomes message.

id persists across events, empty resets it; an ID containing NUL is ignored. retry persists as validated unsigned 32-bit milliseconds; empty, nondigit, negative or overflowing values are ignored. It is metadata, not an instruction to reconnect. Names and JSON are not interpreted by transport.

Strict EOF: finish fails Truncated for any unterminated line (even a comment) or recognized unseparated pending data/name/id/retry fields. It never dispatches a partial last event. Completed comments/ignored fields/empty streams may finish successfully; codecs must still require model completion. CR already terminates a line, so complete CR-separated streams need no trailing LF. Errors are sticky; only destruction/reinitialization creates fresh framing state. Cancellation or sink failure safely discards remaining pending data after native handles stop.

Evidence and remaining boundary #

27 package tests cover exhaustive two-part and bytewise UTF-8/BOM/CRLF splitting, framing/metadata/EOF, exact/default limits, allocation sweeps, serial callback reentry refusal, real loopback GET/POST/chunked/interim/trailers, ordinary/catalog caps, error statuses and in-200 uninterpreted bytes, stalled cancellation, connect/first-byte/idle/overall deadlines, backward-clock rejection in every transfer phase (even above the run's start), concurrent service admission/close, borrowed callbacks held through close, and 20 repeated socket/global lifecycles. An offline Python-stdlib TLS peer presents a synthetic untrusted self-signed certificate; actual libcurl rejects it with code 60. TLS fixture key is public test data, never a credential. Full validator supplies its ephemeral loopback port through MEMORIA_REWRITE_TEST_TLS_PORT and keeps artifacts under the approved temp directory. No external network or authenticated/live-provider checks are used.

python3 -B src.new/scripts/validate.py --out-dir "$APPROVED_TEMP_DIR"

Final results and WP6 handoff: ticket 05. No production protocol completion, retry safety, provider/auth acceptance, proxy configuration, Linux/Windows or frontend implementation is claimed.