reasonally 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,16 +1,143 @@
1
1
  # reasonally
2
2
 
3
- Run the coding agents you already use on Reasonally models, billed to your Reasonally workspace.
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
- reasonally login # approve this computer in your browser
8
- reasonally opencode --model anthropic/claude-sonnet-4.5
8
+ cd my-project
9
+ reasonally # log in (first time), pick a model, start coding
9
10
  ```
10
11
 
11
- Needs Node.js 20 or later.
12
+ The agent needs Node.js 22.19 or later; everything else works on Node.js 20 or later.
12
13
 
13
- ## Agents
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
+ | Plan mode (`--plan`) | none until you approve plan | look-only commands run; rest asks |
41
+ | Don't ask (`--yes`) | auto | auto |
42
+
43
+ - Reading files in your project never asks. Reading or changing anything outside it asks, except in
44
+ "Don't ask".
45
+ - `.env` files and `~/.ssh`, `~/.aws` and `~/.gnupg` ask in every mode. The file holding this
46
+ computer's Reasonally key is never opened.
47
+ - Approved commands run with your permissions, like commands you type. There's no sandbox, so read
48
+ what a command does before approving it, and use "Don't ask" only in projects you trust.
49
+ - Commands run without your Reasonally key in their environment, and pagers are turned off.
50
+
51
+ ### Plan mode
52
+
53
+ The agent looks around and writes a plan, and nothing changes until you approve it:
54
+
55
+ - Commands that only look (`git status`, `git log`, `git diff`, `ls`, `cat`, `rg`…) run without
56
+ asking when every file they name is in your project. Anything else asks, every time.
57
+ - The plan streams in as it's written, then asks **Ready to build?**: `y` builds asking before each
58
+ edit, `a` auto-accepts edits, `n` tells it what to change, `ctrl+g` opens the plan in your editor
59
+ (`$VISUAL` or `$EDITOR`) so you can change it first, and Esc stops.
60
+ - Approving switches to the mode you picked, and the agent starts right away.
61
+
62
+ ### Keys
63
+
64
+ | Key | Does |
65
+ | --------------------- | --------------------------------------------------------- |
66
+ | Enter | Send. Shift+Enter or Ctrl+J for a new line |
67
+ | Esc | Stop the reply and any running command; billing stops too |
68
+ | Shift+Tab | Switch mode |
69
+ | Ctrl+O | Show the full output or diff of the last step |
70
+ | Ctrl+G | Edit a waiting plan in your editor |
71
+ | Ctrl+C | Clear the input; press twice to quit (Ctrl+D also quits) |
72
+ | `@` | Mention a file |
73
+ | Typing while it works | Queues your message for when the current step finishes |
74
+
75
+ ### Commands
76
+
77
+ | Command | Does |
78
+ | ---------- | ------------------------------------------------------- |
79
+ | `/model` | Switch model (only models that can use tools are shown) |
80
+ | `/mode` | Switch mode (`/mode plan` goes straight to Plan mode) |
81
+ | `/new` | Start a new conversation |
82
+ | `/resume` | Continue an earlier conversation in this folder |
83
+ | `/compact` | Summarize the conversation so far to free up context |
84
+ | `/cost` | This session's cost and your balance |
85
+ | `/mcp` | MCP servers and their tools |
86
+ | `/login` | Log in again |
87
+ | `/help` | Commands and keys |
88
+ | `/exit` | Quit |
89
+
90
+ ### Conversations
91
+
92
+ Every conversation is saved as it happens, in `~/.config/reasonally/sessions/`.
93
+
94
+ ```bash
95
+ reasonally --continue # pick up the last conversation in this folder
96
+ reasonally --resume # choose one
97
+ ```
98
+
99
+ When a conversation fills about 80% of the model's context window, earlier turns are summarized
100
+ automatically (or now, with `/compact`).
101
+
102
+ ### Project instructions
103
+
104
+ The agent follows `AGENTS.md` and `CLAUDE.md` files from your repository's root down to the folder
105
+ you're in, and your own `~/.config/reasonally/AGENTS.md` for every project.
106
+
107
+ ### Helpers
108
+
109
+ For broad searches or independent pieces of work, the agent can start helpers that work with fresh
110
+ context and report back, up to four at once. Helpers read freely; their edits and commands always
111
+ ask (except in "Don't ask"), and in Plan mode they change nothing.
112
+
113
+ ### MCP servers
114
+
115
+ Add servers to `~/.config/reasonally/mcp.json`:
116
+
117
+ ```json
118
+ {
119
+ "mcpServers": {
120
+ "github": {
121
+ "command": "npx",
122
+ "args": ["-y", "@modelcontextprotocol/server-github"],
123
+ "env": { "GITHUB_PERSONAL_ACCESS_TOKEN": "…" }
124
+ },
125
+ "docs": { "url": "https://example.com/mcp", "headers": { "Authorization": "Bearer …" } }
126
+ }
127
+ }
128
+ ```
129
+
130
+ Their tools ask before each use (except in "Don't ask"). Project folders are never read for MCP
131
+ servers, so opening a repository can't start a program it names.
132
+
133
+ ### Cost
134
+
135
+ The status line shows the session's estimated cost and your balance; exact charges are on your
136
+ dashboard's Usage page. Pressing Esc stops the reply and its billing.
137
+
138
+ ## Other agents
139
+
140
+ Run the coding agents you already use on Reasonally models:
14
141
 
15
142
  | Command | Agent |
16
143
  | --------------------- | ----------------------------------------------------- |
@@ -69,3 +196,8 @@ Google Chrome (or Edge, or a Chromium from `npx playwright install chromium`). N
69
196
  | `REASONALLY_API_KEY` | Use an existing API key instead of logging in (CI, servers). |
70
197
  | `REASONALLY_URL` | Dashboard URL (default `https://app.reasonally.ai`). |
71
198
  | `REASONALLY_API_URL` | API base URL (default `https://api.reasonally.ai/v1`). |
199
+ | `NO_COLOR` | Turn off colors in the agent. |
200
+
201
+ ## Platforms
202
+
203
+ macOS and Linux. Windows should work (commands run in PowerShell) but hasn't been tested yet.
@@ -0,0 +1,150 @@
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
+ /** A tool call's arguments as streamed so far ("" before any). */
113
+ argumentsOf(index) {
114
+ return this.calls.get(index)?.arguments ?? "";
115
+ }
116
+ get hasToolCalls() {
117
+ return this.calls.size > 0;
118
+ }
119
+ /**
120
+ * The finished message. With `dropIncomplete` (the reply was cut off), tool calls whose
121
+ * arguments never finished are left out instead of being run with half their input.
122
+ */
123
+ message({ dropIncomplete = false } = {}) {
124
+ const toolCalls = [];
125
+ let n = 0;
126
+ for (const [, call] of [...this.calls.entries()].sort(([a], [b]) => a - b)) {
127
+ n++;
128
+ if (!call.name)
129
+ continue;
130
+ if (dropIncomplete && !isCompleteArguments(call.arguments))
131
+ continue;
132
+ toolCalls.push({
133
+ id: call.id || `call_${n}`,
134
+ type: "function",
135
+ function: { name: call.name, arguments: call.arguments },
136
+ });
137
+ }
138
+ const message = {
139
+ role: "assistant",
140
+ content: this.content || (toolCalls.length ? null : ""),
141
+ };
142
+ if (toolCalls.length)
143
+ message.tool_calls = toolCalls;
144
+ if (this.reasoning)
145
+ message.reasoning = this.reasoning;
146
+ if (this.reasoningDetails.length)
147
+ message.reasoning_details = this.reasoningDetails;
148
+ return message;
149
+ }
150
+ }
@@ -0,0 +1,176 @@
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": options.client
80
+ ? `${options.client.name}/${options.client.version}`
81
+ : cliUserAgent(),
82
+ [CANCEL_ON_DISCONNECT_HEADER]: "1",
83
+ },
84
+ body: JSON.stringify(options.body),
85
+ signal: controller.signal,
86
+ });
87
+ }
88
+ catch (error) {
89
+ if (options.signal.aborted)
90
+ throw options.signal.reason;
91
+ const host = new URL(options.apiBaseUrl).host;
92
+ const why = timedOut ? "no response" : error.message;
93
+ throw new ApiError(`Couldn't reach ${host} (${why}).`, 0, null);
94
+ }
95
+ if (!res.ok)
96
+ throw await errorFrom(res);
97
+ if (!res.body)
98
+ throw new ApiError("The server sent an empty response.", res.status, null);
99
+ rearm();
100
+ const events = [];
101
+ const parser = createSseParser((data) => events.push(data));
102
+ const decoder = new TextDecoder();
103
+ const reader = res.body.getReader();
104
+ try {
105
+ for (;;) {
106
+ let read;
107
+ try {
108
+ read = await reader.read();
109
+ }
110
+ catch (error) {
111
+ if (options.signal.aborted)
112
+ throw options.signal.reason;
113
+ throw new StreamError(timedOut
114
+ ? "The connection went quiet."
115
+ : `The connection dropped (${error.message}).`, "connection_lost");
116
+ }
117
+ if (read.done)
118
+ parser.flush();
119
+ else {
120
+ rearm();
121
+ parser.push(decoder.decode(read.value, { stream: true }));
122
+ }
123
+ for (const data of events.splice(0)) {
124
+ if (data === "[DONE]")
125
+ return;
126
+ let payload;
127
+ try {
128
+ payload = JSON.parse(data);
129
+ }
130
+ catch {
131
+ continue;
132
+ }
133
+ const error = payload.error;
134
+ if (error && typeof error === "object") {
135
+ throw new StreamError(typeof error.message === "string" ? error.message : "The reply failed.", typeof error.code === "string" ? error.code : null);
136
+ }
137
+ yield payload;
138
+ }
139
+ if (read.done)
140
+ return;
141
+ }
142
+ }
143
+ finally {
144
+ reader.cancel().catch(() => { });
145
+ }
146
+ }
147
+ finally {
148
+ clearTimeout(timer);
149
+ options.signal.removeEventListener("abort", abort);
150
+ }
151
+ }
152
+ const RETRYABLE_STATUS = new Set([0, 408, 409, 425, 429, 500, 502, 503, 504, 529]);
153
+ export const MAX_RETRIES = 5;
154
+ /** A server asking us to wait longer than this is reported instead of waited out. */
155
+ const MAX_RETRY_AFTER_MS = 120_000;
156
+ /**
157
+ * How long to wait before retrying a failed request, or null to give up. Covers being offline,
158
+ * rate limits (honouring `Retry-After`) and server errors; never billing or auth errors.
159
+ */
160
+ export function retryDelayMs(error, attempt) {
161
+ if (attempt >= MAX_RETRIES)
162
+ return null;
163
+ const backoff = Math.min(1000 * 2 ** attempt, 30_000);
164
+ if (error instanceof ApiError) {
165
+ if (!RETRYABLE_STATUS.has(error.status))
166
+ return null;
167
+ if (error.retryAfterMs !== null) {
168
+ return error.retryAfterMs > MAX_RETRY_AFTER_MS ? null : Math.max(error.retryAfterMs, 500);
169
+ }
170
+ return backoff;
171
+ }
172
+ // An error event or dropped connection before any output: worth another try.
173
+ if (error instanceof StreamError)
174
+ return backoff;
175
+ return null;
176
+ }
@@ -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,11 @@
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.";
4
+ /** Told to the model when Plan mode starts applying (before a message, or after a tool result). */
5
+ export const PLAN_ON_NOTE = "[Plan mode is on: look around and plan, but don't change anything. When the plan is ready, present it with present_plan.]";
6
+ /** The same for helpers, which report back instead of presenting a plan. */
7
+ export const HELPER_PLAN_ON_NOTE = "[Plan mode is on: look around, but don't change anything. Report what you find.]";
8
+ /** Told to the model when Plan mode stops applying without a plan being approved. */
9
+ export const PLAN_OFF_NOTE = "[Plan mode is off: carry on as usual.]";
10
+ /** How an approved plan's tool result starts (the mode it switched to follows). */
11
+ export const PLAN_APPROVED = "The user approved your plan";