reasonally 0.1.0 → 0.3.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 +143 -5
- package/dist/agent/accumulate.js +146 -0
- package/dist/agent/client.js +174 -0
- package/dist/agent/compact.js +79 -0
- package/dist/agent/cost.js +22 -0
- package/dist/agent/loop-constants.js +3 -0
- package/dist/agent/loop.js +559 -0
- package/dist/agent/mcp-config.js +72 -0
- package/dist/agent/mcp.js +194 -0
- package/dist/agent/permissions.js +116 -0
- package/dist/agent/prompt.js +98 -0
- package/dist/agent/session.js +196 -0
- package/dist/agent/sse.js +46 -0
- package/dist/agent/tools/bash.js +176 -0
- package/dist/agent/tools/diff.js +33 -0
- package/dist/agent/tools/files.js +270 -0
- package/dist/agent/tools/index.js +21 -0
- package/dist/agent/tools/paths.js +43 -0
- package/dist/agent/tools/search.js +288 -0
- package/dist/agent/tools/task.js +42 -0
- package/dist/agent/tools/todo.js +59 -0
- package/dist/agent/tools/types.js +57 -0
- package/dist/agent/types.js +2 -0
- package/dist/api.js +5 -1
- package/dist/browser/command.js +93 -0
- package/dist/browser/guards.js +138 -0
- package/dist/browser/pairing.js +123 -0
- package/dist/browser/protocol.js +172 -0
- package/dist/browser/server.js +157 -0
- package/dist/browser/sessions.js +478 -0
- package/dist/catalog.js +12 -0
- package/dist/cli.js +43 -3
- package/dist/config.js +17 -4
- package/dist/tui/app.js +869 -0
- package/dist/tui/args.js +32 -0
- package/dist/tui/commands.js +38 -0
- package/dist/tui/components.js +375 -0
- package/dist/tui/format.js +116 -0
- package/dist/tui/node-version.js +7 -0
- package/dist/tui/start.js +135 -0
- package/dist/tui/theme.js +36 -0
- package/package.json +11 -3
package/README.md
CHANGED
|
@@ -1,16 +1,130 @@
|
|
|
1
1
|
# reasonally
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Reasonally's coding agent in your terminal, plus the coding agents you already use, on Reasonally
|
|
4
|
+
models and billed to your Reasonally workspace.
|
|
4
5
|
|
|
5
6
|
```bash
|
|
6
7
|
npm install -g reasonally
|
|
7
|
-
|
|
8
|
-
reasonally
|
|
8
|
+
cd my-project
|
|
9
|
+
reasonally # log in (first time), pick a model, start coding
|
|
9
10
|
```
|
|
10
11
|
|
|
11
|
-
|
|
12
|
+
The agent needs Node.js 22.19 or later; everything else works on Node.js 20 or later.
|
|
12
13
|
|
|
13
|
-
##
|
|
14
|
+
## The agent
|
|
15
|
+
|
|
16
|
+
Type what you want done. The agent reads your code, makes changes and runs commands, asking first
|
|
17
|
+
when it matters. It works in the folder you start it in.
|
|
18
|
+
|
|
19
|
+
```
|
|
20
|
+
Reasonally · anthropic/claude-sonnet-4.5 · ~/code/shop
|
|
21
|
+
|
|
22
|
+
› Add a dark mode toggle to the settings page
|
|
23
|
+
|
|
24
|
+
● Read src/app/settings/page.tsx (120 lines)
|
|
25
|
+
╭ Edit src/app/settings/page.tsx
|
|
26
|
+
│ @@ -41,3 +41,4 @@
|
|
27
|
+
│ + <ThemeToggle />
|
|
28
|
+
╰ Allow? y yes · a yes, and allow all edits this session · n no, and tell it why
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
It runs in your terminal's normal screen, so scrolling, selecting and copying work as usual, and
|
|
32
|
+
the conversation stays on screen after you quit.
|
|
33
|
+
|
|
34
|
+
### Asking before acting
|
|
35
|
+
|
|
36
|
+
| Mode (Shift+Tab switches) | Edits | Commands, MCP tools |
|
|
37
|
+
| -------------------------- | ----- | ------------------- |
|
|
38
|
+
| Ask before edits (default) | ask | ask |
|
|
39
|
+
| Auto-accept edits | auto | ask |
|
|
40
|
+
| Don't ask (`--yes`) | auto | auto |
|
|
41
|
+
|
|
42
|
+
- Reading files in your project never asks. Reading or changing anything outside it asks, except in
|
|
43
|
+
"Don't ask".
|
|
44
|
+
- `.env` files and `~/.ssh`, `~/.aws` and `~/.gnupg` ask in every mode. The file holding this
|
|
45
|
+
computer's Reasonally key is never opened.
|
|
46
|
+
- Approved commands run with your permissions, like commands you type. There's no sandbox, so read
|
|
47
|
+
what a command does before approving it, and use "Don't ask" only in projects you trust.
|
|
48
|
+
- Commands run without your Reasonally key in their environment, and pagers are turned off.
|
|
49
|
+
|
|
50
|
+
### Keys
|
|
51
|
+
|
|
52
|
+
| Key | Does |
|
|
53
|
+
| --------------------- | --------------------------------------------------------- |
|
|
54
|
+
| Enter | Send. Shift+Enter or Ctrl+J for a new line |
|
|
55
|
+
| Esc | Stop the reply and any running command; billing stops too |
|
|
56
|
+
| Shift+Tab | Switch mode |
|
|
57
|
+
| Ctrl+O | Show the full output or diff of the last step |
|
|
58
|
+
| Ctrl+C | Clear the input; press twice to quit (Ctrl+D also quits) |
|
|
59
|
+
| `@` | Mention a file |
|
|
60
|
+
| Typing while it works | Queues your message for when the current step finishes |
|
|
61
|
+
|
|
62
|
+
### Commands
|
|
63
|
+
|
|
64
|
+
| Command | Does |
|
|
65
|
+
| ---------- | ------------------------------------------------------- |
|
|
66
|
+
| `/model` | Switch model (only models that can use tools are shown) |
|
|
67
|
+
| `/mode` | Switch mode |
|
|
68
|
+
| `/new` | Start a new conversation |
|
|
69
|
+
| `/resume` | Continue an earlier conversation in this folder |
|
|
70
|
+
| `/compact` | Summarize the conversation so far to free up context |
|
|
71
|
+
| `/cost` | This session's cost and your balance |
|
|
72
|
+
| `/mcp` | MCP servers and their tools |
|
|
73
|
+
| `/login` | Log in again |
|
|
74
|
+
| `/help` | Commands and keys |
|
|
75
|
+
| `/exit` | Quit |
|
|
76
|
+
|
|
77
|
+
### Conversations
|
|
78
|
+
|
|
79
|
+
Every conversation is saved as it happens, in `~/.config/reasonally/sessions/`.
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
reasonally --continue # pick up the last conversation in this folder
|
|
83
|
+
reasonally --resume # choose one
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
When a conversation fills about 80% of the model's context window, earlier turns are summarized
|
|
87
|
+
automatically (or now, with `/compact`).
|
|
88
|
+
|
|
89
|
+
### Project instructions
|
|
90
|
+
|
|
91
|
+
The agent follows `AGENTS.md` and `CLAUDE.md` files from your repository's root down to the folder
|
|
92
|
+
you're in, and your own `~/.config/reasonally/AGENTS.md` for every project.
|
|
93
|
+
|
|
94
|
+
### Helpers
|
|
95
|
+
|
|
96
|
+
For broad searches or independent pieces of work, the agent can start helpers that work with fresh
|
|
97
|
+
context and report back, up to four at once. Helpers read freely; their edits and commands always
|
|
98
|
+
ask (except in "Don't ask").
|
|
99
|
+
|
|
100
|
+
### MCP servers
|
|
101
|
+
|
|
102
|
+
Add servers to `~/.config/reasonally/mcp.json`:
|
|
103
|
+
|
|
104
|
+
```json
|
|
105
|
+
{
|
|
106
|
+
"mcpServers": {
|
|
107
|
+
"github": {
|
|
108
|
+
"command": "npx",
|
|
109
|
+
"args": ["-y", "@modelcontextprotocol/server-github"],
|
|
110
|
+
"env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "…" }
|
|
111
|
+
},
|
|
112
|
+
"docs": { "url": "https://example.com/mcp", "headers": { "Authorization": "Bearer …" } }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Their tools ask before each use (except in "Don't ask"). Project folders are never read for MCP
|
|
118
|
+
servers, so opening a repository can't start a program it names.
|
|
119
|
+
|
|
120
|
+
### Cost
|
|
121
|
+
|
|
122
|
+
The status line shows the session's estimated cost and your balance; exact charges are on your
|
|
123
|
+
dashboard's Usage page. Pressing Esc stops the reply and its billing.
|
|
124
|
+
|
|
125
|
+
## Other agents
|
|
126
|
+
|
|
127
|
+
Run the coding agents you already use on Reasonally models:
|
|
14
128
|
|
|
15
129
|
| Command | Agent |
|
|
16
130
|
| --------------------- | ----------------------------------------------------- |
|
|
@@ -43,6 +157,25 @@ reasonally logout # log out and revoke this computer's key
|
|
|
43
157
|
reasonally login --no-browser # print the approval link instead of opening it
|
|
44
158
|
```
|
|
45
159
|
|
|
160
|
+
## Browser use
|
|
161
|
+
|
|
162
|
+
```bash
|
|
163
|
+
reasonally browser # keep it running while a chat uses the browser
|
|
164
|
+
```
|
|
165
|
+
|
|
166
|
+
Lets a chat in your Reasonally dashboard control a visible browser window on this computer, using
|
|
167
|
+
Google Chrome (or Edge, or a Chromium from `npx playwright install chromium`). No login needed.
|
|
168
|
+
|
|
169
|
+
- The first time a chat asks, the terminal asks you to allow it (`y`). That browser stays paired for
|
|
170
|
+
30 days. Only the dashboard's own site can talk to the companion, and only on `127.0.0.1`.
|
|
171
|
+
- Each chat gets its own window with a fresh profile. Logins last until that window closes. Windows
|
|
172
|
+
close after 30 minutes without activity, and all of them close when you stop the companion
|
|
173
|
+
(Ctrl+C).
|
|
174
|
+
- Password, payment-card and one-time-code fields are left for you to fill in.
|
|
175
|
+
- Addresses on this computer or your local network (localhost, 192.168.x.x, `.local`, …) are off.
|
|
176
|
+
Pass `--allow-local` to allow them, e.g. for a dev server.
|
|
177
|
+
- `--port N` changes the port (default 47614).
|
|
178
|
+
|
|
46
179
|
## Environment
|
|
47
180
|
|
|
48
181
|
| Variable | Use |
|
|
@@ -50,3 +183,8 @@ reasonally login --no-browser # print the approval link instead of opening it
|
|
|
50
183
|
| `REASONALLY_API_KEY` | Use an existing API key instead of logging in (CI, servers). |
|
|
51
184
|
| `REASONALLY_URL` | Dashboard URL (default `https://app.reasonally.ai`). |
|
|
52
185
|
| `REASONALLY_API_URL` | API base URL (default `https://api.reasonally.ai/v1`). |
|
|
186
|
+
| `NO_COLOR` | Turn off colors in the agent. |
|
|
187
|
+
|
|
188
|
+
## Platforms
|
|
189
|
+
|
|
190
|
+
macOS and Linux. Windows should work (commands run in PowerShell) but hasn't been tested yet.
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
const isRecord = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
|
|
2
|
+
const str = (v) => (typeof v === "string" ? v : "");
|
|
3
|
+
const int = (v) => (typeof v === "number" && Number.isFinite(v) ? Math.max(0, v) : 0);
|
|
4
|
+
/** Whether a tool call's arguments are complete JSON (empty counts as `{}`). */
|
|
5
|
+
export function isCompleteArguments(args) {
|
|
6
|
+
if (args.trim() === "")
|
|
7
|
+
return true;
|
|
8
|
+
try {
|
|
9
|
+
JSON.parse(args);
|
|
10
|
+
return true;
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return false;
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
/** Builds one assistant message from `chat.completion.chunk` objects. */
|
|
17
|
+
export class MessageAccumulator {
|
|
18
|
+
content = "";
|
|
19
|
+
reasoning = "";
|
|
20
|
+
finishReason = null;
|
|
21
|
+
usage = null;
|
|
22
|
+
reasoningDetails = [];
|
|
23
|
+
calls = new Map();
|
|
24
|
+
apply(chunk) {
|
|
25
|
+
if (!isRecord(chunk))
|
|
26
|
+
return [];
|
|
27
|
+
const deltas = [];
|
|
28
|
+
if (isRecord(chunk.usage)) {
|
|
29
|
+
this.usage = {
|
|
30
|
+
promptTokens: int(chunk.usage.prompt_tokens),
|
|
31
|
+
completionTokens: int(chunk.usage.completion_tokens),
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
const choice = Array.isArray(chunk.choices) ? chunk.choices[0] : null;
|
|
35
|
+
if (!isRecord(choice))
|
|
36
|
+
return deltas;
|
|
37
|
+
if (typeof choice.finish_reason === "string")
|
|
38
|
+
this.finishReason = choice.finish_reason;
|
|
39
|
+
const delta = isRecord(choice.delta) ? choice.delta : null;
|
|
40
|
+
if (!delta)
|
|
41
|
+
return deltas;
|
|
42
|
+
const text = str(delta.content);
|
|
43
|
+
if (text) {
|
|
44
|
+
this.content += text;
|
|
45
|
+
deltas.push({ type: "text", text });
|
|
46
|
+
}
|
|
47
|
+
const thought = str(delta.reasoning) || str(delta.reasoning_content);
|
|
48
|
+
if (thought) {
|
|
49
|
+
this.reasoning += thought;
|
|
50
|
+
deltas.push({ type: "reasoning", text: thought });
|
|
51
|
+
}
|
|
52
|
+
if (Array.isArray(delta.reasoning_details)) {
|
|
53
|
+
for (const detail of delta.reasoning_details) {
|
|
54
|
+
if (isRecord(detail))
|
|
55
|
+
this.mergeReasoningDetail(detail);
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
59
|
+
for (const raw of delta.tool_calls) {
|
|
60
|
+
if (!isRecord(raw))
|
|
61
|
+
continue;
|
|
62
|
+
const started = this.mergeToolCall(raw);
|
|
63
|
+
if (started)
|
|
64
|
+
deltas.push(started);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return deltas;
|
|
68
|
+
}
|
|
69
|
+
mergeToolCall(raw) {
|
|
70
|
+
const fn = isRecord(raw.function) ? raw.function : {};
|
|
71
|
+
const id = str(raw.id);
|
|
72
|
+
let index;
|
|
73
|
+
if (typeof raw.index === "number")
|
|
74
|
+
index = raw.index;
|
|
75
|
+
else if (id && ![...this.calls.values()].some((c) => c.id === id))
|
|
76
|
+
index = this.calls.size;
|
|
77
|
+
else
|
|
78
|
+
index = Math.max(0, this.calls.size - 1);
|
|
79
|
+
let call = this.calls.get(index);
|
|
80
|
+
if (!call) {
|
|
81
|
+
call = { id: "", name: "", arguments: "" };
|
|
82
|
+
this.calls.set(index, call);
|
|
83
|
+
}
|
|
84
|
+
if (id && !call.id)
|
|
85
|
+
call.id = id;
|
|
86
|
+
const named = Boolean(call.name);
|
|
87
|
+
const name = str(fn.name);
|
|
88
|
+
if (name && !call.name)
|
|
89
|
+
call.name = name;
|
|
90
|
+
call.arguments += str(fn.arguments);
|
|
91
|
+
// Announced once, when its name is first known.
|
|
92
|
+
return !named && call.name ? { type: "tool_call", index, name: call.name } : null;
|
|
93
|
+
}
|
|
94
|
+
/** Streamed reasoning blocks share an `index`: their text arrives in pieces. */
|
|
95
|
+
mergeReasoningDetail(detail) {
|
|
96
|
+
const existing = typeof detail.index === "number"
|
|
97
|
+
? this.reasoningDetails.find((d) => d.index === detail.index && d.type === detail.type)
|
|
98
|
+
: undefined;
|
|
99
|
+
if (!existing) {
|
|
100
|
+
this.reasoningDetails.push({ ...detail });
|
|
101
|
+
return;
|
|
102
|
+
}
|
|
103
|
+
for (const [key, value] of Object.entries(detail)) {
|
|
104
|
+
if ((key === "text" || key === "summary") && typeof value === "string") {
|
|
105
|
+
existing[key] = str(existing[key]) + value;
|
|
106
|
+
}
|
|
107
|
+
else if (value !== undefined && value !== null) {
|
|
108
|
+
existing[key] = value;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
get hasToolCalls() {
|
|
113
|
+
return this.calls.size > 0;
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The finished message. With `dropIncomplete` (the reply was cut off), tool calls whose
|
|
117
|
+
* arguments never finished are left out instead of being run with half their input.
|
|
118
|
+
*/
|
|
119
|
+
message({ dropIncomplete = false } = {}) {
|
|
120
|
+
const toolCalls = [];
|
|
121
|
+
let n = 0;
|
|
122
|
+
for (const [, call] of [...this.calls.entries()].sort(([a], [b]) => a - b)) {
|
|
123
|
+
n++;
|
|
124
|
+
if (!call.name)
|
|
125
|
+
continue;
|
|
126
|
+
if (dropIncomplete && !isCompleteArguments(call.arguments))
|
|
127
|
+
continue;
|
|
128
|
+
toolCalls.push({
|
|
129
|
+
id: call.id || `call_${n}`,
|
|
130
|
+
type: "function",
|
|
131
|
+
function: { name: call.name, arguments: call.arguments },
|
|
132
|
+
});
|
|
133
|
+
}
|
|
134
|
+
const message = {
|
|
135
|
+
role: "assistant",
|
|
136
|
+
content: this.content || (toolCalls.length ? null : ""),
|
|
137
|
+
};
|
|
138
|
+
if (toolCalls.length)
|
|
139
|
+
message.tool_calls = toolCalls;
|
|
140
|
+
if (this.reasoning)
|
|
141
|
+
message.reasoning = this.reasoning;
|
|
142
|
+
if (this.reasoningDetails.length)
|
|
143
|
+
message.reasoning_details = this.reasoningDetails;
|
|
144
|
+
return message;
|
|
145
|
+
}
|
|
146
|
+
}
|
|
@@ -0,0 +1,174 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { ApiError } from "../api.js";
|
|
3
|
+
import { createSseParser } from "./sse.js";
|
|
4
|
+
/** Asks the server to stop the reply (and its billing) when we disconnect, e.g. on Esc. */
|
|
5
|
+
export const CANCEL_ON_DISCONNECT_HEADER = "x-reasonally-cancel-on-disconnect";
|
|
6
|
+
/** No response headers within this long means the request is stuck. */
|
|
7
|
+
const CONNECT_TIMEOUT_MS = 90_000;
|
|
8
|
+
/** The server ends replies at about 5 minutes; silence longer than this is a dead connection. */
|
|
9
|
+
const IDLE_TIMEOUT_MS = 6 * 60_000;
|
|
10
|
+
/** The reply stream ended with an error event (the server's deadline, an upstream failure). */
|
|
11
|
+
export class StreamError extends Error {
|
|
12
|
+
code;
|
|
13
|
+
constructor(message, code) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
let userAgent;
|
|
19
|
+
function cliUserAgent() {
|
|
20
|
+
try {
|
|
21
|
+
userAgent ??= `reasonally-cli/${createRequire(import.meta.url)("../../package.json").version}`;
|
|
22
|
+
}
|
|
23
|
+
catch {
|
|
24
|
+
userAgent = "reasonally-cli";
|
|
25
|
+
}
|
|
26
|
+
return userAgent;
|
|
27
|
+
}
|
|
28
|
+
/** `Retry-After` in seconds or as an HTTP date. */
|
|
29
|
+
export function parseRetryAfter(value, now = Date.now()) {
|
|
30
|
+
if (!value)
|
|
31
|
+
return null;
|
|
32
|
+
const seconds = Number(value);
|
|
33
|
+
if (Number.isFinite(seconds) && seconds >= 0)
|
|
34
|
+
return seconds * 1000;
|
|
35
|
+
const date = Date.parse(value);
|
|
36
|
+
return Number.isFinite(date) ? Math.max(0, date - now) : null;
|
|
37
|
+
}
|
|
38
|
+
async function errorFrom(res) {
|
|
39
|
+
const body = (await res.json().catch(() => null));
|
|
40
|
+
const message = typeof body?.error?.message === "string"
|
|
41
|
+
? body.error.message
|
|
42
|
+
: `Request failed with HTTP ${res.status}.`;
|
|
43
|
+
const code = typeof body?.error?.code === "string" ? body.error.code : null;
|
|
44
|
+
return new ApiError(message, res.status, code, parseRetryAfter(res.headers.get("retry-after")));
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Streams `POST /chat/completions`, yielding each parsed chunk. Throws `ApiError` for HTTP errors
|
|
48
|
+
* (status 0 when the server can't be reached), `StreamError` for an error event mid-stream, and
|
|
49
|
+
* the abort reason when `signal` fires.
|
|
50
|
+
*/
|
|
51
|
+
export async function* streamChat(options) {
|
|
52
|
+
const doFetch = options.fetch ?? fetch;
|
|
53
|
+
const controller = new AbortController();
|
|
54
|
+
const abort = () => controller.abort(options.signal.reason);
|
|
55
|
+
if (options.signal.aborted)
|
|
56
|
+
abort();
|
|
57
|
+
options.signal.addEventListener("abort", abort, { once: true });
|
|
58
|
+
let timedOut = false;
|
|
59
|
+
let timer = setTimeout(() => {
|
|
60
|
+
timedOut = true;
|
|
61
|
+
controller.abort();
|
|
62
|
+
}, CONNECT_TIMEOUT_MS);
|
|
63
|
+
const rearm = () => {
|
|
64
|
+
clearTimeout(timer);
|
|
65
|
+
timer = setTimeout(() => {
|
|
66
|
+
timedOut = true;
|
|
67
|
+
controller.abort();
|
|
68
|
+
}, IDLE_TIMEOUT_MS);
|
|
69
|
+
};
|
|
70
|
+
try {
|
|
71
|
+
let res;
|
|
72
|
+
try {
|
|
73
|
+
res = await doFetch(`${options.apiBaseUrl}/chat/completions`, {
|
|
74
|
+
method: "POST",
|
|
75
|
+
headers: {
|
|
76
|
+
authorization: `Bearer ${options.apiKey}`,
|
|
77
|
+
"content-type": "application/json",
|
|
78
|
+
accept: "text/event-stream",
|
|
79
|
+
"user-agent": cliUserAgent(),
|
|
80
|
+
[CANCEL_ON_DISCONNECT_HEADER]: "1",
|
|
81
|
+
},
|
|
82
|
+
body: JSON.stringify(options.body),
|
|
83
|
+
signal: controller.signal,
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
catch (error) {
|
|
87
|
+
if (options.signal.aborted)
|
|
88
|
+
throw options.signal.reason;
|
|
89
|
+
const host = new URL(options.apiBaseUrl).host;
|
|
90
|
+
const why = timedOut ? "no response" : error.message;
|
|
91
|
+
throw new ApiError(`Couldn't reach ${host} (${why}).`, 0, null);
|
|
92
|
+
}
|
|
93
|
+
if (!res.ok)
|
|
94
|
+
throw await errorFrom(res);
|
|
95
|
+
if (!res.body)
|
|
96
|
+
throw new ApiError("The server sent an empty response.", res.status, null);
|
|
97
|
+
rearm();
|
|
98
|
+
const events = [];
|
|
99
|
+
const parser = createSseParser((data) => events.push(data));
|
|
100
|
+
const decoder = new TextDecoder();
|
|
101
|
+
const reader = res.body.getReader();
|
|
102
|
+
try {
|
|
103
|
+
for (;;) {
|
|
104
|
+
let read;
|
|
105
|
+
try {
|
|
106
|
+
read = await reader.read();
|
|
107
|
+
}
|
|
108
|
+
catch (error) {
|
|
109
|
+
if (options.signal.aborted)
|
|
110
|
+
throw options.signal.reason;
|
|
111
|
+
throw new StreamError(timedOut
|
|
112
|
+
? "The connection went quiet."
|
|
113
|
+
: `The connection dropped (${error.message}).`, "connection_lost");
|
|
114
|
+
}
|
|
115
|
+
if (read.done)
|
|
116
|
+
parser.flush();
|
|
117
|
+
else {
|
|
118
|
+
rearm();
|
|
119
|
+
parser.push(decoder.decode(read.value, { stream: true }));
|
|
120
|
+
}
|
|
121
|
+
for (const data of events.splice(0)) {
|
|
122
|
+
if (data === "[DONE]")
|
|
123
|
+
return;
|
|
124
|
+
let payload;
|
|
125
|
+
try {
|
|
126
|
+
payload = JSON.parse(data);
|
|
127
|
+
}
|
|
128
|
+
catch {
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const error = payload.error;
|
|
132
|
+
if (error && typeof error === "object") {
|
|
133
|
+
throw new StreamError(typeof error.message === "string" ? error.message : "The reply failed.", typeof error.code === "string" ? error.code : null);
|
|
134
|
+
}
|
|
135
|
+
yield payload;
|
|
136
|
+
}
|
|
137
|
+
if (read.done)
|
|
138
|
+
return;
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
finally {
|
|
142
|
+
reader.cancel().catch(() => { });
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
finally {
|
|
146
|
+
clearTimeout(timer);
|
|
147
|
+
options.signal.removeEventListener("abort", abort);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const RETRYABLE_STATUS = new Set([0, 408, 409, 425, 429, 500, 502, 503, 504, 529]);
|
|
151
|
+
export const MAX_RETRIES = 5;
|
|
152
|
+
/** A server asking us to wait longer than this is reported instead of waited out. */
|
|
153
|
+
const MAX_RETRY_AFTER_MS = 120_000;
|
|
154
|
+
/**
|
|
155
|
+
* How long to wait before retrying a failed request, or null to give up. Covers being offline,
|
|
156
|
+
* rate limits (honouring `Retry-After`) and server errors; never billing or auth errors.
|
|
157
|
+
*/
|
|
158
|
+
export function retryDelayMs(error, attempt) {
|
|
159
|
+
if (attempt >= MAX_RETRIES)
|
|
160
|
+
return null;
|
|
161
|
+
const backoff = Math.min(1000 * 2 ** attempt, 30_000);
|
|
162
|
+
if (error instanceof ApiError) {
|
|
163
|
+
if (!RETRYABLE_STATUS.has(error.status))
|
|
164
|
+
return null;
|
|
165
|
+
if (error.retryAfterMs !== null) {
|
|
166
|
+
return error.retryAfterMs > MAX_RETRY_AFTER_MS ? null : Math.max(error.retryAfterMs, 500);
|
|
167
|
+
}
|
|
168
|
+
return backoff;
|
|
169
|
+
}
|
|
170
|
+
// An error event or dropped connection before any output: worth another try.
|
|
171
|
+
if (error instanceof StreamError)
|
|
172
|
+
return backoff;
|
|
173
|
+
return null;
|
|
174
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compaction: when the conversation nears the model's context window, earlier turns are replaced
|
|
3
|
+
* by a model-written summary. The pure parts (what to keep, what to send) live here.
|
|
4
|
+
*/
|
|
5
|
+
import { truncateMiddle } from "./tools/types.js";
|
|
6
|
+
/** Compact once the context is this full. */
|
|
7
|
+
export const COMPACT_AT = 0.8;
|
|
8
|
+
/** A rough token count (4 characters per token), for before the server has reported usage. */
|
|
9
|
+
export function estimateTokens(messages) {
|
|
10
|
+
let chars = 0;
|
|
11
|
+
for (const m of messages) {
|
|
12
|
+
chars += typeof m.content === "string" ? m.content.length : 0;
|
|
13
|
+
if (m.role === "assistant" && m.tool_calls) {
|
|
14
|
+
for (const c of m.tool_calls)
|
|
15
|
+
chars += c.function.name.length + c.function.arguments.length;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
return Math.ceil(chars / 4);
|
|
19
|
+
}
|
|
20
|
+
export const shouldCompact = (contextTokens, contextLength) => contextTokens !== null && contextTokens >= contextLength * COMPACT_AT;
|
|
21
|
+
/**
|
|
22
|
+
* Splits the conversation (without the system message) into what gets summarized and what's kept:
|
|
23
|
+
* everything from the latest user message on. Cutting at a user message never separates a tool
|
|
24
|
+
* call from its result. Null when there's nothing earlier to summarize.
|
|
25
|
+
*/
|
|
26
|
+
export function splitForCompaction(messages) {
|
|
27
|
+
const lastUser = messages.map((m) => m.role).lastIndexOf("user");
|
|
28
|
+
if (lastUser <= 0)
|
|
29
|
+
return null;
|
|
30
|
+
return { head: messages.slice(0, lastUser), tail: messages.slice(lastUser) };
|
|
31
|
+
}
|
|
32
|
+
const clip = (text, max) => truncateMiddle(text, max);
|
|
33
|
+
/** The earlier conversation as plain text for the summarizer, within `maxChars`. */
|
|
34
|
+
export function transcriptForSummary(head, maxChars) {
|
|
35
|
+
const parts = [];
|
|
36
|
+
for (const m of head) {
|
|
37
|
+
if (m.role === "user")
|
|
38
|
+
parts.push(`USER:\n${clip(m.content, 8000)}`);
|
|
39
|
+
else if (m.role === "assistant") {
|
|
40
|
+
if (m.content)
|
|
41
|
+
parts.push(`ASSISTANT:\n${clip(m.content, 8000)}`);
|
|
42
|
+
for (const call of m.tool_calls ?? []) {
|
|
43
|
+
parts.push(`TOOL CALL ${call.function.name}: ${clip(call.function.arguments, 1500)}`);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
else if (m.role === "tool")
|
|
47
|
+
parts.push(`TOOL RESULT:\n${clip(m.content, 2000)}`);
|
|
48
|
+
}
|
|
49
|
+
return clip(parts.join("\n\n"), maxChars);
|
|
50
|
+
}
|
|
51
|
+
export const SUMMARY_SYSTEM = "You summarize a coding session between a user and an AI coding agent so the agent can continue " +
|
|
52
|
+
"the work with only your summary. Write it for the agent, in English, as concise Markdown.";
|
|
53
|
+
export const SUMMARY_REQUEST = `Summarize the conversation above. Include:
|
|
54
|
+
- What the user wants: their goals and every request, with constraints and preferences they stated.
|
|
55
|
+
- What has been done: files read, created or changed (with paths), commands run and their outcomes.
|
|
56
|
+
- Decisions made and why, and anything the user declined or asked not to do.
|
|
57
|
+
- The current state: what works, what's broken, errors still open (quote key messages).
|
|
58
|
+
- What remains to do next.
|
|
59
|
+
Keep specifics (paths, names, versions, error text). Leave out pleasantries and repeated detail.`;
|
|
60
|
+
export const SUMMARY_PREFIX = "[Summary of the conversation so far]";
|
|
61
|
+
/** The conversation after compaction: the summary leads the first kept user message. */
|
|
62
|
+
export function compactedMessages(summary, tail, todos) {
|
|
63
|
+
const todoText = todos.length
|
|
64
|
+
? `\n\nCurrent todo list:\n${todos.map((t) => `- [${t.status}] ${t.content}`).join("\n")}`
|
|
65
|
+
: "";
|
|
66
|
+
const [first, ...rest] = tail;
|
|
67
|
+
const lead = `${SUMMARY_PREFIX}\n${summary.trim()}${todoText}\n\n[Latest message]\n`;
|
|
68
|
+
if (first?.role !== "user") {
|
|
69
|
+
return [{ role: "user", content: `${lead}(none)` }, ...tail];
|
|
70
|
+
}
|
|
71
|
+
return [{ role: "user", content: lead + first.content }, ...rest];
|
|
72
|
+
}
|
|
73
|
+
/** Whether an error says the request was too long for the model's context. */
|
|
74
|
+
export function isContextOverflow(error) {
|
|
75
|
+
const e = error;
|
|
76
|
+
if (e?.status !== 400 || typeof e.message !== "string")
|
|
77
|
+
return false;
|
|
78
|
+
return /context (length|window)|too (long|many tokens)|maximum (context|number of tokens)|prompt is too long/i.test(e.message);
|
|
79
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const ceilDiv = (a, b) => (a + b - 1n) / b;
|
|
2
|
+
/** What a request cost, as the server bills it: tokens × price per million, each rounded up. */
|
|
3
|
+
export function costMicros(usage, prices) {
|
|
4
|
+
return (ceilDiv(BigInt(usage.promptTokens) * prices.inputMicrosPerM, 1000000n) +
|
|
5
|
+
ceilDiv(BigInt(usage.completionTokens) * prices.outputMicrosPerM, 1000000n));
|
|
6
|
+
}
|
|
7
|
+
/**
|
|
8
|
+
* "$1.23" from micro-dollars, rounded to the cent; amounts under a cent get up to four decimals
|
|
9
|
+
* ("$0.0042") so a cheap session doesn't read as free.
|
|
10
|
+
*/
|
|
11
|
+
export function formatUsd(micros) {
|
|
12
|
+
if (micros < 0n)
|
|
13
|
+
return `-${formatUsd(-micros)}`;
|
|
14
|
+
const decimals = micros > 0n && micros < 10000n ? 4 : 2;
|
|
15
|
+
const unit = 10n ** BigInt(6 - decimals);
|
|
16
|
+
const rounded = (micros + unit / 2n) / unit; // half up
|
|
17
|
+
const scale = 10n ** BigInt(decimals);
|
|
18
|
+
const whole = rounded / scale;
|
|
19
|
+
const frac = (rounded % scale).toString().padStart(decimals, "0");
|
|
20
|
+
const text = `$${whole.toLocaleString("en-US")}.${frac}`;
|
|
21
|
+
return decimals === 4 && rounded === 0n ? "<$0.0001" : text;
|
|
22
|
+
}
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
/** Notes the agent adds to the conversation itself (also recognized when reprinting sessions). */
|
|
2
|
+
export const INTERRUPTED_NOTE = "[The user interrupted your previous response.]";
|
|
3
|
+
export const CONTINUE_PROMPT = "Your last response was cut off. Continue exactly where you stopped.";
|