Runtime protocol v1
Start freeness serve [runtime options]. Commands use stdin; events use stdout; process diagnostics use stderr. Records are UTF-8 JSON terminated by LF. Split only on LF, not on Unicode U+2028/U+2029. Continuously consume stdout to avoid process backpressure.
Configuration, workspace, bash and credential checks run before session creation and ready. A startup failure exits nonzero with a diagnostic on stderr and no protocol records. It does not count a provider request. freeness doctor [runtime options] --json runs local read-only startup checks separately; its {v, ready, checks, notes} report is not a serve-mode event.
--connection NAME resolves saved endpoint/model settings and a private key-file reference, OS credential-store reference or environment-variable name. An explicit --model overrides the saved model. The TUI opens connection setup before starting serve, or after closing its previous session through /connect. Provider changes start a fresh session, preserving workspace and time/turn limits while explicitly resetting pricing, spending caps and context-window settings. A successful set_model also persists the model when a saved connection is in use.
Connection management is a separate CLI helper, outside the session event protocol: freeness connections list, save, use NAME, remove NAME, and check-keychain. The latter roundtrips and removes a new synthetic item, returning {v:1,available,message}; it never reads an existing credential. save accepts one JSON object of at most 16 KiB on stdin: {name, base_url, model, secret, storage?} or {name, base_url, model, environment}. Secret storage defaults to file; use storage:"keychain" explicitly for the OS store. Environment references cannot specify secret storage. Settings contain {kind:"file",account:UUID} for local keys, whose separate private file is credentials/<UUID>.json with {v:1,key:...}. That private envelope is never returned by connection listing or the session protocol. Never put a secret in argv or a session command. Success returns {v:1,ok:true}; list returns only settings and credential references. Parsing failures omit supplied values. A successful save establishes local storage, not provider authentication; the first prompt makes the real API request.
Commands
Every command has a string id. The runtime responds with type=response, the same id, and ok. A successful prompt response means acceptance, not completion. Wait for settled to know a run has finished and cleanup is complete.
{"type":"prompt","id":"p1","text":"Inspect the project"}
{"type":"prompt","id":"p2","text":"Inspect this screenshot","images":["screen.png"]}
{"type":"status","id":"s1"}
{"type":"history","id":"h1","before_seq":120,"limit":100}
{"type":"sessions","id":"l1","limit":20}
{"type":"cancel","id":"c1"}
{"type":"set_model","id":"m1","model":"YOUR_MODEL"}
{"type":"shutdown","id":"q1"}
One prompt can run at a time. Concurrent prompts receive an unsuccessful response. Cancellation is idempotent. Changing models requires an idle live-provider session and invalidates pricing. Shutdown and stdin EOF cancel active work, clean up jobs, and close the server. A malformed command produces protocol_error; unknown command fields are rejected. Input records are limited to 8 MiB while reading; oversized records are discarded through LF before processing the next command. An unterminated record at EOF is rejected.
set_model also resets model-specific reasoning effort. Its response and the ready/status state expose the effective reasoning_effort (string or null). Canonical GPT-6 Luna/Sol IDs use explicit none for Chat Completions function tools; the setting is also recorded in run_started. An explicit incompatible startup effort is rejected locally, without an API request. Known direct OpenAI models that require Responses for tool calls are rejected before opening a session or saving a changed model. Gateway model namespaces are not assigned the direct OpenAI policy.
prompt.images is an optional array of local file paths, resolved against the workspace. The default is empty. Image paths are read and validated before acceptance; a failure returns ok=false without provider requests or usage changes. Empty text is accepted with images. After acceptance, the combined context still has to pass validation and its 8 MiB serialized limit. Failure then produces an error/settled event and preserves the previous working context. Explicit attachment bytes and paths are not included in run_started; image_count records the number attached. This local interface has the same OS authority as the caller; it is not a remote file-reading service.
history requires an idle engine. before_seq is an optional exclusive upper bound; omit it for the latest entries. limit defaults to 100 and must be 1..200. A successful response includes history: {source: "journal", events: [...], next_before_seq: number|null, invalid_records: number}. Events are chronological display previews with their original sequence/session identifiers. Pass next_before_seq to load an older page; null means the beginning. Queries do not contact a provider, count requests, edit context, or execute commands.
Pages omit transient status/acknowledgement traffic and streamed assistant chunks already represented by a completed message. Interrupted assistant chunks become a preview with incomplete=true. Text fields are UTF-8-safe previews of up to 32 KiB, marked preview_truncated=true where needed; page contents are bounded to 512 KiB plus the small envelope. Tool output and completion records remain separate, so a page may start midway through a command. Malformed/incompatible journal records are skipped and counted. The full journal remains the source for raw artifacts.
sessions lists default sessions under the current workspace's .freeness/sessions; it is available while idle or running. limit defaults to 20 and must be 1..100. A successful response includes catalog: {v: 1, cwd, root, sessions: [...], scanned, skipped, omitted, scan_limit_reached}. Entries contain path, updated_unix_ms (metadata modification time or null), locked, and cumulative usage fields (requests, input_tokens, cached_input_tokens, output_tokens, unmetered_requests, cost_usd, known_cost_usd). They omit last-request details and prompt/context/journal contents. Results are ordered by newest metadata first, with unknown times last and paths breaking ties. Locks and saved usage are observations, not a resume-readiness guarantee.
Discovery scans at most 4,096 directory entries and reads at most 16 MiB of metadata. Each accepted metadata file is limited to 1 MiB; an extra sentinel byte detects oversized files within the aggregate budget. Unsafe, malformed, unreadable and other-workspace entries increment skipped. omitted counts valid entries beyond the requested output limit within the scan. scan_limit_reached=true means uninspected or partially read inputs remain; global recency and coverage are then unknown. No provider calls, request accounting, shell commands or changes to discovered session files occur. The active journal records only catalog_entries, catalog_skipped, catalog_omitted and catalog_scan_limit_reached alongside response metadata. Standalone freeness sessions --cwd PATH --json returns the same report without writing any journal or requiring provider configuration. Custom session paths are not indexed.
Events
Every event contains v=1, increasing session-wide seq, session_id, timestamp_ms, and type. Events are appended to the journal. History and session-list responses journal only query metadata, preserving sequence identity without duplicating their payloads. Consumers should ignore unknown event types within v1; incompatible protocol versions are errors.
| Type | Additional fields |
|---|---|
ready |
path, cwd, model, demo, usage, provider_response, context_messages, context_bytes, context_images, context_window_tokens, limits |
response |
id, ok, command on success, message on rejection |
run_started |
run_id, prompt, image_count, provider settings and task limits |
turn_started |
turn, usage with the pending request recorded |
provider_response |
provider_response with completed response identifiers |
assistant_delta |
text |
assistant_message |
turn, final turn text, tool_calls, updated usage |
guard_review |
call_id, review_id, command, detached, timeout_ms, guard_model |
guard_decision |
call_id, review_id when available, allowed, reason, unavailable on failure, guard_usage |
tool_started |
call_id, job_id, command, detached, timeout_ms |
tool_output |
call_id, job_id, stream, text |
tool_finished |
call_id, result |
job_finished |
job_id, detached job result |
context_edited |
before_messages, after_messages |
context_rejected, error, protocol_error |
message |
meter |
turn (completed turns), context_bytes, context_images, context_messages, context_window_tokens, elapsed_ms, usage, limits, remaining_turns, remaining_seconds |
settled |
run_id, reason, path, elapsed_ms, usage, context_bytes, context_images, context_window_tokens, final_text or null |
server_stopped |
No additional fields |
Status responses include busy and state. While busy, the state is the initial server snapshot; meter events provide current usage. tool_finished on a detached command acknowledges job creation; job_finished reports its actual completion. A detached job can emit output after the creation acknowledgement.
The bundled TUI treats malformed, oversized, incomplete or incompatible backend output as fatal. It rejects pending requests, interrupts the backend, ignores further output, and exits unsuccessfully even when the child returns zero. Commands that remain unacknowledged for ten seconds trigger the same cancellation path. Shutdown has a five-second grace period after acknowledgement/interruption before forced termination and closing local pipe handles. These client protections do not contain OS processes that escape the runtime's process groups.
Usage fields: requests, input_tokens (includes cached), cached_input_tokens, output_tokens, unmetered_requests, cost_usd (null if unpriced/incomplete), and known_cost_usd. All are cumulative for the session. The known cost is the subtotal of requests with valid usage and configured prices; it survives interrupted requests, resume and model changes. A positive subtotal does not restore a complete cost or permit capped requests when cost_usd is null. These are configured-rate costs, not billing records. Older backends can omit the additive subtotal field. Opening an older complete session seeds it from the saved total; an older incomplete session starts it at zero because its lost priced history cannot be reconstructed from cumulative tokens. Context bytes are exact serialized text bytes, not a token estimate.
usage.last_request is null for older sessions with no request record. Otherwise it contains number, model, tokens (input, cached_input, output, or null when pending/unknown), and per-request cost_usd (null when unpriced/unknown). The last input count is provider-reported for the full request including system text, tool schema and meter. It is not the token count of the current edited context. A known last request can have a known cost while the cumulative cost remains unknown because an earlier request was unmetered. Known cumulative tokens are lower bounds whenever unmetered_requests is nonzero. Invalid usage or arithmetic overflow is never converted into a successful zero-cost measurement.
Token counts must be nonnegative integers, cached input cannot exceed input, and a supplied non-null total_tokens must equal input plus output without overflow. Omitted/null cache details retain the API's zero-cache default; malformed supplied details do not. Repeated non-null usage records must agree on the supported counts. Once usage in a response is malformed or contradictory, a later valid record cannot restore complete accounting. The response can still complete with unknown usage, but that session cannot authorize another cost-capped request.
provider_response is null when no provider response record is saved (including older sessions and new demo sessions). Otherwise it contains request_number, request_model (the requested alias/ID), and response: {id, model, system_fingerprint, service_tier}. Each response field is a string or null. They are optional provider assertions as defined by Chat Completions; a reported model does not attest the actual backend. The fingerprint is a deprecated optional field. Missing, null or blank values remain unknown, without falling back to the requested model. Identifiers are limited to 512 UTF-8 bytes, without control characters or the active credential. Repeated nonempty values in a stream must agree; invalid metadata rejects the response before tools execute.
This record describes the last completed provider response, which may precede the current pending/failed request or selected model. It is persisted as last_response in session metadata and emitted once per completed response in the journal, even if token usage is missing. A cancelled or rejected response gets no completed record. ready and status state expose the last saved record; /model-info displays it (also available through Actions). ready additionally exposes the non-secret base_url for catalog route matching. These identifiers are separate from usage, editable context and the injected meter. Older v1 backends may omit this additive field.
context_window_tokens is caller-supplied through --context-window, or null. It is informational and clears on model changes. The injected pre-request meter uses the count of turns already completed: zero before the first request. Remaining turns include the next request; remaining seconds are rounded down from the configured prompt deadline. There is no estimated context utilization percentage or automatic context editing.
context_images counts image parts in the current editable context. context_bytes counts compact JSON bytes, including inline image data; the private context file uses pretty JSON and can be larger. Both formats must fit the context-file limit. Last-request input tokens are provider-reported and include images; there is no separate guessed image-token or pixel-cost meter. Older v1 backends can omit image-count fields. History keeps attachment counts but does not copy attachment bytes into previews.
Possible settled reasons: completed, cancelled, time_limit, error. Turn and cost limit failures currently use error with an explanatory message. A headless failed run exits nonzero. A failed prompt in serve mode emits settled and leaves the server available for the next command.
The provider transport expects one choice. Missing choice indices are accepted for compatible single-choice endpoints; supplied indices must be integer zero. Extra choices, non-assistant roles, malformed command fields and unsupported tool types are rejected. After a choice supplies finish_reason, only empty-choice metadata/usage frames may follow before [DONE]; later choice data cannot replace that finish. Tool-call indices must form a complete zero-based batch, with no repeated index within a chunk. Fragments from different calls may interleave and arrive out of order. Unknown finish reasons produce value-free diagnostics. These checks follow the Chat Completions streaming structure while accepting omitted optional metadata. Native audio output and legacy function_call payloads remain unsupported.
A structured refusal string is displayed and saved as assistant text, with valid usage retained. It does not introduce a runtime refusal policy or a retry. A response combining nonempty refusal text with tool calls is rejected before command execution.
Editable context
{"v":1,"messages":[{"role":"user","content":"Task statement"}]}
Messages use user, assistant and tool. An assistant call has tool_calls with function name bash, JSON-string arguments, and unique id; its results use tool_call_id. Preserve every call/result group together. Only completed turns are present when a shell edits context. The runtime adopts validated edits, then appends the current turn and its results. The system description and meter are injected separately.
User content can be a text string or an array of text and image parts:
{"role":"user","content":[{"type":"text","text":"Screen snapshot"},{"type":"image_url","image_url":{"url":"data:image/png;base64,REPLACE_WITH_IMAGE_BASE64","detail":"auto"}}]}
This follows the Chat Completions image input format. detail can be omitted or set to auto, low, high or original; support depends on the provider/model. Only inline PNG/JPEG/GIF/WebP Base64 data URLs are accepted. Remote URLs, file URLs, audio/file parts and unknown fields are rejected. Data must use standard Base64, match its declared media header and decode to at most 4,000,000 bytes per image. Headers are checked without decoding image pixels; full codec validity remains the provider's responsibility. A user message can contain 1..64 parts with at most 16 images. Assistant and tool content remains text (or null for an assistant tool call). The caller can attach up to 6,000,000 new decoded image bytes per prompt. Base64 expansion and all other content count toward the 8 MiB pretty-serialized context limit.
To view a file through the existing shell tool, the model reads/encodes it and adds such a user message to $FREENESS_CONTEXT. Removing those parts removes the images from later requests. The runtime does not fetch URLs, resize images, strip rejected images, or estimate their token usage. Existing text-only context remains valid. Rejected image edits use the same last-good recovery mechanism as other invalid context edits. Oversized appends are rejected before replacing the prior context. If a rejection notice cannot fit in the restored context, the run stops and leaves the valid file intact for inspection.
Only this tool is exposed:
{"command":"pwd","timeout_ms":5000,"detach":false}
All three fields are required; additional fields are rejected. Context is limited to 8 MiB, including appended turns and inline image data.
Guardrail state and usage
Ready/status state exposes guardrails: {required: true, model, base_url, connection} (null only for an offline fixture without a configured reviewer) and guard_usage. run_started records guardrail settings and guardrail_policy: "v1". meter and settled include cumulative guard_usage with the same schema as usage. Agent usage remains agent-only for request/context feedback. Session catalog and Harbor accounting aggregate both components; cached input remains a subset of input, never added again. No request in a component contributes zero cost merely because its cost is unknown.
guard_review precedes network I/O; a matching guard_decision.allowed=true must precede tool_started. Denied/unavailable actions emit tool_finished with result.blocked=true, never tool_started. Valid denials permit another agent turn. Failed/malformed/timed-out review stops the batch/run after complete blocked call/result groups are saved. Oversized/locally invalid proposals can be blocked without a review request. Every attempted action has a fresh nonce; approvals are not cached or reusable. Journal history previews include guardrail events and blocked results independently of working context.