@roam-agent/roam 0.0.0-stage → 0.2.52
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +82 -0
- package/README.md +73 -2
- package/anthropic.js +82 -0
- package/bedrock-converse-stream.js +96 -0
- package/core/export-html/template.css +1085 -0
- package/core/export-html/template.html +56 -0
- package/core/export-html/template.js +2044 -0
- package/core/export-html/vendor/highlight.min.js +1213 -0
- package/core/export-html/vendor/marked-cjk-friendly.min.js +6 -0
- package/core/export-html/vendor/marked.min.js +79 -0
- package/github-copilot.js +9 -0
- package/image-resize-worker.js +9 -0
- package/kimi-coding.js +9 -0
- package/modes/interactive/assets/clankolas.png +0 -0
- package/modes/interactive/theme/dark.json +78 -0
- package/modes/interactive/theme/light.json +78 -0
- package/openai-codex.js +82 -0
- package/openrouter.js +82 -0
- package/package.json +38 -5
- package/radius.js +82 -0
- package/roam.js +3101 -0
- package/xai.js +9 -0
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [Unreleased]
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
|
|
7
|
+
- Hub profile commands classify `-m` model ids against pi's built-in catalog (`createHubUnknownModelChecker` in `src/coding-agent/hub-model-checker.ts`, built from `@earendil-works/pi-ai/providers/all` and injected into `dispatchHubCommand` for the `roam`/hub/profile aliases): unknown ids are stored as custom model definitions and materialized into the profile's `models.json` instead of failing at pi run time.
|
|
8
|
+
|
|
9
|
+
- The diagram extension (`roam-diagram`, shared core `packages/plus/src/extensions/diagram/`) is registered in the `roam` CLI: `draw_diagram` renders node-edge graphs as box-drawing ASCII inline in the terminal (structured JSON spec, dependency-free layered layout, cycle-safe), and writes a standalone HTML/SVG file when given a `file` parameter.
|
|
10
|
+
|
|
11
|
+
- The session change report extension (`roam-changes`, `src/extensions/changes/`): `/changes` prints the cumulative content diff of every file the agent changed this session — including files `git diff` cannot show, since brand-new (untracked) files render as all-added diffs and deletions as all-removed. A `tool_call` handler snapshots each edited/overwritten file's original content at the agent's first touch (insertion-ordered ledger, 200-path and 256 KB-per-file caps; failures are swallowed so a bad path never blocks the tool, and the file simply goes untracked with a note entry). On demand the baselines are diffed against the current files on disk (`generateDiffString`), edits reverted to their baseline drop out, diff bodies cap at 400 lines with a muted tail note, and the report appends as a custom transcript entry rendered with the fancy-diff pipeline (per-file header with `+N −M` stats and language badge over the `changes — N files +X −Y` summary; custom entries never enter LLM context and persist in the session file, so restored sessions re-render past reports with the current theme). An optional argument filters tracked paths by case-insensitive substring (`/changes src/foo`). Changes made through the `bash` tool are not tracked; TUI mode only.
|
|
12
|
+
- Auto-fold history in the interactive TUI (`src/coding-agent/ui/auto-fold-history.ts`, installed via a side-effect import in the `main.ts` wrapper): the transcript folds on a rolling basis — when the agent starts a new assistant message mid-run (`handleEvent` prototype patch on `message_start`), that step's thinking and finished tool rows collapse (thinking to a "Thinking... (ctrl+o to expand)" hint label, tools to their standard per-tool preview), and when a new user message enters the chat (`addMessageToChat` prototype patch) all previous turns fold. The live step is excluded by identity (streaming assistant component + in-flight `pendingTools`), so only completed content folds while output is still streaming; resume and compaction replays flow through the same `addMessageToChat` chokepoint, so everything before the last user turn is folded at first paint. thinking folds and unfolds exactly like tool output (one shared state model): the fold syncs both flags — `toolOutputExpanded` to false and `hideThinkingBlock` to true — so neither ctrl+o nor ctrl+t ever burns a dead press, and new components inherit them, meaning after a fold a freshly created tool row starts collapsed and a freshly created assistant message starts with hidden thinking (mid-run included; ctrl+o, ctrl+t or a click reveals it). A `setToolsExpanded` prototype patch makes ctrl+o the whole-transcript toggle for both kinds — the thinking sweep covers every assistant component including the streaming one, mirroring upstream's no-exclusion tool sweep — expanding restores the plain "Thinking..." label, collapsing re-folds with the hint and drives `hideThinkingBlock` in lockstep. Clicking a folded block re-opens just that one. Opt out with `PI_AUTO_FOLD_HISTORY=0` (ctrl+o then behaves exactly like upstream, tool output only); verbose startup never folds. CLI-only: `roam-sdk` hosts do their own content folding.
|
|
13
|
+
- The fancy content-change diff extension (`roam-fancy-diff`): the TUI rendering of `edit` and `write` is taken over via `registerToolRenderer` — diff bodies are syntax-highlighted (upstream's cli-highlight pipeline, by file extension), markers are colored `+`/`-` over a dim line-number gutter, the header carries `+N −M` change stats and a language badge, 1:1 modified lines get bold word-level emphasis, and elided context shows a `⋮` separator. A `write` that overwrites an existing file now renders an old-vs-new diff: the pre-image is captured by a `tool_call` handler before execution (LRU-bounded, 256 KB per-file cap); new files keep the streaming content preview. Errors, restored sessions without a pre-image, and all other tools fall back to upstream rendering. Changed lines carry a soft full-row background fill of their diff color and the actually-changed words inside a modified line a stronger one (both mixed from the theme's diff tokens, git-delta style); context lines, the `⋮` separator, and headers stay unfilled, and tool status blocks remain fill-free per the plain-tools house style.
|
|
14
|
+
- The web search extension (`roam-web-search`, shared core `packages/plus/src/extensions/web-search/`) is registered in the `roam` CLI: `WebSearch` searches the web through the provider chain selected by `WEB_SEARCH_PROVIDER`/`*_API_KEY` env vars (keyless DuckDuckGo fallback last) and `WebFetch` reads a URL as text, both returning citation-ready results.
|
|
15
|
+
- The `/init` command (shared core, `packages/plus/src/extensions/init/`): analyzes the codebase and creates `AGENTS.md` at the cwd root, or suggests improvements when it already exists; pi loads `AGENTS.md` automatically.
|
|
16
|
+
- `roam profile add <name> -p <provider>` with no token/model/url/thinking/--set now invokes that provider's interactive login after saving the profile: the OAuth login page opens in the browser (or the API-key setup prompts run in the terminal) and the credential is persisted into the profile's isolated agent dir (`~/.pi/pi-hub/profiles/<name>/auth.json`), so the profile is ready to launch. A cancelled or failed login keeps the profile and suggests `roam profile update <name> -t <key>`. The CLI injects the flow via hub's `dispatchHubCommand` `login` hook; the flow itself lives in the shared core (`packages/plus/src/auth/login.ts`).
|
|
17
|
+
- The interactive TUI's `/login` is disabled: it shows a status line pointing at `roam profile add <name> -p <provider>` instead of starting the login flow, and it no longer appears in autocomplete or `/help` (via the `interactive-mode` and `slash-commands` redirect wrappers in the shared core).
|
|
18
|
+
- `--sign-in` on `roam profile add` / `roam profile update`: runs the provider's interactive login (OAuth page / API-key setup) for the profile even when it already carries a token, and the sign-in overwrites the profile token — the `loginProvider` credential's key is stored as the profile token for api-key logins, and the token is cleared for OAuth logins (whose credential lives in the profile dir's `auth.json`, so it survives re-materialization). The flow is the same `loginProvider` entry `roam-sdk` re-exports; bash/zsh completions list the flag.
|
|
19
|
+
- The session recap extension (`roam-session-recap`, shared core `packages/plus/src/extensions/recap/`) is registered in the `roam` CLI: after the first prompt is answered and after every compaction, a one-off LLM call distills a ≤8-word recap applied as the session name — visible in the tab title and as the displayed text in the resume session list (which shows `name ?? firstMessage` in place of the raw first message). A manual rename permanently locks the session against further recaps.
|
|
20
|
+
|
|
21
|
+
### Changed
|
|
22
|
+
|
|
23
|
+
- **Sub-agent children keep the launching profile** (shared-core fix in `packages/plus/src/extensions/subagent/run.ts`): `roam` subprocesses spawned by the subagent tool and the memory extractor now receive `--as <profile>` derived from the session's materialized agent dir, so background turns authenticate and resolve their endpoint through the session's profile even when the stored default profile points at a different provider; `roam` sessions without a profile are unchanged.
|
|
24
|
+
- **The resume session list hides headless transcripts** (`src/coding-agent/ui/session-selector.ts` wrapper, redirected for `packages/coding-agent/src/modes/interactive/components/session-selector.ts`): `roam --resume`, `roam -r` and the TUI `/resume` share one picker component, so the wrapper filters its session loaders before `super()` starts loading, and headless runs (SDK hosts, automation) no longer crowd out interactive chats. Only transcripts whose header says `interactive: false` (stamped by the plus session-manager overlay) are dropped; the filter applies to the resolved list and to the partial lists published while a large directory is still scanning, and leaves `resolveSessionPath` alone so `--session <id>` / `-r <id>` still reach a headless transcript. Unmarked sessions (pre-marker, or hosts that never declare a mode) stay listed. Side effect: a headless session cannot be renamed or deleted from the picker.
|
|
25
|
+
- **The repository split the roam sources into three packages**: the shared override core (context/compaction/reasoning + the seven non-TUI extensions + the core redirect wrappers) stays in `packages/plus`, all CLI logic (hub dispatch, completion, usage print, banner/vim/tab-title/plain-tools/`/cd`, the main wrapper, the source-mode loader) moved to `packages/plus-cli`, and the programmatic entry moved to `packages/plus-api`. The published `roam` package is now **CLI-only**: `api.js`/`api.d.ts` are gone from the artifact, the `exports` map has no `.` entry (so `import "roam"` fails by design), and the `@earendil-works/pi-coding-agent` types dependency is dropped. Library hosts should depend on the new **`roam-sdk`** package instead, published from `packages/plus-api`.
|
|
26
|
+
- The `/cd` working-directory switch extension moved to the shared core (`packages/plus/src/extensions/cd/`) so the `roam-sdk` artifact registers it too; it is no longer CLI-only.
|
|
27
|
+
- Launching under a hub profile now layers settings at runtime instead of baking them at launch: roam sets `ROAM_BASE_AGENT_DIR` to the plain agent dir before pointing `PI_CODING_AGENT_DIR` at the profile dir, so the session reads `~/.pi/agent/settings.json` deep-merged under the profile `settings.json` (profile wins) and general writes land in the agent file live. With general keys — including `packages` — now written straight to the base file, the old exit hook that synced the profile copy's `packages` back to the agent settings at process exit was dropped (it could only clobber the base after the layering change).
|
|
28
|
+
- Entries below this note predate the split and describe the combined `roam` artifact.
|
|
29
|
+
|
|
30
|
+
### Fixed
|
|
31
|
+
|
|
32
|
+
- `/vim` state now persists across launches under a hub profile. The flag was written into the profile's `settings.json`, which every launch re-materializes while pruning keys that are not profile-scoped, and the reader never consulted the base agent `settings.json` — so the toggle silently reset on restart. Reads now walk project > profile > base agent > `~/.pi` (matching the runtime layering), writes go to the base agent `settings.json` like any general key, and a stale `vim` shadow copy left in the profile file is dropped on write.
|
|
33
|
+
- Manual compactions no longer die silently and strand the TUI's "Compacting context..." spinner forever when a second compaction starts while one is already running (the classic sequence: answer "Compact now?" on resume, then type `/compact` while that compaction is still summarizing). Upstream keeps the manual compaction's abort controller in a singleton field that any overlapping compaction's cleanup resets to `undefined`; the overlap crashed the second compaction with `Cannot read properties of undefined (reading 'signal')` before it could emit `compaction_end`, so the indicator outlived the compaction. The `AgentSession` wrapper now serializes `compact()` calls through a per-session queue (`compaction/serialize.ts`): a `/compact` issued during an in-flight compaction waits its turn instead of interleaving, and each compaction's finally blocks complete before the next starts.
|
|
34
|
+
- A compaction whose summary stream is aborted mid-generation (e.g. the session-level abort fired while the provider was still streaming) is no longer treated as a successful summary: `stopReason: "aborted"` responses are rejected like `error`/`length`, so a partial summary can never be persisted as a checkpoint.
|
|
35
|
+
- Answering "Compact now?" when resuming an over-threshold session now shows the "Compacting context..." indicator. `compaction_start` fired while the compaction ran inside the `session_start` handler, before the TUI had subscribed to session events; the compaction is now deferred one macrotask so the subscription (which happens as soon as extension binding returns) is in place first.
|
|
36
|
+
|
|
37
|
+
### Added
|
|
38
|
+
|
|
39
|
+
- `/cd <dir>` moves the session to a different working directory: the session file relocates to the target cwd's default session dir with only its header `cwd` rewritten (id, timestamp, and entries untouched — the same conversation, not a fork), the runtime then switches to it so tools, extensions, project settings, trust, and the system prompt re-bind to the new directory, and the old session file is removed once the switch completes. `/cd` with no argument shows the current cwd. A session that has not been persisted yet (no messages) starts directly in the target directory.
|
|
40
|
+
- The published `roam` package gains a programmatic library entry alongside the `roam` CLI: `import { createPlusAgentSession, createPlusUIContext, plusSdkExtensionFactories } from "roam"` lets a host application (e.g. a desktop app) embed pi with the full roam layer in-process — the compaction/context/reasoning overrides are baked into `api.js` by the same bundle-time redirect plugin as the CLI, and the seven non-TUI roam extensions (subagent, tasks, memory, plan, ask-user, hooks, context-guard) are registered the same way the CLI wrapper registers them. `createPlusAgentSession()` composes the upstream `createAgentSession` with a `DefaultResourceLoader` carrying those factories, reloads it, and binds extensions once (emitting `session_start`); hosts pass dialog handlers via the `ui` option to get working `ask_user` questions (select/confirm/input bridged to native UI), or omit it for a headless session. The staged package.json now has an `exports` map (deep imports are closed off), ships a hand-authored `api.d.ts` re-exporting `@earendil-works/pi-coding-agent` types (added as an exact-pinned dependency for type resolution only; the runtime stays self-contained), and builds `api.js` as a second esbuild entry, roughly doubling the artifact size. Hosts without a pi CLI on PATH should pass `excludeTools: ["subagent"]`: the subagent tool launches a pi subprocess and could otherwise relaunch the host app itself.
|
|
41
|
+
- The tab-title spinner now also runs while context compaction is in progress (manual `/compact` when idle, or automatic/overflow compaction mid-run): `session_before_compact` marks compaction active and `session_compact`/`session_compact_failed` clear it, so a backgrounded tab shows at a glance that a long compaction is running. The spinner stops only when neither the agent run nor compaction is active, so mid-run compaction (which settles the run before retrying) no longer leaves the tab static.
|
|
42
|
+
- A `<tasks>` system-prompt section (registered by the `roam-tasks` extension on every agent start) nudging the model to break non-trivial multi-step work into TaskCreate tasks and update statuses as it goes, and listing the session's current tasks (with status and blockers) when non-empty so resumed sessions can pick up where they left off.
|
|
43
|
+
- A `<subagents>` system-prompt section (registered by the `roam-subagent` extension on every agent start) nudging the model to delegate self-contained work units via the `subagent` tool — including complete, self-contained prompts and concurrent calls in one turn — and listing the agent types available in this session (built-in `worker`/`explore` plus user- and project-defined agents) with their source, tools, and model.
|
|
44
|
+
- `PI_AUTOCOMPACT_FAILURE_COOLDOWN_MS` env override (minimum 10s, values below the floor fall back to the 5-minute default) for the auto-compact circuit breaker: after 3 consecutive failures the breaker now cools down instead of latching forever — one attempt is allowed through once the cooldown elapses (half-open), and a failed attempt re-trips it.
|
|
45
|
+
- Layered context defense (roam-context-guard extension + AgentSession constructor hook, ported from openclaude): a message-count force trigger compacts when the active message count exceeds `PI_MAX_ACTIVE_MESSAGES` (default 1000) regardless of the token threshold; relevance pruning omits low-relevance old text entries via durable `context_edit` overlays once the projected request reaches the auto-compact threshold, protecting the recent `PI_PRUNE_TAIL_TURNS` (default 3) turns, tool interactions, errors, and prior compaction summaries; time-based micro-compact clears the content of stale tool results (`PI_MICROCOMPACT_IDLE_MINUTES`, default 60; keeps the newest `PI_MICROCOMPACT_KEEP_RECENT`, default 5) when a session is opened after an idle gap, since the server prompt cache is dead anyway; and resuming a session already at ≥ 70% of the auto-compact threshold offers a "Compact now?" confirmation in the TUI.
|
|
46
|
+
- Post-compact re-injection of the active plan file and invoked skills into the compaction summary (openclaude's `createPlanAttachmentIfNeeded` / `createSkillAttachmentIfNeeded`), alongside the existing recent-files re-injection.
|
|
47
|
+
- Recompaction analytics (openclaude's `RecompactionInfo`) persisted in the compaction entry's `details`: whether the compaction continues a chain, turns consumed since the previous compaction, the previous pre-compact token count, and a `willRetriggerNextTurn` prediction; set `PI_COMPACT_ANALYTICS` for a stderr diagnostic line.
|
|
48
|
+
- `/settings` gains an "Auto-compact threshold" row (70%/80%/85%/90%/95%, default 80%), injected into the settings selector by the plus wrapper. The choice persists to `~/.pi/agent/roam-settings.json` and applies as a percent of the effective context window, replacing the CC buffer math as the user-facing default — unlike `PI_AUTOCOMPACT_PCT_OVERRIDE`, which stays a session-scoped test knob capped at the CC buffer.
|
|
49
|
+
- `/settings` gains a "Context floor" row (13000–65536 tokens, default 13000) for the floor under the effective context window: the window used for auto-compact math never drops below the output reserve plus this many tokens, even for small-context models. The choice persists to `~/.pi/agent/roam-settings.json` and can only raise the built-in 13k floor (the issue-#635 guarantee stays intact); `PI_CONTEXT_FLOOR_TOKENS` overrides it for the session.
|
|
50
|
+
- `/settings` gains a "Context window cap" row ("No cap"/131072/262144/524288/1048576, default "No cap") capping the context window used for auto-compact math and the footer fullness meter at min(model window, cap). The choice persists to `~/.pi/agent/roam-settings.json`; `PI_AUTO_COMPACT_WINDOW` keeps its session-scoped can-only-lower semantics on top.
|
|
51
|
+
|
|
52
|
+
### Changed
|
|
53
|
+
|
|
54
|
+
- The `<tasks>` system-prompt section now spells out the TaskCreate/TaskUpdate/TaskList/TaskGet signatures (parameter names, optionality, status enum, numeric-string task ids) in an "Available tools:" block after the prose nudge. Extension tools have no snippet in the `<tools>` section, so the model previously had to discover them blind — flash-tier models in particular ignored the nudge and ran multi-step work as one tool call at a time with no task tracking.
|
|
55
|
+
|
|
56
|
+
- The default context window used for threshold math is no longer ceilinged at 256K (`AUTOCOMPACT_MAX_WINDOW_TOKENS` is gone): with no "Context window cap" chosen in `/settings`, the model's advertised context window is used as-is, so a 1M-context model triggers auto-compaction at 80% of its full window (~784K) and the footer meter reads against full capacity. Choosing a cap restores the old behavior (e.g. 262144 reproduces the 242K effective window and the `14.4%/242K` meter). The floor logic and `PI_AUTO_COMPACT_WINDOW`'s session-scoped lowering are unchanged.
|
|
57
|
+
|
|
58
|
+
- The CC buffer math (ramped 13k–30k by effective window size, openclaude issue #1949; floored effective window for small-context models, issue #635) no longer sets the auto-compact threshold directly — it survives only as the cap for the `PI_AUTOCOMPACT_PCT_OVERRIDE` test knob. The user-facing threshold is now a percent of the effective window chosen in `/settings` (default 80%). `percentLeft` is computed against the raw context window so the displayed percentage reflects full model capacity.
|
|
59
|
+
|
|
60
|
+
### Fixed
|
|
61
|
+
|
|
62
|
+
- Auto-compaction no longer fails with "generation hit the token cap and the summary is incomplete" on reasoning models when the session thinking level is high. The summary's output cap is `0.8 × reserveTokens` and reasoning tokens count against it, so DeepSeek-style thinking at `high` could exhaust the budget and truncate the summary, which pi rightly refuses to persist as a checkpoint. Compaction summarization (both the coding-agent path and the agent-harness path) now always runs with thinking disabled; summary requests carry a `markNoReasoning` flag that the effort wrapper (`wrapStreamFn`) honors by stripping reasoning/thinking budgets instead of re-applying the session level or `PI_EFFORT_LEVEL`.
|
|
63
|
+
- Tab-title spinner no longer dies a couple of seconds into a busy run: `turn_end` fires after every assistant message, including ones whose tool calls keep the run going, so settling there stopped the ticker before long tool executions and `agent_start` (once per run) never restarted it. The `turn_end` backstop now only settles when the turn's `stopReason` is not `toolUse`; `agent_settled` (fired in the run's `finally`) remains the primary stop signal.
|
|
64
|
+
- `roam remove`/`roam install` under a profile now update the source `~/.pi/agent/settings.json` `packages` list, not just the per-profile copy that the next materialization would discard. The wrapper registers a process-exit sync (`syncProfilePackagesToSource` from pi-hub) for profile launches, so the removed extension is not reinstalled on next launch.
|
|
65
|
+
- Context usage detection now sees the whole request, not just conversation messages: heuristic estimates (footer percentage before the first response and after `/compact`, zero-usage/error fallback, mid-session prompt/tool changes) include the folded system prompt and tool declarations, the usage anchor is invalidated when a newer-timestamp message is inserted into the prefix, Anthropic 1h cache writes (`cacheWrite1h`) are counted, and the footer shows a real estimate instead of `?` right after compaction. Wired via `estimateContextTokens`/`calculateContextTokens` shadows in the compaction wrapper plus a 9th module redirect for `coding-agent/src/core/agent-session.ts` (`getContextUsage` override).
|
|
66
|
+
|
|
67
|
+
### Added
|
|
68
|
+
|
|
69
|
+
- Plan mode (openclaude/Claude Code style) via the `EnterPlanMode` / `ExitPlanMode` tools, a `/plan` command (`/plan`, `/plan show`, `/plan edit`), a `ctrl+alt+p` toggle, and a `--plan` launch flag. While active the model is read-only: `edit`/`write` are restricted to the session plan file (`<agent dir>/plans/<sessionId>.md`, the only writable target), `bash` is restricted to a read-only command allowlist, `powershell` and non-allowlisted custom tools (including the `subagent` tool unless the read-only `explore` agent type) are blocked via the `tool_call` event, and a `<plan_mode>` system-prompt section drives a research-then-plan workflow. `EnterPlanMode` asks the user to confirm; `ExitPlanMode` presents the plan with Approve / Stay / Edit options and, on approval, returns the approved plan with full tool access restored. The footer shows a `⏸ plan` indicator; state is per-session in memory (reset on new/resume/fork).
|
|
70
|
+
- `subagent` tool — delegate a task to a specialized sub-agent running in an isolated `pi -p --no-session` subprocess with its own context window (ported from the coding-agent subagent example, single mode only). Agent types are markdown files with frontmatter (`name`, `description`, `tools`, `model`) in `<agent dir>/agents/` (user) or the nearest `.pi/agents/` walking up from the project dir (project); two built-in types always exist: `worker` (full toolset) and `explore` (read-only). Sub-agents cannot spawn further sub-agents unless their definition lists the `subagent` tool; project-local agent definitions require a one-time trust confirmation in the TUI. The tool runs with `executionMode: "parallel"` (issue multiple calls in one turn for concurrency), inherits the session model/thinking by default (`model` param overrides), propagates aborts to the child process, reports child token usage/cost on the result, and truncates oversized final output.
|
|
71
|
+
- Task tools — `TaskCreate` / `TaskUpdate` / `TaskList` / `TaskGet` (openclaude V2 style), file-backed under `<agent dir>/tasks/<sessionId>/` with a monotonic `.highwatermark` id allocator, per-task `owner` and `blocks`/`blockedBy` dependencies, and atomic tmp+rename writes. A `/tasks` command and the `ctrl+shift+t` shortcut open a task-list overlay in the TUI.
|
|
72
|
+
- π+ welcome banner now shows the boxed banner on every launch (the first-run-per-project gate and its `roam-banner.json` state are gone); the condensed tier remains the fallback only where the box cannot fit.
|
|
73
|
+
- `roam completion <bash|zsh>` prints a shell completion script owned by roam, covering the whole CLI: hub subcommands (dynamic profile names and per-profile models, providers, thinking levels) plus pi's native commands and flags. Moved here from the hub package, which no longer ships completion.
|
|
74
|
+
- `roam --help` now ends with a "Profile commands (roam)" section documenting `profile`, `use`/`unuse`, `completion`, and `--as` (via a `cli/args.ts` printHelp wrapper; 8th module redirect).
|
|
75
|
+
- Compiled `roam` CLI artifact: `build.mjs` bundles `roam` (pi + the plus override layer) into `dist/npm/`, a self-contained staging tree for `npm link` / `npm publish`. Exposes a single `roam` bin — never `pi`. The CLI (command, help text, hub usage strings) is named `roam`; the npm package stays `roam`.
|
|
76
|
+
- The plus config wrapper now resolves package assets (themes, HTML export template, interactive assets) from the staged bundle layout.
|
|
77
|
+
- The version check against pi's release train (pi.dev) is skipped.
|
|
78
|
+
- Vim modal editing for the prompt input (core subset ported from [pi-vimmode](https://github.com/pekochan069/pi-vimmode), MIT, (c) 2026 pekochan069), registered as a hidden built-in extension. Modes: insert/normal/visual (`v`)/visual-line (`V`). Motions: `h j k l w b e 0 $ ^ f F t T` with counts. Operators/edits: `x s r J p P`, operator+motion `d/c/y`, linewise `dd cc yy`, insert entries `i a I A o O C`, `u`/Ctrl-r undo/redo, prompt search `/ ? n N`. Enabled with `"vim": true` in settings (project `.pi/settings.json` > agent dir > `~/.pi/settings.json`) or toggled with `/vim`, which persists the new state to the agent dir `settings.json` so it sticks across launches. Excluded: ex commands, macros, marks, named registers, easymotion, visual-block, JS config, cursor-shape escapes.
|
|
79
|
+
|
|
80
|
+
### Removed
|
|
81
|
+
|
|
82
|
+
- The deprecated `roam run` command. `roam --as <name>` (one-off launch under a profile) and plain `roam` (default profile, if set) replace it; hub dispatch is now management-only (`profile`, `use`, `unuse`).
|
package/README.md
CHANGED
|
@@ -1,3 +1,74 @@
|
|
|
1
|
-
#
|
|
1
|
+
# plus-cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The roam CLI surface, on top of the shared override core in [`../plus`](../plus).
|
|
4
|
+
Direct updates to any other folder under `packages/` are forbidden — upstream packages
|
|
5
|
+
stay pristine so they can be synced/updated without merge conflicts.
|
|
6
|
+
|
|
7
|
+
The published npm artifact is **`roam`** (https://www.npmjs.com/package/roam);
|
|
8
|
+
it installs a single global command, **`roam`** — deliberately not `pi` (roam must
|
|
9
|
+
not own pi's command). Library hosts embedding pi in-process use the separate
|
|
10
|
+
**`roam-sdk`** package built from [`../plus-api`](../plus-api).
|
|
11
|
+
|
|
12
|
+
## What this layer adds on top of the shared core
|
|
13
|
+
|
|
14
|
+
The context-detection/compaction/reasoning overrides and the twelve non-TUI extensions
|
|
15
|
+
(subagent, tasks, memory, plan, ask-user, hooks, context-guard, recap, diagram, /cd, /init, web-search) live in
|
|
16
|
+
[`../plus`](../plus) and are shared with the SDK. This package adds the CLI-only pieces:
|
|
17
|
+
|
|
18
|
+
1. **Hub profiles** (`src/coding-agent/main.ts` wrapper, backed by `@roam-agent/roam-hub` = [`../hub`](../hub)) — named pi profiles (provider/models/thinking/token/base URL) stored in `~/.pi/profiles.json`, materialized into isolated agent dirs under `~/.pi/pi-hub/profiles/<name>/`. Adds `roam profile …`, `roam use` / `roam unuse`, and the `roam --as <name>` flag. The wrapper resolves the profile, sets `PI_CODING_AGENT_DIR` in-process (read lazily by `getAgentDir()`), and delegates to the original `main`. `roam profile add <name> -p <provider>` with no credential — or `roam profile add/update <name> --sign-in` for an explicit sign-in that overwrites the profile token — invokes the provider's interactive login (OAuth page / API-key setup) against the profile dir via hub's injected `login` hook, using `loginProvider` from [`../plus`](../plus)`/src/auth/login.ts` (the same entry `roam-sdk` re-exports for embedded hosts); the TUI `/login` is disabled by core redirect wrappers in favour of this flow.
|
|
19
|
+
2. **Shell completion** (`src/completion/`) — `roam completion <bash|zsh>` prints a completion script covering the whole CLI: hub subcommands (with dynamic profile/model names from `~/.pi/profiles.json`) plus pi's native commands and flags.
|
|
20
|
+
3. **Usage print** (`src/coding-agent/cli/args.ts` wrapper) — `roam --help` gains a "Profile commands (roam)" section.
|
|
21
|
+
4. **Welcome banner** (`src/coding-agent/ui/banner.ts`) — roam's TUI startup header is a CC-style banner with a block-character π+ mark: condensed logo by default, boxed variant with Extensions/Skills feeds, compact/plain degradation on narrow terminals, `resumed <id> · <title>` on resume/fork.
|
|
22
|
+
5. **Vim modal editing** (`src/coding-agent/ui/vim/`, core subset ported from [pi-vimmode](https://github.com/pekochan069/pi-vimmode), MIT, (c) 2026 pekochan069) — insert/normal/visual/visual-line modes, motions with counts, `d c y` operators, undo/redo, prompt search. Enable with `"vim": true` in settings or toggle with `/vim`.
|
|
23
|
+
6. **Settings selector rows** (`src/coding-agent/ui/settings-selector.ts` wrapper) — `/settings` gains "Auto-compact threshold", "Context floor", and "Context window cap" rows (persisted in the `roam` block of the base agent settings.json via the shared core's `context/plus-settings.ts`).
|
|
24
|
+
7. **Tab title + busy spinner** (`src/extensions/tab-title/`) — the terminal window/tab title brands as `pi+ - [sessionName -] cwdBasename` with a braille spinner while the agent or compaction is working. TUI mode only.
|
|
25
|
+
8. **Plain tool blocks** (`src/extensions/plain-tools/`) — strips background fills from tool result blocks so tool status reads as text (words, never colored blocks).
|
|
26
|
+
9. **Fancy content-change diffs** (`src/extensions/fancy-diff/`) — takes over the TUI rendering of `edit` and `write`: syntax-highlighted diff bodies, colored +/- markers, a dim line-number gutter, `+N −M` change stats with a language badge, bold word-level emphasis on modified lines, and a ⋮ separator for elided context. A `write` that overwrites an existing file renders as an old-vs-new diff (the pre-image is captured in a `tool_call` handler before execution; new files keep the streaming content preview). No background fills, consistent with plain tool blocks.
|
|
27
|
+
10. **Session change report** (`src/extensions/changes/`) — `/changes` prints the cumulative content diff of every file the agent changed this session, including files git cannot show: brand-new (untracked) files render as all-added diffs and deletions as all-removed. A `tool_call` handler snapshots each file's original content at the agent's first touch; the command diffs those baselines against the current files on disk and appends the report as a custom transcript entry (never in LLM context, re-rendered with the fancy-diff styling, persists across session restore). Optional argument filters paths by substring (`/changes src/foo`). Changes made through the `bash` tool are not tracked. TUI only.
|
|
28
|
+
11. **Auto-fold history** (`src/coding-agent/ui/auto-fold-history.ts`) — rolling fold of the transcript: as the agent starts each new assistant message mid-run, the previous step's thinking and finished tool rows collapse (thinking to the "Thinking... (ctrl+o to expand)" hint label, tools back to their standard preview), and a new user message folds all previous turns. The live step (streaming assistant message + in-flight tools) is always excluded, so output stays open while it's still relevant; resume and compaction replays fold everything before the last user turn. thinking folds and unfolds **exactly like tool output**: the fold syncs both flags (`toolOutputExpanded` false, `hideThinkingBlock` true — so neither ctrl+o nor ctrl+t ever dead-presses), new components inherit them (after a fold a fresh tool row starts collapsed **and** a fresh assistant message starts with hidden thinking, mid-run included — reveal via ctrl+o, ctrl+t or a click), and ctrl+o sweeps the whole transcript for both kinds, streaming component included, like upstream's tool sweep; clicking re-opens a single folded block. With `PI_AUTO_FOLD_HISTORY=0` the whole feature is off and ctrl+o behaves exactly like upstream (tool output only); verbose startup never folds. CLI-only — `roam-sdk` hosts (e.g. the desktop app) do their own folding.
|
|
29
|
+
12. **Resume list hides headless sessions** (`src/coding-agent/ui/session-selector.ts` wrapper) — the session picker reached by `roam --resume`, `roam -r` and the TUI `/resume` drops transcripts the host marked `interactive: false` (the marker itself lives in `../plus/src/coding-agent/core/session-manager.ts`), so SDK and automation runs stop crowding out the chats you actually had. Unmarked sessions stay listed, and `--session <id>` / `-r <id>` still resolve a headless transcript: only the display list is filtered, applied to the resolved list *and* to the partial lists rendered while a scan is still running. Side effect: a headless session cannot be renamed or deleted from the picker.
|
|
30
|
+
|
|
31
|
+
The CLI identifies as **`roam`** (roam) in CLI text via the shared config wrapper's
|
|
32
|
+
`APP_NAME` shadow; the terminal tab title brands as **`pi+`** via `APP_TITLE`.
|
|
33
|
+
|
|
34
|
+
## Running from sources
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
./roam --no-env # pi (roam) from TypeScript sources with the override layer active
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
`loader/hooks.mjs` is a Node module-customization hook that maps `@earendil-works/*`
|
|
41
|
+
to `packages/*/src` and redirects the overridden upstream modules to the wrappers
|
|
42
|
+
(shared core redirects in `../plus/loader/redirects.mjs`, CLI redirects in
|
|
43
|
+
`loader/redirects.mjs`). Importers inside any `packages/plus*` dir are never
|
|
44
|
+
redirected, so wrappers can import the true original via relative path without a loop.
|
|
45
|
+
|
|
46
|
+
## Compiled artifact (npm)
|
|
47
|
+
|
|
48
|
+
`build.mjs` bundles `roam` into `dist/npm/` — a self-contained staging tree that
|
|
49
|
+
`npm link` / `npm publish` operate on (this package itself stays private). The bundle
|
|
50
|
+
applies the redirect tables at bundle time via the shared plugin in
|
|
51
|
+
`../plus/build/redirect-plugin.mjs` and funnels every `packages/*/src` import with a
|
|
52
|
+
compiled `dist/` counterpart to that dist file (singleton preservation). `--no-env`
|
|
53
|
+
is preserved via a banner scrub.
|
|
54
|
+
|
|
55
|
+
```bash
|
|
56
|
+
npm run build:offline # at the repo root, first
|
|
57
|
+
npm run build # in packages/plus-cli
|
|
58
|
+
npm publish --access public --ignore-scripts # in packages/plus-cli/dist/npm
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The staged package is CLI-only: a `roam` bin and **no `.` export**, so
|
|
62
|
+
`import "roam"` fails by design — library hosts use `roam-sdk`.
|
|
63
|
+
|
|
64
|
+
Known limitations of the compiled artifact:
|
|
65
|
+
|
|
66
|
+
- `roam server` / `roam client` experimental subcommands (`PI_EXPERIMENTAL=1`) spawn sibling JS
|
|
67
|
+
files that are not emitted next to the bundle; use source-mode `./roam` for those.
|
|
68
|
+
- `docs/` and `examples/` are not shipped, so `/docs`-style paths into them are absent.
|
|
69
|
+
|
|
70
|
+
## Tests
|
|
71
|
+
|
|
72
|
+
```bash
|
|
73
|
+
npx vitest run # from packages/plus-cli; unit tests under test/ (faux streamFn, no real APIs)
|
|
74
|
+
```
|
package/anthropic.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
|
|
2
|
+
{
|
|
3
|
+
const __noEnvIndex = process.argv.indexOf("--no-env");
|
|
4
|
+
if (__noEnvIndex !== -1) {
|
|
5
|
+
process.argv.splice(__noEnvIndex, 1);
|
|
6
|
+
for (const __key of ["ANTHROPIC_API_KEY", "ANTHROPIC_OAUTH_TOKEN", "OPENAI_API_KEY", "GEMINI_API_KEY", "GROQ_API_KEY", "CEREBRAS_API_KEY", "XAI_API_KEY", "OPENROUTER_API_KEY", "ZAI_API_KEY", "MISTRAL_API_KEY", "MINIMAX_API_KEY", "MINIMAX_CN_API_KEY", "AI_GATEWAY_API_KEY", "OPENCODE_API_KEY", "COPILOT_GITHUB_TOKEN", "GH_TOKEN", "GITHUB_TOKEN", "HF_TOKEN", "GOOGLE_APPLICATION_CREDENTIALS", "GOOGLE_CLOUD_PROJECT", "GCLOUD_PROJECT", "GOOGLE_CLOUD_LOCATION", "AWS_PROFILE", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_REGION", "AWS_DEFAULT_REGION", "AWS_BEARER_TOKEN_BEDROCK", "AWS_CONTAINER_CREDENTIALS_RELATIVE_URI", "AWS_CONTAINER_CREDENTIALS_FULL_URI", "AWS_WEB_IDENTITY_TOKEN_FILE", "AZURE_OPENAI_API_KEY", "AZURE_OPENAI_BASE_URL", "AZURE_OPENAI_RESOURCE_NAME"]) delete process.env[__key];
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env){return env?.[name]||(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}import{createServer}from"node:http";var LOGO_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#F09082" d="M165.29 165.29H517.36V400H400V282.65H165.29Z"/><path fill="#4D9ABF" d="M165.29 282.65H282.65V400H400V517.36H282.65V634.72H165.29Z"/><path fill="#F1BE58" d="M517.36 400H634.72V634.72H517.36Z"/></svg>';function escapeHtml(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(options.message),details=options.details?escapeHtml(options.details):void 0;return`<!doctype html>
|
|
10
|
+
<html lang="en">
|
|
11
|
+
<head>
|
|
12
|
+
<meta charset="utf-8" />
|
|
13
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
14
|
+
<title>${title}</title>
|
|
15
|
+
<style>
|
|
16
|
+
:root {
|
|
17
|
+
--text: #fafafa;
|
|
18
|
+
--text-dim: #a1a1aa;
|
|
19
|
+
--page-bg: #09090b;
|
|
20
|
+
--font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
|
|
21
|
+
--font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
|
|
22
|
+
}
|
|
23
|
+
* { box-sizing: border-box; }
|
|
24
|
+
html { color-scheme: dark; }
|
|
25
|
+
body {
|
|
26
|
+
margin: 0;
|
|
27
|
+
min-height: 100vh;
|
|
28
|
+
display: flex;
|
|
29
|
+
align-items: center;
|
|
30
|
+
justify-content: center;
|
|
31
|
+
padding: 24px;
|
|
32
|
+
background: var(--page-bg);
|
|
33
|
+
color: var(--text);
|
|
34
|
+
font-family: var(--font-sans);
|
|
35
|
+
text-align: center;
|
|
36
|
+
}
|
|
37
|
+
main {
|
|
38
|
+
width: 100%;
|
|
39
|
+
max-width: 560px;
|
|
40
|
+
display: flex;
|
|
41
|
+
flex-direction: column;
|
|
42
|
+
align-items: center;
|
|
43
|
+
justify-content: center;
|
|
44
|
+
}
|
|
45
|
+
.logo {
|
|
46
|
+
width: 72px;
|
|
47
|
+
height: 72px;
|
|
48
|
+
display: block;
|
|
49
|
+
margin-bottom: 24px;
|
|
50
|
+
}
|
|
51
|
+
h1 {
|
|
52
|
+
margin: 0 0 10px;
|
|
53
|
+
font-size: 28px;
|
|
54
|
+
line-height: 1.15;
|
|
55
|
+
font-weight: 650;
|
|
56
|
+
color: var(--text);
|
|
57
|
+
}
|
|
58
|
+
p {
|
|
59
|
+
margin: 0;
|
|
60
|
+
line-height: 1.7;
|
|
61
|
+
color: var(--text-dim);
|
|
62
|
+
font-size: 15px;
|
|
63
|
+
}
|
|
64
|
+
.details {
|
|
65
|
+
margin-top: 16px;
|
|
66
|
+
font-family: var(--font-mono);
|
|
67
|
+
font-size: 13px;
|
|
68
|
+
color: var(--text-dim);
|
|
69
|
+
white-space: pre-wrap;
|
|
70
|
+
word-break: break-word;
|
|
71
|
+
}
|
|
72
|
+
</style>
|
|
73
|
+
</head>
|
|
74
|
+
<body>
|
|
75
|
+
<main>
|
|
76
|
+
<div class="logo">${LOGO_SVG}</div>
|
|
77
|
+
<h1>${heading}</h1>
|
|
78
|
+
<p>${message}</p>
|
|
79
|
+
${details?`<div class="details">${details}</div>`:""}
|
|
80
|
+
</main>
|
|
81
|
+
</body>
|
|
82
|
+
</html>`}function oauthSuccessHtml(message){return renderPage({title:"Authentication successful",heading:"Authentication successful",message})}function oauthErrorHtml(message,details){return renderPage({title:"Authentication failed",heading:"Authentication failed",message,details})}function sendPage(response,status,html){response.writeHead(status,{"content-type":"text/html; charset=utf-8","cache-control":"no-store"}),response.end(html)}async function startOAuthCallbackServer(options){let{providerName,signal}=options;if(signal?.aborted)throw new Error("Login cancelled");let resolveWait=()=>{},rejectWait=()=>{},waitPromise=new Promise((resolve,reject)=>{resolveWait=resolve,rejectWait=reject});waitPromise.catch(()=>{});let claimed=!1,settled=!1,timer,onAbort=()=>finish({error:new Error("Login cancelled")}),finish=result=>{settled||(settled=!0,timer&&clearTimeout(timer),signal?.removeEventListener("abort",onAbort),"error"in result?rejectWait(result.error):resolveWait(result.value))},server=createServer((request,response)=>{(async()=>{let url=new URL(request.url??"/","http://localhost");if(request.method!=="GET"||url.pathname!==options.path){sendPage(response,404,oauthErrorHtml("Callback route not found."));return}if(options.state!==void 0&&url.searchParams.get("state")!==options.state){sendPage(response,400,oauthErrorHtml("State mismatch."));return}if(claimed||settled){sendPage(response,409,oauthErrorHtml("This sign-in has already been handled."));return}let error=url.searchParams.get("error");if(error){let description=url.searchParams.get("error_description")??error;sendPage(response,400,oauthErrorHtml(`${providerName} authorization failed.`,description)),finish({error:new Error(`${providerName} authorization failed: ${description}`)});return}let code=url.searchParams.get("code");if(!code){sendPage(response,400,oauthErrorHtml("Missing authorization code."));return}claimed=!0;try{let value=await options.complete(code);sendPage(response,200,oauthSuccessHtml(`Signed in to ${providerName}. You may now close this page.`)),finish({value})}catch(error2){let failure=error2 instanceof Error?error2:new Error(String(error2));sendPage(response,502,oauthErrorHtml(`${providerName} sign-in failed.`,failure.message)),finish({error:failure})}})()});await new Promise((resolve,reject)=>{server.once("error",reject),server.listen(options.port,options.host,()=>{server.off("error",reject),resolve()})});let address=server.address();if(!address||typeof address=="string")throw server.close(),new Error("OAuth callback server did not bind to TCP");server.on("error",error=>finish({error})),signal?.addEventListener("abort",onAbort,{once:!0}),options.timeoutMs!==void 0&&(timer=setTimeout(()=>finish({error:new Error(`${providerName} sign-in timed out`)}),options.timeoutMs));let redirectHost=options.redirectHost??options.host;return{redirectUri:`http://${redirectHost.includes(":")?`[${redirectHost}]`:redirectHost}:${address.port}${options.path}`,wait:()=>waitPromise,cancel:()=>{claimed||finish({value:void 0})},close:()=>{finish({error:new Error("OAuth callback server closed")}),server.close()}}}async function waitForCallbackOrManualInput(interaction,callback,prompt){let manualAbort=new AbortController,manualError,manual=interaction.prompt({type:"manual_code",...prompt,signal:manualAbort.signal}).then(input=>(callback?.cancel(),input)).catch(error=>{manualError=error instanceof Error?error:new Error(String(error)),callback?.cancel()});try{let value=await callback?.wait();if(manualError)throw manualError;if(value!==void 0)return{type:"callback",value};let input=await manual;if(manualError)throw manualError;return{type:"manual",input:input??""}}finally{manualAbort.abort()}}function base64urlEncode(bytes){let binary="";for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function generatePKCE(){let verifierBytes=new Uint8Array(32);crypto.getRandomValues(verifierBytes);let verifier=base64urlEncode(verifierBytes),data=new TextEncoder().encode(verifier),hashBuffer=await crypto.subtle.digest("SHA-256",data),challenge=base64urlEncode(new Uint8Array(hashBuffer));return{verifier,challenge}}var decode=s=>atob(s),CLIENT_ID=decode("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl"),AUTHORIZE_URL="https://claude.ai/oauth/authorize",TOKEN_URL="https://platform.claude.com/v1/oauth/token",CALLBACK_HOST=getProviderEnvValue("PI_OAUTH_CALLBACK_HOST")||"127.0.0.1",CALLBACK_PORT=53692,CALLBACK_PATH="/callback",REDIRECT_URI=`http://localhost:${CALLBACK_PORT}${CALLBACK_PATH}`,COPY_CODE_REDIRECT_URI="https://platform.claude.com/oauth/code/callback",ANTHROPIC_BROWSER_LOGIN_METHOD="browser",ANTHROPIC_COPY_CODE_LOGIN_METHOD="copy_code",SCOPES="org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload";function parseAuthorizationInput(input){let value=input.trim();if(!value)return{};try{let url=new URL(value);return{code:url.searchParams.get("code")??void 0,state:url.searchParams.get("state")??void 0}}catch{}if(value.includes("#")){let[code,state]=value.split("#",2);return{code,state}}if(value.includes("code=")){let params=new URLSearchParams(value);return{code:params.get("code")??void 0,state:params.get("state")??void 0}}return{code:value}}function formatErrorDetails(error){if(error instanceof Error){let details=[`${error.name}: ${error.message}`],errorWithCode=error;return errorWithCode.code&&details.push(`code=${errorWithCode.code}`),typeof errorWithCode.errno<"u"&&details.push(`errno=${String(errorWithCode.errno)}`),typeof error.cause<"u"&&details.push(`cause=${formatErrorDetails(error.cause)}`),error.stack&&details.push(`stack=${error.stack}`),details.join("; ")}return String(error)}async function postJson(url,body,signal){let response=await fetch(url,{method:"POST",headers:{"Content-Type":"application/json",Accept:"application/json"},body:JSON.stringify(body),signal:AbortSignal.any([signal,AbortSignal.timeout(3e4)])}),responseBody=await response.text();if(!response.ok)throw new Error(`HTTP request failed. status=${response.status}; url=${url}; body=${responseBody}`);return responseBody}async function exchangeAuthorizationCode(code,state,verifier,redirectUri,signal){let responseBody;try{responseBody=await postJson(TOKEN_URL,{grant_type:"authorization_code",client_id:CLIENT_ID,code,state,redirect_uri:redirectUri,code_verifier:verifier},signal)}catch(error){throw new Error(`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${redirectUri}; response_type=authorization_code; details=${formatErrorDetails(error)}`)}let tokenData;try{tokenData=JSON.parse(responseBody)}catch(error){throw new Error(`Token exchange returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`)}return{type:"oauth",refresh:tokenData.refresh_token,access:tokenData.access_token,expires:Date.now()+tokenData.expires_in*1e3-300*1e3}}async function loginAnthropic(interaction){let{verifier,challenge}=await generatePKCE(),startCallbackServer=port=>startOAuthCallbackServer({providerName:"Anthropic",host:CALLBACK_HOST,port,path:CALLBACK_PATH,redirectHost:"localhost",state:verifier,complete:async code=>code,signal:interaction.signal}),callback=await startCallbackServer(CALLBACK_PORT).catch(()=>startCallbackServer(0)).catch(()=>{}),redirectUri=callback?.redirectUri??REDIRECT_URI;try{let authParams=new URLSearchParams({code:"true",client_id:CLIENT_ID,response_type:"code",redirect_uri:redirectUri,scope:SCOPES,code_challenge:challenge,code_challenge_method:"S256",state:verifier});interaction.notify({type:"auth_url",url:`${AUTHORIZE_URL}?${authParams.toString()}`,instructions:"Complete login in your browser. If the browser is on another machine, paste the final redirect URL here."});let result=await waitForCallbackOrManualInput(interaction,callback,{message:"Complete login in your browser, or paste the authorization code / redirect URL here:",placeholder:redirectUri}),code,state=verifier;if(result.type==="callback")code=result.value;else{let parsed=parseAuthorizationInput(result.input);if(parsed.state&&parsed.state!==verifier)throw new Error("OAuth state mismatch");code=parsed.code,state=parsed.state??verifier}if(!code)throw new Error("Missing authorization code");return interaction.notify({type:"progress",message:"Exchanging authorization code for tokens..."}),await exchangeAuthorizationCode(code,state,verifier,redirectUri,interaction.signal)}finally{callback?.close()}}async function loginAnthropicCopyCode(interaction){let{verifier,challenge}=await generatePKCE(),authParams=new URLSearchParams({code:"true",client_id:CLIENT_ID,response_type:"code",redirect_uri:COPY_CODE_REDIRECT_URI,scope:SCOPES,code_challenge:challenge,code_challenge_method:"S256",state:verifier});interaction.notify({type:"auth_url",url:`${AUTHORIZE_URL}?${authParams.toString()}`,instructions:"Complete login in your browser, then copy the code Anthropic shows and paste it here."});let input=await interaction.prompt({type:"manual_code",message:"Paste the code Anthropic shows after you sign in:",placeholder:"code#state",signal:interaction.signal}),parsed=parseAuthorizationInput(input);if(parsed.state&&parsed.state!==verifier)throw new Error("OAuth state mismatch");if(!parsed.code)throw new Error("Missing authorization code");return interaction.notify({type:"progress",message:"Exchanging authorization code for tokens..."}),await exchangeAuthorizationCode(parsed.code,parsed.state??verifier,verifier,COPY_CODE_REDIRECT_URI,interaction.signal)}async function refreshAnthropicToken(refreshToken,signal){let responseBody;try{responseBody=await postJson(TOKEN_URL,{grant_type:"refresh_token",client_id:CLIENT_ID,refresh_token:refreshToken},signal)}catch(error){throw new Error(`Anthropic token refresh request failed. url=${TOKEN_URL}; details=${formatErrorDetails(error)}`)}let data;try{data=JSON.parse(responseBody)}catch(error){throw new Error(`Anthropic token refresh returned invalid JSON. url=${TOKEN_URL}; body=${responseBody}; details=${formatErrorDetails(error)}`)}return{type:"oauth",refresh:data.refresh_token,access:data.access_token,expires:Date.now()+data.expires_in*1e3-300*1e3}}var anthropicOAuth={name:"Anthropic (Claude Pro/Max)",isSubscription:!0,async login(interaction){let method=await interaction.prompt({type:"select",message:"Select Anthropic login method:",options:[{id:ANTHROPIC_BROWSER_LOGIN_METHOD,label:"Browser login (default)"},{id:ANTHROPIC_COPY_CODE_LOGIN_METHOD,label:"Copy code login (headless)"}]});if(method===ANTHROPIC_COPY_CODE_LOGIN_METHOD)return loginAnthropicCopyCode(interaction);if(method!==ANTHROPIC_BROWSER_LOGIN_METHOD)throw new Error(`Unknown Anthropic login method: ${method}`);return loginAnthropic(interaction)},refresh:(credential,signal)=>refreshAnthropicToken(credential.refresh,signal),async toAuth(credential){return{apiKey:credential.access}}};export{anthropicOAuth};
|