codeshark-cli 0.1.1 → 0.1.5

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/PRIVACY.md ADDED
@@ -0,0 +1,73 @@
1
+ # CodeShark Privacy Notice
2
+
3
+ *Last updated: September 5, 2026*
4
+
5
+ This notice describes how CodeShark handles information when you use the CLI,
6
+ the CodeShark website, or the CodeShark community gateway.
7
+
8
+ ## The CLI
9
+
10
+ CodeShark does not include analytics or telemetry by default. The CLI reads and
11
+ writes files in the project directory you select, and it may execute commands
12
+ there after you approve them. Local configuration can contain provider API keys.
13
+ Protect your computer and configuration file; do not place secrets in prompts
14
+ or project files that you send to an AI provider.
15
+
16
+ ## AI requests
17
+
18
+ When you use the shared gateway, your prompts, selected tool definitions, and
19
+ relevant conversation or file content are sent to the gateway and then to one
20
+ or more upstream providers selected by the gateway, including OpenRouter,
21
+ NVIDIA, Google, or
22
+ other providers selected by that service. When you use your own provider key,
23
+ requests go to the provider configured by you.
24
+
25
+ AI providers may process, retain, or log requests under their own policies and
26
+ terms. CodeShark cannot guarantee that prompts, generated output, IP addresses,
27
+ or provider-side request metadata are never retained. Review the applicable
28
+ provider documentation before sending confidential, personal, regulated, or
29
+ proprietary information.
30
+
31
+ ## Gateway data
32
+
33
+ The community gateway receives request data and network information needed to
34
+ route requests, enforce rate limits, prevent abuse, and operate the service.
35
+ The gateway implementation does not intentionally log prompt contents, but
36
+ Cloudflare and upstream providers may process operational metadata according to
37
+ their own policies. The gateway uses in-memory rate-limit state and does not
38
+ promise a particular retention period.
39
+
40
+ ## API keys
41
+
42
+ Keys entered into the CLI are stored locally in the CodeShark configuration
43
+ file. On POSIX systems CodeShark attempts to set restrictive file permissions.
44
+ On Windows, filesystem permissions depend on the account and machine settings;
45
+ users should protect the configuration file and computer themselves. Keys sent
46
+ to the shared gateway are held as server-side deployment secrets and are not
47
+ returned to clients.
48
+
49
+ ## Your choices
50
+
51
+ You can use a local Ollama provider to keep model requests on your machine, or
52
+ configure your own provider directly. You can remove local configuration by
53
+ deleting the path shown by your configuration setup. You can avoid the shared
54
+ gateway by selecting another provider.
55
+
56
+ ## Website
57
+
58
+ The static website does not intentionally collect form submissions or use
59
+ analytics. External resources, including Google Fonts and npm links, may
60
+ receive normal browser request metadata under their own policies.
61
+
62
+ ## Children and regulated data
63
+
64
+ CodeShark is not designed for children or for handling health, payment,
65
+ financial, educational, employment, export-controlled, or other regulated data.
66
+ Do not send such information unless you have confirmed that the selected
67
+ provider and your legal obligations permit it.
68
+
69
+ ## Changes and contact
70
+
71
+ This notice may change as the service changes. For questions or privacy
72
+ requests, open an issue in the CodeShark repository listed in `package.json`.
73
+ This notice is informational and is not legal advice.
package/README.md CHANGED
@@ -1,260 +1,125 @@
1
- # CodeShark 🦈
1
+ # CODESHARK
2
2
 
3
- An open-source **terminal coding agent** with a pixel-shark mascotfive
4
- frontier models (GPT-5.6 Sol, DeepSeek-V4 Flash, GLM 5.3 Flash Thinking,
5
- Kimi-K3, Gemini 3.6 Flash) behind one OpenAI-compatible endpoint.
3
+ An open-source coding agent that reads your project, plans the work, edits files, and runs commandswith your approval. Eight model choices, one familiar terminal.
6
4
 
7
- Run `codeshark banner --plain` to see the live mascot in your terminal: a dark
8
- grey head with black eyes, white teeth, and a red mouth.
9
-
10
- ## How it works
11
-
12
- Everything routes through **UnoRouter** (`https://api.unorouter.com/v1`), one
13
- OpenAI-compatible endpoint. CodeShark ships with a zero-setup **community
14
- gateway**, so you can start without configuring anything; bring your own
15
- UnoRouter key whenever you want your own rate limits and private prompts.
16
-
17
- The gateway strictly serves only UnoRouter's `:free` lane identifiers — any
18
- other identifier is refused, so there is no paid path through the gateway.
5
+ [Source code](https://github.com/ajashratripathi-crypto/codeshark-cli) | [Quick start](#quick-start) | [Models](#models) | [License](LICENSE)
19
6
 
20
7
  ## Quick start
21
8
 
22
- CodeShark is intentionally **project-folder-only**. You must select the folder
23
- that the agent is allowed to work in with `--folder` (or `--cwd`). It refuses to
24
- start chat, setup, model switching, key management, or a prompt without a real
25
- project folder.
26
-
27
- ```bash
28
- # From a cloned checkout:
29
- npm install
30
- npm run build
31
- npm install -g .
32
-
33
- # Start CodeShark in the project folder:
34
- codeshark --folder .
35
- codeshark --folder . "explain this project"
9
+ Requires **Node.js 18.17 or later** and npm.
36
10
 
37
- # Or select another folder from anywhere:
38
- codeshark --folder path/to/your-project
39
- codeshark --cwd path/to/your-project "fix the tests"
11
+ ### Install with npm
40
12
 
41
- # After the package is published:
42
- npx codeshark-cli # run from any folder without a global install
13
+ ```bash
43
14
  npm install -g codeshark-cli
44
15
  ```
45
16
 
46
- Out of the box, CodeShark talks to the community gateway (which routes through
47
- UnoRouter), so there is **nothing to configure**. If you installed from a
48
- checkout and `codeshark` is not recognized yet, use `node dist/index.js
49
- --folder .` or run `npm install -g .`. All file edits, searches, and commands
50
- stay inside the selected project folder.
51
-
52
- By using CodeShark you agree to the [Terms of Service](TERMS.md) — the first
53
- interactive start asks you to accept them once, and `codeshark terms` prints
54
- them anytime.
55
-
56
- ### Setup: shared gateway or your own key?
57
-
58
- On first launch the CLI asks how you want to connect — and you can re-run it
59
- anytime with `codeshark setup`:
17
+ Then open the project you want to work on:
60
18
 
61
- - **My own API key (recommended)** — typed into the terminal **hidden (never
62
- echoed)**, stored only on your computer in a locked config file (`0600`
63
- permissions), and never printed by CodeShark. Your own key means your own
64
- rate limits and private prompts. One UnoRouter key unlocks all 5 models.
65
- - **Shared gateway** — no key on your computer at all; the gateway's keys live
66
- as server-side secrets. Shared free lanes are rate-limited, so the gateway
67
- **queues** bursts (you wait a moment instead of erroring) and fails over
68
- between UnoRouter → OpenRouter → NVIDIA automatically.
69
- - **Local Ollama** — fully offline on your own machine.
70
-
71
- Your local keys are protected further by the password-locked key vault
72
- (`codeshark keys`) — scrypt-hashed password, session + CSRF tokens, and keys
73
- never appear in the page's HTML or the terminal.
19
+ ```bash
20
+ cd path/to/your-project
21
+ codeshark --folder .
22
+ ```
74
23
 
75
- ## Usage
24
+ Or send a task directly:
76
25
 
26
+ ```bash
27
+ codeshark --folder . "explain this project"
28
+ codeshark --folder . "find and fix the failing tests"
77
29
  ```
78
- codeshark --folder . interactive chat for this folder
79
- codeshark --folder . "fix the tests" one-shot prompt for this folder
80
- codeshark banner just the mascot (no folder needed)
81
- codeshark --folder . setup providers / keys wizard
82
- codeshark --folder . model list the catalog and active model
83
- codeshark --folder . keys open the local key vault
84
- ```
85
30
 
86
- REPL commands: `/help` `/model` `/keys` `/key-status` `/setup` `/clear` `/quit`
87
- (Ctrl+C also quits). Read the terms anytime with `codeshark terms`. The `/keys` page listens only on `127.0.0.1`, requires a
88
- local password, and keeps key values hidden in password-style fields; the
89
- terminal status command only shows masked values.
90
-
91
- ## Tools the agent can use
92
-
93
- - `read_file` / `write_file` / `edit_file` (strict: `oldString` must match **exactly once** or the edit is rejected)
94
- - `list_directory` / `glob` (`**`, `*`, `?`, `{a,b}`)
95
- - `code_search` (ripgrep when installed, dependency-free fallback otherwise)
96
- - `run_command` (bash / cmd, 30s timeout, output capped) — with a built-in
97
- danger blocklist: `rm -rf`, `git push`, `sudo`, `curl | sh`, … are refused
98
- unless you set `CODESHARK_ALLOW_DANGEROUS=1`
99
- - `finish` — the model signals completion with a summary
100
-
101
- ## Providers & models
102
-
103
- Everything runs through **UnoRouter** (`https://api.unorouter.com/v1`), one
104
- OpenAI-compatible endpoint that routes to 45+ upstream providers — all five
105
- catalog models are served on its `:free` lanes. Switch anytime with
106
- `/model <name>` in the REPL (or `codeshark model <name>`).
107
-
108
- | Model | API identifier | Context | |
109
- | --- | --- | --- | --- |
110
- | Chat-GPT 5.6 Sol | `gpt-5.6-sol:free` | 400K | |
111
- | DeepSeek-V4 Flash | `deepseek-v4-flash-0731:free` | 256K | |
112
- | GLM 5.3 Flash Thinking | `glm-5.3-flash-thinking:free` | 1M | default |
113
- | Kimi-K3 | `kimi-k3:free` | 256K | |
114
- | Gemini 3.6 Flash | `gemini-3.6-flash:free` | 1M | |
115
-
116
- \* All models run through the zero-setup gateway without any key — nothing to
117
- configure.
118
-
119
- **Keys:**
120
- - UnoRouter → https://unorouter.com/en/tokens (one key, 200+ models — the only key you really need)
121
- - Google AI Studio → https://aistudio.google.com/apikey (`AIza…`)
122
-
123
- Run `codeshark setup` to paste a key and pick a default model — it tests the key
124
- live before saving.
125
-
126
- **Rate limits:** shared lanes throttle (~20 req/min, ~200/day). If you hit
127
- a 429, the agent tells you — wait a moment or switch models with `/model`.
128
-
129
- ## Configuration
130
-
131
- `~/.codeshark.json` (env vars override):
132
-
133
- ```json
134
- {
135
- "provider": "unorouter",
136
- "model": "unorouter/glm-5.3-flash-thinking",
137
- "unorouterApiKey": "ur-…",
138
- "openrouterApiKey": "sk-…",
139
- "nvidiaApiKey": "nvapi-…",
140
- "geminiApiKey": "AIza…",
141
- "gatewayUrl": "https://your-gateway.workers.dev",
142
- "ollamaBaseUrl": "http://127.0.0.1:11434/v1",
143
- "ollamaModel": "qwen3-coder:30b",
144
- "maxIterations": 25
145
- }
31
+ Or run without a global installation:
32
+
33
+ ```bash
34
+ npx codeshark-cli --folder .
146
35
  ```
147
36
 
148
- Env vars: `CODESHARK_MODEL`, `UNOROUTER_API_KEY`, `OPENROUTER_API_KEY`,
149
- `GEMINI_API_KEY`, `CODESHARK_GATEWAY_URL`, `CODESHARK_GATEWAY_KEY`,
150
- `CODESHARK_NO_COLOR`, `CODESHARK_NO_BANNER`, `CODESHARK_NO_LOADING`,
151
- `CODESHARK_ALLOW_DANGEROUS`.
37
+ CodeShark works with project folders. Run it from your project directory or choose a folder with `--folder` or `--cwd`.
152
38
 
153
- ## Run your own community gateway
39
+ On first launch, follow the connection setup and accept the [Terms](TERMS.md). The shared gateway lets you start without a personal API key; its free lanes are shared, rate-limited, and subject to availability.
154
40
 
155
- Anyone can fork the repo and deploy their own gateway — the URL is configurable,
156
- so your users hit *your* gateway:
41
+ ### Install from source
157
42
 
158
43
  ```bash
159
- cd worker
160
- npx wrangler secret put UNOROUTER_API_KEY # your UnoRouter key (primary), stays server-side
161
- npx wrangler secret put OPENROUTER_API_KEY # optional: OpenRouter fallback key
162
- npx wrangler secret put NVIDIA_API_KEY # optional: NVIDIA NIM fallback key (nvapi-…)
163
- npx wrangler deploy
44
+ git clone https://github.com/ajashratripathi-crypto/codeshark-cli.git
45
+ cd codeshark-cli
46
+ npm install
47
+ npm run build
48
+ npm install -g .
164
49
  ```
165
50
 
166
- Then point CodeShark at it:
167
-
168
- ```bash
169
- codeshark setup # or edit ~/.codeshark.json: "gatewayUrl": "https://<you>.workers.dev"
51
+ For contributors or anyone who prefers a local build. If the command is not recognized after building, use `node dist/index.js --folder .` from the checkout.
52
+
53
+ ## Everyday commands
54
+
55
+ | Command | What it does |
56
+ | --- | --- |
57
+ | `codeshark --folder .` | Start an interactive session in this folder |
58
+ | `codeshark --folder . "your task"` | Run a one-shot task |
59
+ | `codeshark setup` | Configure your connection and model |
60
+ | `codeshark model` | Show the model catalog |
61
+ | `codeshark keys` | Open the password-protected local key vault |
62
+ | `codeshark banner` | Print the CODESHARK banner |
63
+ | `codeshark update` | Check for and install an npm update |
64
+ | `codeshark terms` | Read the terms |
65
+
66
+ Inside a conversation:
67
+
68
+ ```text
69
+ /help Show available commands
70
+ /plan Work through a plan
71
+ /build Switch to building
72
+ /model See model choices
73
+ /keys Open the local key vault
74
+ /setup Reconfigure your connection
75
+ /clear Clear the conversation
76
+ /quit End the session
170
77
  ```
171
78
 
172
- The gateway serves only `:free` model identifiers it never routes anything
173
- paid — rate-limits per IP, adds CORS, and refuses any non-`:free` identifier.
174
- When a provider rate-limits (429), the gateway **waits and retries**, then
175
- hands off to the next configured provider (UnoRouter → OpenRouter → NVIDIA),
176
- and per-IP bursts **queue** (wait for a slot) instead of failing. Your keys are
177
- Worker secrets: never logged, never returned, never visible to users. Clients
178
- also retry 429s with backoff, so shared lanes feel smooth.
79
+ For example, `/model deepseek-v4-flash` switches to DeepSeek-V4 Flash. Your selection is saved locally.
179
80
 
180
- ## Architecture
81
+ ## Models
181
82
 
182
- ```
183
- ┌────────────┐ messages/tools ┌──────────────────┐ OpenAI-compatible ┌──────────────┐
184
- │ terminal │ ─────────────────▶ │ agent loop │ ───────────────────▶ │ provider │
185
- │ (repl/cli) │ ◀───────────────── │ (tools, guard) │ ◀─────────────────── │ chain │
186
- └────────────┘ streamed text └──────────────────┘ SSE stream └──────┬───────┘
187
-
188
- gateway (Cloudflare Worker, :free only) ◀─────────┤
189
- unorouter (:free, your key) ◀────────────────────┤
190
- gemini ◀──────────────────────────────────────────┤
191
- ollama (local) ◀──────────────────────────────────┘
192
- ```
83
+ The catalog is checked at startup, and unavailable models are marked. These context windows describe the configured catalog; availability depends on the connection and provider.
193
84
 
194
- - `src/provider/` canonical `ChatClient` interface + adapters (OpenAI-compatible
195
- shared core, UnoRouter, OpenRouter, NVIDIA NIM, Gemini conversion, Ollama)
196
- - `src/agent.ts` the loop: model → tool calls → results → repeat (25-iteration guard)
197
- - `src/tools/` file, search, and shell tools (zero dependencies)
198
- - `src/banner.ts` the mascot, defined as a character grid
199
- - `worker/`the Cloudflare Worker gateway
85
+ | Model | Context | Selection command |
86
+ | --- | --- | --- |
87
+ | Chat-GPT 5.6 Sol | 400K | `/model gpt-5.6-sol` |
88
+ | DeepSeek-V4 Flash | 256K | `/model deepseek-v4-flash` |
89
+ | MiniMax M3 | 128K | `/model minimax-m3` |
90
+ | **GLM 5.3 Flash Think Search default** | **1M** | `/model glm-5.3-flash-think-search` |
91
+ | Gemini 3.6 Flash | 1M | `/model gemini-3.6-flash` |
92
+ | Sarvam 30B | 128K | `/model sarvam-30b` |
93
+ | GPT-OSS 120B | 128K | `/model gpt-oss-120b` |
94
+ | Nemotron 3 Ultra 550B A55B | 256K | `/model nemotron-3-ultra-550b-a55b` |
200
95
 
201
- ## Share it with other computers
96
+ ## Connection and privacy
202
97
 
203
- Other people run your CodeShark the exact same way you do through npm.
204
- Publish once, and anyone with Node.js 18+ can run it from any computer.
98
+ Run `codeshark setup` to choose the shared gateway, your own API connection, or local Ollama. Provider keys are stored on your computer and are typed hidden during setup. `codeshark keys` opens a password-protected local page for managing them.
205
99
 
206
- The package name is `codeshark-cli` (npm's anti-squatting rules reserve the
207
- bare `codeshark` name, which is too similar to the existing `code-shark`
208
- package). The command you type stays `codeshark`:
100
+ When you use hosted models, prompts and relevant project content are sent through your configured connection. A personal key does not make hosted processing local; the provider’s privacy and retention policies still apply. See the [Privacy Notice](PRIVACY.md) and [Terms](TERMS.md).
209
101
 
210
- ```bash
211
- npm login # once per computer (create an npm account first)
212
- npm run typecheck && npm test
213
- npm pack --dry-run # preview exactly what ships: dist/, README, LICENSE
214
- npm publish --access public # publish version 0.1.0
215
- ```
102
+ Configuration is stored in `~/.codeshark.json`. Environment options include `CODESHARK_MODEL`, `CODESHARK_GATEWAY_URL`, `CODESHARK_GATEWAY_KEY`, `CODESHARK_NO_COLOR`, `CODESHARK_NO_BANNER`, and `CODESHARK_NO_UPDATE`.
216
103
 
217
- Bump the version for every release: `npm version patch` (or `minor`/`major`),
218
- then `npm publish` again.
219
-
220
- From that moment, on **any computer** with Node.js 18+:
104
+ ## Update
221
105
 
222
106
  ```bash
223
- npx codeshark-cli --folder . # run instantly — no install needed
224
- npm install -g codeshark-cli # or install it like a real CLI
225
- codeshark --folder . # then use it anywhere
107
+ npm install -g codeshark-cli@latest
226
108
  ```
227
109
 
228
- The person on the other computer needs no API key and no account — the model
229
- provider stays server-side, so it works out of the box. The agent only works
230
- inside the folder they open with `--folder`; it edits, searches, and runs
231
- commands there and nowhere else.
232
-
233
- Not ready to publish? `npm pack` produces a single `codeshark-<version>.tgz`
234
- file — send that one file and the receiver runs `npm install -g
235
- ./codeshark-0.1.0.tgz`.
236
-
237
110
  ## Development
238
111
 
239
112
  ```bash
240
113
  npm install
241
- npm run typecheck # tsc --noEmit
242
- npm test # build + node:test (agent loop, tools, parsers, banner)
243
- npm run worker:build # typecheck the gateway worker
114
+ npm run build
115
+ npm run typecheck
116
+ npm test
244
117
  ```
245
118
 
246
- ## Roadmap
119
+ ## License
247
120
 
248
- - [x] Mascot banner, REPL, one-shot mode, setup wizard
249
- - [x] UnoRouter provider: 5 frontier models, one key
250
- - [x] Agent loop with streaming + tool calling (UnoRouter/Gemini/Ollama/gateway)
251
- - [x] File, search, and shell tools with safety blocklist
252
- - [x] Cloudflare Worker gateway (`:free`-only, UnoRouter-routed)
253
- - [ ] Session memory / project context
254
- - [x] npm package metadata and `npx codeshark-cli`/global-install support (publish manually)
255
- - [ ] Approval prompts for sensitive commands
256
- - [ ] More providers (Groq, Cerebras, …)
121
+ [MIT](LICENSE).
257
122
 
258
- ## License
123
+ ## Provider details
259
124
 
260
- MIT. 🦈
125
+ The current free catalog uses UnoRouter through an OpenAI-compatible connection. Configure your own key with `codeshark setup`. Additional adapters support OpenRouter, NVIDIA NIM, Gemini, and local Ollama.
package/TERMS.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # CodeShark Terms of Service
2
2
 
3
- *Last updated: September 4, 2026*
3
+ *Last updated: September 5, 2026*
4
4
 
5
5
  By installing, downloading, or using CodeShark (the "Software"), you agree to
6
6
  these Terms of Service. If you do not agree, do not use the Software.
@@ -8,8 +8,9 @@ these Terms of Service. If you do not agree, do not use the Software.
8
8
  ## 1. What CodeShark is
9
9
 
10
10
  CodeShark is an open-source terminal coding agent. It can read, create, and
11
- edit files, run searches, and execute commands **inside the project folder you
12
- explicitly open with `--folder`**. It is a tool you operate — you are
11
+ edit files, run searches, and execute commands **inside the current directory or
12
+ the project folder selected with `--folder` or `--cwd`**. The selected path must
13
+ be a directory, not an individual file. It is a tool you operate — you are
13
14
  responsible for choosing when and how it acts.
14
15
 
15
16
  ## 2. No warranty
@@ -36,10 +37,13 @@ routed through shared free-tier provider lanes. You agree to:
36
37
 
37
38
  ## 4. Your content
38
39
 
39
- You retain all rights to the prompts you enter and the files you edit. You are
40
- solely responsible for them. Do not paste passwords, API keys, or other secrets
41
- into prompts they may pass through third-party providers. Prompts and
42
- generated content are not private; treat them accordingly.
40
+ You retain rights you already hold in the prompts you enter and the files you
41
+ edit. Rights in generated content depend on applicable law, originality, and
42
+ the terms of the selected provider; CodeShark does not guarantee ownership or
43
+ exclusivity of generated content. You are solely responsible for your content.
44
+ Do not paste passwords, API keys, or other secrets into prompts — they may pass
45
+ through third-party providers. Prompts and generated content are not private;
46
+ treat them accordingly. See `PRIVACY.md` for more information.
43
47
 
44
48
  ## 5. Limitation of liability
45
49
 
@@ -50,23 +54,38 @@ content or executed commands. You use the Software entirely at your own risk.
50
54
 
51
55
  ## 6. API keys
52
56
 
53
- If you paste your own provider key, it is stored locally on your computer in a
54
- locked configuration file and is never printed by CodeShark. Keys configured on
55
- the shared gateway are stored as server-side secrets and are never exposed,
56
- logged, or returned to clients. You are responsible for protecting your own
57
- keys.
57
+ If you paste your own provider key, CodeShark stores it locally and does not
58
+ print it intentionally. CodeShark attempts restrictive permissions on POSIX
59
+ systems; on Windows, protection depends on your account and machine settings.
60
+ Keys configured on the shared gateway are deployment secrets and are not
61
+ returned to clients. Third-party providers may process request data under their
62
+ own terms. You are responsible for protecting your own keys.
58
63
 
59
- ## 7. Changes
64
+ ## 7. Third-party services
65
+
66
+ CodeShark may connect to third-party services, including model providers,
67
+ Cloudflare, Google, and Ollama. Those services have separate terms,
68
+ privacy policies, availability limits, model restrictions, and data practices.
69
+ You are responsible for complying with the terms that apply to the provider
70
+ and model you select. CodeShark does not represent or endorse those providers.
71
+
72
+ ## 8. Updates
73
+
74
+ The CLI may check npm for a newer CodeShark release at startup and asks for
75
+ confirmation before installing it. You can skip the check with
76
+ `CODESHARK_NO_UPDATE=1` or run `codeshark update` manually.
77
+
78
+ ## 9. Changes
60
79
 
61
80
  These Terms may be updated at any time. Continued use of the Software after
62
81
  changes constitutes acceptance of the revised Terms.
63
82
 
64
- ## 8. Termination
83
+ ## 10. Termination
65
84
 
66
85
  We may refuse or terminate access to the shared gateway at any time, with or
67
86
  without notice, for any reason — including violation of these Terms. The
68
87
  open-source Software itself remains available under its MIT license.
69
88
 
70
- ## 9. Contact
89
+ ## 11. Contact
71
90
 
72
91
  For questions about these Terms, open an issue in the CodeShark repository.
package/dist/agent.js CHANGED
@@ -8,15 +8,22 @@ import { DEFAULT_MAX_ITERATIONS } from "./config.js";
8
8
  */
9
9
  export async function runAgent(input, opts, events) {
10
10
  const maxIterations = opts.maxIterations ?? DEFAULT_MAX_ITERATIONS;
11
+ if (!Number.isSafeInteger(maxIterations) || maxIterations < 1)
12
+ throw new Error("maxIterations must be a positive integer.");
11
13
  const messages = opts.initialMessages ? [...opts.initialMessages] : [];
12
14
  const systemPrompt = opts.systemPrompt ?? defaultSystemPrompt(opts.cwd);
13
- if (!messages.some((message) => message.role === "system")) {
15
+ const systemIndex = messages.findIndex((message) => message.role === "system");
16
+ if (systemIndex === -1) {
14
17
  messages.unshift({ role: "system", content: systemPrompt });
15
18
  }
19
+ else {
20
+ messages[systemIndex] = { role: "system", content: systemPrompt };
21
+ }
16
22
  messages.push({ role: "user", content: input });
17
- const ctx = { cwd: opts.cwd, log: opts.debug };
23
+ const ctx = { cwd: opts.cwd, log: opts.debug, readOnly: opts.readOnly, signal: opts.signal };
18
24
  let lastError = null;
19
25
  for (let i = 0; i < maxIterations; i++) {
26
+ opts.signal?.throwIfAborted();
20
27
  let assistant = null;
21
28
  let streamedText = "";
22
29
  for (const client of opts.clients) {
@@ -32,11 +39,18 @@ export async function runAgent(input, opts, events) {
32
39
  }
33
40
  : undefined;
34
41
  try {
35
- assistant = await client.chat(messages, opts.registry.schemas(), clientEvents);
42
+ assistant = await client.chat(messages, opts.registry.schemas(opts.readOnly), clientEvents, opts.signal);
43
+ if (assistant.role !== "assistant")
44
+ throw new Error("Provider returned a non-assistant response.");
36
45
  streamedText = clientStreamedText;
37
46
  break;
38
47
  }
39
48
  catch (e) {
49
+ assistant = null;
50
+ opts.signal?.throwIfAborted();
51
+ // A partial answer is already visible; avoid mixing it with another provider's answer.
52
+ if (clientStreamedText)
53
+ throw e;
40
54
  lastError = e instanceof Error ? e : new Error(String(e));
41
55
  opts.debug?.(`[provider] ${client.provider} failed: ${lastError.message}`);
42
56
  }
@@ -56,12 +70,28 @@ export async function runAgent(input, opts, events) {
56
70
  };
57
71
  }
58
72
  for (const call of calls) {
73
+ opts.signal?.throwIfAborted();
59
74
  if (call.name === "finish") {
60
75
  const summary = typeof call.args.summary === "string" && call.args.summary.trim() ? call.args.summary.trim() : "Task complete.";
76
+ const remaining = calls.slice(calls.indexOf(call));
77
+ for (const pending of remaining) {
78
+ messages.push({ role: "tool", content: pending === call ? summary : "Skipped because the task was finished.", toolCallId: pending.id, toolName: pending.name });
79
+ }
80
+ messages.push({ role: "assistant", content: summary });
61
81
  return { text: summary, iterations: i + 1, history: messages };
62
82
  }
63
83
  opts.debug?.(`[tool] ${call.name}`);
64
84
  events?.onToolCall?.(call);
85
+ if (opts.approveToolCall && !(await opts.approveToolCall(call))) {
86
+ messages.push({
87
+ role: "tool",
88
+ content: `User denied the requested action: ${call.name}. Do not retry it unless the user asks again.`,
89
+ toolCallId: call.id,
90
+ toolName: call.name,
91
+ isError: true,
92
+ });
93
+ continue;
94
+ }
65
95
  const result = await opts.registry.execute(call.name, call.args, ctx);
66
96
  messages.push({
67
97
  role: "tool",