# Changelog All notable user-visible changes to Pythinker land here. The project follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/) and uses [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [Unreleased] ### Added - Added `runtime.maxConcurrentSubagents` to cap how many subagents run their LLM/tool loop at once (`0` = unlimited, preserving prior behavior). - Added Telegram webhook mode (`channels.telegram.mode: "webhook"`) with `webhookUrl`/`webhookSecretToken` and related listener settings, plus per-conversation ordered delivery of incoming Telegram updates. - Added sustained-goal support: the `/goal` command plus `long_task` / `complete_goal` tools let the agent track a long-running objective across turns (mirrored into runtime context, kept active until `complete_goal`). ### Fixed - Updated the Kagi web-search integration to the v1 Search API (`POST`, `Bearer` auth, `data.search` results). - Codex provider transport/API failures now return typed, retryable error metadata (status, kind, retry-after) instead of a bare error string, and no longer leak raw upstream response bodies into error messages or logs. - Codex provider now honors `PYTHINKER_AI_STREAM_IDLE_TIMEOUT_S` (default 90s) for its stream timeout instead of a hardcoded 60s, matching the other streaming providers. - A non-integer `PYTHINKER_AI_STREAM_IDLE_TIMEOUT_S` now falls back to the 90s default across all streaming providers instead of crashing the request. ## [2.7.1] - 2026-05-25 ### Added - Added `providers.openai.apiType` to force OpenAI Chat Completions or Responses API requests, with Responses-shaped `extraBody` merging. - Added structured `apply_patch`, long-running exec sessions, `write_stdin`, `list_exec_sessions`, and `find_files` for safer coding workflows. ### Changed - Improved file-edit progress events and coding-tool guidance for patch, search, file, and process workflows. - Fixed WebUI file-activity summaries, inline file-reference alignment, and optimistic new-chat visibility during session refreshes. - Switched the documented native installer entrypoints to short universal URLs: `curl -fsSL https://pythinker.com/ai | bash` for macOS/Linux and `irm https://pythinker.com/ai.ps1 | iex` for Windows. - **BREAKING: renamed the CLI command, runtime directory, and environment-variable prefix to avoid clashing with the separate `pythinker-code` tool**, which also installs a `pythinker` executable and reads `~/.pythinker/`. - Console script is now `pythinker-ai` (was `pythinker`); native, `.deb`, `.rpm`, and Homebrew installs expose the same `pythinker-ai` command. `python -m pythinker` is unchanged. The Homebrew formula no longer needs `conflicts_with "pythinker-code"`, so both tools can be installed side by side. - Per-user runtime directory moved from `~/.pythinker/` to `~/.pythinker-ai/`, and the per-workspace directory from `.pythinker/` to `.pythinker-ai/` (config, sessions, workspace, history, bridge, tool-results, task-results, `plan.md`). No automatic migration: copy existing state across by hand if you need it. - Environment variables now use the `PYTHINKER_AI_` prefix (e.g. `PYTHINKER_AI_TOKEN`, `PYTHINKER_AI_CONFIG`, `PYTHINKER_AI_API_URL`, `PYTHINKER_AI_TOOLS__WEB__BROWSER__*`). Update any shell profiles, service units, or compose files that set `PYTHINKER_*`. ## [2.7.0] - 2026-05-22 ### Added - **Native installers for every platform.** Pythinker now ships per-OS packages alongside the PyPI wheel: - Windows: `PythinkerSetup-2.7.0.exe` (Inno Setup wizard, per-user install, HKCU PATH edit, no UAC). - macOS (Apple Silicon + Intel): `brew install mohamed-elkholy95/pythinker/pythinker-ai` via auto-published Homebrew tap. - Debian / Ubuntu: `pythinker-ai_2.7.0_{amd64,arm64}.deb`. - Fedora / RHEL / openSUSE: `pythinker-ai-2.7.0.{x86_64,aarch64}.rpm`. - Cross-OS curl-bash: `scripts/install-native.sh` auto-detects OS+arch, verifies SHA-256, lands a single PyInstaller-frozen binary at `~/.local/bin/pythinker`. Every artifact ships with a matching `.sha256` file; the release workflow uploads both to the GitHub Release. - **`pythinker update` command** — queries the GitHub Releases API, detects how the running CLI was installed (brew / dpkg / rpm / exe / pyinstaller / pip), verifies SHA-256, and re-runs the matching installer in place. Set `PYTHINKER_CLI_NO_AUTO_UPDATE=1` to disable the proactive startup check. - **Homebrew tap auto-publish.** `.github/workflows/homebrew-tap.yml` regenerates `Formula/pythinker-ai.rb` on every release and pushes it to [`mohamed-elkholy95/homebrew-pythinker`](https://github.com/mohamed-elkholy95/homebrew-pythinker), so `brew upgrade pythinker-ai` always finds the latest version with no hand-curation. - **Pre-built container image** published to GitHub Container Registry on every release at `ghcr.io/mohamed-elkholy95/pythinker-ai`. Multi-platform (amd64 + arm64). Pull directly with `docker pull ghcr.io/mohamed-elkholy95/pythinker-ai:latest` instead of running `docker build` locally. See `docs/deployment.md`. - WebUI bundle is now built inside the Dockerfile via a dedicated `webui-builder` stage (Bun runtime, pinned to BUILDPLATFORM), so fresh checkouts produce a self-contained image without a pre-step. - **Novita AI provider** (`novita`) — OpenAI-compatible gateway for hosted model APIs at `https://api.novita.ai/openai`. Set `NOVITA_API_KEY` or the config key `providers.novita.apiKey`. ### Changed - Legacy install paths (`scripts/install.sh`, `scripts/install.ps1`, `uvx`, `uv tool install`, `pipx install`, bare `pip install`) keep working but now print a deprecation banner. Set `PYTHINKER_INSTALL_QUIET_DEPRECATION=1` to silence it. README Quick Start leads with the per-OS native installer table. ### Fixed - Dockerfile now copies `hatch_build.py` alongside `pyproject.toml`, fixing a clean-checkout build that would otherwise fail when hatchling tries to load the wheel-time freshness hook declared in `pyproject.toml`. - `pythinker-gateway` compose service now exposes port 8765 so the WebUI / WebSocket channel is reachable on host (previously only 18790 was bound). ## [2.6.0] - 2026-05-20 ### Added - **Signal channel** adapter using the `signal-cli` daemon (HTTP/SSE). Supports DMs and group chats with independent open/allowlist policies, markdown→Signal text-style conversion (with UTF-16 offsets), typing indicators, attachment handling, group-message context buffering, and automatic reconnect with exponential backoff. See `docs/chat-apps.md` for setup. - **DM pairing system** — first-time DM senders on any channel now receive a one-time pairing code; the owner approves via `/pairing approve ` and the sender is added to the channel's persistent approval list at `~/.pythinker/pairing.json`. New `/pairing` slash command supports `list | approve | deny | revoke`. - `BaseChannel` instances now expose `self.logger` (a loguru logger bound with `channel=`) so per-channel diagnostics carry context automatically. - Channel modules are now loaded lazily via `discover_enabled()`: only modules for explicitly enabled channels are imported, skipping heavy SDK imports (telegram, discord, slack, etc.) at startup. ### Performance - OpenAI-compatible provider clients (`AsyncOpenAI`) are now initialized on first use instead of at provider construction time, saving ~700 ms cold-start cost from the openai + httpx import chain. ### Fixed - `AnthropicProvider.chat()` now transparently retries via `chat_stream` when the Anthropic SDK raises `ValueError("Streaming is required for operations that may take longer than 10 minutes...")` for non-stream `messages.create` calls. Long generations no longer surface this provider-specific error to callers. - Shell tool commands now detach stdin (`stdin=DEVNULL`) so interactive prompts no longer block agent turns. - Skywork provider `default_api_base` corrected from `/v1` to `/agent/v1`. - Packaging: WebUI dist files are now declared via hatch `artifacts` instead of duplicate `include` + `force-include` directives, fixing a duplicate-filename error that caused PyPI to reject the 2.5.2 wheel upload. ## [2.5.2] - 2026-05-19 ### Added - File-edit chips now animate added/deleted line counts *while the model is still streaming the tool-call JSON*, instead of materializing only after the call completes. A new `StreamingFileEditTracker` consumes per-chunk tool-call argument deltas from the provider's streaming surface, runs them through an incremental JSON-string scanner that survives partial `\uXXXX` escapes split across chunks, and emits throttled `file_activity` events (`approximate=true`) with a leading `~` rendered in the chip. The streaming hook covers OpenAI-compatible chat/completions, Anthropic Messages, and the OpenAI Responses API surface (chat.completions providers animate counts in real time; the OpenAI Responses API — Codex / GPT-5 / o-series — ships full argument payloads at `output_item.done` time, so its chips show the path immediately but the count snaps from the start state to the exact diff rather than climbing). Live counts cleanly merge with the eventual exact diff once the tool actually executes. - WebUI now restores the in-flight file-edit chip cluster after a refresh. The runtime appends each `file_activity` / `provider_failover` event to a small per-chat JSONL transcript under `~/.pythinker//webui/activity/.jsonl` (256 KiB cap, opportunistic trim), and the WebUI sends a `webui_activity.replay` envelope on attach. The server returns only events after the most recent turn boundary, so completed turns stay quiet and a refresh mid-turn rebuilds the chip cluster instead of leaving the user staring at a bare assistant bubble. Replay is best-effort: persistence and reply failures are silent so the live event delivery remains the source of truth. - The runtime's per-tool `file_activity` events (shipped in 44f917ea) now drive a live "files being edited" cluster above the assistant bubble in the WebUI. Each cluster is a collapsed one-line summary ("3 files edited (+45 −12)") that expands to a row of `FileEditChip`s; chips animate while editing, show a check + diff stats on completion, and a red alert on error. Clicking a chip opens a read-only side panel that fetches the file via the new admin-only `webui_file_read.get` envelope (workspace-relative paths only; resolved paths are checked against the workspace root, content is capped at 1 MiB with a "truncated" notice, binary files surface a placeholder instead of mojibake). Clusters freeze on the turn boundary so subsequent turns get their own cluster. - WebUI Config Workbench now renders the masked preview hint that the admin endpoint returns for each configured secret (e.g. `sk-1••••cdef`) instead of a static "Secret value hidden" label, and the restart banner is now driven by the live `requires_restart` flag — it appears immediately when pending sections exist (carried across reloads), lists which top-level sections changed, and offers a "Copy restart command" button that puts `pythinker restart` on the clipboard. - The admin overview now lists the resolved fallback chain (e.g. `anthropic/claude → openai/gpt-mini`) next to the active provider, and a dismissible amber toast surfaces above the thread composer whenever the runtime transparently fails over to a backup model. The toast is deduped per turn so a single swap surfaces once even when the WebUI replays multiple delivery attempts; starting a new turn re-enables notices for the same pair. Backend-wise, `FallbackProvider` now emits a `provider_failover` bus event through a contextvar-bound callback that the agent loop installs around `_run_agent_loop`. - The WebUI sidebar now consumes the `webui_sidebar_state.get` / `.set` envelopes that the gateway has shipped since 21c331ce: a new "View options" dropdown next to the sidebar's theme toggle lets the admin switch the chat-list density between Comfortable and Compact and toggle "Show archived". The Pinned / Recent / Archived collapse state is now persisted too, so a reload restores exactly what was on screen. Writes are debounced to 500 ms; non-admin connections fall back to in-memory state so the UI keeps working but warns nothing has been persisted. Pin / archive themselves continue to live in per-session sidecars — the new typed state stores view preferences only. - `agents.defaults.fallbackModels` now drives a runtime failover chain: when the primary model returns a transient error (timeout, rate-limit, 5xx, overloaded) and nothing has been streamed yet, the runtime tries each fallback model in order. Entries can reference an existing `modelPresets` entry by name or inline a `{ model, provider, ... }` object that inherits generation params from the primary preset. The primary is circuit-broken after 3 consecutive failures (60 s cooldown) to stop wasting requests on a known-bad endpoint. Authentication, permission, content-filter, context-length, and 4xx-invalid-request errors do not trigger failover. ### Fixed - WhatsApp media downloads now pass Baileys' media reupload callback, retry transient fetch failures, skip undecryptable payloads with sanitized metadata, and redact upstream Signal session objects from bridge console output. - WhatsApp bridge startup now reports a friendly port-in-use error instead of an unhandled WebSocket server exception when another bridge is already bound to the same port. - WhatsApp bridge reconnects keep retrying indefinitely, but after 10 failed attempts the retry interval stretches further to reduce repeated connection churn while the bridge is down. ## [2.5.1] - 2026-05-17 ### Added - WhatsApp replies now keep a Baileys typing indicator active while the agent turn is in progress. - WhatsApp can send blue-tick read receipts on accepted inbound messages (`channels.whatsapp.send_read_receipts`). - WhatsApp typing, text chunking, media size limits, bridge reconnect backoff, and bridge socket timeouts are now configurable. - WhatsApp direct messages can be gated with `dm_policy`, including one-time pairing codes from `pythinker channels pair whatsapp`. - WhatsApp group handling supports `group_policy: "allowlist"` with `group_allow_from`. - WhatsApp voice/Opus outbound audio is sent as a proper voice note. ### Changed - WhatsApp chat-level presence now targets the phone JID instead of the LID when available. ## [2.5.0] - 2026-05-17 ### Added - Provider-aware model metadata registry with checked-in curated model limits, source/confidence tracking, user overrides, and Azure deployment-to-base-model mapping. Runtime startup remains offline by default. - Per-model context-window profiles are used automatically when `contextWindowTokens` is unset, including Codex OAuth GPT-5.5 at 400k total / 272k input / 128k output and direct/gateway profiles with provider-specific limits and tokenizer encodings. - Native Anthropic providers can count tokens via `POST /v1/messages/count_tokens` with a 60s in-memory TTL cache and 429-aware retry. - `BudgetPolicy` unifies consolidator and runner snip budget math and clamps invalid output reserves instead of crashing a turn. - WebUI usage displays a stacked `floor / history / headroom` bar with `floor_status`, and assistant turns emit a PII-safe structured `context_turn` event for estimator drift tracking. - Usage ledger rows now include estimated USD costs for priced models, starting with GPT-5.5 input/cache/output pricing from the OpenAI model docs; the WebUI cost card shows estimated or partial totals when available. ### Fixed - Progressive suffix matching now resolves multi-slash gateway model ids such as `openrouter/anthropic/claude-opus-4-7`. - Consolidator boundary selection has a relaxed fallback for assistant/tool stretches, and token probes include the real incoming user message instead of a placeholder. - Background auto-compact archives acquire the per-session lock via an injected lock provider, preventing concurrent archive from swapping the session while a turn is assembling context. - `derive_window` is defensive against provider subclasses that raise from `get_model_limits`. ### Changed - Microcompact eligibility is now determined by `Tool.compactable` rather than a hardcoded tool-name set, so MCP tool results are eligible by default while side-effect tools opt out. - `clamp_context_window` is preserved as an alias for the new `derive_window` helper. - The maintainer metadata refresh tool writes atomically, supports strict parser-regression exits, and can refresh provider snapshots from supported public metadata APIs. ## [2.4.0] - 2026-05-15 ### Added - Slash-command exchanges are now persisted to chat history so the TUI can replay them across sessions, while a sentinel tag keeps the rows out of the LLM context window. ### Changed - Onboarding visual refresh on the clack timeline: the completed-step marker is now `●` (solid circle), the active prompt is `◉`, and note panels close with a rounded `╰─╯` corner so each block reads as a closed loop on the rail. The wizard accent shifts from terminal cyan to a muted violet (`#9277c4`) across the welcome banner, settings tables, signup panel, and inline highlights. - Mascot rebrand from `🐍` to `🤖` across the logo, TUI welcome, `/commands` header, onboarding outro, SOUL persona template, WhatsApp bridge banner, README, and docs. - Long titles, status lines, and resolved-answer rows now wrap so every continuation row stays on the `│` timeline rail instead of breaking out at column 0; the recorded answer row no longer escapes the bar on narrow terminals. - Active questionary choice rows are aligned to the timeline rail, and the stale default-row green highlight that lingered after the cursor moved is cleared so only the hovered row is styled. - Settings field editor and other Rich-rendered hover states share the same green-on-default treatment as the onboarding picker for visual consistency. ### Fixed - Slash-command history is now persisted between sessions instead of being lost when the TUI restarts. - Resolved-question records and status lines no longer break the persistent `│` timeline when they wrap on narrow terminals. ## [2.3.0] - 2026-05-14 ### Added - WhatsApp voice messages now download bridge-side `audioMessage` media so the Python channel can transcribe them when voice transcription is configured. - Added an internal upstream audit log tracking fixes that were ported, already present, deferred, or not applicable. ### Changed - Project-facing descriptions now use “tiny agent” wording instead of “ultra-lightweight” to match the intended positioning. - `web_fetch` now reports common site-side blocks (`401`, `403`, `451`) as structured `blockedBySite` tool results and logs them as warnings instead of errors. - `web_fetch` trims common Markdown/backtick/quote wrappers around URLs before validation, making copied links like `` `"https://example.com"` `` work as expected without loosening SSRF checks. - MCP server startup is more defensive: HTTP/SSE servers are TCP-probed before entering MCP transports, servers connect sequentially to avoid anyio cancel scope spin, and MCP-derived tool/resource/prompt names are sanitized for provider API compatibility. - OpenAI/Groq voice transcription now retries transient failures and handles malformed provider responses without throwing away the whole channel turn. ### Security - Telegram, Email, and WhatsApp now apply `allowFrom` checks before inbound side effects such as media downloads, attachment extraction, reactions, and voice transcription. - Matrix now ignores pre-startup replay events, stops sync on fatal auth responses, and skips sending blank outbound text messages. ### Fixed - `reasoningEffort: "none"` now disables provider-specific thinking flags for DashScope, MiniMax, VolcEngine/BytePlus, Xiaomi MiMo, and Kimi thinking models instead of accidentally enabling them. - VolcEngine providers now use `max_completion_tokens`, matching providers that reject legacy `max_tokens` for reasoning-capable endpoints. ## [2.2.0] - 2026-05-06 ### Added - **Multi-agent workspace layout.** New `pythinker agents` subcommand plus a wizard-driven onboarding flow lay out per-agent configs under `~/.pythinker/agents//` with isolated workspace, history, and memory. Per-agent config-path resolution (`pythinker --agent ...`) lets one host run several independent agents side by side. - **`/init` slash command.** Generate a tuned `AGENTS.md` for the current workspace from a template, populating provider, channel, and tool defaults so a fresh agent has sensible operating ground rules on first run. - **Dynamic prompt injection.** Runner now ships a dynamic-injection scaffold with `plan` and `afk` providers that compose just-in-time context into the system prompt — laying groundwork for richer context-aware steering without permanent prompt bloat. - **Subagent role split.** Subagents now ship in three flavours — `coder` (full tool set), `explore` (read-only navigation), and `plan` (planning-only, no write/edit/shell) — selectable from the spawn call. Default remains `coder` for backwards compatibility. - **Structured compaction prompt.** History consolidation now runs a structured prompt that yields tighter, role-aware summaries with predictable section ordering (status / decisions / open threads). - **Coding-directives prompt block.** Root system prompt now includes a coding-directives block reinforcing surgical edits, verification before completion, and explicit assumption-surfacing. Lifts the baseline behaviour of the agent on engineering tasks without per-tool prompt rewrites. - **Autonomous task spine.** Subagents are now tracked as first-class task records with durable per-task output files under `.pythinker/task-results/`. Three new chat commands let you observe and steer them: `/tasks` lists active and recent tasks for the current session, `/task-output ` shows the latest bounded output tail, and `/task-stop ` cancels a running task by id. Output files survive process restarts and can be re-read after a crash via `/task-output`. - **WebUI admin: live agent + subagent panel.** The Agents tab now shows, for each session, whether a turn is in flight and any spawned subagents — with phase, iteration, elapsed time, and the last tool event. Stale empty entries from the agent loop's per-session task map are filtered so the panel only lists sessions that are actually busy. - **WebUI admin: stop, restart, and cancel controls.** Per-row buttons in the Sessions tab and the Live agents panel hit three new GET routes (`/api/admin/sessions/{key}/stop`, `/api/admin/sessions/{key}/restart`, `/api/admin/subagents/{task_id}/cancel`). Restart cancels the in-flight turn and clears the runtime checkpoint and pending-turn state so the next message starts fresh from persisted history; it refuses to materialise a session for an unknown key. - **WebUI admin: log timestamps.** The Logs tab now renders a `HH:MM:SS` leading column when the backing entry carries a `ts`, `time`, or `timestamp` field. Entries without a timestamp are unchanged. ### Security - Admin write endpoints require an `X-Pythinker-Admin-Action: 1` request header in addition to the existing bearer token. Cross-site browser tabs can fire GET requests from `` / `
` elements but cannot set custom headers without a CORS preflight that the server never answers, so this header alone defeats drive-by writes for the localhost-only deployment posture Pythinker targets. See `docs/security.md` for the full rationale. ### Fixed - **TUI slash menu Down arrow moves in one press.** The completion popup paints row 0 as highlighted via a render-time index lie (`HighlightFirstCompletionsMenu`); prompt_toolkit's default Down handler then transitioned `complete_index` from `None → 0`, producing no visible change. Custom Down/Up bindings now treat the visual state as the source of truth and cycle modulo the completion count, so the first arrow press visibly moves to the second option. Enter applies the completion at the highlighted index. ### Internal - **Large refactor pass.** Split `loop.py`, `runner.py`, `commands.py`, `memory.py`, `websocket.py`, `telegram.py`, the filesystem-tool guards, and the onboarding driver into focused packages with thinner top-level files. No public-API change — all existing imports continue to work via re-exports. ## [2.1.1] - 2026-05-03 ### Fixed - **WebUI: empty stream-end placeholders no longer linger.** Reasoning models that emit only `...` text on the wire before a tool call (DeepSeek-R1, MiniMax `reasoning_split`, VolcEngine `thinking`) used to leave a blank assistant bubble after the stream closed; the WS stream end now drops messages whose visible delta text is empty. - **Agent: `` blocks are now stripped from generated chat titles.** Reasoning models occasionally prepended chain-of-thought to the title prompt response; `_clean_title` now removes any `...` span before quote/punctuation trimming so titles read cleanly in the sessions list. ### Changed - **Internal lint hygiene.** Test tree now passes the full ruff rule set (E, F, I, N, W) cleanly; `pytest.mark.timeout` is registered; `asyncio.wait_for(coro, timeout=...)` in `pythinker/agent/loop.py` is replaced with the recommended `async with asyncio.timeout(...)` form to suppress a spurious `RuntimeWarning: coroutine 'Queue.get' was never awaited`. No public API change. - **PyPI metadata.** Author now resolves cleanly to `Mohamed Elkholy `; project Homepage now points to `https://pythinker.com`. ## [2.1.0] - 2026-05-02 ### Added - **Config Workbench admin UI.** The Admin Config tab now ships a schema-driven workbench replacing the previous dotted-path text editor. Includes a left-rail service navigator, 11 service dashboards, secret rotation modal, full-text search, pending-diff drawer, provider matrix, channel grid, and SSRF coverage bar (`webui/src/components/admin/config/ConfigWorkbench.tsx`, `webui/src/components/admin/config/SchemaForm.tsx`). - **Smoother streaming in the WebUI.** `usePythinkerStream` now coalesces WebSocket deltas through `requestAnimationFrame`, collapsing bursty token chunks into one render per frame. All cleanup paths (stream_end, error, stop, regenerate, edit, chat-switch) cancel the pending frame and flush trailing text. - **Streamdown-powered markdown rendering.** `MarkdownText` swaps `react-markdown` for Streamdown — block-level memoization, `parseIncompleteMarkdown`, per-word `fadeIn` animation gated on `isStreaming` and a JS-side `useReducedMotion`. - **Stick-to-bottom scroll behavior.** `ThreadViewport` replaces the hand-rolled `scrollTo` + `NEAR_BOTTOM_PX` heuristic with `use-stick-to-bottom` (ResizeObserver + spring). Single upward flick disengages auto-follow cleanly; the floating pill calls `scrollToBottom('smooth')`. - **Reasoning-aware typing dots.** `MessageBubble` now gates the typing-dots placeholder on the post-`extractThink` visible text so reasoning-model deltas (DeepSeek-R1, Claude extended thinking, MiniMax `reasoning_split`, Volcengine `thinking`) keep the dots bouncing until the actual answer starts streaming. The reasoning drawer renders alongside the dots so users can watch reasoning roll in. - **Usage tab redesign.** `admin/UsageView` now ships segmented Summary / Sessions / Ledger sub-views, four tone-tinted KPI cards, an SVG donut + segment legend for the last-turn breakdown (auto-includes provider extras like cached_input/reasoning tokens), a top-sessions panel with color-escalated context-window bars, channel rollup with gradient bars, and a full sessions table with progress bars. Raw ledger preserved under its own view. - **Package-first browser tool launch mode.** `playwright` now ships with the default install, `tools.web.browser.mode` supports `auto` / `launch` / `cdp`, launch mode can lazily provision Playwright Chromium, and `pythinker doctor` reports browser configuration and provisioning status. - **Browser runtime lifecycle controls.** Browser contexts now enforce idle eviction, optional browser disconnect-on-idle, per-context page limits, and next-turn hot reload when browser config changes. - **Browser maintainer guidance.** Runtime prompt templates now distinguish `web_fetch` from headless Chromium browser automation, and maintainer skills cover browser triage and verification paths. ### Changed - **`pythinker-ai[browser]` compatibility alias.** The extra remains accepted for older install commands, but no longer adds packages because Playwright is part of the base dependency set. ### Fixed - **First-use Chromium provisioning no longer blocks other chats.** `BrowserSessionManager._ensure_browser` now releases its connect lock while `python -m playwright install chromium` runs, so a 30-300 s provisioning subprocess on chat A cannot stall chat B's `acquire()`. - **`auto` mode falls back to launch mode when an explicit `cdpUrl` is unreachable.** Now covered by a regression test (`test_auto_mode_falls_back_to_launch_when_configured_cdp_unreachable`). - **`shutdown(force=True)` actually skips per-context cleanup.** Used by the hot-reload 10 s deadline path so a hanging context-close cannot block configuration changes from taking effect. - **`pythinker doctor` no longer crashes when invoked from inside a running event loop.** The CDP probe is skipped with a `warn` result instead of raising `asyncio.run() cannot be called from a running event loop`. ## [2.0.2] - 2026-05-01 ### Fixed - **Onboarding wizard — Use existing config short-circuits to outro.** Picking *Use existing* now jumps straight to the final step instead of walking the user through provider/channel/search/save prompts that would overwrite the on-disk config (`pythinker/cli/onboard.py:339-361`, `:1459`). - **Onboarding OAuth login passes the registry id, not the display name.** `_step_run_auth` now hands `_login_via_oauth_remote` the canonical `spec.name` (e.g. `openai_codex`) instead of the human-readable `ctx.auth` label, fixing browser-login failures for providers whose display name and registry id differ (`pythinker/cli/onboard.py:706`). - **"Saved" vs "Updated" wording for fresh installs.** First-time saves log `Saved ` instead of misleadingly reporting an update (`pythinker/cli/onboard.py:1334`). ### Changed - **Existing-config and pre-save summaries iterate the provider registry.** `render_existing_summary` and `render_pre_save` no longer rely on a hard-coded shortlist; any provider declared in `PROVIDERS` is now detected, and channel configs stored as dict extras are correctly reported as enabled (`pythinker/cli/onboard_views/summary.py`). ## [2.0.1] - 2026-05-01 ### Added - **Admin dashboard** — tabbed web UI surface (`/admin`) with Overview, Config, Sessions, and Usage tabs; powered by new `pythinker/admin/service.py` and `webui/src/components/admin/AdminDashboard.tsx`. - **`UsageLedger`** — per-session token and cost accounting (`pythinker/agent/usage_ledger.py`) surfaced in the admin Usage tab. - **Config editing API** — `pythinker/config/editing.py` exposes `read_config_value`, `set_config_value`, `unset_config_value`, and `save_config_with_backup` for safe, auditable config mutations from the admin UI or CLI. - **WebSocket admin endpoints** — `/admin/config`, `/admin/sessions`, `/admin/usage` REST surfaces on the gateway port; token-gated so only authenticated clients can mutate config. - **TUI: Tavily web-search explanation** — `/mcp` screen now distinguishes Tavily's MCP server from the built-in `web_search` tool and explains when to use each. ### Changed - **WebUI enabled by default** on local loopback (`127.0.0.1:8765`); the admin surface stays hidden behind the bearer token on external interfaces. - **TUI message queue** — messages received during an active agent turn are queued (up to 20) and processed after the turn completes rather than being dropped. - **TUI scrolling** — auto-scroll and cursor positioning stabilised; chat pane no longer fights the scroll position on every render. - **TUI MCP config** — `/mcp` screen syncs provider state from disk on each open instead of caching the initial snapshot. ### Fixed - `commands.py`: `suggested_target_command` and `target_install_command` were used but not imported — caused `NameError` at runtime on `pythinker update --target VERSION`. - `onboard.py`: loop variable `field` shadowed `dataclasses.field` import. - Import ordering in `admin/service.py`, `agent/loop.py`, and `runtime/` modules (ruff I001/W291). ## [2.0.0] - 2026-04-30 First major release past the `0.1.x` line. Skipping `1.x` is intentional: the runtime + UI rewrite earns the `2.0.0` cut directly. **Major-version upgrades are not auto-installed** — `pythinker upgrade` will refuse to cross from `1.x → 2.x` and prompts for `pythinker update --target 2.0.0`. ### Added - **`pythinker tui` (alias `chat`)** — full-screen `prompt_toolkit` chat with persistent pane, live streaming, slash-command pickers (`/model`, `/provider`, `/sessions`, `/theme`, `/help`, `/status`), fuzzy search, Ctrl+C cancellation of in-flight turns, default + monochrome themes, Claude-Code-style welcome card. - **Governed-execution runtime** *(off by default)* — `RuntimeConfig` schema (`policyEnabled`, `telemetrySink`, `sessionCacheMax`, `max*`, `manifestsDir`, `defaultAgentId`, `blockedSenders`), `PolicyService` (allow-lists, budgets, recursion depth), `ToolEgressGateway` chokepoint, `AgentRegistry` + `AgentManifest` directory loader, `RequestContext` + `BudgetCounters` spine primitive, pluggable `TelemetrySink` (loguru / JSONL / composite). Same-shape configuration is bit-for-bit identical to the legacy path when `runtime.policyEnabled` is unset. - **Provider hot-reload** — `AgentLoop` accepts `provider_snapshot_loader` + `provider_signature`; `_refresh_provider_snapshot()` runs at the top of every `_process_message`. Edits to model / provider / api_key in `~/.pythinker/config.json` cascade through the runner, subagent manager, consolidator, and dream at the next turn boundary without restarting the SDK or the gateway. - **Research-grade PDF reports** — `make_pdf` agent tool renders structured Markdown to a styled PDF via ReportLab. Optional `[reports]` extra: `pip install 'pythinker-ai[reports]'`. - **Onboard wizard polish** — MiniMax token-plan flow, error/summary views, save-on-back, sensitive-field masking, Telegram "Allow From" → "Allowed IDs" rename, `--non-interactive --flow quickstart` end-to-end. - **Release-readiness gate** — `pythinker release check` runs the same battery as `publish.yml`: PEP 440 version validity, `pyproject.toml ↔ pythinker/__init__.py` fallback equality, `CHANGELOG.md` per-version section presence, git-tag/pyproject equality, optional `--build` (python -m build, twine check, wheel filename verification). - **Updater UX** — `pythinker update --target VERSION` for exact-version installs across `uv tool` / `pipx` / `pip` venv, with refusals printed for editable / container / system-pip paths. `pythinker upgrade` keeps its "latest stable" semantics but now refuses to cross a major version without explicit `--target` opt-in. - **Auth** — per-provider refresh-token file lock; `oauth_remote` refresh resilience. - **Provider plumbing** — factory hardening; extra-body config support for `github_copilot` / `openai_codex` / `openai_compat`. ### Changed - **`AgentLoop.__init__`** accepts new optional kwargs: `provider_snapshot_loader`, `provider_signature`, `policy`, `runtime_config`, `session_cache_max`. All default to safe values; embedders that pass kwargs **positionally** must adapt. - **`Pythinker.from_config`** (SDK facade) wires hot-reload + governed-execution by default. Programs constructing `AgentLoop` directly opt out by leaving the new kwargs at their defaults. - **API server** — typed `web.AppKey` storage migration; `PermissionError` → 403 on the non-streaming + streaming pre-authorize paths; SDK traffic labelled `channel="sdk"` (was `channel="api"`). - **CI** — `astral-sh/setup-uv` SHA-pinned; GitHub Actions Node 24-ready bumps; `publish.yml` purges GitHub camo cache after each release so shields.io PyPI badges refresh in minutes instead of hours. ### Deprecated - Hardcoded `pythinker/__init__.py` fallback drift now fails `pythinker release check`. Bump both files in lockstep — see `docs/cli-reference.md` `pythinker release` for details. ### Migration notes | Audience | Action | |---|---| | Stable-only users | `python -m pip install --upgrade pythinker-ai` will **not** auto-jump from `1.x` to `2.0.0`. Run `pythinker update --target 2.0.0 -y` (or `python -m pip install --force-reinstall "pythinker-ai==2.0.0"`) to opt in. | | Embedders calling `AgentLoop.__init__` positionally | Switch to keyword arguments. The new kwargs (`provider_snapshot_loader`, `policy`, …) are appended after `tools_config` and have safe defaults. | | Operators pinning `runtime.*` config | The runtime layer is **off by default**. To enable: set `runtime.policyEnabled=true` and either (a) set `runtime.manifestsDir` to a directory of `AgentManifest` YAML files, or (b) opt into `runtime.policyMigrationMode="allow-all"` for an explicit allow-all bridge. Without either, every tool call is denied — this is intentional. | | Source checkouts | `pythinker/__init__.py` and `pyproject.toml` must agree. Run `pythinker release check` after any version bump. | ### Removed - Stale documentation references to the `pdf` extra for `make_pdf` — the branded report tool ships under `[reports]`. The `[pdf]` extra remains for read-only PyMuPDF-backed PDF text extraction. ## [Unreleased — pre-2.0.0 WebUI overhaul, captured for history] This entry covers the WebUI overhaul that promotes the browser surface from a minimum-viable chat into a daily-use surface. Five focused phases shipped on the `port/cli` branch; everything is gated to the `pythinker gateway` process and consumes existing channel-manager seams without introducing new transports or processes. ### Added — WebUI #### Conversational control (Phase 1) - Per-message actions toolbar on hover/focus: **Copy** (both roles), **Regenerate** (assistant turns), and **Edit** (user turns; opens an inline editor that truncates the thread and re-runs from the rewritten message). - Composer **Stop** button replaces the send icon while a turn is streaming; forwards `/stop` to the agent loop's priority router. Cancels mid-turn cleanly without orphaning typing-dots placeholders. - New WebSocket envelopes: `stop`, `regenerate`, `edit`. Backend routes regenerate/edit through the priority command queue to coordinate with the session lock. #### Visibility (Phase 2) - **Context-usage pill** in the thread header showing `used / limit` tokens with a thin progress bar (amber > 75%, red > 90%). Refetches after every `stream_end`; backed by `GET /api/sessions//usage`. - **Tool-trace chips** under each assistant turn — one chip per unique tool kind with a `× N` count suffix when repeated. Click the chevron to expand the full trace lines. Replaces the prior verbose listing. - **Latency subscript** ("thinking… Ns") next to the typing dots, shown only after the first second to avoid flicker on snappy turns. #### Power features (Phase 3) - **Slash-command palette**: typing `/` at the start of the composer opens a filterable list of every built-in command (sourced from `BUILTIN_COMMAND_METADATA` via a new `GET /api/commands`). Up/Down navigates, Enter or Tab fills the textarea with ` `, Esc closes. - **Inline model switcher**: the model name in the composer footer is now a dropdown listing the configured default plus `agents.defaults.alternate_models`. Selection sets a per-chat override persisted on `Session.metadata['model_override']`. The agent loop honors it per turn. - New routes: `GET /api/commands`, `GET /api/models`. New envelope: `set_model`. New config field: `agents.defaults.alternate_models`. #### Search & organize (Phase 4) - **In-chat search** (`⌘F` / `Ctrl+F`): overlay highlights every match in the open thread. ↓ / Enter steps forward, ↑ / Shift+Enter steps back, Esc closes. Highlights both user pills and assistant Markdown bodies (paragraphs, headings, list items, blockquotes, emphasis). Each match has a unique `data-match-id` so navigation is unambiguous across siblings. - **Cross-chat search**: a debounced (200ms) input above "Recent" scans every persisted session's `history.jsonl`. Backed by `GET /api/search` with `?q=&offset=&limit=` pagination (default 50, cap 200) and a flat result list with snippet highlighting. Click a hit to jump to the chat and scroll directly to the matched message. - **Pin / archive**: each chat row's overflow menu offers Pin and Archive. Sidebar renders three sections: Pinned, Recent, Archived (collapsed by default). Archived chats stay in cross-chat search results with a small "archived" chip. - New routes: `GET /api/search`, `GET /api/sessions//pin`, `GET /api/sessions//archive` (toggles). - **Sidecar consolidation**: `.title` legacy sidecar is folded into a unified `.meta.json` carrying `{title, pinned, archived, model_override}`. Legacy `.title` files keep working until the first write of any other field collapses state. Migration is invisible. #### Polish & a11y (Phase 5) - **Reduced-motion respect**: every `animate-*` / `transition-*` class is gated behind Tailwind's `motion-safe:` so users with `prefers-reduced-motion: reduce` see static UI. - **Per-message timestamps**: subscript appears on hover under each bubble (relative `2m ago` for <24h, absolute date+time otherwise; full ISO in a tooltip). - **Drag-and-drop attachments**: drop image files anywhere on the chat area, not just the paperclip. Reuses the existing validator pipeline. - **Reasoning drawer**: assistant turns containing `...` blocks render the chain-of-thought in a collapsed disclosure above the visible body. Copy actions never include the reasoning. - **Mobile / iOS pass**: `100dvh` shell so the iOS Safari URL bar doesn't push the composer offscreen; ≥44px tap targets on touch viewports; `font-size: 16px` textarea minimum to prevent zoom-on-focus. - **Global keyboard shortcuts** with `?` opening a help modal: `⌘K` new chat, `⌘/` toggle search, `⌘↑` / `⌘↓` cycle chats, `Esc` cancel/close. Hotkeys are skipped while typing in inputs/textareas, except `Esc` which always fires. - **Voice input**: a microphone button next to the paperclip records audio via `MediaRecorder` and sends it as a `transcribe` WebSocket envelope (base64-encoded webm/mp4/wav). The backend writes to a temp file, dispatches to the configured `transcription_provider` (Groq or OpenAI Whisper, both already in `pythinker/providers/transcription.py`), and emits `transcription_result`. Active when `channels.transcription_provider` and the matching API key are set in `~/.pythinker/config.json`; bootstrap's `voice_enabled` flag flips automatically. ### Added — Backend / agent - `MessageBus`-coordinated regenerate/edit flow that drops the trailing assistant turn, truncates after the target user message, and re-runs. - `Session.metadata['model_override']` consumed at every turn — per-chat model override without bypassing the configured provider. - `MEMORY.md` / `.meta.json` JSON sidecar replaces the legacy plain `.title` file. - `iter_message_files_for_search` read-only generator (does not resurrect deleted sessions or mutate `_cache`). - `BUILTIN_COMMAND_METADATA` single-source-of-truth constant; existing `build_help_text()` derives from it instead of duplicating the list. - Cross-chat search helper (`search_sessions` + `build_snippet`) — pure substring match, paginated, deterministic ordering. ### Fixed - Regenerate/edit no longer leak deltas from a cancelled stream into the next placeholder bubble. - Empty edit content is rejected client-side and server-side. - `format_tool_hints`-shaped trace lines parse correctly into `` (the original colon-split assumption was wrong; verbs are now the first whitespace-or-paren token, with `× N` repeats preserved). - `messageBubbleSearch` test no longer flakes under default `vitest run` parallel mode (preloads the lazy `MarkdownTextRenderer` chunk so Suspense doesn't race `waitFor`). ### Removed - `webui/src/components/ChatPane.tsx`, `Composer.tsx`, `MessageList.tsx` — unreferenced scaffolding superseded by `ThreadShell` + `ThreadComposer` during Phases 1–5 (-353 LOC). Flagged in the Phase 5 plan self-review. ### Notes - This branch (`port/cli`, 79 commits) has not yet been merged to `main` or `dev`. No live browser smoke pass run — `vitest` (186 passing) and `pytest` (2235 passing, 1 skipped) cover the unit and integration layers. [Unreleased]: https://github.com/mohamed-elkholy95/Pythinker-ai/compare/v2.0.0...HEAD [2.0.0]: https://github.com/mohamed-elkholy95/Pythinker-ai/releases/tag/v2.0.0