@crowgentai/emo-cli 0.0.0-stage → 0.1.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.
@@ -0,0 +1,228 @@
1
+ import { Agent } from "@crowgentai/emo-agent";
2
+ import { Session } from "@crowgentai/emo-session";
3
+ import { Container, Input, ProcessTerminal, Text, Tui, theme as tuiTheme, } from "@crowgentai/emo-tui";
4
+ import { truncate } from "./theme.js";
5
+ export class AgentApp {
6
+ settings;
7
+ sessionId;
8
+ lines = [];
9
+ input = new Input({ prompt: "❯ ", placeholder: "type a task, /help for commands" });
10
+ status = new Text("");
11
+ transcript = new Text("");
12
+ container;
13
+ streaming = "";
14
+ busy = false;
15
+ exited = false;
16
+ pendingApproval = null;
17
+ onExit = () => { };
18
+ driver = null;
19
+ interruptDriver = () => { };
20
+ renderRequested = () => { };
21
+ constructor(settings, sessionId) {
22
+ this.settings = settings;
23
+ this.sessionId = sessionId;
24
+ this.container = new Container([this.transcript, this.status, this.input]);
25
+ this.input.onSubmit = (value) => {
26
+ void this.submit(value);
27
+ };
28
+ this.lines.push(`emo — session ${this.sessionId} (${settings.provider}/${settings.model}, mode ${settings.mode})`);
29
+ this.lines.push(tuiTheme.dim("type a task, /help for commands, /exit to quit"));
30
+ this.setTranscript();
31
+ this.setStatus("ready");
32
+ }
33
+ async runTask(task) {
34
+ await this.submit(task);
35
+ }
36
+ setDriver(driver) {
37
+ this.driver = driver;
38
+ this.interruptDriver = () => driver.interrupt();
39
+ }
40
+ setExitHandler(handler) {
41
+ this.onExit = handler;
42
+ }
43
+ setRenderHandler(handler) {
44
+ this.renderRequested = handler;
45
+ }
46
+ isExited() {
47
+ return this.exited;
48
+ }
49
+ isBusy() {
50
+ return this.busy;
51
+ }
52
+ getLines() {
53
+ return [...this.lines];
54
+ }
55
+ observer() {
56
+ return {
57
+ onStep: (index, max) => this.append(`${tuiTheme.dim(`[step ${index}/${max}]`)}`),
58
+ onTextDelta: (text) => {
59
+ this.streaming += text;
60
+ this.setTranscript();
61
+ this.renderRequested();
62
+ },
63
+ onAssistant: (text) => {
64
+ this.streaming = "";
65
+ if (text.trim().length > 0)
66
+ this.append(text);
67
+ this.setTranscript();
68
+ },
69
+ onToolCall: (name, args) => {
70
+ this.streaming = "";
71
+ this.append(`${tuiTheme.tool(`→ ${name}`)} ${tuiTheme.dim(truncate(JSON.stringify(args) ?? "{}", 200))}`);
72
+ },
73
+ onToolResult: (_name, content) => {
74
+ const head = content.replace(/\s+$/, "").split("\n").slice(0, 5).join("\n");
75
+ if (head.trim().length > 0)
76
+ this.append(tuiTheme.dim(head));
77
+ },
78
+ onNotice: (text) => this.append(tuiTheme.dim(text)),
79
+ onStepLimit: () => this.append(tuiTheme.warning("step limit reached")),
80
+ onError: (message) => this.append(tuiTheme.error(`error: ${message}`)),
81
+ onUsage: (usage) => {
82
+ const parts = [];
83
+ if (usage.inputTokens !== undefined)
84
+ parts.push(`${usage.inputTokens} in`);
85
+ if (usage.outputTokens !== undefined)
86
+ parts.push(`${usage.outputTokens} out`);
87
+ if (parts.length > 0)
88
+ this.append(tuiTheme.dim(`tokens: ${parts.join(", ")}`));
89
+ },
90
+ requestApproval: (name, args, permission) => {
91
+ this.append(`${tuiTheme.warning(`approve ${name}`)} ${tuiTheme.dim(truncate(JSON.stringify(args) ?? "{}", 200))} (${permission}) [y/N]`);
92
+ return new Promise((resolve) => {
93
+ this.pendingApproval = { resolve };
94
+ });
95
+ },
96
+ };
97
+ }
98
+ render(width) {
99
+ return this.container.render(width);
100
+ }
101
+ handleInput(data) {
102
+ if (data.includes("")) {
103
+ if (this.busy) {
104
+ this.interruptDriver();
105
+ this.append(tuiTheme.dim("interrupted"));
106
+ }
107
+ else {
108
+ this.exit();
109
+ }
110
+ return;
111
+ }
112
+ if (data.includes("") && this.input.getValue().length === 0 && !this.busy) {
113
+ this.exit();
114
+ return;
115
+ }
116
+ this.input.handleInput(data);
117
+ }
118
+ invalidate() {
119
+ this.container.invalidate();
120
+ }
121
+ setStatus(text) {
122
+ this.status.setText(tuiTheme.dim(text));
123
+ }
124
+ setTranscript() {
125
+ const body = this.streaming.length > 0 ? [...this.lines, this.streaming] : this.lines;
126
+ this.transcript.setText(body.slice(-200).join("\n"));
127
+ }
128
+ append(line) {
129
+ this.lines.push(line);
130
+ this.setTranscript();
131
+ this.renderRequested();
132
+ }
133
+ exit() {
134
+ if (this.exited)
135
+ return;
136
+ this.exited = true;
137
+ this.onExit();
138
+ }
139
+ async submit(raw) {
140
+ const value = raw.trim();
141
+ this.input.setValue("");
142
+ if (this.pendingApproval) {
143
+ const pending = this.pendingApproval;
144
+ this.pendingApproval = null;
145
+ const approved = value.toLowerCase() === "y" || value.toLowerCase() === "yes";
146
+ this.append(approved ? tuiTheme.success("approved") : tuiTheme.dim("denied"));
147
+ pending.resolve(approved);
148
+ return;
149
+ }
150
+ if (value.length === 0)
151
+ return;
152
+ if (value === "/exit" || value === "/quit") {
153
+ this.exit();
154
+ return;
155
+ }
156
+ if (value === "/help") {
157
+ this.append("/exit — quit · /clear — clear the transcript · /mode plan|build — switch permission mode · Ctrl+C — interrupt, or quit when idle");
158
+ return;
159
+ }
160
+ if (value === "/clear") {
161
+ this.lines.length = 0;
162
+ this.streaming = "";
163
+ this.setTranscript();
164
+ this.renderRequested();
165
+ return;
166
+ }
167
+ const modeMatch = /^\/mode\s+(plan|build)\s*$/.exec(value);
168
+ if (modeMatch) {
169
+ const mode = modeMatch[1];
170
+ this.settings.mode = mode;
171
+ this.driver?.setMode(mode);
172
+ this.append(`mode: ${mode}`);
173
+ return;
174
+ }
175
+ if (value.startsWith("/")) {
176
+ this.append(tuiTheme.error(`unknown command: ${value} (try /help)`));
177
+ return;
178
+ }
179
+ if (this.busy || !this.driver)
180
+ return;
181
+ this.append(`${tuiTheme.user("you")} ${value}`);
182
+ this.busy = true;
183
+ this.setStatus("working…");
184
+ this.renderRequested();
185
+ try {
186
+ await this.driver.send(value);
187
+ }
188
+ finally {
189
+ this.busy = false;
190
+ this.setStatus("ready");
191
+ this.renderRequested();
192
+ }
193
+ }
194
+ }
195
+ export async function startTuiApp(settings, options = {}) {
196
+ const session = await Session.create(settings.stateDir, {
197
+ cwd: settings.cwd,
198
+ provider: settings.provider,
199
+ model: settings.model,
200
+ title: options.initialTask ?? "interactive",
201
+ });
202
+ const app = new AgentApp(settings, session.id);
203
+ const terminal = options.terminal ?? new ProcessTerminal();
204
+ const tui = new Tui({ terminal, root: app, altScreen: true });
205
+ app.setRenderHandler(() => tui.requestRender());
206
+ let resolveExit = () => { };
207
+ const exited = new Promise((resolve) => {
208
+ resolveExit = resolve;
209
+ });
210
+ app.setExitHandler(() => {
211
+ tui.stop();
212
+ resolveExit();
213
+ });
214
+ const agent = await Agent.create({ settings, session, observer: app.observer() });
215
+ app.setDriver({
216
+ send: (task) => agent.send(task),
217
+ interrupt: () => agent.interrupt(),
218
+ close: () => agent.close(),
219
+ setMode: (mode) => agent.setMode(mode),
220
+ });
221
+ tui.start();
222
+ if (options.initialTask) {
223
+ void app.runTask(options.initialTask);
224
+ }
225
+ await exited;
226
+ await agent.close();
227
+ }
228
+ //# sourceMappingURL=tui-app.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tui-app.js","sourceRoot":"","sources":["../src/tui-app.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,KAAK,EAAE,MAAM,uBAAuB,CAAC;AAE9C,OAAO,EAAE,OAAO,EAAE,MAAM,yBAAyB,CAAC;AAClD,OAAO,EACL,SAAS,EACT,KAAK,EACL,eAAe,EACf,IAAI,EACJ,GAAG,EACH,KAAK,IAAI,QAAQ,GAGlB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EAAE,QAAQ,EAAE,MAAM,YAAY,CAAC;AAsBtC,MAAM,OAAO,QAAQ;IAeU;IAAqC;IAdjD,KAAK,GAAa,EAAE,CAAC;IACrB,KAAK,GAAG,IAAI,KAAK,CAAC,EAAE,MAAM,EAAE,IAAI,EAAE,WAAW,EAAE,iCAA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CAAC,OAAO,CAAC,WAAW,CAAC,CAAC;IACxC,CAAC;IACD,MAAM,MAAM,CAAC;IACb,MAAM,KAAK,CAAC,KAAK,EAAE,CAAC;AACtB,CAAC"}
package/docs/api.md ADDED
@@ -0,0 +1,145 @@
1
+ # @crowgentai/emo-cli reference
2
+
3
+ ## Modes
4
+
5
+ | Mode | How to run | Behaviour |
6
+ | --- | --- | --- |
7
+ | Interactive TUI | `emo` with no task, in a terminal, or `emo tui [task]` | Full-screen app built on `@crowgentai/emo-tui`: transcript, input, `/help`, `/mode plan\|build`, `/clear`, `/exit`, Ctrl+C interrupts |
8
+ | Print (one-shot) | `emo <task>`, `emo run <task>`, `emo --print <task>` | One task in a new durable session, streamed to stdout |
9
+ | JSON | `emo --output json <task>` (or `--mode json`) | One JSON object per line: `session`, `step`, `text`, `assistant`, `tool_call`, `tool_result`, `notice`, `error`, `usage`, `approval_request` |
10
+ | RPC | `emo --output rpc` (or `--mode rpc`) | JSONL over stdin/stdout: `ping`, `send`, `status`, `interrupt`, `close`. Each request gets `{id, ok, result?|error?}`; agent events arrive as `{type:"event", event}` lines |
11
+
12
+ In JSON and RPC mode approvals are always denied and reported as an
13
+ `approval_request` event, so automation never blocks on stdin. One-shot
14
+ invocations (print, JSON, and the `tool`/`fork`/`clone`/`export` commands) exit
15
+ the process explicitly once their work is done, so idle network sockets from a
16
+ dead MCP server cannot keep the CLI hanging after the result is printed.
17
+
18
+ ## Commands
19
+
20
+ | Command | Description |
21
+ | --- | --- |
22
+ | `emo` | interactive TUI when attached to a terminal, otherwise usage |
23
+ | `emo tui [task]` | start the interactive TUI, optionally with a first task |
24
+ | `emo <task>` | run one task in a new durable session |
25
+ | `emo run <task>` | same as above |
26
+ | `emo resume <id> <task>` | append one task to an existing session |
27
+ | `emo fork <id> [n]` | fork a session at user message n (default: last) |
28
+ | `emo clone <id>` | copy a session into a new one |
29
+ | `emo export <id> [--format json\|jsonl] [--out file]` | export a session journal |
30
+ | `emo sessions` | list sessions (id, updated, status, provider/model, title) |
31
+ | `emo login <provider> [--api-key <key>]` | save a provider key to `auth.json` (mode 0600) |
32
+ | `emo logout <provider>` | remove a stored credential |
33
+ | `emo model` | list providers with auth status, models and the current selection |
34
+ | `emo install <npm:\|git:\|./path>` | install a package of extensions/skills/prompts |
35
+ | `emo packages` | list installed packages |
36
+ | `emo remove <spec>` | remove an installed package |
37
+ | `emo mcp list` | list MCP servers |
38
+ | `emo mcp add <name> --url <url>` | add an HTTP MCP server |
39
+ | `emo mcp add <name> -- <cmd> [args]` | add a stdio MCP server |
40
+ | `emo mcp remove <name>` | remove an MCP server |
41
+ | `emo tools` | list registered tools with permission and description |
42
+ | `emo tool <name> [json]` | run one tool directly, respecting plan mode and permissions |
43
+ | `emo providers` | list provider ids, types and models |
44
+ | `emo prompts` | list prompt templates from `.emo/prompts` and the agent directory |
45
+ | `emo prompt <name> [args]` | print an expanded prompt template |
46
+ | `emo skills` | list skills with their source and warnings |
47
+ | `emo skill <name>` | print a skill's instructions |
48
+ | `emo init` | scaffold `.emo/settings.json`, a skill and a prompt template |
49
+ | `emo /<prompt> [args]` | expand a prompt template and run it as the task |
50
+ | `emo memory list [--limit N]` | recent memories |
51
+ | `emo memory search <query>` | ranked memory search |
52
+ | `emo memory add <text>` | save a memory |
53
+ | `emo memory forget <id>` | delete a memory by id or suffix |
54
+ | `emo help` / `emo version` | usage / version |
55
+
56
+ Running `emo` with no arguments starts the TUI in a terminal and prints usage
57
+ otherwise.
58
+
59
+ ## Flags
60
+
61
+ ```
62
+ --cwd <path> working directory (default: cwd)
63
+ --provider <id> any provider id from the catalog, settings.json or models.json
64
+ --model <name> model id (default: the provider's defaultModel)
65
+ --mode <plan|build> initial permission mode (json|rpc here mean output mode, see above)
66
+ --print one-shot run, streamed to stdout (no TUI)
67
+ --output <print|json|rpc> output mode (default: print)
68
+ --tui start the interactive TUI
69
+ --base-url <url> override the provider base URL
70
+ --api-key <key> override the provider API key
71
+ --max-steps <n> loop step budget (default 40)
72
+ --agent-dir <path> agent directory (default $EMO_AGENT_DIR or ~/.emo/agent)
73
+ --session-dir <path> session directory (default $EMO_SESSION_DIR or <agent-dir>/state/<project>)
74
+ --offline disable network refreshes (also $EMO_OFFLINE=1)
75
+ ```
76
+
77
+ ## Settings and environment
78
+
79
+ Settings stack home → agent → project (`settings.json` in each), then `mcp.json` and
80
+ `models.json` from the agent and project directories. Keys resolve in order: CLI
81
+ `--api-key`, `auth.json`, `apiKey` in `settings.json`/`models.json`, then the environment
82
+ (`<PROVIDER>_API_KEY`, e.g. `ANTHROPIC_API_KEY`, `GROQ_API_KEY`, `DEEPSEEK_API_KEY`).
83
+
84
+ 30 providers ship in the catalog (see `@crowgentai/emo-ai`): OpenAI, Anthropic, Google,
85
+ DeepSeek, Groq, Cerebras, Mistral, xAI, OpenRouter, Together, Fireworks, Baseten, Moonshot,
86
+ MiniMax, Kimi, Qwen, Hugging Face, NVIDIA, Vercel AI Gateway, ZAI, Meta, Cloudflare AI
87
+ Gateway, GitHub Copilot, Ollama, Azure OpenAI, Amazon Bedrock, Google Vertex AI and
88
+ OpenAI Codex (OAuth-only). Add more in `models.json` with `baseUrl` + `api`, or with an
89
+ extension's `registerProvider()`.
90
+
91
+ ## RPC
92
+
93
+ Send one JSON object per line on stdin. `send` creates a session (or resumes
94
+ one with `params.sessionId`) and runs the task; events stream back as
95
+ `{"type":"event","event":{...}}` lines while it runs.
96
+
97
+ ```json
98
+ {"id": 1, "method": "ping"}
99
+ {"id": 2, "method": "send", "params": {"task": "list the files"}}
100
+ {"id": 3, "method": "status"}
101
+ {"id": 4, "method": "interrupt"}
102
+ {"id": 5, "method": "close"}
103
+ ```
104
+
105
+ ## Approvals
106
+
107
+ Tools whose policy resolves to `ask` prompt on stdin:
108
+
109
+ ```
110
+ approve write_file {"path":"a.txt"} (write) [y/N]
111
+ ```
112
+
113
+ Without a TTY the tool is denied and the reason is printed, so `emo` is safe to run from
114
+ CI and scripts.
115
+
116
+ ## State layout
117
+
118
+ ```
119
+ ~/.emo/agent/
120
+ ├── settings.json # global config
121
+ ├── AGENTS.md # instructions for every project
122
+ ├── SYSTEM.md # replaces the built-in prompt
123
+ ├── APPEND_SYSTEM.md # appended to the prompt
124
+ ├── mcp.json # MCP servers for every project
125
+ ├── skills/ # global skills
126
+ ├── prompts/ # global prompt templates
127
+ ├── plugins/ # global extensions
128
+ └── state/<project>-<hash>/
129
+ ├── sessions/<id>/{meta.json,journal.ndjson}
130
+ └── memory.json
131
+ ```
132
+
133
+ Per-project resources live in `<project>/.emo/`: `settings.json`, `skills/`, `prompts/`,
134
+ `plugins/`, `mcp.json`, `SYSTEM.md`, `APPEND_SYSTEM.md`, `rules.md` and the project's
135
+ `AGENTS.md` at the repository root. See [configuration.md](configuration.md).
136
+
137
+ ## Embedding
138
+
139
+ ```ts
140
+ import { run, theme, truncate, wrap } from "@crowgentai/emo-cli";
141
+
142
+ await run(["tools"]); // same as `emo tools`
143
+ truncate(`${theme.red}very long text`, 8); // ANSI-aware ellipsis-free cut
144
+ wrap("some long paragraph", 40); // string[]
145
+ ```
@@ -0,0 +1,126 @@
1
+ # Configuration
2
+
3
+ emo reads configuration from three layers. Later layers win, and each one is read for the
4
+ same file names, so there is exactly one layout to learn:
5
+
6
+ 1. the **home layer**, `~/.emo` by default;
7
+ 2. the **agent directory**, `~/.emo/agent` by default (`EMO_AGENT_DIR` or `--agent-dir`);
8
+ 3. the **project directory**, `.emo` in the project root.
9
+
10
+ The home layer is always the agent directory's parent, so moving the agent directory with
11
+ `EMO_AGENT_DIR=/srv/emo/agent` makes the home layer `/srv/emo`. Sessions, memory and todos
12
+ for a project live under `<agent-dir>/state/<project-key>/`, so they never pollute the
13
+ repository.
14
+
15
+ ## Home layer, `~/.emo`
16
+
17
+ | Path | Purpose |
18
+ |---|---|
19
+ | `settings.json` | defaults shared by every project |
20
+ | `AGENTS.md` | instructions applied in every working directory |
21
+ | `SYSTEM.md` | replaces the built-in system prompt |
22
+ | `APPEND_SYSTEM.md` | appended to the system prompt |
23
+ | `skills/` | shared skills |
24
+ | `prompts/` | shared prompt templates |
25
+ | `plugins/` | extension modules loaded into every project |
26
+ | `mcp.json` | MCP servers available in every project |
27
+
28
+ ## Agent directory, `~/.emo/agent`
29
+
30
+ | Path | Purpose |
31
+ |---|---|
32
+ | `settings.json` | provider, model, permissions, MCP and LSP servers, extra resource paths |
33
+ | `AGENTS.md` | instructions applied in every working directory |
34
+ | `AGENTS.override.md` | replaces the other instruction files in this directory |
35
+ | `SYSTEM.md` | replaces the built-in system prompt |
36
+ | `APPEND_SYSTEM.md` | appended to the system prompt |
37
+ | `skills/` | user skills, each a directory with `SKILL.md` |
38
+ | `prompts/` | markdown prompt templates exposed as `emo /<name>` |
39
+ | `plugins/` | extension modules loaded into every project |
40
+ | `mcp.json` | MCP servers available in every project (bare map or `{ "mcpServers": { … } }`) |
41
+ | `state/<project>/` | sessions, `memory.json` and todos for that project |
42
+
43
+ ## Project `.emo`
44
+
45
+ | Path | Purpose |
46
+ |---|---|
47
+ | `settings.json` | project settings; merged over the home and agent settings |
48
+ | `SYSTEM.md` | replaces the system prompt for this project |
49
+ | `APPEND_SYSTEM.md` | appends project instructions to the system prompt |
50
+ | `skills/` | project skills |
51
+ | `prompts/` | project prompt templates |
52
+ | `plugins/` | project extensions |
53
+ | `rules.md` | extra instructions, read in addition to `AGENTS.md` |
54
+ | `mcp.json` | MCP servers for this project, merged over the other layers |
55
+
56
+ `emo init` scaffolds `settings.json`, `skills/example/SKILL.md` and `prompts/review.md`.
57
+
58
+ ## Settings
59
+
60
+ ```json
61
+ {
62
+ "provider": "anthropic",
63
+ "model": "claude-3-5-sonnet-latest",
64
+ "temperature": 0,
65
+ "maxSteps": 40,
66
+ "mode": "build",
67
+ "autocompact": true,
68
+ "contextLimit": 128000,
69
+ "providers": {
70
+ "local": { "type": "openai", "baseUrl": "http://localhost:11434/v1", "defaultModel": "qwen2.5-coder" }
71
+ },
72
+ "permissions": { "default": "ask", "allow": ["read_file"], "deny": ["run_command"] },
73
+ "mcpServers": {
74
+ "docs": { "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] }
75
+ },
76
+ "lspServers": {
77
+ "ts": { "command": "typescript-language-server", "args": ["--stdio"], "extensions": [".ts"] }
78
+ },
79
+ "skills": ["./tools/skills"],
80
+ "prompts": ["./tools/prompts"],
81
+ "plugins": ["./tools/plugin.ts"]
82
+ }
83
+ ```
84
+
85
+ Paths in `skills`, `prompts` and `plugins` are resolved from the working directory. Setting
86
+ an unknown `provider` is an error rather than a silent substitution: add it under
87
+ `providers` first.
88
+
89
+ ## Instructions and prompts
90
+
91
+ Instruction files are discovered from the home layer and the agent directory, then from the
92
+ project root down to the working directory. `AGENTS.override.md` replaces `AGENTS.md` in the
93
+ same directory. `.emo/rules.md` is always added.
94
+
95
+ `SYSTEM.md` and `APPEND_SYSTEM.md` are read from all three layers; the last copy found wins
96
+ and the layers are not combined.
97
+
98
+ ## Skills
99
+
100
+ A skill is a directory containing `SKILL.md` with frontmatter:
101
+
102
+ ```markdown
103
+ ---
104
+ name: pdf-tools
105
+ description: Extract text and tables from PDF files. Use when reading or converting PDFs.
106
+ ---
107
+
108
+ Run scripts relative to this directory.
109
+ ```
110
+
111
+ Supported fields: `name`, `description` (required), `license`, `compatibility`,
112
+ `allowed-tools`, `disable-model-invocation`. Skills are discovered recursively in the project
113
+ `.emo/skills`, the agent directory's `skills`, the home layer's `skills`, `~/.agents/skills`
114
+ and `.agents/skills` up to the project root. A duplicate name keeps the first skill found.
115
+
116
+ ## Prompt templates
117
+
118
+ `prompts/review.md` becomes `emo /review`. Frontmatter:
119
+
120
+ ```markdown
121
+ ---
122
+ description: Review staged changes
123
+ argument-hint: "[focus]"
124
+ ---
125
+ Review the staged changes. Focus on ${1:-correctness}.
126
+ ```
@@ -0,0 +1,42 @@
1
+ # Environment variables
2
+
3
+ There is no `.env` file in the repository and none is needed. Export variables in your
4
+ shell, or set the same values in `settings.json` where a settings key exists. Precedence is:
5
+ command-line flag, then environment, then settings file, then default.
6
+
7
+ ## Paths
8
+
9
+ | Variable | Meaning |
10
+ |---|---|
11
+ | `EMO_AGENT_DIR` | agent directory, default `~/.emo/agent`; its parent is the home layer |
12
+
13
+ ## Provider and model
14
+
15
+ | Variable | Meaning |
16
+ |---|---|
17
+ | `EMO_PROVIDER` | provider id: `openai`, `anthropic`, `google`, or a key from `providers` |
18
+ | `EMO_MODEL` | model id, default comes from the provider |
19
+ | `OPENAI_API_KEY` | OpenAI key |
20
+ | `ANTHROPIC_API_KEY` | Anthropic key |
21
+ | `GEMINI_API_KEY`, `GOOGLE_API_KEY` | Google key |
22
+ | `<PROVIDER>_API_KEY` | key for a custom provider, for example `LOCAL_API_KEY` |
23
+
24
+ ## Runtime
25
+
26
+ | Variable | Meaning |
27
+ |---|---|
28
+ | `EMO_MODE` | `build` or `plan` |
29
+ | `EMO_MAX_STEPS` | loop budget, default `40` |
30
+ | `EMO_TEMPERATURE` | sampling temperature, default `0` |
31
+ | `EMO_CONTEXT_LIMIT` | tokens before compaction, default `128000` |
32
+ | `EMO_AUTOCOMPACT` | `true` or `false`, default `true` |
33
+ | `EMO_COMMAND_TIMEOUT_MS` | shell command timeout, default `120000` |
34
+
35
+ Example:
36
+
37
+ ```bash
38
+ export ANTHROPIC_API_KEY=... # keep it out of shell history if you can
39
+ export EMO_PROVIDER=anthropic
40
+ export EMO_MODEL=claude-3-5-sonnet-latest
41
+ emo "add a regression test for the parser"
42
+ ```
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "@crowgentai/emo-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "The emo command line interface: interactive TUI, one-shot print mode, JSON output and JSONL RPC.",
5
+ "type": "module",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/crowgent/emo.git",
10
+ "directory": "packages/cli"
11
+ },
12
+ "homepage": "https://github.com/crowgent/emo#readme",
13
+ "bugs": {
14
+ "url": "https://github.com/crowgent/emo/issues"
15
+ },
16
+ "keywords": [
17
+ "agent",
18
+ "ai",
19
+ "llm",
20
+ "emo",
21
+ "cli"
22
+ ],
23
+ "engines": {
24
+ "node": ">=20"
25
+ },
26
+ "main": "./dist/index.js",
27
+ "types": "./dist/index.d.ts",
28
+ "exports": {
29
+ ".": {
30
+ "types": "./dist/index.d.ts",
31
+ "import": "./dist/index.js"
32
+ }
33
+ },
34
+ "files": [
35
+ "dist",
36
+ "README.md",
37
+ "docs"
38
+ ],
39
+ "publishConfig": {
40
+ "access": "public"
41
+ },
42
+ "scripts": {
43
+ "build": "tsc -p tsconfig.json",
44
+ "typecheck": "tsc -p tsconfig.json --noEmit",
45
+ "test": "node --import tsx --test \"test/*.test.ts\"",
46
+ "prepublishOnly": "npm run build"
47
+ },
48
+ "dependencies": {
49
+ "@crowgentai/emo-core": "^0.1.0",
50
+ "@crowgentai/emo-ai": "^0.1.0",
51
+ "@crowgentai/emo-session": "^0.1.0",
52
+ "@crowgentai/emo-memory": "^0.1.0",
53
+ "@crowgentai/emo-skills": "^0.1.0",
54
+ "@crowgentai/emo-prompts": "^0.1.0",
55
+ "@crowgentai/emo-context": "^0.1.0",
56
+ "@crowgentai/emo-tools": "^0.1.0",
57
+ "@crowgentai/emo-agent": "^0.1.0",
58
+ "@crowgentai/emo-tui": "^0.1.0",
59
+ "@crowgentai/emo-packages": "^0.1.0"
60
+ },
61
+ "bin": {
62
+ "emo": "./dist/cli.js"
63
+ }
64
+ }