Consts
BlueFg = "\e[34m"
BoldOn = "\e[1m"
BrightWhiteFg = "\e[97m"
CyanFg = "\e[36m"
GreyFg = "\e[38;5;244m"
OffWhiteFg = "\e[38;5;252m"
Reset = "\e[0m"
Procs
proc applyInlineMd(line: string): string {....raises: [], tags: [], forbids: [].}
- Strict in-line replacements for ***bold-italic***, **bold**, *italic* / _italic_, and backtick-code. Body text rides the terminal's default foreground (no envelope SGR), so the reverts just cancel bold / italic / underline back to default — no need to re-engage \x1b[2m (we no longer dim the body). Bold and inline code: \x1b[1m (bold/bright). Italic: \x1b[3m plus \x1b[4m so it shows on terminals whose monospace font lacks an italic face (italic alone would be invisible there). Strict matching: opening delimiter must be immediately followed by a non-space, closing delimiter immediately preceded by a non-space, and the inner span must not contain the delimiter. Italic additionally requires whitespace/punctuation flanking on the outside, so snake_case and 5*5 survive untouched. Unmatched / malformed markers pass through verbatim.
proc bundledCaFile(): string {....raises: [], tags: [], forbids: [].}
- Path to the cacert.pem we ship alongside the binary on macOS / Windows (see release.yml). Returns "" when not present (Linux release tarball, dev builds) — newContext will scan default system cert locations in that case, which works on every Linux distro.
proc bundledSslContext(): SslContext {....raises: [LibraryError, SslError, Exception, IOError], tags: [RootEffect, ReadDirEffect, ReadEnvEffect], forbids: [].}
- Drop-in SslContext for newHttpClient(sslContext = ...) and anywhere else a TLS context is consumed. macOS/Windows ship OpenSSL whose OPENSSLDIR is baked to a build-runner path that doesn't exist on user systems, so verifyMode = CVerifyPeer can't scan the default location — we feed cacert.pem from next to the binary. Linux passes caFile = "" and falls through to the system trust store. The streamhttp SSE path takes bundledCaFile() directly (it builds its own context internally), so the bundle wiring lives in one place either way.
proc charWrapAnsi(s: string; width: int): seq[string] {....raises: [], tags: [], forbids: [].}
- Character-wrap: break at exactly width visible columns, even mid-word. ANSI CSI escapes pass through without counting toward width. Lines that fit are returned as-is.
proc clipMiddle(s: string; head, tail: int): string {....raises: [], tags: [], forbids: [].}
proc collapseHome(path: string): string {....raises: [], tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
- Collapse the user's home dir prefix to ~/. Guards against the getHomeDir() trailing-slash footgun that produced things like ~e/hellodeepseek for /home/carlo/e/hellodeepseek.
proc debugOut(msg, tag: string) {....raises: [IOError], tags: [TimeEffect, WriteIOEffect], forbids: [].}
proc debugOut(msg: string) {....raises: [IOError], tags: [TimeEffect, WriteIOEffect], forbids: [].}
proc detectMdHeader(line: string): (bool, string) {....raises: [], tags: [], forbids: [].}
- A line of ###... followed by a space and at least one non-space char. Returns (true, body) on match, (false, "") otherwise.
proc humanBytes(n: int): string {....raises: [], tags: [], forbids: [].}
proc humanTokens(n: int): string {....raises: [], tags: [], forbids: [].}
proc isBinaryContent(s: string): bool {....raises: [], tags: [], forbids: [].}
-
Scan the first 512 bytes for binary indicators: any NUL byte, or
5% non-printable control chars (excluding t n r).
proc isMdFenceLine(line: string): bool {....raises: [], tags: [], forbids: [].}
-
```
(3+ backticks, optional language label after). proc isMdSepRow(line: string): bool {....raises: [], tags: [], forbids: [].}
- Detect the |---|:---:|---:| alignment-separator row between header and body — its cells contain only -, :, and spaces.
proc isMdTableRow(line: string): bool {....raises: [], tags: [], forbids: [].}
- A markdown-table row both opens and closes with a |. Rejects bare prose that happens to contain a pipe.
proc levenshtein(a, b: string): int {....raises: [], tags: [], forbids: [].}
proc levenshteinCapped(a, b: string; cap: int): int {....raises: [], tags: [], forbids: [].}
- Standard edit distance with an early cutoff: returns cap+1 once the minimum row value exceeds cap. Cap keeps the cost linear-ish for the "compare against every file line" use case.
proc looksLikePath(s: string): bool {....raises: [], tags: [], forbids: [].}
- Heuristic for the path-on-its-own-line preceding a write/patch fence in text mode. Rejects prose (whitespace inside, fence markers, headings). Accepts anything containing / or . — paths typically have one.
proc renderMdTable(rows: seq[string]; indent = " "; maxWidth = 0): string {. ...raises: [], tags: [], forbids: [].}
-
Render a buffered markdown table as an aligned, box-drawn block. Each output line is prefixed with indent so the table sits in the harness's col-2 content area. Skips the alignment-separator row but uses it as the header/body divider when present.
When maxWidth > 0, the natural column widths are compressed to fit maxWidth total columns: the widest column is shaved by one visible char at a time until the row fits, never going below a per-column minimum of MinCol. Cells longer than their column are word-wrapped across multiple visual lines so the row stays readable. If even MinCol per column doesn't fit (too many columns for the terminal), the table degrades to a vertical label: value rendering: readable, no overflow, but loses the grid.
proc replaceFirst(s, needle, repl: string): (string, bool) {....raises: [], tags: [], forbids: [].}
proc resolvePath(path: string): string {....raises: [], tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
proc safeCwd(): string {....raises: [], tags: [], forbids: [].}
- The current working directory, or / when the process's cwd has been removed or renamed out from under it. Nim's getCurrentDir raises OSError in that case (Linux getcwd returns ENOENT), which would crash the REPL. The filesystem no longer has a name for the deleted dir, so callers that only need an absolute path label for context, logging, or session identity get / — every dir-walk, ls, git and fileExists against it then simply finds nothing and degrades gracefully.
proc sanitizeUtf8(s: string): string {....raises: [], tags: [], forbids: [].}
-
Return a copy of s that is valid UTF-8: every invalid byte or malformed sequence is replaced with a single U+FFFD, and every valid codepoint (including multibyte) passes through untouched.
Strings that cross a system boundary into a JSON request body must be valid UTF-8. Tool output and resumed-session text can carry bytes that aren't — e.g. a command that printed a truncated multi-byte rune left a lone continuation byte in its result, which std/json emits verbatim into the serialized body. The provider then rejects the whole body with a 400, and since the offending message recurs in every subsequent request (tool messages can't be dropped) the session is bricked until the .3log is hand-edited. This is the boundary guard that stops that.
proc stripPreamble(s: string): string {....raises: [], tags: [], forbids: [].}
- Strip <session_context>...</session_context> and <project_notes>...</project_notes> blocks from a stored user message so the replay UI shows the prompt the user typed, not the auto-injected context the model needs. Only acts on a leading block (s.strip starts with <session_context>); leaves the string alone if either tag appears mid-message — that would be the user's own text, not our preamble.
proc tokenSlot(icon: string; n: int): string {....raises: [], tags: [], forbids: [].}
- "iconvalue" — no space between glyph and number. Slots are joined with two spaces for visual separation. When the value is 0 the slot is omitted entirely (returns ""); the caller strips the preceding spacer too so no dangling gaps appear.
proc userConfigRoot(): string {....raises: [], tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
- XDG config root for 3code: ~/.config/3code/ on Linux, ~/Library/Application Support/3code/ on macOS, %APPDATA%/3code/ on Windows. Holds user-edited config and skill overrides only.
proc userDataRoot(): string {....raises: [], tags: [ReadEnvEffect, ReadIOEffect], forbids: [].}
- XDG data root for 3code: ~/.local/share/3code/ on Linux, ~/Library/Application Support/3code/ on macOS, %APPDATA%/3code/ on Windows (collapses with config-root there — fine, the split is a Linux convention). Holds app-managed state: sessions, history, extracted built-in skills.
proc utf8ByteCut(s: string; n: int): string {....raises: [], tags: [], forbids: [].}
- Slice s to at most n bytes, backing up to a UTF-8 codepoint boundary so the result is valid UTF-8. Strings in JSON request bodies must be valid UTF-8 — Pydantic-backed providers (deepinfra) reject the body with "There was an error parsing the body" when a naive byte slice splits a multi-byte rune (e.g. → chopped after two bytes).
proc utf8ByteCutEnd(s: string; n: int): string {....raises: [], tags: [], forbids: [].}
- Take the last up-to-n bytes of s, advancing past any leading UTF-8 continuation byte so the result is valid UTF-8. Mirror of utf8ByteCut for tail slices (used by clipMiddle).
proc visibleWidth(s: string): int {....raises: [], tags: [], forbids: [].}
- Count visible columns in a string that may contain ANSI CSI escape sequences (\e[...<letter>). Each rune is weighted by its East Asian Width: CJK / emoji count as 2, combining marks as 0.
proc wrapAnsi(s: string; width: int): seq[string] {....raises: [], tags: [], forbids: [].}
- Greedy word-wrap on whitespace; each chunk's visible width is at most width. ANSI CSI escape sequences pass through without counting toward width. Words longer than width overflow on their own line — terminal wrap takes them from there. Multiple inter-word spaces collapse to one.