@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 +175 -111
- package/dist/chat/chatController.d.ts +8 -0
- package/dist/chat/chatController.js +4 -1
- package/dist/core/agentSpec.d.ts +4 -1
- package/dist/core/claudeAuth.d.ts +53 -21
- package/dist/core/claudeAuth.js +135 -22
- package/dist/core/externalExtensions.js +21 -12
- package/dist/core/gitClone.d.ts +13 -0
- package/dist/core/gitClone.js +117 -0
- package/dist/core/hooks/languageReminder.d.ts +16 -0
- package/dist/core/hooks/languageReminder.js +24 -0
- package/dist/core/hooks/stepGate.d.ts +6 -1
- package/dist/core/hooks/stepGate.js +11 -2
- package/dist/core/hooks/transcriptLogger.d.ts +2 -2
- package/dist/core/hooks/transcriptLogger.js +2 -2
- package/dist/core/marketplaces.d.ts +9 -0
- package/dist/core/marketplaces.js +3 -15
- package/dist/core/messages/de.js +9 -7
- package/dist/core/messages/en.d.ts +7 -5
- package/dist/core/messages/en.js +9 -7
- package/dist/core/messages/es.js +9 -7
- package/dist/core/messages/fr.js +9 -7
- package/dist/core/packaged.d.ts +6 -0
- package/dist/core/packaged.js +18 -3
- package/dist/core/session.js +8 -3
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/dist/tui/chatTui.d.ts +2 -0
- package/dist/tui/chatTui.js +1 -0
- package/dist/tui/claudeAuth.d.ts +12 -17
- package/dist/tui/claudeAuth.js +37 -66
- package/dist/tui/ink/runChatInk.js +1 -0
- package/package.json +2 -1
package/README.md
CHANGED
|
@@ -1,111 +1,175 @@
|
|
|
1
|
-
<
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
[](https://www.npmjs.com/package/@falkenslab/agent-kit)
|
|
11
|
+

|
|
12
|
+

|
|
13
|
+

|
|
14
|
+
[](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
|
-
|
|
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))
|
package/dist/core/agentSpec.d.ts
CHANGED
|
@@ -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
|
-
/**
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
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
|
-
*
|
|
11
|
-
*
|
|
12
|
-
*
|
|
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
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
* `
|
|
23
|
-
*
|
|
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
|
|
57
|
+
export declare function signInUrl(output: string, complete?: boolean): string | undefined;
|
package/dist/core/claudeAuth.js
CHANGED
|
@@ -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
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
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
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
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
|
-
|
|
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
|
}
|