# chatium v3

Source Git CLI, replacing the earlier `chatium` npm implementation without backward compatibility.
Requires Node.js 22+ and Git on macOS, desktop Linux, or Windows, plus a browser and available system
secret storage. Version 3 completely replaces the previous package; old commands and settings are not migrated.

## Install and start

After the public v3 release:

```sh
npm install -g chatium@latest
chatium --version
chatium clone your-account.example.com
```

Use your account domain, HTTPS origin, or the exact repository URL from its Source Git page. Confirm `chatium --version` reports a 3.x version.
Browser login requires a real Auth2 account owner/developer. Clone then generates tsconfig, installs Git hooks,
downloads IDE declarations and installs Chatium skills for Codex and Claude Code. You can open the resulting
folder in your editor and start working. The initial Chatium skill is a template; full guidance is still pending.

In an existing checkout, run `chatium setup` after installing v3. If setup fails, fix the reported cause and
rerun it in the preserved checkout. See the command and system requirements below.

## Switch an existing repository to Chatium CLI

```sh
npm install -g chatium@latest
cd your-existing-repository
chatium setup
```

Setup signs in with the `chatium-cli` OAuth client, configures the repository's account-scoped Git
credential helper, then generates tsconfig and installs hooks, typings and skills. Retry the original
Git command afterwards; you do not need to clone again. Global helpers and other accounts are preserved.
An existing CLI session issued to the old client requires one browser login. Cancellation or failure
preserves that session for another transition attempt; old refresh tokens are never reused under the new client.

Source Git rejects old-client tokens for reading and pushing. The old OAuth client can no longer authorize
or refresh, but logout can still revoke its saved session. The old OAuth shell installer has been removed.
Transition messages support Russian and English. CLI language comes from `LANGUAGE`, `LC_ALL`,
`LC_MESSAGES`, then `LANG`, with English fallback. HTTP messages use `Accept-Language`; browser pages
use the user's existing language settings. Existing unrelated CLI messages are unchanged.

## Updates through npm

Automatic updates are enabled by default. After a successful `login`, `clone`, `setup`, `get-typings`,
`get-skills`, or merge/rebase setup, a detached worker checks public npm at most once an hour. The command
finishes without waiting. The worker installs only npm `latest`, provided it is a non-deprecated stable release
in the current major that supports the running Node version; it never downgrades or selects another version.
When `latest` moves to the next major, this major stops receiving automatic updates. Checkout, commit, credential helper, logout, offline commands,
help, failures and cancellation do not trigger updates. Nested CLI calls do not launch additional workers.

```sh
chatium update --check
chatium update
```

Both commands perform a fresh check outside or inside a checkout. `--check` only reports the current and
available versions, Node, installation prefix, automatic-update setting and previous attempt. `update`
installs with visible progress. No available update is successful; an unsupported installation, failed check
or busy updater returns an error. Set `CHATIUM_NO_AUTO_UPDATE=1` to disable automatic updates; manual commands
still work. Background results never appear during ordinary commands.

Only real global npm installations are updated, including custom prefixes and nvm. Source checkouts,
`npm link`, local dependencies and npx caches are excluded. The updater invokes npm through the running Node
and targets this installation's prefix, not npm's current default. It runs outside the checkout and preserves
absolute hook/helper paths. It does not ask for elevated privileges.

Active CLI commands, including nested Git helpers, defer installation. A deferred candidate can be installed
after the next eligible command, but metadata from a previous run is fetched again before installation,
even within the hourly interval. A registry failure prevents installation; fresh metadata from the current
run is reused without a second request. Coordination and diagnostic state
are stored per installation under `$XDG_STATE_HOME/chatium/updates` (otherwise Windows `%LOCALAPPDATA%`,
or `~/.local/state`). Do not remove these files while commands or npm are active.

### Recovery and major upgrades

npm replacement is not atomic. A new concurrent invocation can hit missing files during installation and
need a retry; external npm commands do not participate in CLI locking. Failed npm installation can leave
Chatium unusable, including `chatium update --check`. There is no automatic backup or rollback.
Reinstall directly with npm, using the **same prefix**:

```sh
npm install --global --prefix "/your/original/prefix" chatium@3.0.0 --registry=https://registry.npmjs.org
```

Replace the example version with the version you want. To keep that version, set `CHATIUM_NO_AUTO_UPDATE=1`.
The updater also records a recovery command and its last error in `state.json`. To move to the next major,
run `npm install -g chatium@latest`, adding `--prefix` for your custom prefix.

## Clone

```sh
chatium clone your-account.chatium.ru
chatium clone https://your-domain.example
chatium clone https://your-account.example.com/s/git/your-account.git
chatium clone https://your-account.example.com/s/git/your-account.git "my checkout"
```

Clone opens browser login when needed or reuses the same session as login. Without a destination, the origin's hostname (without scheme or port) is used, including for full repository URLs.
For example, `chatium clone your-domain.example` creates `your-domain.example`, even if the account has another name. The new checkout's account-scoped credential helper and `useHttpPath` are
configured before its initial fetch; subsequent ordinary Git commands use the same session. Global
credential helpers remain unchanged.

The command reports success after cloning and running setup: local TypeScript configuration, managed hooks
and declarations, then Chatium skills for Codex and Claude Code. The generated root tsconfig is overwritten even if tracked; other tracked files and
legacy helper scripts are preserved. Project installation/lifecycle scripts are not run. The credential helper refers to this installed CLI and Node executable, so keep them
available while using the checkout.

If preparation fails, the checkout is retained and the error names its location and recovery commands.
Run `chatium setup` inside it after fixing the cause. Git clone failures
retain Git's exit code and normal cleanup behavior; the CLI never removes an existing destination to retry.

Custom domains remain in the remote URL, OAuth and setup, with a separate session per origin.
External proxies and path prefixes are unsupported.

## Multiple account remotes

```sh
git remote add prod https://acme.chatium.ru/s/git/acme.git
git push prod main
chatium exec --remote prod 'return await someFunction()'
```

A checkout may have remotes for several accounts. Clone and setup configure the credential helper for HTTPS
Source Git URLs on the default port whose host has two to four labels, so a newly added account remote
authenticates on its first fetch or push, opening the browser login when that account has no session. Checkouts
prepared by an earlier version receive this after one `chatium setup` (or the next merge hook), which also moves
their single-URL remotes from the pre-rename `/s/source-git/` path to `/s/git/`. Other remotes
(loopback, custom ports, deeper hosts) need `chatium setup --remote <name>`. Requires Git 2.26 or later.

Commands that work with an account (`login`, `logout`, `exec`, `setup`, `get-typings`, `generate-tsconfig`,
`typecheck` and `storage upload`) use `origin` unless `--remote <name>` selects another remote. The choice is
not remembered: installed hooks and later commands use `origin` again, and they fail with a request for
`--remote` if `origin` is not a Source Git remote. `setup --remote <name>` signs in to that account and prepares
tsconfig and typings from it; other account remotes sign in on first use.

## Login

```sh
chatium login https://your-account.example.com
chatium login your-account.example.com
chatium login
chatium login --remote prod
```

Inside a Source Git checkout, the URL defaults to the `origin` remote, including from subdirectories;
`--remote <name>` uses another remote instead of a URL.
Outside a checkout, supply an account URL. Authorization requires a real Auth2 account Owner or Developer
and grants `repo:read repo:write code:execute`. Login reuses a valid local session with all three scopes, refreshes an expired one, or opens the browser as needed.
Press Ctrl+C to cancel; unattended login times out after five minutes.

Account URLs require HTTPS. HTTP is accepted only for literal loopback hosts `127.0.0.1` and `[::1]`,
for local development. The local OAuth callback continues to use HTTP. Credentials embedded in URLs,
query strings, and fragments are rejected.

In Chatium Code, login checks the existing native session first. Otherwise it exchanges the injected
`CHATIUM_TOKEN` only when the target origin exactly matches `https://${CHATIUM_ACCOUNT}`, saves the ordinary
OAuth pair, and skips the browser. Invalid local values or server 401/403 fall back to browser login;
transport, server and malformed-response failures stop the command.

## Logout

```sh
chatium logout your-account.example.com
chatium logout
chatium logout --remote prod
```

A hostname without a scheme defaults to HTTPS and uses the same session as the full HTTPS origin.
Without an argument, logout uses the checkout's `origin` (or `--remote <name>`), including from subdirectories. It revokes the saved
refresh-token family on the server before deleting the local native entry. All local clones of that origin
share the session; other origins and other devices' token families are unaffected. No saved entry is a
successful no-op. Logout never opens the browser or clears the browser's Chatium session.

A network error or unconfirmed response retains the entry and exits unsuccessfully: retry logout when
connected. If server revocation succeeds but native deletion fails, the error explicitly says so; unlock
the native store and retry. Server revocation accepts consumed refresh tokens and repeated requests.
The next Git credential request can start a new browser login.
Logout is disabled while both managed Chatium Code variables are present.

## Execute code

```sh
chatium exec 'return await someFunction()'
printf '%s\n' 'return { ok: true }' | chatium exec
chatium exec --remote prod 'return await someFunction()'
```

Run `chatium exec` on a branch inside a Source Git checkout. It executes the snippet against the latest compatible
successful Source Build for that branch in the `origin` account, or in the account of `--remote <name>`, falling back
to `main` when the branch has none. Detached HEAD is rejected.
Local commits and staged, unstaged, untracked or dirty-submodule changes are unavailable; dirty checkouts warn and
continue. Ignored files do not trigger the warning, and the snippet is never added to Git.
The command may change account data. It has no read-only mode, rollback, or dedicated VM: execution reuses the
account VM when available. Only account owners and developers can grant the separate `code:execute` permission.

The result goes to stdout: strings are printed without JSON quotes, other JSON values are serialized. The executed
commit SHA, `console.*` output and errors go to stderr. Pass one snippet argument or pipe a snippet to stdin; put `--`
before a snippet argument that starts with `-`.

## Prepare hooks and typings

```sh
chatium setup
chatium generate-tsconfig
chatium install-hooks
chatium get-typings
chatium get-skills
chatium typecheck [paths...]
chatium generate-typings
```

Generated and migrated repositories provide `npm run setup` (`chatium setup`) for full repository preparation;
the old `install-hooks` npm script is removed. `chatium install-hooks` remains available separately.

The old command names `typings`, `sync-typings` and `tsconfig` are no longer accepted.

Run these in a Source Git checkout, its subdirectory or a Git worktree. `setup` authorizes and configures the account-scoped Git helper, then generates tsconfig,
installs hooks, downloads declarations, then installs the current Chatium skills. Both clone and setup print the checkout path and each preparation
step, then report success once. Failures show the cause; clone preserves the checkout and suggests retrying setup. `generate-tsconfig` works offline and derives aliases from local folders
and the account in origin; it overwrites even customized/tracked root configuration without staging.
`install-hooks` also works offline. Only downloading declarations needs the shared OAuth session.
`typecheck` regenerates tsconfig before running `vue-tsgo` (the `@chatium/vue-ts-mapper-rs` `.vue` mapper with `tsrs`, a Rust port of TypeScript 7; where `tsrs` has no build, such as Intel macOS, with `@chatium/tsc-rs`, and on Windows with TypeScript 7; `VUE_TSGO_TSC=tsc-rs` or `VUE_TSGO_TSC=typescript` picks those; `VUE_TSGO_MAX_MEMORY=1G` keeps `tsrs` near that much memory, the parsed program being the floor), all installed with the CLI as its dependencies; folders/files passed to `typecheck` (relative to the current directory) narrow the check to them and what they import, to use less memory; `generate-typings` replaces .typings using the public files in package.json. Only
`generate-typings` uses npm; the generator follows its latest release without a Chatium CLI update. Setup does not run them. `get-typings` leaves hooks unchanged and scans `.ts`, `.tsx`, `.js`, `.jsx` and
`.vue` files for scoped imports, excluding `.git`, `.chatium`, `.typings` and `node_modules`.
It downloads builtin and external-account declarations; it does not generate the project's public typings.

Installation uses Git's common hooks directory. Only recognized Chatium-managed hooks can be replaced; all hook destinations are checked before writing. The hook invokes this CLI through absolute Node/CLI paths; after moving the installation rerun
install-hooks. A foreign hook, symlink, or custom `core.hooksPath` (including an explicitly empty value) causes
an error during install-hooks/setup; get-typings does not inspect hooks or core.hooksPath.
The hook runs the installed CLI offline with Node and Git; no network access is needed during commit.
Directory metadata must be a regular index file. ID insertion rejects symlink paths and atomically replaces
the worktree file while preserving its permissions, formatting and partially staged edits.

Installed hooks run full setup after merge (including fast-forward pull), after rebase and on worktree creation,
so a new worktree gets declarations and skills too. After branch checkout/switch or detached HEAD checkout, only
tsconfig is regenerated, without network access. Checkout of individual files, amend, push and pull without changes do not trigger preparation.
Automatic setup downloads skills too and may open the OAuth browser. Failures print the cause and a manual retry command without
failing the completed Git operation; manual setup/generate-tsconfig still fail normally.
Existing checkouts receive these hooks after `chatium setup` or `chatium install-hooks`.

Typings output is restricted to declaration files inside this checkout's `node_modules`. The complete
response is checked before writing declarations: traversal, tracked files, symlinks, and conflicting paths
are refused. Valid untracked declarations are replaced regardless of their creator; stale files are retained.
Each file is replaced through a temporary file so a failed write does not truncate the existing declaration.
A failure midway can leave earlier files updated; rerun the command after fixing the cause.

The CLI adds `/node_modules/` to Git's local `info/exclude`. Only tsconfig generation changes tracked
configuration in older checkouts; legacy helper files are preserved but their installation workflow is no longer supported.
The old `/s/source-git/hooks/pre-commit` endpoint has been removed. Run `chatium setup` in existing
checkouts to install the CLI hooks instead of running `.chatium/install-hooks.mjs`. The installed merge/rebase hooks also run preparation after successful Git operations.

## Native storage and recovery

One native secret per account origin stores the access/refresh pair, expiry and scope.
Clones of one account share its session; different origins have independent entries.
Storage errors fail the command: unlock or repair the system store and retry. No plaintext fallback exists.
macOS uses Keychain and `open`; Windows uses Credential Manager and the default browser. Linux needs
`xdg-open` and a working desktop Secret Service for persistence across reboots; the native dependency's
kernel-keyring fallback may require a new login after reboot.

Login always prints the authorization link, and a failed browser launcher is only a warning. On a remote or headless
machine, open the link in any browser; after approval it fails to reach the CLI's `127.0.0.1` callback, so paste that
page's address into the terminal. Pasting needs an interactive terminal, so run `chatium login` there before a Git
credential request would need it.

A refresh-pending marker is saved in the same secret before the HTTP request. If the response is lost,
the process dies or saving the rotated pair fails, retrying performs a new browser login instead of
reusing the old refresh token. `proper-lockfile` coordinates processes per origin in the user's local
state directory, using a heartbeat and a 10-second stale threshold. Lock files contain no tokens.
Do not remove active locks. A killed process's lock may take about ten seconds to recover.
Coordination is local to a desktop, not shared across machines.

## Git helper contract

`chatium credential-helper [<account-origin>] get|store|erase` uses Git's stdin/stdout protocol.
An explicit origin binds it to the account; unsupported hosts, protocols, usernames and repository
paths receive no tokens. Without an origin, the request host is the account: only HTTPS (or loopback HTTP)
Source Git repository paths are served, and each token goes only to the origin that issued it.
`store` cannot overwrite the OAuth pair. `erase` removes only a matching current access token; it does
not revoke server tokens.

Setup tooling must configure the helper locally for the exact account context and for the account remote
patterns `https://*.*/s/git/` through `https://*.*.*.*/s/git/` (and the same for the pre-rename `/s/source-git/`
prefix), reset inherited helpers
for those contexts and enable `credential.useHttpPath` there. Do not configure it as an unrestricted global
helper. Clone and setup configure this automatically.

## Chatium skills

Run `chatium get-skills` (or `npm run get-skills` in newly generated/migrated projects) to download the
current default branch of https://github.com/chatium/chatium-agent-skills. Git and network access are
required; Chatium login is not. The command works from subdirectories and worktrees.

Whole skill directories are copied independently into `.agents/skills/` and `.claude/skills/` for Codex
and Claude Code. Names starting with `chatium` are managed: local edits are replaced and retired skills
removed. Other skills and agent files remain yours. No agent configuration or lock file is generated.
The source currently contains a development template; substantive guidance will be maintained there.

The complete source and destination paths are validated before replacement. Download/validation failures
preserve installed skills. Fix the reported cause and rerun `chatium get-skills`; retry also repairs a
partial filesystem failure. Ctrl+C cancels download and removes temporary files.

Only `/.agents/skills/chatium*` and `/.claude/skills/chatium*` are excluded via local Git info/exclude.
New repository templates and migrated repositories include these rules in .gitignore, preserving
other rules. The command does not edit tracked .gitignore or stage/untrack files.

## Upload local files

From the account's Source Git checkout (including subdirectories):

```sh
chatium storage upload ./photo.jpg ./document.pdf
chatium storage upload --protected ./private.pdf
chatium storage upload -- -filename.txt
chatium storage upload --remote prod ./photo.jpg
```

The account comes from the `origin` remote (or `--remote <name>`); the CLI reuses its OAuth session or opens login.
Files are public by default. Paths are relative to the current directory; directories are not uploaded.
Each successful upload prints a text block with `file`, `file_hash`, `download_url`, `get_url`, and
`thumbnail_url` (800px wide, when the format supports thumbnails). Protected URLs are unsigned;
use `@app/storage` helpers in your application to obtain authorized access URLs.

Files upload sequentially. File errors go to stderr and remaining files continue; any failure gives
exit code 1. Authorization failure or cancellation stops the command. Successful uploads remain stored.
