@falkenslab/agent-kit 0.30.1 → 0.32.0

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/README.md CHANGED
@@ -1,111 +1,175 @@
1
- <h1>
2
- <img src="https://raw.githubusercontent.com/falkenslab/agent-kit/main/docs/assets/logo-readme-any.svg" alt="agent-kit" height="64">
3
- </h1>
4
-
5
- [![npm](https://img.shields.io/npm/v/@falkenslab/agent-kit?logo=npm)](https://www.npmjs.com/package/@falkenslab/agent-kit)
6
- [![npm downloads](https://img.shields.io/npm/dm/@falkenslab/agent-kit)](https://www.npmjs.com/package/@falkenslab/agent-kit)
7
- [![types](https://img.shields.io/npm/types/@falkenslab/agent-kit)](https://www.npmjs.com/package/@falkenslab/agent-kit)
8
- [![node](https://img.shields.io/node/v/@falkenslab/agent-kit)](https://nodejs.org/)
9
- [![license](https://img.shields.io/npm/l/@falkenslab/agent-kit)](LICENSE)
10
- [![docs](https://img.shields.io/badge/docs-falkenslab.github.io%2Fagent--kit-4453b8)](https://falkenslab.github.io/agent-kit/)
11
-
12
- **[📖 Documentation](https://falkenslab.github.io/agent-kit/)** · [📖 Documentación en español](https://falkenslab.github.io/agent-kit/es/)
13
-
14
- A foundation for building AI agents on top of the [Claude Agent SDK](https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk). It isn't an agent itself: it solves once what every agent needs (human oversight, safety, memory and a good terminal interface), so each concrete agent only has to write what belongs to its own domain: what it knows how to do, with which tools, and how it talks.
15
-
16
- ## What an agent built with it can do
17
-
18
- - **Work at different levels of oversight.** Autonomous, guided (it asks for permission before anything that can't be undone or that other people will see) or step by step (it asks before every action), and a plan mode where it only reads and plans until you let it act. Within the same conversation you can switch among guided, step by step and plan.
19
- - **Ask a person for help.** It asks for approvals, or stops so someone can do something by hand, such as signing in to a website. It can be answered from the keyboard or from another program driving it, for example a desktop app.
20
- - **Remember between sessions.** It keeps its own knowledge base, a small wiki of notes that grows with every session, and keeps the original documents you give it or that it downloads untouched. Each conversation stays in the project's folder, so you can pick it up again with `--continue` (the latest one) or `/resume` (any of them).
21
- - **Speak your language.** Its interface comes in English, Spanish, French or German, the system's by default or the one you ask for with `--language=fr`, and it answers in that language unless you write to it in another one.
22
- - **Delegate to subagents safely.** Only to the ones it declares, always waiting for their result, and without the main agent being able to slip past its own limits through them.
23
- - **Stay within limits.** It only reads and writes in the folders that belong to it, and never in protected files, such as one holding passwords.
24
- - **Use external tools.** MCP servers of its own or of the project, and skills and commands organized in plugins.
25
- - **Leave a trail.** It records every action and the whole conversation, with secrets hidden.
26
- - **Look the way you want.** The terminal's colors come from a theme by roles (the agent's replies, tool results, the focused option, borders…): pass only the ones you want to change, as a color name, a hex or a function.
27
- - **Chat in a terminal the way Claude Code does.** Full screen, with the reply written live and its markdown already formatted, the tools it uses shown in as much detail as the agent chooses (each call with its result, the calls alone, or one line per group; Ctrl+O unfolds them), panels for approvals, history and search, a suggestion for the next message, pasted blocks, file mentions with `@`, mouse selection (right-click to copy), and the agent's status in the tab and in the Windows taskbar.
28
- - **Also work without a terminal.** The same foundation runs inside a desktop app or a server, which bring their own interface.
29
-
30
- ## Examples
31
-
32
- ### Captain Whiskers
33
-
34
- [Captain Whiskers](./examples/captain-whiskers) is a toy agent to see the kit in action: a retired pirate cat who tells jokes in the terminal, in your language. It starts full screen with its logo and has a small crew of subagents: one looks for new jokes on the web, another rates them before they're told, and a third tells the time with a tool of the captain's own. It lets you try the different levels of oversight and is the best starting point for an agent of your own. Its README explains how to run it.
35
-
36
- ![Captain Whiskers in Windows Terminal: his logo with the mode and the agent-kit version at the top, his crew at work in the middle, a task list under the spinner, and the framed prompt and status bar at the bottom](docs/assets/captain-whiskers.png)
37
-
38
- See [everything he can do](https://falkenslab.github.io/agent-kit/docs/next/examples/captain-whiskers#what-he-can-do), with screenshots.
39
-
40
- ### miyagi
41
-
42
- [miyagi](https://github.com/falkenslab/miyagi) is a real assistant for Moodle teachers. It signs in with your account in a Chrome window and works as you would: it grades submissions, answers in the forum, creates or reviews content and sums up how the class is going. It asks for your permission before publishing anything students will see, and takes notes about the course to remember everything in the next session.
43
-
44
- Oversight, memory, safety and the chat come from the kit; miyagi brings what it knows about Moodle and driving the browser.
45
-
46
- ## Installation
47
-
48
- ```
49
- npm install @falkenslab/agent-kit
50
- ```
51
-
52
- To try changes to the kit without publishing them, point to a local clone with `"file:../agent-kit"` in your `package.json` and build it with `npm run build` after each change.
53
-
54
- Requires Node.js 20 or later.
55
-
56
- ## A minimal agent
57
-
58
- An agent only describes what belongs to it (who it is, which MCP servers, skills and subagents it has) and picks a level of oversight; the kit sets up the session and the chat:
59
-
60
- ```ts
61
- import path from "node:path";
62
- import { buildSessionOptions, ensureClaudeAuth, runChatInk, type AgentSpec, type BaseSessionConfig } from "@falkenslab/agent-kit";
63
-
64
- // The only part specific to the agent: who it is and what it has.
65
- const spec: AgentSpec<BaseSessionConfig> = {
66
- buildSystemPrompt: () => "You are a pirate cat who tells jokes. Always answer in character.",
67
- buildMcpServers: () => ({}), // its own MCP servers, if any
68
- pluginRoots: () => [], // folders with skills and commands
69
- buildSubagents: () => undefined, // subagents, if it delegates to any
70
- };
71
-
72
- await ensureClaudeAuth(); // offers to create a Claude token if it finds none
73
-
74
- const config: BaseSessionConfig = { mode: "guided", projectDir: process.cwd() };
75
-
76
- // Each run gets a folder of its own under .run/ (keep it out of git): its log, its
77
- // transcript and the conversation, to pick it up again with --continue or /resume.
78
- await runChatInk((run) => buildSessionOptions(config, run.dir, spec, { run }), {
79
- runsDir: path.resolve(".run"),
80
- header: { title: "My agent" },
81
- mode: config.mode, // Shift+Tab cycles through guided, step by step and plan
82
- fullscreen: true,
83
- theme: { toolResult: "gray", selection: "#ffb86c" }, // only the colors you want to change
84
- });
85
- ```
86
-
87
- Save it as `agent.ts` in a project with the kit and `tsx` installed and `"type": "module"` in its `package.json`, and run it with `npx tsx agent.ts`. Captain Whiskers is this same skeleton with more pieces: skills, subagents and its logo.
88
-
89
- ## Documentation
90
-
91
- The full documentation is at **[falkenslab.github.io/agent-kit](https://falkenslab.github.io/agent-kit/)**: a tutorial, guides for every part of the kit (modes, human in the loop, security, tools, subagents, the knowledge base, the terminal UI, runs, languages, themes, hosts without a terminal), recipes, and an API reference generated from the source, for each released version.
92
-
93
- For whoever works on the kit itself, the specification in [`.minispec/`](./.minispec/README.md) explains how each part is built and why, including the SDK behaviors checked by hand that motivate several of its safeguards.
94
-
95
- ## Development
96
-
97
- | Command | What it does |
98
- | --- | --- |
99
- | `npm run build` | Builds the kit into `dist/` |
100
- | `npm run typecheck` | Checks the types without building |
101
- | `npm run lint` | Checks the code style |
102
- | `npm test` | Runs all the tests |
103
- | `npm run docs:install` | Installs the documentation site's dependencies (once) |
104
- | `npm run docs:start` | Serves the documentation site locally, reloading on changes |
105
- | `npm run docs:build` | Builds the documentation site (fails on broken links) |
106
-
107
- To run a single test file:
108
-
109
- ```
110
- npx tsx --test test/tui/promptErrors.test.ts
111
- ```
1
+ <div align="center">
2
+
3
+ <img src="https://raw.githubusercontent.com/falkenslab/agent-kit/main/docs/static/img/logo.svg" alt="agent-kit logo: three blue building blocks and a coral one being set in place" width="112"/>
4
+
5
+ # agent-kit
6
+
7
+ **Build an AI agent on Claude that asks before it acts, remembers, and chats like Claude Code.**<br/>
8
+ You write what your agent knows and does; the kit brings oversight, safety, memory and the interface.
9
+
10
+ [![npm](https://img.shields.io/npm/v/@falkenslab/agent-kit?color=cb3837&logo=npm)](https://www.npmjs.com/package/@falkenslab/agent-kit)
11
+ ![Node.js 20+](https://img.shields.io/badge/node-20%2B-339933?logo=node.js&logoColor=white)
12
+ ![Claude Agent SDK](https://img.shields.io/badge/Claude-Agent%20SDK-d97757?logo=anthropic&logoColor=white)
13
+ ![TypeScript](https://img.shields.io/badge/types-included-3178c6?logo=typescript&logoColor=white)
14
+ [![License: MIT](https://img.shields.io/badge/license-MIT-16a34a)](LICENSE)
15
+
16
+ **[📖 Documentation](https://falkenslab.github.io/agent-kit/)** · [📖 Documentación en español](https://falkenslab.github.io/agent-kit/es/)
17
+
18
+ </div>
19
+
20
+ agent-kit is a foundation for building AI agents on top of the [Claude Agent SDK](https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk). It isn't an agent itself: it solves once what every agent needs (levels of oversight, approvals, safe limits, memory across sessions, extensions, and a terminal chat as good as Claude Code's), so each agent writes only what belongs to its own domain: what it knows how to do, with which tools, and how it talks. A teacher's assistant for Moodle and a pirate cat who tells jokes are built the same way.
21
+
22
+ ## ✨ Why agent-kit
23
+
24
+ - 🎚️ **You choose how much it acts alone.** Autonomous, guided (it asks before what others will see or can't be undone), step by step, or a plan mode where it only reads and plans; switch among them in the same conversation.
25
+ - ✋ **It asks a person, and the kit makes sure.** Approvals, choices, a file, a sign-in by hand; an installed extension's tool that changes things waits for a yes whatever the model decided, and answers can last for the session or for good.
26
+ - 🧠 **It remembers.** A knowledge base that grows with every session, the original documents it learns from kept untouched, a memory of the person, and every conversation to pick up again with `--continue` or `/resume`.
27
+ - 🛡️ **It stays within limits.** Only its own folders, never protected files, subagents that can't slip past the main agent's limits, secrets hidden from the logs, remote servers allowed, asked about or denied.
28
+ - 🧩 **It grows with extensions.** Claude Code plugins with MCP servers, skills and commands, installed from a marketplace or a folder, with their own options, sign-in and a catalog in the chat; no Git needed.
29
+ - 🌐 **It speaks your language.** Its interface in English, Spanish, French or German, and it answers in that language unless you write in another.
30
+ - 🖥️ **A terminal chat like Claude Code's, or none at all.** Full screen, live markdown, folded tool calls, panels, history, themes; or the same agent inside a desktop app or a web page with its own interface.
31
+
32
+ ## 🚀 Quick start
33
+
34
+ You need [Node.js](https://nodejs.org) 20 or later and a Claude account. In a project with `"type": "module"` in its `package.json`:
35
+
36
+ ```bash
37
+ npm install @falkenslab/agent-kit tsx
38
+ ```
39
+
40
+ Save this as `agent.ts`: the only part that's your agent's is the spec at the top.
41
+
42
+ ```ts
43
+ import path from "node:path";
44
+ import { buildSessionOptions, ensureClaudeAuth, runChatInk, type AgentSpec, type BaseSessionConfig } from "@falkenslab/agent-kit";
45
+
46
+ const spec: AgentSpec<BaseSessionConfig> = {
47
+ buildSystemPrompt: () => "You are a pirate cat who tells jokes. Always answer in character.",
48
+ buildMcpServers: () => ({}), // its own MCP servers, if any
49
+ pluginRoots: () => [], // folders with skills and commands
50
+ buildSubagents: () => undefined, // subagents, if it delegates to any
51
+ };
52
+
53
+ await ensureClaudeAuth(); // offers to sign in with your Claude account, on Anthropic's page, if it isn't
54
+ const config: BaseSessionConfig = { mode: "guided", projectDir: process.cwd() };
55
+
56
+ // Each run gets a folder under .run/ (keep it out of git): its log, transcript and conversation.
57
+ await runChatInk((run) => buildSessionOptions(config, run.dir, spec, { run }), {
58
+ runsDir: path.resolve(".run"),
59
+ header: { title: "My agent" },
60
+ mode: config.mode, // Shift+Tab cycles through guided, step by step and plan
61
+ fullscreen: true,
62
+ });
63
+ ```
64
+
65
+ Run it with `npx tsx agent.ts`: a full-screen chat opens, in your system's language, and the agent asks before anything it shouldn't do alone. The [tutorial](https://falkenslab.github.io/agent-kit/docs/getting-started/first-agent) takes it from there.
66
+
67
+ ## 🧪 A taste of the code
68
+
69
+ Give it a memory and a folder of sources, with the kit's own extensions:
70
+
71
+ ```ts
72
+ import { knowledge, memory, sources } from "@falkenslab/agent-kit";
73
+
74
+ const spec: AgentSpec<BaseSessionConfig> = {
75
+ // …
76
+ extensions: [sources({ dir: "sources" }), knowledge({ dir: "knowledge" }), memory({ dir: "memory" })],
77
+ };
78
+ ```
79
+
80
+ Let it install extensions from your marketplace, and keep its data from leaving the computer without asking:
81
+
82
+ ```ts
83
+ const config: BaseSessionConfig = {
84
+ mode: "guided",
85
+ projectDir: process.cwd(),
86
+ extensionDirs: { agent: path.join(os.homedir(), ".my-agent", "extensions") },
87
+ officialMarketplace: "falkenslab/agent-extensions",
88
+ remoteServers: "ask",
89
+ };
90
+ ```
91
+
92
+ Make a tool always wait for the person's yes, on every call:
93
+
94
+ ```ts
95
+ const spec: AgentSpec<BaseSessionConfig> = {
96
+ // …
97
+ extensionGate: { confirmTools: { canva: ["create-design", "publish-design"] } },
98
+ };
99
+ ```
100
+
101
+ ## 📸 See it at work
102
+
103
+ [Captain Whiskers](./examples/captain-whiskers), the kit's example agent: a retired pirate cat who tells jokes in your language, with a crew of subagents (one looks for new jokes on the web, one rates them, one tells the time), a logbook and an extension of his own. He runs in the terminal, in a browser and as a Windows app.
104
+
105
+ <div align="center">
106
+
107
+ <img src="https://raw.githubusercontent.com/falkenslab/agent-kit/main/docs/assets/captain-whiskers.png" alt="Captain Whiskers in Windows Terminal: his logo with the mode and the agent-kit version at the top, his crew at work in the middle, a task list under the spinner, and the framed prompt and status bar at the bottom" width="760"/>
108
+
109
+ </div>
110
+
111
+ See [everything he can do](https://falkenslab.github.io/agent-kit/docs/examples/captain-whiskers#what-he-can-do), with screenshots. For a real one, [miyagi](https://github.com/falkenslab/miyagi) is an assistant for Moodle teachers: it grades, answers the forum, builds content and sums up how the class is going, asking before publishing anything students will see. Oversight, memory, safety and the chat come from the kit; miyagi brings what it knows about Moodle.
112
+
113
+ ## 🧰 What's inside
114
+
115
+ | Area | For example |
116
+ | --- | --- |
117
+ | 🎚️ Modes and gates | Autonomous, guided, step by step and plan; the guided gate for extensions' tools, the plan gate, the step gate |
118
+ | ✋ Human in the loop | Approvals, choices, free text, files, manual steps, MCP elicitation forms, a response file for hosts without a keyboard |
119
+ | 🧠 Memory | A knowledge base (an LLM wiki), sources kept as obtained, a memory of the person, runs resumed with `--continue` and `/resume` |
120
+ | 🧩 Extensions | Claude Code plugins with MCP servers (local, npm, remote with OAuth), skills, commands and subagents; scopes, a lock, workspace trust, options, marketplaces and a catalog |
121
+ | 🛡️ Security | A file scope gate, denied paths, subagent gates, a remote-servers gate, isolation from the runner's own Claude Code, redacted transcripts |
122
+ | 🤖 Subagents | Declared types only, in the foreground, without Bash for the main agent |
123
+ | 🖥️ Interfaces | A full-screen Ink chat, a plain readline chat, a progress view, a wizard, themes; a chat controller for desktop apps and web pages |
124
+ | 🌐 Languages | English, Spanish, French and German, for the interface, the replies and the extensions' servers |
125
+
126
+ Every export, with what it takes and what it gives, is in the [API reference](https://falkenslab.github.io/agent-kit/docs/api).
127
+
128
+ ## 📚 Documentation
129
+
130
+ - **[Getting started](https://falkenslab.github.io/agent-kit/docs/getting-started/installation)**: installation and a first agent, step by step.
131
+ - **[Modes](https://falkenslab.github.io/agent-kit/docs/core-concepts/modes)** and **[human in the loop](https://falkenslab.github.io/agent-kit/docs/human-in-the-loop/overview)**: how much the agent does alone, and how it asks.
132
+ - **[Extensions](https://falkenslab.github.io/agent-kit/docs/extensions/overview)**: installing, writing and publishing them.
133
+ - **[Security](https://falkenslab.github.io/agent-kit/docs/security/overview)**: every guardrail, and what the kit doesn't protect.
134
+ - **[The terminal chat](https://falkenslab.github.io/agent-kit/docs/terminal-ui/ink-chat)**: its keys, panels, options and themes.
135
+ - **[Captain Whiskers](https://falkenslab.github.io/agent-kit/docs/examples/captain-whiskers)**: the example agent, piece by piece.
136
+
137
+ ## 🛠️ Developing
138
+
139
+ The design decisions, and the SDK behaviors checked by hand behind several safeguards, are in [`.minispec/`](./.minispec/README.md).
140
+
141
+ | Command | What it does |
142
+ | --- | --- |
143
+ | `npm run build` | Builds the kit into `dist/` |
144
+ | `npm run typecheck` | Checks the types without building |
145
+ | `npm run lint` | Checks the code style |
146
+ | `npm test` | Runs all the tests (one file: `npx tsx --test test/tui/promptErrors.test.ts`) |
147
+ | `npm run docs:install` | Installs the documentation site's dependencies (once) |
148
+ | `npm run docs:start` | Serves the documentation site locally, reloading on changes |
149
+ | `npm run docs:build` | Builds the documentation site (fails on broken links) |
150
+
151
+ To try changes to the kit in an agent without publishing them, point its `package.json` to a local clone (`"file:../agent-kit"`) and run `npm run build` after each change.
152
+
153
+ Working on the kit with Claude Code goes through Falken's Lab's own skills (commit, verify, update-docs, release, sync-issues, and the house style for READMEs, sites and Markdown), from the [falkenslab/falkenslab-plugins](https://github.com/falkenslab/falkenslab-plugins) marketplace. Install them once, for all of Falken's Lab's repositories:
154
+
155
+ ```bash
156
+ claude plugin marketplace add falkenslab/falkenslab-plugins
157
+ claude plugin install falkenslab-dev@falkenslab-plugins
158
+ claude plugin install falkenslab-style@falkenslab-plugins
159
+ ```
160
+
161
+ <details>
162
+ <summary>What each plugin brings, and what stays in this repository</summary>
163
+
164
+ - 🔧 **falkenslab-dev**: `commit`, `verify`, `update-docs`, `release`, `sync-issues`, `upgrade-deps` and `add-tool`.
165
+ - 🎨 **falkenslab-style**: `falkenslab-docs`, `falkenslab-site-style`, `falkenslab-terminal-screenshots` and `markdown-writing`.
166
+
167
+ Inside Claude Code, the same with `/plugin marketplace add falkenslab/falkenslab-plugins` and `/plugin install falkenslab-dev@falkenslab-plugins`; `/plugin marketplace update falkenslab-plugins` brings their latest version. This repository keeps only the skills that are agent-kit's own, in `.claude/skills/` (`add-export`, the MiniSpec ones and `upgrade-sdk`), and what its release adds to the general one is in [`CLAUDE.md`](./CLAUDE.md#releasing).
168
+
169
+ </details>
170
+
171
+ <div align="center">
172
+
173
+ Made with 💖 by Falken's Lab Team
174
+
175
+ </div>
@@ -71,6 +71,14 @@ export interface ChatSettings {
71
71
  * The link is shown either way, on a line of its own, for another computer.
72
72
  */
73
73
  openBrowser?: boolean | ((url: string) => Promise<boolean>);
74
+ /**
75
+ * Claude Code's own commands in the `/` menu and the state's `commands` (#87): none by default,
76
+ * since they're for whoever develops with Claude Code (`/batch`, `/agents`, `/mcp`…), not for the
77
+ * agent's person; `"all"`, or the ones named (`["compact", "context"]`). The agent's own, its
78
+ * plugins', its extensions', the project's, the kit's and the view's are always there, and a
79
+ * command typed by hand still reaches the SDK.
80
+ */
81
+ cliCommands?: "all" | readonly string[];
74
82
  }
75
83
  /** One tool call in the transcript. */
76
84
  export interface TranscriptCall {
@@ -183,7 +183,10 @@ export async function createChatController(options, settings = {}) {
183
183
  { name: "extensions", description: t().commandExtensions, argumentHint: "[enable|disable|config|search|install|update|remove|reload]" },
184
184
  ];
185
185
  const details = new Map();
186
- for (const command of [...(commands ?? []).map(({ name, description, argumentHint }) => ({ name, description: description ?? "", argumentHint: argumentHint ?? "" })), ...local])
186
+ // Claude Code's own (builtin) only when the agent asks for them (#87).
187
+ const cli = settings.cliCommands;
188
+ const offered = (commands ?? []).filter((command) => !command.builtin || cli === "all" || (Array.isArray(cli) && cli.includes(command.name)));
189
+ for (const command of [...offered.map(({ name, description, argumentHint }) => ({ name, description: description ?? "", argumentHint: argumentHint ?? "" })), ...local])
187
190
  details.set(command.name, command);
188
191
  for (const name of exits)
189
192
  if (!details.has(name))
@@ -154,8 +154,11 @@ export interface AgentSpec<TConfig extends BaseSessionConfig> {
154
154
  * Whether the kit tells the agent (and each subagent) to reply in the resolved language
155
155
  * (`config.language`, `--language`, the system's), following the human if they write in
156
156
  * another one. On by default; `false` leaves the reply language to the agent's own prompt.
157
+ * When the language isn't English, the kit also says it again after each of the main agent's
158
+ * tool calls and with each message of the person (#85), since the narration between tool calls
159
+ * drifted to English after an English result; `"prompt-only"` keeps only the prompt's line.
157
160
  */
158
- replyInLanguage?: boolean;
161
+ replyInLanguage?: boolean | "prompt-only";
159
162
  /**
160
163
  * Which filesystem settings the session loads (the SDK's `settingSources`): "project" is
161
164
  * the project's `.claude/` (settings, skills, commands) and its CLAUDE.md files, "local"
@@ -1,25 +1,57 @@
1
- /** What `resolveClaudeAuth()` and `ensureClaudeAuth()` accept besides the environment. */
2
- export interface ClaudeAuthConfig {
3
- /** A previously-resolved token the caller already has (from wherever it stores one, if
4
- * anywhere) — this module owns no persistence of its own, unlike an earlier version
5
- * that read/wrote `~/.<appName>/config.json` itself (see git history). Sourcing this
6
- * value across runs, if a concrete agent wants that at all, is entirely its own concern. */
7
- claudeCodeOAuthToken?: string;
1
+ /**
2
+ * The Claude Code binary the Agent SDK ships (`@anthropic-ai/claude-agent-sdk-<platform>-<arch>`),
3
+ * unmodified: the copy unpacked next to the archive when the agent runs packaged, or else the
4
+ * one resolved from `node_modules` as the SDK resolves it. `undefined` when it isn't installed.
5
+ * `resolve` and the platform are replaceable for tests.
6
+ */
7
+ export declare function claudeExecutable(resolve?: (request: string) => string, platform?: NodeJS.Platform, arch?: string): string | undefined;
8
+ /** What `claudeSignedIn()` and `startClaudeSignIn()` accept. */
9
+ export interface ClaudeAuthOptions {
10
+ /** The binary to run instead of the SDK's own (`claudeExecutable()`); a `.js`/`.mjs` file runs with Node, as the SDK runs one. */
11
+ executable?: string;
8
12
  }
13
+ /** The binary and its arguments as a process to spawn: a JavaScript file runs with this Node. */
14
+ export declare function claudeCommand(executable: string, args: string[]): {
15
+ file: string;
16
+ args: string[];
17
+ };
9
18
  /**
10
- * Pure lookup, no I/O and no console output of any kind — safe to call from a
11
- * headless/non-interactive consumer (a server, an Electron main process) as much as from a
12
- * terminal one.
19
+ * Whether the agent can reach Claude: true when the person's environment has `ANTHROPIC_API_KEY`
20
+ * or `CLAUDE_CODE_OAUTH_TOKEN` (their own setting); otherwise what the Claude Code binary says
21
+ * (`claude auth status --json`, its `loggedIn`). Never reads the credentials file, and prints
22
+ * nothing: safe from a server or an Electron main process. False when there is no binary.
23
+ */
24
+ export declare function claudeSignedIn(options?: ClaudeAuthOptions): Promise<boolean>;
25
+ /** A sign-in in progress (`startClaudeSignIn()`): Claude Code's own `auth login`, which keeps the credentials itself. */
26
+ export interface ClaudeSignIn {
27
+ /** Anthropic's sign-in page, to show as a link in case the browser didn't open; `undefined` if the binary ended without printing one. */
28
+ url: Promise<string | undefined>;
29
+ /** The code Anthropic's page shows after signing in, when it shows one: handed to the binary, which waits for it. */
30
+ sendCode(code: string): void;
31
+ /** Once the binary has ended: whether the person is signed in (`claudeSignedIn()`). */
32
+ done: Promise<boolean>;
33
+ /** Stops the sign-in; `done` then resolves with whether the person is signed in anyway. */
34
+ cancel(): void;
35
+ }
36
+ /**
37
+ * Signs the person in to their Claude account through Anthropic's own flow, for a host without a
38
+ * terminal (a web page, a desktop app): runs `claude auth login` (`console: true` for an
39
+ * Anthropic Console account, billed by API usage) with plain pipes. The binary opens the browser
40
+ * itself; the host shows `url` as a link in case it didn't, and a box for the code Anthropic's
41
+ * page shows (`sendCode`). The binary keeps the credentials: the kit never sees a token. Throws
42
+ * when the binary isn't installed.
13
43
  *
14
- * Checks, in order: `ANTHROPIC_API_KEY` (a complete authentication path on its own — API
15
- * billing instead of subscription, so nothing else is checked when it's set),
16
- * `CLAUDE_CODE_OAUTH_TOKEN`, then `config.claudeCodeOAuthToken` if the caller passed one.
17
- * Returns `true` and (for the `config` case) sets `CLAUDE_CODE_OAUTH_TOKEN` on the process
18
- * as a side effect once a token is found — the SDK's own subprocess reads that env var
19
- * directly, never anything this kit passes it explicitly; `false` when none of the three
20
- * has one. Getting a token in that case (e.g. by walking the user through
21
- * `claude setup-token`) is a terminal-UX concern, not this function's — see
22
- * `ensureClaudeAuth()` in tui/claudeAuth.ts, which calls this first and only falls back to
23
- * that interactive flow when it returns `false`.
44
+ * Confirmed empirically (Claude Code 2.1.310): without a TTY, `auth login` prints "If the browser
45
+ * didn't open, visit: <url>" (the URL may come wrapped in OSC 8 hyperlink escapes) and then waits
46
+ * at "Paste code here if prompted >".
47
+ */
48
+ export declare function startClaudeSignIn(options?: ClaudeAuthOptions & {
49
+ console?: boolean;
50
+ }): ClaudeSignIn;
51
+ /**
52
+ * The sign-in URL in what `claude auth login` printed so far: an OSC 8 hyperlink's target, or a
53
+ * URL in the text with its escapes removed, Anthropic's authorize page (`/oauth/authorize`)
54
+ * first. A URL in the text counts only once whitespace follows it (the rest may still be on its
55
+ * way), unless `complete` says the output is all there is.
24
56
  */
25
- export declare function resolveClaudeAuth(config?: ClaudeAuthConfig): boolean;
57
+ export declare function signInUrl(output: string, complete?: boolean): string | undefined;
@@ -1,27 +1,140 @@
1
+ import { execFile, spawn } from "node:child_process";
2
+ import { existsSync } from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import { claudeBinaryRequests, unpackedClaudeExecutable } from "./packaged.js";
5
+ /*
6
+ * Signing in to Claude without ever touching a credential (ADR-009, #90). Anthropic's terms
7
+ * (https://code.claude.com/docs/en/legal-and-compliance, "Authentication and credential use")
8
+ * say an Agent SDK developer may not collect, store or intermediate Claude.ai credentials or
9
+ * session tokens: a Claude account signs in through Anthropic's own flow, in the unmodified
10
+ * Claude Code binary. The SDK ships that binary, so the kit runs its `auth status` and
11
+ * `auth login` and nothing else: the binary opens Anthropic's page and keeps the credentials
12
+ * itself (`~/.claude/.credentials.json`, the Keychain on macOS), where the SDK's sessions find
13
+ * them. The kit never reads, returns or stores a token. An API key (`ANTHROPIC_API_KEY`) is
14
+ * allowed, and so is a person's own `CLAUDE_CODE_OAUTH_TOKEN`: both are their setting, not
15
+ * something the kit collects.
16
+ */
1
17
  /**
2
- * Pure lookup, no I/O and no console output of any kind — safe to call from a
3
- * headless/non-interactive consumer (a server, an Electron main process) as much as from a
4
- * terminal one.
5
- *
6
- * Checks, in order: `ANTHROPIC_API_KEY` (a complete authentication path on its own — API
7
- * billing instead of subscription, so nothing else is checked when it's set),
8
- * `CLAUDE_CODE_OAUTH_TOKEN`, then `config.claudeCodeOAuthToken` if the caller passed one.
9
- * Returns `true` and (for the `config` case) sets `CLAUDE_CODE_OAUTH_TOKEN` on the process
10
- * as a side effect once a token is found — the SDK's own subprocess reads that env var
11
- * directly, never anything this kit passes it explicitly; `false` when none of the three
12
- * has one. Getting a token in that case (e.g. by walking the user through
13
- * `claude setup-token`) is a terminal-UX concern, not this function's — see
14
- * `ensureClaudeAuth()` in tui/claudeAuth.ts, which calls this first and only falls back to
15
- * that interactive flow when it returns `false`.
18
+ * The Claude Code binary the Agent SDK ships (`@anthropic-ai/claude-agent-sdk-<platform>-<arch>`),
19
+ * unmodified: the copy unpacked next to the archive when the agent runs packaged, or else the
20
+ * one resolved from `node_modules` as the SDK resolves it. `undefined` when it isn't installed.
21
+ * `resolve` and the platform are replaceable for tests.
16
22
  */
17
- export function resolveClaudeAuth(config = {}) {
18
- if (process.env.ANTHROPIC_API_KEY)
19
- return true;
20
- if (process.env.CLAUDE_CODE_OAUTH_TOKEN)
21
- return true;
22
- if (config.claudeCodeOAuthToken) {
23
- process.env.CLAUDE_CODE_OAUTH_TOKEN = config.claudeCodeOAuthToken;
23
+ export function claudeExecutable(resolve = createRequire(import.meta.url).resolve, platform = process.platform, arch = process.arch) {
24
+ const unpacked = unpackedClaudeExecutable(resolve, platform, arch);
25
+ if (unpacked)
26
+ return unpacked;
27
+ for (const request of claudeBinaryRequests(platform, arch)) {
28
+ try {
29
+ const file = resolve(request);
30
+ if (existsSync(file))
31
+ return file;
32
+ }
33
+ catch {
34
+ // That package isn't installed: the next one.
35
+ }
36
+ }
37
+ return undefined;
38
+ }
39
+ /** The binary and its arguments as a process to spawn: a JavaScript file runs with this Node. */
40
+ export function claudeCommand(executable, args) {
41
+ return /\.(c|m)?js$/i.test(executable) ? { file: process.execPath, args: [executable, ...args] } : { file: executable, args };
42
+ }
43
+ /**
44
+ * Whether the agent can reach Claude: true when the person's environment has `ANTHROPIC_API_KEY`
45
+ * or `CLAUDE_CODE_OAUTH_TOKEN` (their own setting); otherwise what the Claude Code binary says
46
+ * (`claude auth status --json`, its `loggedIn`). Never reads the credentials file, and prints
47
+ * nothing: safe from a server or an Electron main process. False when there is no binary.
48
+ */
49
+ export async function claudeSignedIn(options = {}) {
50
+ if (process.env.ANTHROPIC_API_KEY || process.env.CLAUDE_CODE_OAUTH_TOKEN)
24
51
  return true;
52
+ const executable = options.executable ?? claudeExecutable();
53
+ if (!executable)
54
+ return false;
55
+ const command = claudeCommand(executable, ["auth", "status", "--json"]);
56
+ // Exit code 1 when signed out, with the same JSON (confirmed empirically): read it either way.
57
+ const output = await new Promise((resolve) => {
58
+ execFile(command.file, command.args, { timeout: 30_000, windowsHide: true }, (_error, stdout) => resolve(String(stdout ?? "")));
59
+ });
60
+ try {
61
+ return JSON.parse(output).loggedIn === true;
25
62
  }
26
- return false;
63
+ catch {
64
+ return false;
65
+ }
66
+ }
67
+ /**
68
+ * Signs the person in to their Claude account through Anthropic's own flow, for a host without a
69
+ * terminal (a web page, a desktop app): runs `claude auth login` (`console: true` for an
70
+ * Anthropic Console account, billed by API usage) with plain pipes. The binary opens the browser
71
+ * itself; the host shows `url` as a link in case it didn't, and a box for the code Anthropic's
72
+ * page shows (`sendCode`). The binary keeps the credentials: the kit never sees a token. Throws
73
+ * when the binary isn't installed.
74
+ *
75
+ * Confirmed empirically (Claude Code 2.1.310): without a TTY, `auth login` prints "If the browser
76
+ * didn't open, visit: <url>" (the URL may come wrapped in OSC 8 hyperlink escapes) and then waits
77
+ * at "Paste code here if prompted >".
78
+ */
79
+ export function startClaudeSignIn(options = {}) {
80
+ const executable = options.executable ?? claudeExecutable();
81
+ if (!executable)
82
+ throw new Error("Claude Code's binary, which the Agent SDK ships (@anthropic-ai/claude-agent-sdk-<platform>-<arch>), isn't installed.");
83
+ const command = claudeCommand(executable, ["auth", "login", ...(options.console ? ["--console"] : [])]);
84
+ const child = spawn(command.file, command.args, { stdio: ["pipe", "pipe", "pipe"], windowsHide: true });
85
+ let output = "";
86
+ let resolveUrl;
87
+ const url = new Promise((resolve) => (resolveUrl = resolve));
88
+ const read = (chunk) => {
89
+ output += chunk.toString("utf8");
90
+ // Anthropic's page as soon as it's all there; any other URL only once the binary has ended.
91
+ const found = signInUrl(output);
92
+ if (found?.includes("/oauth/authorize"))
93
+ resolveUrl(found);
94
+ };
95
+ child.stdout?.on("data", read);
96
+ child.stderr?.on("data", read);
97
+ // A write after the binary ended fails on the stream: nothing to tell then.
98
+ child.stdin?.on("error", () => { });
99
+ const ended = new Promise((resolve) => {
100
+ child.on("error", () => resolve());
101
+ child.on("close", () => resolve());
102
+ });
103
+ const done = ended.then(() => {
104
+ resolveUrl(signInUrl(output, true));
105
+ return claudeSignedIn(options);
106
+ });
107
+ return {
108
+ url,
109
+ sendCode(code) {
110
+ if (child.stdin?.writable)
111
+ child.stdin.write(`${code.trim()}\n`);
112
+ },
113
+ done,
114
+ cancel() {
115
+ if (child.exitCode === null && child.signalCode === null)
116
+ child.kill();
117
+ },
118
+ };
119
+ }
120
+ // An OSC sequence (a hyperlink's `ESC ] 8 ; ; URL ESC \`, a title), ended by BEL or ST.
121
+ // eslint-disable-next-line no-control-regex -- ESC and BEL delimit terminal escapes, on purpose
122
+ const OSC = /\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
123
+ // A CSI sequence (colors, cursor moves).
124
+ // eslint-disable-next-line no-control-regex -- ESC starts the sequence
125
+ const CSI = /\x1b\[[0-9;?]*[ -/]*[@-~]/g;
126
+ // eslint-disable-next-line no-control-regex -- an OSC 8 hyperlink's target, between ESC/BEL delimiters
127
+ const HYPERLINK_TARGET = /\x1b\]8;[^;\x07\x1b]*;(https:\/\/[^\x07\x1b]+)(?:\x07|\x1b\\)/g;
128
+ /**
129
+ * The sign-in URL in what `claude auth login` printed so far: an OSC 8 hyperlink's target, or a
130
+ * URL in the text with its escapes removed, Anthropic's authorize page (`/oauth/authorize`)
131
+ * first. A URL in the text counts only once whitespace follows it (the rest may still be on its
132
+ * way), unless `complete` says the output is all there is.
133
+ */
134
+ export function signInUrl(output, complete = false) {
135
+ const targets = [...output.matchAll(HYPERLINK_TARGET)].map((match) => match[1]);
136
+ const text = output.replace(OSC, " ").replace(CSI, "");
137
+ const inText = [...text.matchAll(complete ? /https:\/\/\S+/g : /https:\/\/\S+(?=\s)/g)].map((match) => match[0]);
138
+ const urls = [...targets, ...inText];
139
+ return urls.find((url) => url.includes("/oauth/authorize")) ?? urls[0];
27
140
  }