reasonally 0.3.0 → 0.5.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 +33 -7
- package/dist/agent/accumulate.js +4 -0
- package/dist/agent/client.js +53 -1
- package/dist/agent/loop-constants.js +8 -0
- package/dist/agent/loop.js +243 -34
- package/dist/agent/mcp.js +3 -2
- package/dist/agent/permissions.js +99 -3
- package/dist/agent/prompt.js +16 -2
- package/dist/agent/readonly-command.js +315 -0
- package/dist/agent/session.js +234 -12
- package/dist/agent/tools/bash.js +22 -2
- package/dist/agent/tools/index.js +11 -0
- package/dist/agent/tools/plan.js +101 -0
- package/dist/agent/tools/task.js +2 -2
- package/dist/agent/tools/web/ddg.js +131 -0
- package/dist/agent/tools/web/dom.js +9 -0
- package/dist/agent/tools/web/html.js +90 -0
- package/dist/agent/tools/web/page.js +218 -0
- package/dist/agent/tools/web-fetch.js +175 -0
- package/dist/agent/tools/web-search.js +158 -0
- package/dist/api.js +3 -1
- package/dist/cli.js +1 -1
- package/dist/login.js +41 -13
- package/dist/tui/app.js +176 -30
- package/dist/tui/args.js +16 -1
- package/dist/tui/commands.js +5 -1
- package/dist/tui/components.js +105 -1
- package/dist/tui/external-editor.js +103 -0
- package/dist/tui/format.js +9 -1
- package/dist/tui/start.js +10 -4
- package/package.json +5 -2
package/README.md
CHANGED
|
@@ -33,11 +33,12 @@ the conversation stays on screen after you quit.
|
|
|
33
33
|
|
|
34
34
|
### Asking before acting
|
|
35
35
|
|
|
36
|
-
| Mode (Shift+Tab switches) | Edits
|
|
37
|
-
| -------------------------- |
|
|
38
|
-
| Ask before edits (default) | ask
|
|
39
|
-
| Auto-accept edits | auto
|
|
40
|
-
|
|
|
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 |
|
|
41
42
|
|
|
42
43
|
- Reading files in your project never asks. Reading or changing anything outside it asks, except in
|
|
43
44
|
"Don't ask".
|
|
@@ -47,6 +48,30 @@ the conversation stays on screen after you quit.
|
|
|
47
48
|
what a command does before approving it, and use "Don't ask" only in projects you trust.
|
|
48
49
|
- Commands run without your Reasonally key in their environment, and pagers are turned off.
|
|
49
50
|
|
|
51
|
+
### The web
|
|
52
|
+
|
|
53
|
+
The agent can search the web and read pages, for current docs, releases and error messages. Both
|
|
54
|
+
are free.
|
|
55
|
+
|
|
56
|
+
- **Searching** runs without asking. Searches start from your computer; if that doesn't work,
|
|
57
|
+
Reasonally searches for you.
|
|
58
|
+
- **Reading a page** asks once per site (`y` yes, `a` yes and don't ask again for that site, `n` no).
|
|
59
|
+
Links you paste open without asking, and "Don't ask" (`--yes`) never asks.
|
|
60
|
+
- Pages are read from your computer. Addresses on your computer or local network are never opened;
|
|
61
|
+
the agent can use `curl` for those, which asks like any command.
|
|
62
|
+
- `reasonally --no-web` starts without either.
|
|
63
|
+
|
|
64
|
+
### Plan mode
|
|
65
|
+
|
|
66
|
+
The agent looks around and writes a plan, and nothing changes until you approve it:
|
|
67
|
+
|
|
68
|
+
- Commands that only look (`git status`, `git log`, `git diff`, `ls`, `cat`, `rg`…) run without
|
|
69
|
+
asking when every file they name is in your project. Anything else asks, every time.
|
|
70
|
+
- The plan streams in as it's written, then asks **Ready to build?**: `y` builds asking before each
|
|
71
|
+
edit, `a` auto-accepts edits, `n` tells it what to change, `ctrl+g` opens the plan in your editor
|
|
72
|
+
(`$VISUAL` or `$EDITOR`) so you can change it first, and Esc stops.
|
|
73
|
+
- Approving switches to the mode you picked, and the agent starts right away.
|
|
74
|
+
|
|
50
75
|
### Keys
|
|
51
76
|
|
|
52
77
|
| Key | Does |
|
|
@@ -55,6 +80,7 @@ the conversation stays on screen after you quit.
|
|
|
55
80
|
| Esc | Stop the reply and any running command; billing stops too |
|
|
56
81
|
| Shift+Tab | Switch mode |
|
|
57
82
|
| Ctrl+O | Show the full output or diff of the last step |
|
|
83
|
+
| Ctrl+G | Edit a waiting plan in your editor |
|
|
58
84
|
| Ctrl+C | Clear the input; press twice to quit (Ctrl+D also quits) |
|
|
59
85
|
| `@` | Mention a file |
|
|
60
86
|
| Typing while it works | Queues your message for when the current step finishes |
|
|
@@ -64,7 +90,7 @@ the conversation stays on screen after you quit.
|
|
|
64
90
|
| Command | Does |
|
|
65
91
|
| ---------- | ------------------------------------------------------- |
|
|
66
92
|
| `/model` | Switch model (only models that can use tools are shown) |
|
|
67
|
-
| `/mode` | Switch mode
|
|
93
|
+
| `/mode` | Switch mode (`/mode plan` goes straight to Plan mode) |
|
|
68
94
|
| `/new` | Start a new conversation |
|
|
69
95
|
| `/resume` | Continue an earlier conversation in this folder |
|
|
70
96
|
| `/compact` | Summarize the conversation so far to free up context |
|
|
@@ -95,7 +121,7 @@ you're in, and your own `~/.config/reasonally/AGENTS.md` for every project.
|
|
|
95
121
|
|
|
96
122
|
For broad searches or independent pieces of work, the agent can start helpers that work with fresh
|
|
97
123
|
context and report back, up to four at once. Helpers read freely; their edits and commands always
|
|
98
|
-
ask (except in "Don't ask").
|
|
124
|
+
ask (except in "Don't ask"), and in Plan mode they change nothing.
|
|
99
125
|
|
|
100
126
|
### MCP servers
|
|
101
127
|
|
package/dist/agent/accumulate.js
CHANGED
|
@@ -109,6 +109,10 @@ export class MessageAccumulator {
|
|
|
109
109
|
}
|
|
110
110
|
}
|
|
111
111
|
}
|
|
112
|
+
/** A tool call's arguments as streamed so far ("" before any). */
|
|
113
|
+
argumentsOf(index) {
|
|
114
|
+
return this.calls.get(index)?.arguments ?? "";
|
|
115
|
+
}
|
|
112
116
|
get hasToolCalls() {
|
|
113
117
|
return this.calls.size > 0;
|
|
114
118
|
}
|
package/dist/agent/client.js
CHANGED
|
@@ -16,6 +16,10 @@ export class StreamError extends Error {
|
|
|
16
16
|
}
|
|
17
17
|
}
|
|
18
18
|
let userAgent;
|
|
19
|
+
/** The user agent for our own requests: the host app's name and version, or the CLI's. */
|
|
20
|
+
export const userAgentFor = (client) => client ? `${client.name}/${client.version}` : cliUserAgent();
|
|
21
|
+
/** For requests to websites: browser-compatible, and names the app honestly. */
|
|
22
|
+
export const webUserAgent = (client) => `Mozilla/5.0 (compatible; ${userAgentFor(client)})`;
|
|
19
23
|
function cliUserAgent() {
|
|
20
24
|
try {
|
|
21
25
|
userAgent ??= `reasonally-cli/${createRequire(import.meta.url)("../../package.json").version}`;
|
|
@@ -76,7 +80,7 @@ export async function* streamChat(options) {
|
|
|
76
80
|
authorization: `Bearer ${options.apiKey}`,
|
|
77
81
|
"content-type": "application/json",
|
|
78
82
|
accept: "text/event-stream",
|
|
79
|
-
"user-agent":
|
|
83
|
+
"user-agent": userAgentFor(options.client),
|
|
80
84
|
[CANCEL_ON_DISCONNECT_HEADER]: "1",
|
|
81
85
|
},
|
|
82
86
|
body: JSON.stringify(options.body),
|
|
@@ -147,6 +151,54 @@ export async function* streamChat(options) {
|
|
|
147
151
|
options.signal.removeEventListener("abort", abort);
|
|
148
152
|
}
|
|
149
153
|
}
|
|
154
|
+
/** How long the fallback search may take (the server gives its provider 6 s). */
|
|
155
|
+
const SEARCH_TIMEOUT_MS = 12_000;
|
|
156
|
+
/**
|
|
157
|
+
* Runs `POST /web/search`. Throws `ApiError` for HTTP errors (status 0 when the server can't be
|
|
158
|
+
* reached or took too long), and the abort reason when `signal` fires.
|
|
159
|
+
*/
|
|
160
|
+
export async function searchWeb(options) {
|
|
161
|
+
const doFetch = options.fetch ?? fetch;
|
|
162
|
+
const timeout = AbortSignal.timeout(SEARCH_TIMEOUT_MS);
|
|
163
|
+
let res;
|
|
164
|
+
try {
|
|
165
|
+
res = await doFetch(`${options.apiBaseUrl}/web/search`, {
|
|
166
|
+
method: "POST",
|
|
167
|
+
headers: {
|
|
168
|
+
authorization: `Bearer ${options.apiKey}`,
|
|
169
|
+
"content-type": "application/json",
|
|
170
|
+
"user-agent": userAgentFor(options.client),
|
|
171
|
+
},
|
|
172
|
+
body: JSON.stringify(options.body),
|
|
173
|
+
signal: AbortSignal.any([options.signal, timeout]),
|
|
174
|
+
});
|
|
175
|
+
}
|
|
176
|
+
catch (error) {
|
|
177
|
+
if (options.signal.aborted)
|
|
178
|
+
throw options.signal.reason;
|
|
179
|
+
const why = timeout.aborted ? "no response" : error.message;
|
|
180
|
+
throw new ApiError(`Couldn't reach Reasonally's search (${why}).`, 0, null);
|
|
181
|
+
}
|
|
182
|
+
if (!res.ok)
|
|
183
|
+
throw await errorFrom(res);
|
|
184
|
+
const body = (await res.json().catch(() => null));
|
|
185
|
+
if (!body || !Array.isArray(body.results)) {
|
|
186
|
+
throw new ApiError("Reasonally's search sent an unexpected response.", res.status, null);
|
|
187
|
+
}
|
|
188
|
+
return body.results.flatMap((r) => {
|
|
189
|
+
const item = r;
|
|
190
|
+
if (typeof item.url !== "string" || typeof item.title !== "string")
|
|
191
|
+
return [];
|
|
192
|
+
return [
|
|
193
|
+
{
|
|
194
|
+
title: item.title,
|
|
195
|
+
url: item.url,
|
|
196
|
+
snippet: typeof item.snippet === "string" ? item.snippet : "",
|
|
197
|
+
published: typeof item.published === "string" ? item.published : null,
|
|
198
|
+
},
|
|
199
|
+
];
|
|
200
|
+
});
|
|
201
|
+
}
|
|
150
202
|
const RETRYABLE_STATUS = new Set([0, 408, 409, 425, 429, 500, 502, 503, 504, 529]);
|
|
151
203
|
export const MAX_RETRIES = 5;
|
|
152
204
|
/** A server asking us to wait longer than this is reported instead of waited out. */
|
|
@@ -1,3 +1,11 @@
|
|
|
1
1
|
/** Notes the agent adds to the conversation itself (also recognized when reprinting sessions). */
|
|
2
2
|
export const INTERRUPTED_NOTE = "[The user interrupted your previous response.]";
|
|
3
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";
|
package/dist/agent/loop.js
CHANGED
|
@@ -1,18 +1,44 @@
|
|
|
1
1
|
import { MessageAccumulator } from "./accumulate.js";
|
|
2
|
-
import { retryDelayMs, StreamError, streamChat } from "./client.js";
|
|
2
|
+
import { retryDelayMs, searchWeb, StreamError, streamChat, webUserAgent, } from "./client.js";
|
|
3
3
|
import { compactedMessages, estimateTokens, isContextOverflow, shouldCompact, splitForCompaction, SUMMARY_REQUEST, SUMMARY_SYSTEM, transcriptForSummary, } from "./compact.js";
|
|
4
4
|
import { costMicros } from "./cost.js";
|
|
5
|
-
import { alwaysLabel, decide, rememberAllow, } from "./permissions.js";
|
|
5
|
+
import { alwaysLabel, decide, hostsIn, MODE_LABELS, rememberAllow, } from "./permissions.js";
|
|
6
6
|
import { toolSchemas } from "./tools/index.js";
|
|
7
|
+
import { MAX_PLAN_CHARS, partialPlan, PLAN_OUTCOME_LABELS, PLAN_TOOL, } from "./tools/plan.js";
|
|
7
8
|
import { HELPER_NOTE, MAX_PARALLEL_HELPERS } from "./tools/task.js";
|
|
9
|
+
import { WEB_FETCH_TOOL } from "./tools/web-fetch.js";
|
|
10
|
+
import { WEB_SEARCH_TOOL } from "./tools/web-search.js";
|
|
8
11
|
import { ToolInputError, truncateMiddle, } from "./tools/types.js";
|
|
12
|
+
/** A web tool the user turned off (a model may still try one it used earlier in the thread). */
|
|
13
|
+
const TURNED_OFF = {
|
|
14
|
+
[WEB_SEARCH_TOOL]: "Web search is turned off.",
|
|
15
|
+
[WEB_FETCH_TOOL]: "Reading web pages is turned off.",
|
|
16
|
+
};
|
|
9
17
|
/** Per request; keeps credit holds modest when several requests run at once. */
|
|
10
18
|
export const MAX_OUTPUT_TOKENS = 32_000;
|
|
11
19
|
/** Model calls per user message before the agent stops and asks. */
|
|
12
20
|
export const MAX_STEPS = 200;
|
|
13
21
|
const MAX_TOOL_OUTPUT_CHARS = 50_000;
|
|
14
|
-
import { CONTINUE_PROMPT, INTERRUPTED_NOTE } from "./loop-constants.js";
|
|
22
|
+
import { CONTINUE_PROMPT, HELPER_PLAN_ON_NOTE, INTERRUPTED_NOTE, PLAN_APPROVED, PLAN_OFF_NOTE, PLAN_ON_NOTE, } from "./loop-constants.js";
|
|
15
23
|
export { CONTINUE_PROMPT, INTERRUPTED_NOTE };
|
|
24
|
+
/** Plan drafts are sent to the screen at most this often while the model writes. */
|
|
25
|
+
const PLAN_DRAFT_EVERY_MS = 50;
|
|
26
|
+
/**
|
|
27
|
+
* Whether the conversation last told the model Plan mode was on: the latest mode note, or an
|
|
28
|
+
* approved plan (which switched it off). False when it was never mentioned.
|
|
29
|
+
*/
|
|
30
|
+
export function lastToldPlan(messages) {
|
|
31
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
32
|
+
const m = messages[i];
|
|
33
|
+
if ((m.role !== "user" && m.role !== "tool") || typeof m.content !== "string")
|
|
34
|
+
continue;
|
|
35
|
+
const on = Math.max(m.content.lastIndexOf(PLAN_ON_NOTE), m.content.lastIndexOf(HELPER_PLAN_ON_NOTE));
|
|
36
|
+
const off = Math.max(m.content.lastIndexOf(PLAN_OFF_NOTE), m.content.startsWith(PLAN_APPROVED) ? 0 : -1);
|
|
37
|
+
if (on !== -1 || off !== -1)
|
|
38
|
+
return on > off;
|
|
39
|
+
}
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
16
42
|
/** Resolves after `ms`, or rejects with the abort reason. */
|
|
17
43
|
export function sleep(ms, signal) {
|
|
18
44
|
return new Promise((resolve, reject) => {
|
|
@@ -51,13 +77,32 @@ export class Agent {
|
|
|
51
77
|
/** The last request's usage: its prompt plus output is the context in use. */
|
|
52
78
|
lastUsage = null;
|
|
53
79
|
interrupted = false;
|
|
80
|
+
/** Whether the model was last told Plan mode is on (see `modeNote`). */
|
|
81
|
+
toldPlan = false;
|
|
82
|
+
/** Whether the current model call has shown a plan draft. */
|
|
83
|
+
planDrafted = false;
|
|
54
84
|
/** A token estimate after compaction, until the server reports usage again. */
|
|
55
85
|
estimatedTokens = null;
|
|
56
86
|
sleep;
|
|
87
|
+
/** What the web tools use: credentials are read when a search runs, so a new key applies. */
|
|
88
|
+
web;
|
|
57
89
|
constructor(options) {
|
|
58
90
|
this.options = options;
|
|
59
91
|
this.messages = [{ role: "system", content: options.systemPrompt }];
|
|
60
92
|
this.sleep = options.sleep ?? sleep;
|
|
93
|
+
this.web = {
|
|
94
|
+
fetch: (input, init) => (this.options.webFetch ?? fetch)(input, init),
|
|
95
|
+
fallback: (body, signal) => searchWeb({
|
|
96
|
+
apiBaseUrl: this.options.apiBaseUrl,
|
|
97
|
+
apiKey: this.options.apiKey,
|
|
98
|
+
body,
|
|
99
|
+
signal,
|
|
100
|
+
fetch: this.options.fetch,
|
|
101
|
+
client: this.options.client,
|
|
102
|
+
}),
|
|
103
|
+
userAgent: webUserAgent(options.client),
|
|
104
|
+
transport: options.webTransport,
|
|
105
|
+
};
|
|
61
106
|
}
|
|
62
107
|
get model() {
|
|
63
108
|
return this.options.model;
|
|
@@ -79,6 +124,7 @@ export class Agent {
|
|
|
79
124
|
/** Picks up a saved conversation (resume). Its earlier cost isn't counted again. */
|
|
80
125
|
restore(messages) {
|
|
81
126
|
this.messages.splice(1, this.messages.length - 1, ...messages);
|
|
127
|
+
this.toldPlan = lastToldPlan(messages);
|
|
82
128
|
this.lastUsage = null;
|
|
83
129
|
this.estimatedTokens = messages.length ? estimateTokens(this.messages) : null;
|
|
84
130
|
}
|
|
@@ -86,16 +132,47 @@ export class Agent {
|
|
|
86
132
|
async *send(text, signal) {
|
|
87
133
|
const content = this.interrupted ? `${INTERRUPTED_NOTE}\n\n${text}` : text;
|
|
88
134
|
this.interrupted = false;
|
|
135
|
+
// Pages on sites the user links to open without asking. (A helper's prompt is the model's.)
|
|
136
|
+
if (!this.options.isHelper) {
|
|
137
|
+
for (const host of hostsIn(text))
|
|
138
|
+
this.options.permissions.allows.hosts.add(host);
|
|
139
|
+
}
|
|
140
|
+
const note = this.modeNote();
|
|
89
141
|
const last = this.messages.at(-1);
|
|
90
142
|
// After a failed request the user's message is still last: add to it.
|
|
91
143
|
if (last?.role === "user") {
|
|
92
|
-
|
|
144
|
+
const merged = `${last.content}\n\n${content}`;
|
|
145
|
+
last.content = note ? `${note}\n\n${merged}` : merged;
|
|
93
146
|
this.replaceAll(this.messages.slice(1), "merge");
|
|
94
147
|
}
|
|
95
148
|
else
|
|
96
|
-
this.append({ role: "user", content });
|
|
149
|
+
this.append({ role: "user", content: note ? `${note}\n\n${content}` : content });
|
|
97
150
|
yield* this.work(signal);
|
|
98
151
|
}
|
|
152
|
+
/**
|
|
153
|
+
* A note for the model when Plan mode starts or stops applying, else null. The note goes in
|
|
154
|
+
* front of the next user message or after the next tool result, so the system prompt and the
|
|
155
|
+
* tool list never change (which keeps the provider's prompt cache).
|
|
156
|
+
*/
|
|
157
|
+
modeNote() {
|
|
158
|
+
const planning = this.options.permissions.mode === "plan";
|
|
159
|
+
if (planning === this.toldPlan)
|
|
160
|
+
return null;
|
|
161
|
+
this.toldPlan = planning;
|
|
162
|
+
if (!planning)
|
|
163
|
+
return PLAN_OFF_NOTE;
|
|
164
|
+
return this.options.isHelper ? HELPER_PLAN_ON_NOTE : PLAN_ON_NOTE;
|
|
165
|
+
}
|
|
166
|
+
/** Adds a tool result (with a mode note when the mode changed since the model last heard). */
|
|
167
|
+
appendToolResult(callId, output) {
|
|
168
|
+
const content = truncateMiddle(output, MAX_TOOL_OUTPUT_CHARS);
|
|
169
|
+
const note = this.modeNote();
|
|
170
|
+
this.append({
|
|
171
|
+
role: "tool",
|
|
172
|
+
tool_call_id: callId,
|
|
173
|
+
content: note ? `${content}\n\n${note}` : content,
|
|
174
|
+
});
|
|
175
|
+
}
|
|
99
176
|
/** Tries again after an error, without a new message (e.g. after adding credits). */
|
|
100
177
|
async *retry(signal) {
|
|
101
178
|
yield* this.work(signal);
|
|
@@ -118,9 +195,17 @@ export class Agent {
|
|
|
118
195
|
}
|
|
119
196
|
}
|
|
120
197
|
yield { type: "model_start" };
|
|
198
|
+
this.planDrafted = false;
|
|
121
199
|
const outcome = yield* this.callModel(signal);
|
|
122
200
|
const { acc } = outcome;
|
|
123
201
|
const cost = this.recordUsage(acc);
|
|
202
|
+
if (this.planDrafted) {
|
|
203
|
+
const kept = outcome.kind === "ok" || outcome.kind === "cut";
|
|
204
|
+
const calls = kept ? acc.message({ dropIncomplete: true }).tool_calls : undefined;
|
|
205
|
+
if (!calls?.some((c) => c.function.name === PLAN_TOOL)) {
|
|
206
|
+
yield { type: "plan_draft_dropped" };
|
|
207
|
+
}
|
|
208
|
+
}
|
|
124
209
|
if (outcome.kind === "aborted") {
|
|
125
210
|
this.commitPartial(acc);
|
|
126
211
|
this.interrupted = true;
|
|
@@ -228,6 +313,7 @@ export class Agent {
|
|
|
228
313
|
body,
|
|
229
314
|
signal,
|
|
230
315
|
fetch: this.options.fetch,
|
|
316
|
+
client: this.options.client,
|
|
231
317
|
})) {
|
|
232
318
|
acc.apply(chunk);
|
|
233
319
|
}
|
|
@@ -254,6 +340,8 @@ export class Agent {
|
|
|
254
340
|
return false;
|
|
255
341
|
}
|
|
256
342
|
this.replaceAll(compactedMessages(summary, split.tail, this.options.toolContext.todos), "compact");
|
|
343
|
+
// Notes that were summarized away no longer count: say it again if it matters.
|
|
344
|
+
this.toldPlan = lastToldPlan(this.messages);
|
|
257
345
|
this.lastUsage = null;
|
|
258
346
|
this.estimatedTokens = estimateTokens(this.messages);
|
|
259
347
|
yield { type: "compacted", beforeTokens: before, afterTokens: this.estimatedTokens };
|
|
@@ -277,6 +365,22 @@ export class Agent {
|
|
|
277
365
|
for (let attempt = 0;; attempt++) {
|
|
278
366
|
const acc = new MessageAccumulator();
|
|
279
367
|
let received = false;
|
|
368
|
+
// The plan being written (Plan mode only), shown as it arrives.
|
|
369
|
+
let planIndex = null;
|
|
370
|
+
let draft = "";
|
|
371
|
+
let draftAt = 0;
|
|
372
|
+
const nextDraft = (force) => {
|
|
373
|
+
if (planIndex === null)
|
|
374
|
+
return null;
|
|
375
|
+
const text = partialPlan(acc.argumentsOf(planIndex))?.trimStart() ?? "";
|
|
376
|
+
const now = Date.now();
|
|
377
|
+
if (!text || text === draft || (!force && now - draftAt < PLAN_DRAFT_EVERY_MS))
|
|
378
|
+
return null;
|
|
379
|
+
draft = text;
|
|
380
|
+
draftAt = now;
|
|
381
|
+
this.planDrafted = true;
|
|
382
|
+
return { type: "plan_draft", text };
|
|
383
|
+
};
|
|
280
384
|
try {
|
|
281
385
|
for await (const chunk of streamChat({
|
|
282
386
|
apiBaseUrl: this.options.apiBaseUrl,
|
|
@@ -284,15 +388,27 @@ export class Agent {
|
|
|
284
388
|
body,
|
|
285
389
|
signal,
|
|
286
390
|
fetch: this.options.fetch,
|
|
391
|
+
client: this.options.client,
|
|
287
392
|
})) {
|
|
288
393
|
for (const delta of acc.apply(chunk)) {
|
|
289
394
|
received = true;
|
|
290
|
-
if (delta.type === "tool_call")
|
|
395
|
+
if (delta.type === "tool_call") {
|
|
396
|
+
const planning = this.options.permissions.mode === "plan" && !this.options.isHelper;
|
|
397
|
+
if (delta.name === PLAN_TOOL && planning && planIndex === null) {
|
|
398
|
+
planIndex = delta.index;
|
|
399
|
+
}
|
|
291
400
|
yield { type: "tool_call_streaming", name: delta.name };
|
|
401
|
+
}
|
|
292
402
|
else
|
|
293
403
|
yield delta;
|
|
294
404
|
}
|
|
405
|
+
const drafted = nextDraft(false);
|
|
406
|
+
if (drafted)
|
|
407
|
+
yield drafted;
|
|
295
408
|
}
|
|
409
|
+
const last = nextDraft(true);
|
|
410
|
+
if (last)
|
|
411
|
+
yield last;
|
|
296
412
|
// A stream that ends without a finish reason was cut short.
|
|
297
413
|
if (!acc.finishReason && received) {
|
|
298
414
|
return { kind: "cut", acc, error: new StreamError("The reply ended early.", null) };
|
|
@@ -320,8 +436,14 @@ export class Agent {
|
|
|
320
436
|
/** Runs each call in order. Returns why the turn stops early, or null to carry on. */
|
|
321
437
|
async *runTools(calls, signal) {
|
|
322
438
|
let stop = null;
|
|
439
|
+
/** Calls after a presented plan wait for the user's answer to it, so they're not run. */
|
|
440
|
+
let afterPlan = false;
|
|
323
441
|
for (let i = 0; i < calls.length; i++) {
|
|
324
442
|
const call = calls[i];
|
|
443
|
+
if (afterPlan && !stop && !signal.aborted) {
|
|
444
|
+
this.appendToolResult(call.id, "Not run: present_plan has to be the last call in a reply. Carry on from the user's answer.");
|
|
445
|
+
continue;
|
|
446
|
+
}
|
|
325
447
|
// Consecutive helper tasks run at the same time.
|
|
326
448
|
if (!stop && !signal.aborted && call.function.name === "task" && !this.options.isHelper) {
|
|
327
449
|
const batch = [call];
|
|
@@ -331,13 +453,7 @@ export class Agent {
|
|
|
331
453
|
}
|
|
332
454
|
i += batch.length - 1;
|
|
333
455
|
const outcomes = yield* this.runConcurrently(batch, signal);
|
|
334
|
-
outcomes.forEach(({ result }, j) =>
|
|
335
|
-
this.append({
|
|
336
|
-
role: "tool",
|
|
337
|
-
tool_call_id: batch[j].id,
|
|
338
|
-
content: truncateMiddle(result.output, MAX_TOOL_OUTPUT_CHARS),
|
|
339
|
-
});
|
|
340
|
-
});
|
|
456
|
+
outcomes.forEach(({ result }, j) => this.appendToolResult(batch[j].id, result.output));
|
|
341
457
|
for (const [j, { result, title }] of outcomes.entries()) {
|
|
342
458
|
yield { type: "tool_done", id: batch[j].id, name: "task", title, result };
|
|
343
459
|
}
|
|
@@ -347,22 +463,23 @@ export class Agent {
|
|
|
347
463
|
}
|
|
348
464
|
if (stop || signal.aborted) {
|
|
349
465
|
stop ??= "aborted";
|
|
350
|
-
this.
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
content: stop === "declined"
|
|
354
|
-
? "Not run: the user declined an earlier action."
|
|
355
|
-
: "Not run: the user interrupted.",
|
|
356
|
-
});
|
|
466
|
+
this.appendToolResult(call.id, stop === "declined"
|
|
467
|
+
? "Not run: the user declined an earlier action."
|
|
468
|
+
: "Not run: the user interrupted.");
|
|
357
469
|
continue;
|
|
358
470
|
}
|
|
359
471
|
const { result, title, declined } = yield* this.runTool(call, signal);
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
472
|
+
// The mode it switched to (if approved) comes first, so screens show both together.
|
|
473
|
+
if (result.plan?.outcome === "approved-ask" || result.plan?.outcome === "approved-auto") {
|
|
474
|
+
yield {
|
|
475
|
+
type: "mode_changed",
|
|
476
|
+
mode: result.plan.outcome === "approved-auto" ? "auto-edit" : "ask",
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
this.appendToolResult(call.id, result.output);
|
|
365
480
|
yield { type: "tool_done", id: call.id, name: call.function.name, title, result };
|
|
481
|
+
if (call.function.name === PLAN_TOOL && result.plan)
|
|
482
|
+
afterPlan = true;
|
|
366
483
|
if (signal.aborted)
|
|
367
484
|
stop = "aborted";
|
|
368
485
|
else if (declined)
|
|
@@ -395,26 +512,38 @@ export class Agent {
|
|
|
395
512
|
}
|
|
396
513
|
/** Runs helper agents for the `task` tool: same model and project, fresh conversation. */
|
|
397
514
|
helpers = {
|
|
398
|
-
run: async ({ description, prompt }, signal, progress) => {
|
|
515
|
+
run: async ({ description, prompt, callId: taskCallId }, signal, progress) => {
|
|
399
516
|
const parent = this.options;
|
|
400
517
|
const helper = new Agent({
|
|
401
518
|
apiBaseUrl: parent.apiBaseUrl,
|
|
402
519
|
apiKey: parent.apiKey,
|
|
403
520
|
model: parent.model,
|
|
404
|
-
tools: parent.tools.filter((t) => t.name !== "task" && t.name !== "todo"),
|
|
521
|
+
tools: parent.tools.filter((t) => t.name !== "task" && t.name !== "todo" && t.name !== PLAN_TOOL),
|
|
405
522
|
systemPrompt: `${this.messages[0].content}\n\n${HELPER_NOTE}`,
|
|
406
523
|
toolContext: { ...parent.toolContext, todos: [] },
|
|
407
|
-
// Helpers read freely; their edits and commands ask unless the user chose "Don't ask"
|
|
524
|
+
// Helpers read freely; their edits and commands ask unless the user chose "Don't ask",
|
|
525
|
+
// and in Plan mode they change nothing.
|
|
408
526
|
permissions: {
|
|
409
527
|
get mode() {
|
|
410
|
-
|
|
528
|
+
const mode = parent.permissions.mode;
|
|
529
|
+
return mode === "full" || mode === "plan" ? mode : "ask";
|
|
411
530
|
},
|
|
412
531
|
allows: parent.permissions.allows,
|
|
413
532
|
context: parent.permissions.context,
|
|
533
|
+
get web() {
|
|
534
|
+
return parent.permissions.web;
|
|
535
|
+
},
|
|
414
536
|
},
|
|
415
|
-
approve: (request, sig) => parent.approve({ ...request, title: `Helper "${description}": ${request.title}` }, sig
|
|
537
|
+
approve: (request, sig, origin) => parent.approve({ ...request, title: `Helper "${description}": ${request.title}` }, sig, {
|
|
538
|
+
callId: origin?.callId ?? "",
|
|
539
|
+
helper: { description, callId: taskCallId },
|
|
540
|
+
}),
|
|
416
541
|
fetch: parent.fetch,
|
|
542
|
+
webFetch: parent.webFetch,
|
|
543
|
+
webTransport: parent.webTransport,
|
|
417
544
|
sleep: parent.sleep,
|
|
545
|
+
onProcess: parent.onProcess,
|
|
546
|
+
client: parent.client,
|
|
418
547
|
isHelper: true,
|
|
419
548
|
onChange: (change) => {
|
|
420
549
|
// Its cost is this conversation's cost (and is saved with it).
|
|
@@ -473,7 +602,7 @@ export class Agent {
|
|
|
473
602
|
});
|
|
474
603
|
const tool = this.options.tools.find((t) => t.name === name);
|
|
475
604
|
if (!tool)
|
|
476
|
-
return fail(`There is no tool called "${name}".`);
|
|
605
|
+
return fail(TURNED_OFF[name] ?? `There is no tool called "${name}".`);
|
|
477
606
|
let args;
|
|
478
607
|
try {
|
|
479
608
|
const parsed = call.function.arguments.trim()
|
|
@@ -489,8 +618,12 @@ export class Agent {
|
|
|
489
618
|
const ctx = {
|
|
490
619
|
...this.options.toolContext,
|
|
491
620
|
signal,
|
|
621
|
+
callId: call.id,
|
|
492
622
|
progress: (text) => this.options.onProgress?.(call.id, text),
|
|
623
|
+
output: this.options.onOutput && ((chunk) => this.options.onOutput?.(call.id, chunk)),
|
|
624
|
+
process: this.options.onProcess,
|
|
493
625
|
helpers: this.options.isHelper ? undefined : this.helpers,
|
|
626
|
+
web: this.web,
|
|
494
627
|
};
|
|
495
628
|
let prepared;
|
|
496
629
|
try {
|
|
@@ -503,14 +636,18 @@ export class Agent {
|
|
|
503
636
|
return fail(message);
|
|
504
637
|
}
|
|
505
638
|
yield { type: "tool_start", id: call.id, name, title: prepared.title };
|
|
639
|
+
if (name === PLAN_TOOL)
|
|
640
|
+
return await this.presentPlan(prepared, call.id, signal);
|
|
506
641
|
const request = {
|
|
507
642
|
tool: name,
|
|
508
643
|
kind: prepared.kind,
|
|
509
644
|
paths: prepared.paths,
|
|
510
645
|
command: prepared.command,
|
|
646
|
+
readOnlyPaths: prepared.readOnlyPaths,
|
|
647
|
+
host: prepared.host,
|
|
511
648
|
};
|
|
512
|
-
const { mode, allows, context } = this.options.permissions;
|
|
513
|
-
const decision = decide(request, mode, context, allows);
|
|
649
|
+
const { mode, allows, context, web } = this.options.permissions;
|
|
650
|
+
const decision = decide(request, mode, context, allows, web);
|
|
514
651
|
if (decision.kind === "deny") {
|
|
515
652
|
return { ...fail(decision.reason, prepared.title) };
|
|
516
653
|
}
|
|
@@ -524,7 +661,7 @@ export class Agent {
|
|
|
524
661
|
preview: prepared.preview,
|
|
525
662
|
reason: decision.reason,
|
|
526
663
|
always: decision.canAlways ? alwaysLabel(request) : null,
|
|
527
|
-
}, signal);
|
|
664
|
+
}, signal, { callId: call.id });
|
|
528
665
|
}
|
|
529
666
|
catch {
|
|
530
667
|
answer = { kind: "no" };
|
|
@@ -556,4 +693,76 @@ export class Agent {
|
|
|
556
693
|
return fail(`${prepared.title} failed: ${error.message}`, prepared.title);
|
|
557
694
|
}
|
|
558
695
|
}
|
|
696
|
+
/** Shows a plan and waits for the user's answer. Approving switches the mode to the one chosen. */
|
|
697
|
+
async presentPlan(prepared, callId, signal) {
|
|
698
|
+
const title = prepared.title;
|
|
699
|
+
const original = prepared.preview ?? "";
|
|
700
|
+
if (this.options.permissions.mode !== "plan") {
|
|
701
|
+
return {
|
|
702
|
+
result: {
|
|
703
|
+
output: "Plan mode is off, so there's nothing to approve: go ahead with the work (the user " +
|
|
704
|
+
"approves edits and commands as usual).",
|
|
705
|
+
summary: "Plan mode is off",
|
|
706
|
+
isError: true,
|
|
707
|
+
},
|
|
708
|
+
title,
|
|
709
|
+
declined: false,
|
|
710
|
+
};
|
|
711
|
+
}
|
|
712
|
+
let answer;
|
|
713
|
+
try {
|
|
714
|
+
answer = await this.options.approve({
|
|
715
|
+
tool: PLAN_TOOL,
|
|
716
|
+
kind: "meta",
|
|
717
|
+
title,
|
|
718
|
+
preview: original,
|
|
719
|
+
reason: null,
|
|
720
|
+
always: "yes, auto-accept edits",
|
|
721
|
+
}, signal, { callId });
|
|
722
|
+
}
|
|
723
|
+
catch {
|
|
724
|
+
answer = { kind: "no" };
|
|
725
|
+
}
|
|
726
|
+
const edited = editedPlan(answer.plan, original);
|
|
727
|
+
const text = edited ?? original;
|
|
728
|
+
const finish = (outcome, output, feedback = null) => {
|
|
729
|
+
const plan = { text, edited: edited !== null, outcome, feedback };
|
|
730
|
+
const failed = outcome === "not-approved" || outcome === "stopped";
|
|
731
|
+
return {
|
|
732
|
+
result: {
|
|
733
|
+
output,
|
|
734
|
+
summary: PLAN_OUTCOME_LABELS[outcome],
|
|
735
|
+
detail: text,
|
|
736
|
+
isError: failed,
|
|
737
|
+
plan,
|
|
738
|
+
},
|
|
739
|
+
title,
|
|
740
|
+
declined: outcome === "not-approved",
|
|
741
|
+
};
|
|
742
|
+
};
|
|
743
|
+
if (signal.aborted)
|
|
744
|
+
return finish("stopped", "Not run: the user interrupted.");
|
|
745
|
+
if (answer.kind === "no") {
|
|
746
|
+
const feedback = answer.feedback?.trim();
|
|
747
|
+
if (!feedback)
|
|
748
|
+
return finish("not-approved", "The user didn't approve the plan.");
|
|
749
|
+
return finish("sent-back", `The user wants changes before you start: ${feedback}` +
|
|
750
|
+
(edited ? `\n\nThey also edited your plan. Start from their version:\n\n${edited}` : "") +
|
|
751
|
+
"\n\nRevise the plan (look into anything you need first) and present it again with present_plan.", feedback);
|
|
752
|
+
}
|
|
753
|
+
const mode = answer.kind === "always" ? "auto-edit" : "ask";
|
|
754
|
+
this.options.permissions.mode = mode;
|
|
755
|
+
this.toldPlan = false;
|
|
756
|
+
const how = mode === "auto-edit"
|
|
757
|
+
? "edits in this project run without asking; commands still ask"
|
|
758
|
+
: "the user approves each edit and command";
|
|
759
|
+
return finish(mode === "auto-edit" ? "approved-auto" : "approved-ask", `${PLAN_APPROVED}${edited ? " after editing it" : ""}. The mode is now "${MODE_LABELS[mode]}": ` +
|
|
760
|
+
`${how}. Carry out the plan now${edited ? ", following their version below" : ""}, and ` +
|
|
761
|
+
`keep the todo list up to date as you go.${edited ? `\n\n${edited}` : ""}`);
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
/** The user's edited plan, when it really differs from the original (trimmed, capped), else null. */
|
|
765
|
+
export function editedPlan(edit, original) {
|
|
766
|
+
const text = edit?.trim().slice(0, MAX_PLAN_CHARS);
|
|
767
|
+
return text && text !== original.trim() ? text : null;
|
|
559
768
|
}
|
package/dist/agent/mcp.js
CHANGED
|
@@ -121,7 +121,8 @@ export class McpManager {
|
|
|
121
121
|
this.onChange?.();
|
|
122
122
|
}
|
|
123
123
|
async open(config, onStderr) {
|
|
124
|
-
const
|
|
124
|
+
const info = this.options.client ?? { name: "reasonally", version: version() };
|
|
125
|
+
const client = new Client(info, { capabilities: {} });
|
|
125
126
|
if (config.url) {
|
|
126
127
|
const url = new URL(config.url);
|
|
127
128
|
const requestInit = { headers: config.headers ?? {} };
|
|
@@ -132,7 +133,7 @@ export class McpManager {
|
|
|
132
133
|
}
|
|
133
134
|
catch {
|
|
134
135
|
// Older servers only speak the SSE transport.
|
|
135
|
-
const fallback = new Client(
|
|
136
|
+
const fallback = new Client(info, { capabilities: {} });
|
|
136
137
|
const transport = new SSEClientTransport(url, { requestInit });
|
|
137
138
|
await fallback.connect(transport);
|
|
138
139
|
return { client: fallback, transport };
|