@koneeric/onetool 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 CHANGED
@@ -16,15 +16,23 @@ You list your own servers in a settings file. onetool connects to them and offer
16
16
 
17
17
  ## Install
18
18
 
19
- You need Node 22 or later. A host program starts onetool with one of these two commands:
19
+ You need Node 22 or later. The first thing to do is to run this command once:
20
20
 
21
21
  ```sh
22
- npx github:KoneEric/onetool
23
- # once published on npm, this one too:
24
- npx @koneeric/onetool
22
+ npx @koneeric/onetool init
25
23
  ```
26
24
 
27
- Until it is published on npm, use the first.
25
+ It makes the settings file, `~/.config/onetool/settings.json`, when it is not there. When the command `claude`
26
+ is found on this machine, it proposes Claude Code as a server behind onetool. It then prints the entry to paste
27
+ into the MCP settings of your host program. It takes `--config` to set up another settings file than that one.
28
+
29
+ A host program starts onetool with one of these two commands:
30
+
31
+ ```sh
32
+ npx @koneeric/onetool
33
+ # or straight from this repository:
34
+ npx github:KoneEric/onetool
35
+ ```
28
36
 
29
37
  The one option is `--config`, the path of the settings file. Add this entry to the MCP settings of your host
30
38
  program:
@@ -34,7 +42,7 @@ program:
34
42
  "mcpServers": {
35
43
  "onetool": {
36
44
  "command": "npx",
37
- "args": ["-y", "github:KoneEric/onetool", "--config", "/absolute/path/to/settings.json"]
45
+ "args": ["-y", "@koneeric/onetool", "--config", "/absolute/path/to/settings.json"]
38
46
  }
39
47
  }
40
48
  }
@@ -0,0 +1,302 @@
1
+ // The sign-in by OAuth to a listed server reached at an address. See the meeting point of auth.
2
+ import crypto from "node:crypto";
3
+ import fs from "node:fs";
4
+ import http from "node:http";
5
+ import os from "node:os";
6
+ import path from "node:path";
7
+ import { auth } from "@modelcontextprotocol/sdk/client/auth.js";
8
+
9
+ const isText = (v) => typeof v === "string" && v.length > 0;
10
+ const isObject = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
11
+
12
+ function checkName(name) {
13
+ if (!isText(name)) throw new TypeError("name must be a non-empty string");
14
+ }
15
+
16
+ function checkUrl(url) {
17
+ if (!isText(url)) throw new TypeError("url must be a non-empty string");
18
+ }
19
+
20
+ function checkOauth(oauth) {
21
+ if (oauth === undefined) return;
22
+ if (!isObject(oauth) || typeof oauth.clientId !== "string") throw new TypeError("oauth must be an object with a string clientId");
23
+ if ("redirectHost" in oauth && oauth.redirectHost !== "127.0.0.1" && oauth.redirectHost !== "localhost") throw new TypeError("oauth.redirectHost must be 127.0.0.1 or localhost");
24
+ }
25
+
26
+ export function authFolder({ home = os.homedir() } = {}) {
27
+ return path.join(home, ".onetool", "auth");
28
+ }
29
+
30
+ export function authFile(name, { home = os.homedir() } = {}) {
31
+ checkName(name);
32
+ return path.join(authFolder({ home }), encodeURIComponent(name) + ".json");
33
+ }
34
+
35
+ /** The parsed file when it belongs to `(name, url)`, whatever else it holds; else `null`. Never throws. */
36
+ function readDoc(name, url, home) {
37
+ try {
38
+ const doc = JSON.parse(fs.readFileSync(authFile(name, { home }), "utf8"));
39
+ if (isObject(doc) && doc.server === name && doc.url === url) return doc;
40
+ } catch {}
41
+ return null;
42
+ }
43
+
44
+ const usableTokens = (doc) => (doc && isObject(doc.tokens) && isText(doc.tokens.access_token) ? doc.tokens : undefined);
45
+
46
+ /** Writes the file whole: beside it, then renamed over it. Throws when it cannot. */
47
+ function writeDoc(name, doc, home) {
48
+ const folder = authFolder({ home });
49
+ const made = fs.mkdirSync(folder, { recursive: true, mode: 0o700 });
50
+ if (made !== undefined) fs.chmodSync(folder, 0o700);
51
+ const file = authFile(name, { home });
52
+ const temp = path.join(folder, `.${crypto.randomBytes(8).toString("hex")}.tmp`);
53
+ try {
54
+ const fd = fs.openSync(temp, "wx", 0o600);
55
+ try {
56
+ fs.fchmodSync(fd, 0o600);
57
+ fs.writeSync(fd, JSON.stringify({ ...doc, stamp: crypto.randomUUID() }, null, 2) + "\n");
58
+ fs.fsyncSync(fd);
59
+ } finally {
60
+ fs.closeSync(fd);
61
+ }
62
+ fs.renameSync(temp, file);
63
+ } catch (e) {
64
+ try {
65
+ fs.unlinkSync(temp);
66
+ } catch {}
67
+ throw e;
68
+ }
69
+ }
70
+
71
+ export function signInStamp(name, url, { home = os.homedir() } = {}) {
72
+ checkName(name);
73
+ checkUrl(url);
74
+ const doc = readDoc(name, url, home);
75
+ if (!usableTokens(doc)) return null;
76
+ if (isText(doc.stamp)) return doc.stamp;
77
+ try {
78
+ const st = fs.statSync(authFile(name, { home }));
79
+ return `m-${st.mtimeMs}-${st.size}-${st.ino}`;
80
+ } catch {
81
+ return null;
82
+ }
83
+ }
84
+
85
+ export function logout(name, { home = os.homedir() } = {}) {
86
+ checkName(name);
87
+ try {
88
+ fs.unlinkSync(authFile(name, { home }));
89
+ return true;
90
+ } catch (e) {
91
+ if (e?.code === "ENOENT" || e?.code === "ENOTDIR") return false;
92
+ throw new Error("the sign-in could not be removed");
93
+ }
94
+ }
95
+
96
+ const clientOf = (oauth) => ({ client_id: oauth.clientId, ...(oauth.clientSecret !== undefined ? { client_secret: oauth.clientSecret } : {}) });
97
+ const scopeOf = (oauth) => (Array.isArray(oauth?.scopes) && oauth.scopes.length > 0 ? oauth.scopes.join(" ") : undefined);
98
+
99
+ export function quietProvider(name, url, { home = os.homedir(), oauth } = {}) {
100
+ checkName(name);
101
+ checkUrl(url);
102
+ checkOauth(oauth);
103
+ const redirect = "http://127.0.0.1/callback";
104
+ return {
105
+ get redirectUrl() {
106
+ return redirect;
107
+ },
108
+ get clientMetadata() {
109
+ return { client_name: "onetool", redirect_uris: [redirect], scope: scopeOf(oauth) };
110
+ },
111
+ clientInformation() {
112
+ if (oauth) return clientOf(oauth);
113
+ const doc = readDoc(name, url, home);
114
+ return isObject(doc?.client) ? doc.client : undefined;
115
+ },
116
+ tokens() {
117
+ return usableTokens(readDoc(name, url, home));
118
+ },
119
+ saveTokens(tokens) {
120
+ const doc = readDoc(name, url, home) ?? { server: name, url };
121
+ writeDoc(name, { ...doc, tokens }, home);
122
+ },
123
+ saveCodeVerifier() {},
124
+ codeVerifier() {
125
+ throw new Error("no code verifier");
126
+ },
127
+ redirectToAuthorization() {},
128
+ invalidateCredentials(scope) {
129
+ if (scope !== "all" && scope !== "tokens") return;
130
+ // The tokens go, the client stays: the request that follows ends as a plain 401, not as a refused registration.
131
+ const doc = readDoc(name, url, home);
132
+ if (!doc || !("tokens" in doc)) return;
133
+ const { tokens: _gone, ...rest } = doc;
134
+ try {
135
+ writeDoc(name, rest, home);
136
+ } catch {}
137
+ },
138
+ };
139
+ }
140
+
141
+ export function browserCommand(address, platform = process.platform) {
142
+ if (platform === "darwin") return ["open", address];
143
+ if (platform === "linux") return ["xdg-open", address];
144
+ return null;
145
+ }
146
+
147
+ const MAX_TIMER_MS = 2 ** 31 - 1;
148
+ const PLAIN = { "content-type": "text/plain; charset=utf-8", connection: "close" };
149
+
150
+ export async function login({ name, url, oauth } = {}, { home = os.homedir(), waitSeconds = 300, say, open } = {}) {
151
+ checkName(name);
152
+ checkUrl(url);
153
+ checkOauth(oauth);
154
+ if (typeof waitSeconds !== "number" || !Number.isFinite(waitSeconds) || waitSeconds <= 0) throw new TypeError("waitSeconds must be a finite number above 0");
155
+ if (say !== undefined && typeof say !== "function") throw new TypeError("say must be a function");
156
+ if (open !== undefined && typeof open !== "function") throw new TypeError("open must be a function");
157
+
158
+ return new Promise((resolve) => {
159
+ const state = crypto.randomBytes(16).toString("base64url");
160
+ const abort = new AbortController();
161
+ const server = http.createServer();
162
+ let settled = false;
163
+ let started = false;
164
+ let exchanging = false;
165
+ let written = false;
166
+ let keepFailed = false;
167
+ let timer;
168
+
169
+ const finish = (result) => {
170
+ if (settled) return;
171
+ settled = true;
172
+ clearTimeout(timer);
173
+ abort.abort();
174
+ server.close();
175
+ server.closeIdleConnections?.();
176
+ setImmediate(() => server.closeAllConnections?.());
177
+ resolve(result);
178
+ };
179
+ const fail = (reason) => finish({ ok: false, reason });
180
+ const fetchFn = (input, init) =>
181
+ fetch(input, { ...init, signal: init?.signal ? AbortSignal.any([init.signal, abort.signal]) : abort.signal });
182
+ const answer = (res, status, text, then) => {
183
+ res.writeHead(status, PLAIN);
184
+ res.end(text, then);
185
+ };
186
+
187
+ let port = 0;
188
+ const callback = () => `http://${oauth?.redirectHost ?? "127.0.0.1"}:${port}/callback`;
189
+ let client;
190
+ let verifier;
191
+ let discovery;
192
+ let tokens;
193
+ const provider = {
194
+ get redirectUrl() {
195
+ return callback();
196
+ },
197
+ get clientMetadata() {
198
+ return {
199
+ client_name: "onetool",
200
+ redirect_uris: [callback()],
201
+ grant_types: ["authorization_code", "refresh_token"],
202
+ response_types: ["code"],
203
+ token_endpoint_auth_method: oauth?.clientSecret !== undefined ? "client_secret_post" : "none",
204
+ scope: scopeOf(oauth),
205
+ };
206
+ },
207
+ state: () => state,
208
+ clientInformation: () => (oauth ? clientOf(oauth) : client),
209
+ tokens: () => tokens,
210
+ saveTokens(t) {
211
+ if (settled) throw new Error("late");
212
+ const doc = { server: name, url, tokens: t, ...(client && !oauth ? { client } : {}) };
213
+ try {
214
+ writeDoc(name, doc, home);
215
+ } catch (e) {
216
+ keepFailed = true;
217
+ throw e;
218
+ }
219
+ written = true;
220
+ tokens = t;
221
+ },
222
+ saveCodeVerifier(v) {
223
+ verifier = v;
224
+ },
225
+ codeVerifier: () => verifier,
226
+ discoveryState: () => discovery,
227
+ saveDiscoveryState(d) {
228
+ discovery = d;
229
+ },
230
+ invalidateCredentials() {},
231
+ redirectToAuthorization(address) {
232
+ started = true;
233
+ if (settled) return;
234
+ const text = String(address);
235
+ for (const fn of [say, open]) {
236
+ if (!fn) continue;
237
+ try {
238
+ const r = fn(text);
239
+ if (r && typeof r.then === "function") r.then(undefined, () => {});
240
+ } catch {}
241
+ }
242
+ },
243
+ };
244
+ // The client is the one `oauth` names, or one registered now: never the one of an earlier sign-in.
245
+ if (!oauth) {
246
+ provider.saveClientInformation = (info) => {
247
+ client = info;
248
+ };
249
+ }
250
+ const scope = scopeOf(oauth);
251
+
252
+ const exchange = async (code, res) => {
253
+ try {
254
+ const r = await auth(provider, { serverUrl: url, authorizationCode: code, scope, fetchFn });
255
+ if (settled) return;
256
+ if (r !== "AUTHORIZED") throw new Error("not authorized");
257
+ answer(res, 200, "signed in, you can close this page", () => finish({ ok: true }));
258
+ } catch {
259
+ if (settled) return;
260
+ answer(res, 400, "not signed in", () => fail(keepFailed ? "the sign-in could not be kept" : "the sign-in could not be finished"));
261
+ }
262
+ };
263
+
264
+ server.on("request", (req, res) => {
265
+ if (settled) {
266
+ answer(res, 404, "");
267
+ return;
268
+ }
269
+ let u;
270
+ try {
271
+ u = new URL(req.url, "http://127.0.0.1");
272
+ } catch {
273
+ answer(res, 404, "");
274
+ return;
275
+ }
276
+ if (u.pathname !== "/callback" || req.method !== "GET") return answer(res, 404, "");
277
+ if (u.searchParams.get("state") !== state) return answer(res, 400, "not signed in");
278
+ if (exchanging) return answer(res, 400, "not signed in");
279
+ const code = u.searchParams.get("code");
280
+ if (u.searchParams.has("error") || !code) {
281
+ exchanging = true;
282
+ return answer(res, 400, "not signed in", () => fail("the sign-in was refused"));
283
+ }
284
+ exchanging = true;
285
+ exchange(code, res);
286
+ });
287
+
288
+ timer = setTimeout(() => finish(written ? { ok: true } : { ok: false, reason: `no answer in ${String(waitSeconds)} seconds` }), Math.min(waitSeconds * 1000, MAX_TIMER_MS));
289
+ server.once("error", () => fail(`cannot listen on port ${oauth?.port ?? 0}`));
290
+ server.listen({ port: oauth?.port ?? 0, host: "127.0.0.1" }, async () => {
291
+ server.removeAllListeners("error");
292
+ server.on("error", () => {});
293
+ port = server.address().port;
294
+ try {
295
+ const r = await auth(provider, { serverUrl: url, scope, fetchFn });
296
+ if (r !== "REDIRECT" || !started) fail("the sign-in could not be started");
297
+ } catch {
298
+ if (!started) fail("the sign-in could not be started");
299
+ }
300
+ });
301
+ });
302
+ }
package/core/src/index.js CHANGED
@@ -53,11 +53,43 @@ const ONETOOL_KEYS = {
53
53
  ask: { fallback: [], valid: isPatternList, problem: "must be a list of patterns" },
54
54
  };
55
55
 
56
- const EXTRA_KEYS = ["shell", "trail", "log", "logFolder", "hostRules", "hostServers", "backgroundSeconds", "maxJobs", "libraryCap"];
56
+ const EXTRA_KEYS = ["shell", "trail", "log", "logFolder", "hostRules", "hostServers", "backgroundSeconds", "maxJobs", "libraryCap", "instructions"];
57
57
 
58
58
  const isTexts = (list) => Array.isArray(list) && list.every((item) => typeof item === "string");
59
59
  const isObjectOfTexts = (value) => isObject(value) && Object.values(value).every((item) => typeof item === "string");
60
60
 
61
+ const OAUTH_KEYS = ["clientId", "clientSecret", "scopes", "port", "redirectHost"];
62
+
63
+ /** The reason the `oauth` of an entry is not valid, or null when it is. */
64
+ function oauthReason(oauth) {
65
+ if (!isObject(oauth) || typeof oauth.clientId !== "string" || oauth.clientId.trim() === "") return "oauth has no clientId";
66
+ const has = (key) => Object.hasOwn(oauth, key);
67
+ if (has("clientSecret") && (typeof oauth.clientSecret !== "string" || oauth.clientSecret === "")) {
68
+ return "oauth.clientSecret is not a text";
69
+ }
70
+ if (has("scopes") && !(Array.isArray(oauth.scopes) && oauth.scopes.every((scope) => typeof scope === "string" && /^\S+$/.test(scope)))) {
71
+ return "oauth.scopes is not a list of words";
72
+ }
73
+ if (has("port") && !isWhole(oauth.port, 1, 65535)) return "oauth.port is not a port";
74
+ if (has("redirectHost") && oauth.redirectHost !== "127.0.0.1" && oauth.redirectHost !== "localhost") {
75
+ return "oauth.redirectHost is not 127.0.0.1 or localhost";
76
+ }
77
+ if (Object.keys(oauth).some((key) => !OAUTH_KEYS.includes(key))) return "oauth has an unknown key";
78
+ return null;
79
+ }
80
+
81
+ /** The `oauth` of a usable entry as `servers` holds it: a new object with the keys the file has. */
82
+ function oauthValue(oauth) {
83
+ const value = { clientId: oauth.clientId };
84
+ if (Object.hasOwn(oauth, "clientSecret")) value.clientSecret = oauth.clientSecret;
85
+ if (Object.hasOwn(oauth, "scopes")) value.scopes = [...oauth.scopes];
86
+ if (Object.hasOwn(oauth, "port")) value.port = oauth.port;
87
+ if (Object.hasOwn(oauth, "redirectHost")) value.redirectHost = oauth.redirectHost;
88
+ return value;
89
+ }
90
+
91
+ const isToolNames = (list) => Array.isArray(list) && list.every((name) => typeof name === "string" && name.trim() !== "");
92
+
61
93
  /** The reason an entry of mcpServers is unusable, or null when it is usable. */
62
94
  function badReason(name, entry, shellOn) {
63
95
  if (name.trim() === "") return "the name is empty";
@@ -74,11 +106,24 @@ function badReason(name, entry, shellOn) {
74
106
  }
75
107
  if (entry.type === "sse") return "the old SSE transport is not supported";
76
108
  if (has("headers") && !isObjectOfTexts(entry.headers)) return "headers is not an object of texts";
77
- return null;
109
+ if (has("oauth")) {
110
+ const why = oauthReason(entry.oauth);
111
+ if (why !== null) return why;
112
+ if (has("headers") && Object.keys(entry.headers).some((key) => key.toLowerCase() === "authorization")) {
113
+ return "both oauth and an Authorization header";
114
+ }
115
+ }
116
+ return toolsReason(entry);
78
117
  }
79
118
  if (typeof entry.command !== "string" || entry.command === "") return "no command";
80
119
  if (has("args") && !isTexts(entry.args)) return "args is not a list of texts";
81
120
  if (has("env") && !isObjectOfTexts(entry.env)) return "env is not an object of texts";
121
+ return toolsReason(entry);
122
+ }
123
+
124
+ /** The reason the `tools` of an entry is not valid, or null when it is (or the entry has none). */
125
+ function toolsReason(entry) {
126
+ if (Object.hasOwn(entry, "tools") && !isToolNames(entry.tools)) return "tools is not a list of tool names";
82
127
  return null;
83
128
  }
84
129
 
@@ -133,6 +178,7 @@ export function readSettings(path) {
133
178
  let backgroundSeconds = 7200;
134
179
  let maxJobs = 3;
135
180
  let libraryCap = 50;
181
+ let instructions = true;
136
182
  if (!isObject(onetool)) {
137
183
  problems.push("onetool: not an object");
138
184
  } else {
@@ -188,6 +234,10 @@ export function readSettings(path) {
188
234
  if (isWhole(onetool.libraryCap, 1, 1000)) libraryCap = onetool.libraryCap;
189
235
  else problems.push("onetool.libraryCap: must be a whole number from 1 to 1000");
190
236
  }
237
+ if (Object.hasOwn(onetool, "instructions")) {
238
+ if (typeof onetool.instructions === "boolean") instructions = onetool.instructions;
239
+ else problems.push("onetool.instructions: must be true or false");
240
+ }
191
241
  }
192
242
  if (problems.length > 0) throw new SettingsError(problems);
193
243
 
@@ -196,11 +246,20 @@ export function readSettings(path) {
196
246
  for (const [name, entry] of Object.entries(file.mcpServers)) {
197
247
  const reason = badReason(name, entry, shell !== null);
198
248
  if (reason !== null) bad.push({ name, reason });
199
- else if (Object.hasOwn(entry, "url")) servers.push({ name, url: entry.url, headers: entry.headers ?? {} });
200
- else servers.push({ name, command: entry.command, args: entry.args ?? [], env: entry.env ?? {} });
249
+ else {
250
+ let server;
251
+ if (Object.hasOwn(entry, "url")) {
252
+ server = { name, url: entry.url, headers: entry.headers ?? {} };
253
+ if (Object.hasOwn(entry, "oauth")) server.oauth = oauthValue(entry.oauth);
254
+ } else {
255
+ server = { name, command: entry.command, args: entry.args ?? [], env: entry.env ?? {} };
256
+ }
257
+ if (Object.hasOwn(entry, "tools")) server.tools = [...entry.tools];
258
+ servers.push(server);
259
+ }
201
260
  }
202
261
  const { answerLimit, timeoutSeconds, connectSeconds, searchLimit, stateLimit, allow, deny, ask } = values;
203
- return { servers, bad, answerLimit, timeoutSeconds, connectSeconds, searchLimit, stateLimit, allow, deny, ask, shell, trail, log, logFolder, hostRules, hostServers, backgroundSeconds, maxJobs, libraryCap };
262
+ return { servers, bad, answerLimit, timeoutSeconds, connectSeconds, searchLimit, stateLimit, allow, deny, ask, shell, trail, log, logFolder, hostRules, hostServers, backgroundSeconds, maxJobs, libraryCap, instructions };
204
263
  }
205
264
 
206
265
  // -- allow and deny ----------------------------------------------------------
@@ -297,6 +356,30 @@ function sentenceOf(description) {
297
356
  return sentence.length > 160 ? `${sentence.slice(0, 157)}...` : sentence;
298
357
  }
299
358
 
359
+ /** The tools of a server that onetool keeps: all of them, or those whose name is in `keep`. */
360
+ export function keptTools(tools, keep) {
361
+ if (!Array.isArray(tools)) throw new TypeError("keptTools takes a list of tools");
362
+ if (keep === undefined) return [...tools];
363
+ if (!Array.isArray(keep)) throw new TypeError("keptTools takes a list of names, or undefined");
364
+ const names = new Set(keep);
365
+ return tools.filter((tool) => names.has(tool.name));
366
+ }
367
+
368
+ /** Whether onetool may sign in to this server: at an address, with no Authorization header. */
369
+ export function signsIn(entry) {
370
+ if (!isObject(entry)) throw new TypeError("signsIn takes an entry of settings.servers");
371
+ if (!Object.hasOwn(entry, "url")) return false;
372
+ return !Object.keys(entry.headers).some((key) => key.toLowerCase() === "authorization");
373
+ }
374
+
375
+ /** The text a program gets when it calls a tool of a server that needs a sign-in. */
376
+ export function signInMessage(server, configPath) {
377
+ for (const value of [server, configPath]) {
378
+ if (typeof value !== "string" || value === "") throw new TypeError("signInMessage takes two texts that are not empty");
379
+ }
380
+ return `sign in needed: run "onetool login ${server} --config ${configPath}" in a terminal`;
381
+ }
382
+
300
383
  export function toolLine(server, tool) {
301
384
  const schema = tool.inputSchema;
302
385
  const properties = isObject(schema?.properties) ? schema.properties : {};
@@ -341,16 +424,20 @@ function programScore(program, words) {
341
424
  return total;
342
425
  }
343
426
 
344
- export function searchTools(catalog, words, { limit = 10, programs = [] } = {}) {
427
+ export function searchTools(catalog, words, { limit = 10, programs = [], session } = {}) {
345
428
  const query = typeof words === "string" ? words.trim() : "";
346
429
  if (query === "") {
347
430
  const lines = catalog.map((entry) =>
348
- entry.error !== undefined && entry.error !== null
349
- ? `${entry.server}: not connected (${entry.error})`
350
- : `${entry.server}: ${entry.tools.length} tools`,
431
+ entry.signIn === true
432
+ ? `${entry.server}: sign in needed`
433
+ : entry.error !== undefined && entry.error !== null
434
+ ? `${entry.server}: not connected (${entry.error})`
435
+ : `${entry.server}: ${entry.tools.length} tools`,
351
436
  );
352
437
  if (programs.length > 0) lines.push(`library: ${programs.length} programs`);
353
- return lines.length === 0 ? "No server is listed." : lines.join("\n");
438
+ const answer = lines.length === 0 ? "No server is listed." : lines.join("\n");
439
+ const line = session === undefined || session === null ? "" : sessionLine(session.programs, session.calls);
440
+ return line === "" ? answer : `${answer}\n${line}`;
354
441
  }
355
442
 
356
443
  const terms = query.toLowerCase().split(/\s+/);
@@ -534,6 +621,30 @@ export const sameAsNote = (name) => `(lib.${String(name)} does this: call it)`;
534
621
  export const archivedNote = (name, failures) =>
535
622
  `(lib.${String(name)} failed ${String(failures)} times in a row: it was moved to the archive)`;
536
623
 
624
+ // -- the session -------------------------------------------------------------
625
+
626
+ export const INSTRUCTIONS =
627
+ "onetool gives you two tools, run and search. It saves context only when one program does several steps. " +
628
+ "Before the first run, list the steps of the task. Put every step that needs no decision into one program: " +
629
+ "loops, filters, several tools. Return only the small result you need to decide what comes next. " +
630
+ "Keep large results in state and look at them in a later program. " +
631
+ "Never use run for one tool call when the next call is already known: put both calls in one program.";
632
+
633
+ export function nextStreak(streak, program, { times = 3 } = {}) {
634
+ const counts = program.ok === true && program.calls === 1 && program.asked === false && program.lib === 0;
635
+ if (!counts) return { streak: 0, say: false };
636
+ if (streak + 1 >= times) return { streak: 0, say: true };
637
+ return { streak: streak + 1, say: false };
638
+ }
639
+
640
+ export const oneProgramNote = (times) =>
641
+ `(the last ${String(times)} programs each made one call: they could have been one program)`;
642
+
643
+ export function sessionLine(programs, calls) {
644
+ if (programs === 0) return "";
645
+ return `this session: ${programs} programs, ${calls} calls, ${(calls / programs).toFixed(1)} calls per program`;
646
+ }
647
+
537
648
  // -- state -------------------------------------------------------------------
538
649
 
539
650
  export function nextState(kept, before, after, { limit = 10000000 } = {}) {