No description
  • TypeScript 97.5%
  • Nix 2.5%
Find a file
2026-10-09 15:54:55 -07:00
.nut/chat Migrate to Effect CLI and add ACP stdio integration 2026-10-09 15:54:55 -07:00
docs Migrate to Effect CLI and add ACP stdio integration 2026-10-09 15:54:55 -07:00
nix Migrate to Effect CLI and add ACP stdio integration 2026-10-09 15:54:55 -07:00
scripts Add Nix package, registry dependencies and fast mode; remove tests and include chat traces 2026-10-08 12:21:50 -07:00
src Migrate to Effect CLI and add ACP stdio integration 2026-10-09 15:54:55 -07:00
.gitignore Pack immutable memory objects automatically and hide routine memory activity 2026-10-09 01:21:15 -07:00
AGENTS.md Pack immutable memory objects automatically and hide routine memory activity 2026-10-09 01:21:15 -07:00
bun.lock Migrate to Effect CLI and add ACP stdio integration 2026-10-09 15:54:55 -07:00
bunfig.toml Add Nix package, registry dependencies and fast mode; remove tests and include chat traces 2026-10-08 12:21:50 -07:00
flake.lock Add Nix package, registry dependencies and fast mode; remove tests and include chat traces 2026-10-08 12:21:50 -07:00
flake.nix Add Nix package, registry dependencies and fast mode; remove tests and include chat traces 2026-10-08 12:21:50 -07:00
package.json Migrate to Effect CLI and add ACP stdio integration 2026-10-09 15:54:55 -07:00
README.md Migrate to Effect CLI and add ACP stdio integration 2026-10-09 15:54:55 -07:00
tsconfig.json Add Nix package, registry dependencies and fast mode; remove tests and include chat traces 2026-10-08 12:21:50 -07:00

Nut

An endless coding chat built with Effect v4 and pi-durable. Based on Victor Taelin's OptChat specification. The pinned specification is in docs/optchat.md.

Each turn starts with a fresh model context. A bounded view of the selected history plus shared-head discovery supplies memory. The agent can open summaries with zoom to read the original messages.

Graph memory is the only storage backend. Run bun start to continue the primary local session; empty chat paths initialize automatically. A second instance gets an independent execution lane. Shared memory brought in through Git is discovered before model requests and exposed as context for discussion; Nut does not run Git or silently resolve competing decisions. --session/--head remain optional overrides. Imported history and legacy zoom references are preserved. The retired v1 migration tooling is available at checkpoint 6bfa91a. Subagent orchestration is not implemented.

Status: working local CLI. Automated tests are currently omitted. Existing session usage confirms post-tool cache reads; controlled steering/cache and billing measurements remain outstanding. See the cutover review and the differences below.

Setup

Requires Bun 1.4.2+ and macOS or Linux. Node.js is not required. The directory lock uses a Unix socket.

bun install --frozen-lockfile
bun run check

Pi packages are pinned to 1.1.0 in package.json; effect and @effect/platform-bun are pinned to 4.0.2. Dependencies and their integrity hashes are locked in bun.lock. No Pi/Effect source checkout, setup script, or separate model-catalog download is required: published Pi AI includes model data.

Source files use some node: compatibility APIs supplied by Bun; they do not start Node.js. Nut runs its TypeScript entrypoint with Bun and loads the published dependencies' compiled JavaScript, including Pi's dynamic OAuth modules.

Editor integration (ACP)

Run nut acp (or bun start acp) as a custom editor agent. It speaks Agent Client Protocol v1 over stdio, with sessions, streamed responses, cancellation, tool approvals and stdio MCP tools. Existing login/model settings apply; the normal CLI/TUI is unchanged. See ACP setup, supported capabilities and limitations.

Nix

The flake exports packages.<system>.nut (also default), a nut app, and overlays.default. Supported systems: Apple Silicon macOS, x86_64 Linux, and aarch64 Linux.

nix build .#nut          # result/bin/nut
nix run . -- --help
nix run . -- login --provider openai-codex
nix run .               # chat in the current project directory
nix profile install .#nut
nix flake check         # sandboxed TypeScript check

The package runs Nut's TypeScript entrypoint with Bun and the same published dependencies as bun install. Bun and registry tarballs (including Pi's bundled model data) are pinned; no install, submodule checkout, or catalog download is needed at runtime. Chat logs, credentials and local caches are excluded from package sources. Settings/memory still use the normal writable user/project paths, not the Nix store.

For an untracked working-tree flake, use path:. instead of . until the new files have been added to Git. For example, nix run path:. -- --help.

After changing bun.lock, regenerate Nix's integrity-pinned dependency manifest:

bun scripts/nix-deps.ts
bun scripts/nix-deps.ts --check

nix develop provides Bun and nixfmt for development (run bun install in the checkout). Pi updates are made through package.json and bun.lock, then the dependency-manifest regeneration above.

Run

Command parsing, validation, generated help, and shell completions use Effect v4's built-in effect/cli; the interactive chat remains Pi TUI. Bare bun start still starts chat, and existing shared flags work before or after subcommand names. Omitted flags retain the environment/saved-setting defaults.

bun start --help
bun start login --help
bun start memory zoom --help
bun start --version
bun start --completions bash  # also zsh, fish, sh

Inside chat, /help lists interactive commands and keyboard shortcuts. Memory maintenance commands still require an explicit --chat PATH.

export ANTHROPIC_API_KEY=...
bun start

Defaults:

  • Chat directory: existing <working-directory>/.nut/chat, otherwise ~/.nut/chat.
  • Agent and compactor: no implicit defaults. Login, then choose both with /model and /compactor; choices are saved. Chat opens without selections, but messages are not submitted until both are set.
  • Working directory: the current directory.
  • Instructions: AGENTS.md in the working directory, if present.
bun start --chat /path/to/chat --cwd /path/to/project
bun start --model openai/gpt-5-mini --compactor anthropic/claude-sonnet-4-5
bun start --prompt 'Inspect the project and suggest the next task.'

OpenAI supports either OPENAI_API_KEY (API billing) or ChatGPT subscription login. NUT_CHAT, NUT_MODEL, NUT_COMPACTOR, and NUT_AUTH_DIR set defaults through Effect Config. CLI flags take priority.

Memory uses an existing .nut/chat inside --cwd (or the launch directory); if absent, it falls back to ~/.nut/chat. No parent-directory or Git-root search is performed. To create project-local memory, run bun start --chat .nut/chat. Missing explicit memory directories are created automatically.

--chat overrides NUT_CHAT, which overrides automatic local/global selection. Credentials and saved model/thinking preferences remain global in ~/.nut/auth and ~/.nut/settings.json. Memory contains plaintext messages and tool output; review it before sharing.

Tool execution and recovered work use the current session's --cwd (or launch directory), independently of --chat. New agent configuration does not persist cwd. Older chats remain readable: saved cwd is ignored and cleared from current agent state, without rewriting historical records, message IDs, summaries, or zoom data. This does not redact paths already present in messages, tool arguments/output, or old runtime records.

ChatGPT subscription

  1. Stop any running Nut process that uses the same auth directory.

  2. Run the login command in an interactive terminal:

    bun start login --provider openai-codex
    
  3. Open the displayed URL in your browser.

  4. Sign in with your ChatGPT account.

  5. If the local callback does not finish, paste the full final redirect URL into the terminal.

  6. Select Codex for both the main agent and compactor:

    bun start --model openai-codex/gpt-5.5 --compactor openai-codex/gpt-5.5
    

No Anthropic or OpenAI API key is needed for this command. Both models consume your subscription's usage allowance. Model availability and limits depend on your account. There are no implicit model defaults; choose and save both models with /model and /compactor, or supply flags/environment variables.

bun start auth-status
bun start logout

Login defaults to Pi's openai-codex provider: its Codex OAuth client and ChatGPT backend, including browser and device-code login choices. This is distinct from the newer direct-token openai flow, which uses a different OAuth client and the public Responses API. Enterprise policy may allow one and not the other; live enterprise login has not been verified here. Pi owns OAuth, account metadata, and refresh for both paths.

To use the newer flow instead, run bun start login --provider openai, then select openai/... models. Existing openai credentials are preserved. logout also defaults to openai-codex; auth-status lists all providers unless --provider is supplied. Browser callbacks use port 1455; stop other pending logins if it is occupied.

Credentials live in ~/.nut/auth/auth.json, separate from chat history. The directory has mode 0700; the file has mode 0600. Writes use an fsynced temporary file and atomic rename. A stable installation ID is stored beside the credentials. OAuth metadata and refreshed tokens survive restarts. Nut serializes refreshes and waits for an active refresh to save its tokens before closing.

Multiple Nut processes can share an auth directory. Each read/update takes a short cross-process lock and reloads the file; OAuth refresh holds that lock through token rotation and saving, so another process uses the refreshed token. Login, logout and auth-status can run alongside chats. Logout affects future authenticated requests in all sessions. Use --auth-dir PATH or NUT_AUTH_DIR for a different private directory. Nut does not read or change Pi's or Codex's own credential files.

For the openai provider, saved OAuth credentials take priority over OPENAI_API_KEY. Codex credentials are separate and never fall back to this API key. A failed refresh does not silently switch to API billing. After logout, a set OPENAI_API_KEY becomes active again. Logout removes local credentials; it does not revoke the account grant remotely.

Credentials are plaintext secrets. Do not add the auth directory to Git or share it. A corrupt credential file causes an error rather than being replaced. Tests use fake tokens and mocked login/refresh flows; live account login has not been verified.

Model selection

  • bun start models: list the registered Anthropic, OpenAI, and Codex models, with credential status.
  • /models [filter]: searchable agent-model picker in the TUI; type to filter, use arrows and Enter, or Escape to cancel. Shows models with configured credentials, not a guarantee of account entitlement. Plain mode prints the catalog.
  • /model provider/model-id: select an agent model directly. /model opens the picker in the TUI or shows the selection in plain mode.
  • /compactor: separate compactor-model picker. /compactor provider/model-id selects directly.
  • /thinking and /compactor-thinking: separate thinking pickers; append a level for direct selection (e.g. /thinking high). Levels: off, minimal, low, medium, high, xhigh. Pi maps these to provider-specific options; non-reasoning models may ignore them and providers may map unsupported levels.
  • Selections are saved globally to ~/.nut/settings.json (override with NUT_SETTINGS). Agent and compactor choices are independent. Model precedence: CLI flags > NUT_MODEL / NUT_COMPACTOR > saved settings > unset (choose both before sending). --thinking and --compactor-thinking override the corresponding saved level for one launch without rewriting it.
  • /fast toggles agent fast mode; /fast on, /fast off, and /fast status are explicit forms. Saved globally with model preferences. Thinking effort and compactor speed remain unchanged.
  • Agent model/thinking/fast changes require an idle queue; finish work or /cancel first. Compactor changes affect new summary requests, not in-flight summaries.
  • If no settings have been saved yet, log in and run bun start, then use /model and /compactor to save choices. Subsequent launches need no model flags.

Multiple provider logins

Credentials coexist for anthropic, openai, and openai-codex. One credential per provider is supported, not multiple accounts within one provider. OAuth is the default; API-key login is available where Pi's provider supports it:

bun start login --provider openai-codex
bun start login --provider anthropic                 # Claude subscription OAuth
bun start login --provider openai --auth-method api_key
bun start auth-status                               # all providers, no token values
bun start logout --provider openai                   # leaves other logins intact

API-key prompts hide input. Credentials remain in the private auth directory, never the settings file. Auth commands use the same short transaction locks as running chats. /auth inside chat shows configured providers and login instructions. Existing environment-variable API keys still work.

Fast mode

Fast mode requests service_tier: "priority" for Codex/OpenAI Responses. Anthropic uses speed: "fast" and the fast-mode-2026-02-01 beta, preserving existing beta/cache settings. Supported Anthropic models follow the current fast-mode documentation: Opus 4.8, 5, and 5.5 (not Sonnet or Opus 4.6/4.7). The pinned catalog may not contain every supported model.

Availability depends on the model/account and provider limits; the UI reports requested, not confirmed fast service. Providers can reject a request or run it at standard speed. This is not a lower thinking budget. Premium prices or higher subscription usage may apply; footer estimates may omit fast-mode surcharges. Live fast-mode access is unverified.

Multiple instances

Run separate memories concurrently, sharing logins and saved preferences:

bun start --chat .nut/chat-one
bun start --chat .nut/chat-two    # in a second terminal

Nut automatically selects a private local session; if it is already busy, another instance gets an independent writer without stealing the primary default. --session new [--head EVENT_ID] explicitly forks and selects a new default; --session UUID selects a specific local session, which cannot be opened twice. Its runtime stays in ~/.nut/local/, outside shared memory. Shared settings updates also serialize across processes; existing sessions keep their own active selections. Different memories do not isolate filesystem/tool changes if both sessions use the same working directory. Restart sessions running older Nut code first: those still hold an auth lock for their whole lifetime.

Pi terminal UI

Interactive terminals open the Pi TUI by default. It uses @earendil-works/pi-tui components, not Pi coding-agent's separate session loop. The durable harness and memory tree still own all model work.

  • Multiline editor with input history and bracketed paste.
  • Markdown replies and working/thinking status.
  • Tool cards with running, done, and error states.
  • Command and file-path completion with Tab.
  • Terminal scrollback, resize handling, and recent messages on startup.
Key Action
Enter Send; when busy, steer at the next response/tool-round boundary
Alt+Enter Queue a fresh-turn follow-up
Shift+Enter / Ctrl+J Add a line (terminal support varies)
Tab Complete a command or file path
Esc Dismiss completion, or cancel active and queued work
Ctrl+O Expand or collapse retained tool output
Ctrl+D Quit when the editor is empty; wait for accepted work
Ctrl+C Suspend saved work and restore the terminal

File completion inserts a path; it does not attach the file. The agent can read it with read. The TUI shows thinking status, not reasoning text. Tool previews are bounded; the memory log remains the durable record.

Use bun start --plain for the previous line-based interface. Piped input and --prompt also use plain mode. The summary view is available through /view instead of filling the TUI at startup.

Terminal commands

Command Action
/view Print the current summary view
/zoom ID N Open a summary; N=1 returns the original message
/date ID Print the local date and time of a message
/tools List the tools available to the agent
/queue TEXT Queue a fresh-turn follow-up (also in plain mode)
/cancel Cancel active and queued work; keep user input in memory
/quit Stop reading input and wait for accepted turns to finish
/help Print help

Input sent during a run steers through Pi’s durable inbox, retaining the active context. It is delivered after the current response/tool round; it does not abort streaming or kill running tools. Alt+Enter or /queue TEXT saves a separate FIFO follow-up that starts with a fresh, settled memory view. Input arriving while idle (or still preparing the initial memory view) starts a fresh turn. EOF also waits for accepted turns. Ctrl-C closes the process and suspends durable work. Nut resumes the primary local session automatically; use --session UUID to resume a secondary lane specifically. --session new never resumes another session’s tools. Use /cancel to cancel work instead.

Available tools

Tool Action
read Read text files; large output can be truncated
write Create or replace a file
edit Replace exact text in a file
bash Run a shell command
zoom Open a memory summary or original message
date Get a memory message's local date and time

Use /tools in chat or bun start tools without credentials. Web search, browser control and subagents are not connected. Client-supplied stdio MCP tools are available in ACP mode only.

The tools are not sandboxed. read, write, edit, and bash run with your account's permissions. The working directory is not a security boundary.

Browse and import

These commands use the same directory lock. Stop the chat process first.

bun start view --chat /path/to/chat
bun start browse --chat /path/to/chat --output memory.html
bun start import --chat /path/to/chat --input old-notes.txt
bun start import --chat /path/to/chat --input history.jsonl

Text files become one note. JSONL imports use one record per line:

{"kind":"user","text":"Keep the original algorithm.","date":"2026-01-02T03:04:05.000Z"}
{"kind":"talk","text":"Saved it in src/algorithm.ts."}

Valid kinds: user, talk, tool, echo, note. Dates are optional. Nut assigns permanent message IDs. Import validates all records before writing. Importing the same file contents again in the same local session does not duplicate messages. Changed file contents are a new import.

The HTML export contains the selected path's view, original messages, and tree levels. Links connect summaries to children and original messages. It escapes message text and does not run scripts.

Storage and recovery

chat/
  format.json                       Graph format marker (version 2)
  objects/YYYY-MM-DD/<sha256>.json   Immutable events, threads, summaries, imports
  packs/YYYY-MM-DD/<sha256>.jsonl   Immutable packs of the same objects
  blobs/<sha256>                    Immutable attachments (when present)
~/.nut/local/<store-key>/
  default-session.json              Private primary-session pointer
  sessions/<uuid>/session.json      Private ownership descriptor
  sessions/<uuid>/runtime/          Pi entries, queue, tasks and checkpoints
~/.nut/local-locks/                 Process-local socket locks

Objects are content-addressed and validated on load. Publication fsyncs a temporary file, links it without overwriting an existing object, then fsyncs its directory. Missing or corrupt dependencies stop loading; Nut never skips records or renumbers history. The view is a bounded first-parent projection, not the entire graph. Every preserved message remains reachable through hash-based zoom and paginated history/thread discovery.

Reducing file count

Writable sessions silently check for maintenance at startup and every 30 seconds, packing when at least 256 loose objects have accumulated. Errors are reported; normal maintenance requires no action. Read-only views do not run maintenance. Stop/upgrade pre-pack-support processes before starting this version.

For explicit maintenance or inspection, these commands remain available:

bun start memory pack --chat .nut/chat
bun start memory verify --chat .nut/chat

pack groups loose objects by their original local day into roughly 4 MiB packs (one larger object can exceed that target). It verifies each packed copy before removing loose files. Exact contents, object IDs, timestamps, links, summaries and legacy zoom references do not change. Attachments stay separate.

New objects are written loose and automatically packed at the threshold. Packs are immutable and shareable through Git. Overlapping packs from independent writers are deduplicated by object hash, not merged or rewritten. Readers rebuild their index in memory, so no database or tracked index is needed. Pack-aware sessions can stay open during maintenance. Interrupted packing may leave redundant copies but can be rerun safely. Existing packs are never deleted by this command.

Packing adds storage: "packs-v1" to the format marker so older Nut versions refuse to open the store instead of silently ignoring packed history. Do not remove that marker or use an older, already-running reader after packing.

Raw runtime entries project into memory with session-scoped source IDs. Startup scans them, including entries hidden by resets, repairing a crash between a runtime commit and memory projection without duplication. Runtime stays private; pulling shared memory cannot resume another machine's tools. Explicitly selecting a local session can resume its own pending work.

The pinned Pi JSONL backend flushes sidecars; src/runtime-storage.ts also flushes its main commit marker before publication. Unsafe interrupted tools are not automatically replayed. This is not a claim of exhaustive power-loss safety; see the cutover review.

Back up shared memory and private runtime separately. Git stores history, not pending execution. Files are unencrypted and may contain private messages or secrets copied by tools. Scan traces before sharing; never commit runtime, credentials, settings or locks. V1 storage and migration commands are retired; use checkpoint 6bfa91a for an offline conversion of an older store. Imported objects and numeric-reference mappings remain supported.

Effect architecture

  • src/app.ts: AppConfig, NutModels, MemoryStore, and ChatAgent services. Layers own resources with Effect.acquireRelease. Errors are schema-backed tagged errors.
  • src/cli.ts: Effect workflows, input streams, scoped fibers, and BunRuntime.runMain.
  • src/tui.ts: Pi editor, Markdown transcript, and committed tool activity. Its lifetime belongs to the CLI scope.
  • src/auth.ts: scoped Effect authentication service and browser-login terminal interface.
  • src/credentials.ts: private, locked, atomic credential storage for Pi's OAuth callbacks.
  • src/schema.ts: persisted record and import schemas.
  • src/memory.ts: incremental view and binary tree. Node workers use Effect.retry with a fixed Schedule.spaced delay.
  • src/compactor.ts: named Effect workflow around the model SDK. Byte-limit correction stays in one conversation.
  • src/durable.ts: Promise adapter for Pi's durable API, fresh contexts, recovery, and memory projection.
  • src/cache.ts: complete-line view splits and provider payload policy.

The memory engine and Pi adapter retain Promise interfaces at their integration boundary. The Effect service layer owns their lifetime. Shutdown closes the agent before releasing the memory lock.

Spec coverage and differences

Implemented:

  • Append-only, word-for-word memory records, except capped ordinary tool results.
  • Pure binary summaries; short sources become free nodes.
  • Ordered leaf compression with summarized context and concurrent merges.
  • 512-byte summaries; over-limit compressor results retry without truncation. Imported over-limit artifacts remain unchanged.
  • Eight worker slots and fixed 10-second retries, with the first failure reported once per node.
  • Incremental 128,000-byte view; oldest-relative-to-size merge order; no splits.
  • Wait for summaries before new turns; capture the view before logging new input.
  • Fresh model context per turn; stable system prompt and tools.
  • Anthropic view cache marks near 50k, 80k, and 100k characters, plus automatic request-end caching.
  • Tool results capped to 30,000 characters with head and tail retained.

Deliberate differences and limits:

  1. Reasoning: Shared graph events and summaries do not include provider reasoning. Pi's private runtime/ log does store reasoning and signatures for recovery and within-turn replay. It retains old turns too.
  2. Busy input: Enter steers within the current context at Pi’s next boundary (one message per boundary). Explicit follow-ups remain separate fresh turns, not a batch. Both modes survive restart; /cancel cancels both and retains unanswered user input. Existing saved FIFO turns keep their original behavior.
  3. OpenAI caching: uses implicit caching, store: false, encrypted reasoning replay, and all_turns reasoning context. Per-block prompt_cache_breakpoint fields are not added. Post-tool cache reads have been observed; controlled mid-run-message measurements remain outstanding (see the cutover review).
  4. Full-message zoom: exempt from the tool-result cap, so large original messages remain retrievable. Built-in coding tools can apply their own output limits before Nut's cap.
  5. No ordinary compaction: Pi's threshold and overflow compaction are disabled. A single very long tool loop can exhaust the model context and fail. Start a new turn to use the summary view.
  6. Local process: no remote attachment server, optional subagents, computer tools, or automatic backups. Run in a persistent terminal session on an always-on machine if needed.
  7. Scale: history and tree indexes are held in RAM. Large-history performance has not been benchmarked.
  8. Terminal presentation: the TUI redraws content for usability. Use --plain for the spec's line-based interface.

Automated tests are intentionally omitted for now. Use bun run check; manual verification and its limits are recorded in docs/memory-review.md.

bun audit currently reports one high-severity advisory for braces in the linked Pi development-tool chain (shx → shelljs → fast-glob → micromatch → braces). Nut does not call that tool chain. No forced dependency downgrade has been applied.

The interactive footer shows current-run input/output tokens, cache reads/writes, latest agent prompt cache-hit percentage, and catalog-estimated cost (with compactor cost included in the total). Totals include completed agent and summary responses, including summary length retries, and update when responses finish—not token-by-token. They reset on restart; restored history is not charged again in this display. Provider usage may be unavailable for failed/interrupted requests. Catalog estimates are not invoices or subscription quota/charges (including Codex subscriptions).

Startup context and lock errors

Startup does not display memory paths, session details, or context tables. Request /context for a snapshot preview or /view for the memory table. This is the context for a fresh turn, not an exact provider request: summaries can finish afterward, and recovered in-flight work may retain an earlier snapshot.

A chat memory has one process owner. If startup says Chat is already open, use a different --chat directory or close its owner. Shared credential/settings transactions wait briefly for each other; never delete an active lock. Flags override settings for that run only; use /model and /compactor to save choices for flag-free startup.