reasonally 0.0.0-stage → 0.2.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.
@@ -0,0 +1,55 @@
1
+ /** Used when the catalog doesn't publish a limit. */
2
+ export const FALLBACK_CONTEXT = 128_000;
3
+ const FALLBACK_OUTPUT = 16_384;
4
+ const num = (value) => (typeof value === "number" && value > 0 ? value : null);
5
+ const price = (value) => {
6
+ const n = typeof value === "string" ? Number(value) : NaN;
7
+ return Number.isFinite(n) && n >= 0 ? n : 0;
8
+ };
9
+ const strings = (value) => Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
10
+ export function parseCatalog(payload) {
11
+ const data = payload?.data;
12
+ if (!Array.isArray(data))
13
+ return [];
14
+ const models = [];
15
+ for (const raw of data) {
16
+ const m = raw;
17
+ if (typeof m?.id !== "string" || !m.id)
18
+ continue;
19
+ const params = strings(m.supported_parameters);
20
+ const contextLength = num(m.context_length) ?? FALLBACK_CONTEXT;
21
+ const pricing = (m.pricing ?? {});
22
+ models.push({
23
+ id: m.id,
24
+ name: typeof m.name === "string" && m.name ? m.name : m.id,
25
+ contextLength,
26
+ maxOutput: Math.min(num(m.max_completion_tokens) ?? FALLBACK_OUTPUT, contextLength),
27
+ images: strings(m.input_modalities).includes("image"),
28
+ reasoning: params.includes("reasoning") || params.includes("include_reasoning"),
29
+ tools: params.length === 0 || params.includes("tools"),
30
+ inputPerM: price(pricing.input_per_million),
31
+ outputPerM: price(pricing.output_per_million),
32
+ });
33
+ }
34
+ return models;
35
+ }
36
+ /** Coding agents call tools on every turn, so models that can't are left out of their configs. */
37
+ export const agentModels = (models) => models.filter((m) => m.tools);
38
+ /** Exact id match, or up to five ids containing every word of the query. */
39
+ export function findModel(models, query) {
40
+ const exact = models.find((m) => m.id === query);
41
+ if (exact)
42
+ return { ok: true, model: exact };
43
+ const words = query
44
+ .toLowerCase()
45
+ .split(/[\s/:._-]+/)
46
+ .filter(Boolean);
47
+ const suggestions = models
48
+ .filter((m) => {
49
+ const haystack = `${m.id} ${m.name}`.toLowerCase();
50
+ return words.length > 0 && words.every((w) => haystack.includes(w));
51
+ })
52
+ .slice(0, 5)
53
+ .map((m) => m.id);
54
+ return { ok: false, suggestions };
55
+ }
package/dist/cli.js ADDED
@@ -0,0 +1,220 @@
1
+ import { createRequire } from "node:module";
2
+ import { ApiError, fetchAccount, fetchModels, revokeKey } from "./api.js";
3
+ import { findModel } from "./catalog.js";
4
+ import { appUrlFrom, deleteCredentials, harnessDir, readCredentials, readLastModel, resolveSession, writeCredentials, writeLastModel, } from "./config.js";
5
+ import { findHarness, HARNESSES } from "./harnesses/index.js";
6
+ import { launch } from "./launch.js";
7
+ import { browserLogin } from "./login.js";
8
+ const log = (line) => console.error(line);
9
+ const HELP = `Run the coding agents you already use on Reasonally models.
10
+
11
+ Usage:
12
+ reasonally login Log in through your browser (--no-browser: print the link)
13
+ reasonally <agent> [--model <id>] [agent args…]
14
+ reasonally models [search] List models you can use
15
+ reasonally whoami Show the account and balance
16
+ reasonally logout Log out and revoke this computer's key
17
+ reasonally browser Let your Reasonally chats use a browser window on this computer
18
+ (--port N, default 47614; --allow-local: allow local addresses)
19
+
20
+ Agents:
21
+ ${HARNESSES.map((h) => ` ${h.id.padEnd(10)} ${h.name}`).join("\n")}
22
+
23
+ Anything after the agent's name (except --model) is passed to it unchanged.
24
+ Set REASONALLY_API_KEY to use an existing key instead of logging in.`;
25
+ /** Pulls our `--model` out of an agent's arguments; everything else passes through. */
26
+ export function splitModelFlag(args) {
27
+ const rest = [];
28
+ let model = null;
29
+ for (let i = 0; i < args.length; i++) {
30
+ const arg = args[i];
31
+ if (arg === "--") {
32
+ rest.push(...args.slice(i));
33
+ break;
34
+ }
35
+ if (model === null && arg === "--model" && i + 1 < args.length) {
36
+ model = args[++i];
37
+ }
38
+ else if (model === null && arg.startsWith("--model=")) {
39
+ model = arg.slice("--model=".length);
40
+ }
41
+ else {
42
+ rest.push(arg);
43
+ }
44
+ }
45
+ return { model, rest };
46
+ }
47
+ async function requireSession() {
48
+ const session = resolveSession(process.env, await readCredentials());
49
+ if (!session)
50
+ throw new UsageError("You're not logged in. Run `reasonally login` first.");
51
+ return session;
52
+ }
53
+ class UsageError extends Error {
54
+ }
55
+ async function login(args) {
56
+ const previous = await readCredentials();
57
+ const appUrl = appUrlFrom(process.env, previous);
58
+ const token = await browserLogin(appUrl, log, { open: !args.includes("--no-browser") });
59
+ await writeCredentials({
60
+ appUrl,
61
+ apiBaseUrl: token.api_base_url,
62
+ apiKey: token.api_key,
63
+ keyId: token.key_id,
64
+ email: token.email,
65
+ });
66
+ // Retire the key from the previous login so repeat logins don't pile up keys.
67
+ if (previous && previous.apiKey !== token.api_key) {
68
+ await revokeKey(previous.appUrl, previous.apiKey).catch(() => { });
69
+ }
70
+ log(`Logged in as ${token.email}.`);
71
+ if (process.env.REASONALLY_API_KEY) {
72
+ log("Note: REASONALLY_API_KEY is set in your environment and takes precedence over this login.");
73
+ }
74
+ log(`Start an agent, e.g. \`reasonally ${HARNESSES[0].id}\`.`);
75
+ return 0;
76
+ }
77
+ async function logout() {
78
+ const creds = await readCredentials();
79
+ if (!creds) {
80
+ log("You're not logged in.");
81
+ return 0;
82
+ }
83
+ try {
84
+ await revokeKey(creds.appUrl, creds.apiKey);
85
+ }
86
+ catch (error) {
87
+ // An already-revoked key is fine; anything else leaves a key the user should revoke.
88
+ if (!(error instanceof ApiError && error.status === 401)) {
89
+ log(`Couldn't revoke this computer's key (${error.message}).`);
90
+ log("Revoke it on the API keys page of your dashboard.");
91
+ }
92
+ }
93
+ await deleteCredentials();
94
+ log("Logged out.");
95
+ return 0;
96
+ }
97
+ async function whoami() {
98
+ const session = await requireSession();
99
+ const account = await fetchAccount(session.appUrl, session.apiKey);
100
+ console.log(`${account.email} · ${account.workspace}`);
101
+ console.log(`Balance: ${account.balance}`);
102
+ if (session.fromEnv)
103
+ console.log("(using the key in REASONALLY_API_KEY)");
104
+ return 0;
105
+ }
106
+ const formatK = (tokens) => tokens >= 1_000_000 ? `${+(tokens / 1_000_000).toFixed(2)}M` : `${Math.round(tokens / 1000)}K`;
107
+ export function formatModels(models) {
108
+ const rows = models.map((m) => [
109
+ m.id,
110
+ formatK(m.contextLength),
111
+ `$${m.inputPerM} / $${m.outputPerM}`,
112
+ [m.tools && "tools", m.images && "images", m.reasoning && "reasoning"]
113
+ .filter(Boolean)
114
+ .join(", "),
115
+ ]);
116
+ const header = ["MODEL", "CONTEXT", "PRICE PER 1M (IN / OUT)", "SUPPORTS"];
117
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
118
+ return [header, ...rows]
119
+ .map((r) => r
120
+ .map((cell, i) => cell.padEnd(widths[i]))
121
+ .join(" ")
122
+ .trimEnd())
123
+ .join("\n");
124
+ }
125
+ async function models(search) {
126
+ const session = await requireSession();
127
+ const all = await fetchModels(session.apiBaseUrl, session.apiKey);
128
+ const words = search.join(" ").toLowerCase().split(/\s+/).filter(Boolean);
129
+ const matches = all.filter((m) => words.every((w) => `${m.id} ${m.name}`.toLowerCase().includes(w)));
130
+ if (matches.length === 0) {
131
+ log(words.length ? `No models match "${search.join(" ")}".` : "No models are available.");
132
+ return 1;
133
+ }
134
+ console.log(formatModels(matches));
135
+ return 0;
136
+ }
137
+ async function runAgent(harness, args) {
138
+ const session = await requireSession();
139
+ const { model: requested, rest } = splitModelFlag(args);
140
+ const catalog = await fetchModels(session.apiBaseUrl, session.apiKey);
141
+ const wanted = requested ?? (harness.needsModel ? await readLastModel(harness.id) : null);
142
+ let model = null;
143
+ if (wanted) {
144
+ const match = findModel(catalog, wanted);
145
+ if (!match.ok) {
146
+ log(`Unknown model "${wanted}".`);
147
+ if (match.suggestions.length)
148
+ log(`Did you mean:\n ${match.suggestions.join("\n ")}`);
149
+ log("See all models with `reasonally models`.");
150
+ return 1;
151
+ }
152
+ model = match.model;
153
+ }
154
+ if (harness.needsModel && !model) {
155
+ log(`${harness.name} needs a model to start. Pick one (it's remembered for next time):`);
156
+ log(`\n reasonally ${harness.id} --model <id>\n`);
157
+ log("See all models with `reasonally models`.");
158
+ return 1;
159
+ }
160
+ if (model && harness.needsModel)
161
+ await writeLastModel(harness.id, model.id);
162
+ const plan = harness.plan({
163
+ apiBaseUrl: session.apiBaseUrl,
164
+ apiKey: session.apiKey,
165
+ models: catalog,
166
+ model,
167
+ dir: harnessDir(harness.id),
168
+ args: rest,
169
+ });
170
+ return launch(harness, plan, log);
171
+ }
172
+ export async function main(argv) {
173
+ const [command, ...args] = argv;
174
+ try {
175
+ switch (command) {
176
+ case undefined:
177
+ case "help":
178
+ case "--help":
179
+ case "-h":
180
+ console.log(HELP);
181
+ return 0;
182
+ case "--version":
183
+ case "-v":
184
+ console.log(createRequire(import.meta.url)("../package.json").version);
185
+ return 0;
186
+ case "login":
187
+ return await login(args);
188
+ case "logout":
189
+ return await logout();
190
+ case "whoami":
191
+ return await whoami();
192
+ case "models":
193
+ return await models(args);
194
+ case "browser": {
195
+ const { browserCommand } = await import("./browser/command.js");
196
+ return await browserCommand(args, log);
197
+ }
198
+ }
199
+ const harness = findHarness(command);
200
+ if (!harness) {
201
+ log(`Unknown command "${command}".\n\n${HELP}`);
202
+ return 1;
203
+ }
204
+ return await runAgent(harness, args);
205
+ }
206
+ catch (error) {
207
+ if (error instanceof UsageError) {
208
+ log(error.message);
209
+ return 1;
210
+ }
211
+ if (error instanceof ApiError) {
212
+ log(error.status === 401
213
+ ? "Your login was rejected (the key may have been revoked). Run `reasonally login` again."
214
+ : error.message);
215
+ return 1;
216
+ }
217
+ log(error.message);
218
+ return 1;
219
+ }
220
+ }
package/dist/config.js ADDED
@@ -0,0 +1,86 @@
1
+ import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
2
+ import { homedir } from "node:os";
3
+ import { dirname, join } from "node:path";
4
+ export const DEFAULT_APP_URL = "https://app.reasonally.ai";
5
+ export const DEFAULT_API_URL = "https://api.reasonally.ai/v1";
6
+ /** `$XDG_CONFIG_HOME/reasonally`, `%APPDATA%\reasonally` on Windows, else `~/.config/reasonally`. */
7
+ export function configDir(env = process.env, platform = process.platform) {
8
+ if (env.XDG_CONFIG_HOME)
9
+ return join(env.XDG_CONFIG_HOME, "reasonally");
10
+ if (platform === "win32" && env.APPDATA)
11
+ return join(env.APPDATA, "reasonally");
12
+ return join(homedir(), ".config", "reasonally");
13
+ }
14
+ /** Where a harness keeps the config it generates (never the agent's own config directory). */
15
+ export const harnessDir = (id, env = process.env) => join(configDir(env), "harness", id);
16
+ const credentialsPath = (env) => join(configDir(env), "credentials.json");
17
+ export async function readCredentials(env = process.env) {
18
+ try {
19
+ const parsed = JSON.parse(await readFile(credentialsPath(env), "utf8"));
20
+ if (!parsed.apiKey || !parsed.appUrl || !parsed.apiBaseUrl)
21
+ return null;
22
+ return parsed;
23
+ }
24
+ catch {
25
+ return null;
26
+ }
27
+ }
28
+ /** Writes a file only its owner can read: it holds an API key (or a config naming one). */
29
+ export async function writePrivateFile(path, content) {
30
+ await mkdir(dirname(path), { recursive: true, mode: 0o700 });
31
+ await writeFile(path, content, { mode: 0o600 });
32
+ await chmod(path, 0o600); // `mode` only applies when the file is created
33
+ }
34
+ export async function writeCredentials(creds, env = process.env) {
35
+ await writePrivateFile(credentialsPath(env), `${JSON.stringify(creds, null, 2)}\n`);
36
+ }
37
+ export async function deleteCredentials(env = process.env) {
38
+ await rm(credentialsPath(env), { force: true });
39
+ }
40
+ export function appUrlFrom(env, creds) {
41
+ return trimSlash(env.REASONALLY_URL ?? creds?.appUrl ?? DEFAULT_APP_URL);
42
+ }
43
+ export function resolveSession(env, creds) {
44
+ const appUrl = appUrlFrom(env, creds);
45
+ if (env.REASONALLY_API_KEY) {
46
+ const apiBaseUrl = env.REASONALLY_API_URL ?? (env.REASONALLY_URL ? `${appUrl}/v1` : DEFAULT_API_URL);
47
+ return {
48
+ appUrl,
49
+ apiBaseUrl: trimSlash(apiBaseUrl),
50
+ apiKey: env.REASONALLY_API_KEY,
51
+ fromEnv: true,
52
+ };
53
+ }
54
+ if (!creds)
55
+ return null;
56
+ return {
57
+ appUrl,
58
+ apiBaseUrl: trimSlash(env.REASONALLY_API_URL ?? creds.apiBaseUrl),
59
+ apiKey: creds.apiKey,
60
+ fromEnv: false,
61
+ };
62
+ }
63
+ const trimSlash = (url) => url.replace(/\/+$/, "");
64
+ /** Small per-agent memory (the last model used), for agents that need a model to start. */
65
+ const statePath = (env) => join(configDir(env), "state.json");
66
+ export async function readLastModel(agent, env = process.env) {
67
+ try {
68
+ const state = JSON.parse(await readFile(statePath(env), "utf8"));
69
+ const value = state.lastModel?.[agent];
70
+ return typeof value === "string" ? value : null;
71
+ }
72
+ catch {
73
+ return null;
74
+ }
75
+ }
76
+ export async function writeLastModel(agent, model, env = process.env) {
77
+ let state = {};
78
+ try {
79
+ state = JSON.parse(await readFile(statePath(env), "utf8"));
80
+ }
81
+ catch {
82
+ // first write
83
+ }
84
+ state.lastModel = { ...state.lastModel, [agent]: model };
85
+ await writePrivateFile(statePath(env), `${JSON.stringify(state, null, 2)}\n`);
86
+ }
@@ -0,0 +1,26 @@
1
+ import { emptyPlan } from "./types.js";
2
+ /**
3
+ * Cline keeps provider settings in its data directory (`CLINE_DATA_DIR`). We give it a separate
4
+ * one and configure its OpenAI-compatible provider there with `cline auth` before each launch
5
+ * (which also picks up a new key after a re-login). The user's own Cline setup is untouched,
6
+ * and their rules and skills in `~/.cline` still load. This is the one agent that stores the key
7
+ * itself, in that directory.
8
+ */
9
+ export const cline = {
10
+ id: "cline",
11
+ name: "Cline",
12
+ bin: "cline",
13
+ install: "npm install -g cline",
14
+ needsModel: true,
15
+ plan(ctx) {
16
+ const plan = emptyPlan("cline", ctx);
17
+ plan.env.CLINE_DATA_DIR = ctx.dir;
18
+ if (ctx.model) {
19
+ plan.setup.push({
20
+ args: ["auth", "-p", "openai", "-k", ctx.apiKey, "-b", ctx.apiBaseUrl, "-m", ctx.model.id],
21
+ env: { CLINE_DATA_DIR: ctx.dir },
22
+ });
23
+ }
24
+ return plan;
25
+ },
26
+ };
@@ -0,0 +1,47 @@
1
+ import { join } from "node:path";
2
+ import { configModels, emptyPlan, KEY_ENV, PROVIDER_ID, PROVIDER_NAME, } from "./types.js";
3
+ /** Single-quotes a value for Bash (Crush's crushrc is a Bash script). */
4
+ export const shellQuote = (value) => `'${value.replaceAll("'", `'\\''`)}'`;
5
+ /**
6
+ * Crush reads its global config from `$CRUSH_GLOBAL_CONFIG/crushrc`. We point that at our own
7
+ * directory with a generated crushrc that first sources the user's real one, so their settings,
8
+ * providers and MCP servers still load, then adds the Reasonally provider.
9
+ */
10
+ export const crush = {
11
+ id: "crush",
12
+ name: "Crush",
13
+ bin: "crush",
14
+ install: "npm install -g @charmland/crush",
15
+ plan(ctx) {
16
+ const lines = [
17
+ "# Generated by `reasonally crush` on every launch; edits here are overwritten.",
18
+ "# Your own global crushrc loads first, so your settings still apply.",
19
+ 'reasonally_user_rc="${XDG_CONFIG_HOME:-$HOME/.config}/crush/crushrc"',
20
+ 'if [[ -f "$reasonally_user_rc" ]]; then source "$reasonally_user_rc"; fi',
21
+ "",
22
+ [
23
+ `provider add ${PROVIDER_ID}`,
24
+ "--type openai-compat",
25
+ `--name ${shellQuote(PROVIDER_NAME)}`,
26
+ `--base-url ${shellQuote(ctx.apiBaseUrl)}`,
27
+ `--api-key "$${KEY_ENV}"`,
28
+ ].join(" "),
29
+ ...configModels(ctx).map((m) => [
30
+ `model add ${shellQuote(`${PROVIDER_ID}/${m.id}`)}`,
31
+ `--name ${shellQuote(m.name)}`,
32
+ `--context-window ${m.contextLength}`,
33
+ `--default-max-tokens ${m.maxOutput}`,
34
+ `--can-reason ${m.reasoning}`,
35
+ `--supports-images ${m.images}`,
36
+ `--price-input ${m.inputPerM}`,
37
+ `--price-output ${m.outputPerM}`,
38
+ ].join(" ")),
39
+ ];
40
+ if (ctx.model)
41
+ lines.push("", `model large ${shellQuote(`${PROVIDER_ID}/${ctx.model.id}`)}`);
42
+ const plan = emptyPlan("crush", ctx);
43
+ plan.env.CRUSH_GLOBAL_CONFIG = ctx.dir;
44
+ plan.files.push({ path: join(ctx.dir, "crushrc"), content: `${lines.join("\n")}\n` });
45
+ return plan;
46
+ },
47
+ };
@@ -0,0 +1,33 @@
1
+ import { emptyPlan } from "./types.js";
2
+ /** Hermes recommends at least this much context for agent work. */
3
+ export const HERMES_MIN_CONTEXT = 64_000;
4
+ /**
5
+ * `hermes chat` takes a custom OpenAI-compatible endpoint for one launch (`--provider custom
6
+ * --base-url --api-key`), which Hermes keeps in memory only. Nothing in `~/.hermes` changes, so
7
+ * the user's memory, skills and default provider stay as they are.
8
+ */
9
+ export const hermes = {
10
+ id: "hermes",
11
+ name: "Hermes",
12
+ bin: "hermes",
13
+ install: "curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash",
14
+ needsModel: true,
15
+ plan(ctx) {
16
+ const plan = emptyPlan("hermes", ctx);
17
+ plan.args = [
18
+ "chat",
19
+ "--provider",
20
+ "custom",
21
+ "--base-url",
22
+ ctx.apiBaseUrl,
23
+ "--api-key",
24
+ ctx.apiKey,
25
+ ...(ctx.model ? ["--model", ctx.model.id] : []),
26
+ ...ctx.args,
27
+ ];
28
+ if (ctx.model && ctx.model.contextLength < HERMES_MIN_CONTEXT) {
29
+ plan.notes.push(`${ctx.model.id} has a ${Math.round(ctx.model.contextLength / 1000)}K context window. Hermes works best with at least 64K.`);
30
+ }
31
+ return plan;
32
+ },
33
+ };
@@ -0,0 +1,7 @@
1
+ import { cline } from "./cline.js";
2
+ import { crush } from "./crush.js";
3
+ import { hermes } from "./hermes.js";
4
+ import { opencode } from "./opencode.js";
5
+ import { pi } from "./pi.js";
6
+ export const HARNESSES = [opencode, crush, cline, pi, hermes];
7
+ export const findHarness = (id) => HARNESSES.find((h) => h.id === id);
@@ -0,0 +1,44 @@
1
+ import { configModels, emptyPlan, KEY_ENV, PROVIDER_ID, PROVIDER_NAME, } from "./types.js";
2
+ /**
3
+ * OpenCode merges `OPENCODE_CONFIG_CONTENT` (inline JSON) over the user's config files, so the
4
+ * provider is injected for this launch only and nothing is written to disk.
5
+ */
6
+ export const opencode = {
7
+ id: "opencode",
8
+ name: "OpenCode",
9
+ bin: "opencode",
10
+ install: "npm install -g opencode-ai",
11
+ plan(ctx) {
12
+ const models = Object.fromEntries(configModels(ctx).map((m) => [
13
+ m.id,
14
+ {
15
+ name: m.name,
16
+ limit: { context: m.contextLength, output: m.maxOutput },
17
+ cost: { input: m.inputPerM, output: m.outputPerM },
18
+ reasoning: m.reasoning,
19
+ tool_call: m.tools,
20
+ attachment: m.images,
21
+ modalities: { input: m.images ? ["text", "image"] : ["text"], output: ["text"] },
22
+ },
23
+ ]));
24
+ const config = {
25
+ $schema: "https://opencode.ai/config.json",
26
+ provider: {
27
+ [PROVIDER_ID]: {
28
+ npm: "@ai-sdk/openai-compatible",
29
+ name: PROVIDER_NAME,
30
+ options: { baseURL: ctx.apiBaseUrl, apiKey: `{env:${KEY_ENV}}` },
31
+ models,
32
+ },
33
+ },
34
+ enabled_providers: [PROVIDER_ID],
35
+ ...(ctx.model && {
36
+ model: `${PROVIDER_ID}/${ctx.model.id}`,
37
+ small_model: `${PROVIDER_ID}/${ctx.model.id}`,
38
+ }),
39
+ };
40
+ const plan = emptyPlan("opencode", ctx);
41
+ plan.env.OPENCODE_CONFIG_CONTENT = JSON.stringify(config);
42
+ return plan;
43
+ },
44
+ };
@@ -0,0 +1,46 @@
1
+ import { join } from "node:path";
2
+ import { configModels, emptyPlan, KEY_ENV, PROVIDER_ID, PROVIDER_NAME, } from "./types.js";
3
+ /**
4
+ * Pi loads extensions passed with `-e`, and an extension can register a provider. We generate
5
+ * one per launch, so `~/.pi/agent` (models.json, sessions, settings) is never touched.
6
+ */
7
+ export const pi = {
8
+ id: "pi",
9
+ name: "Pi",
10
+ bin: "pi",
11
+ install: "npm install -g @earendil-works/pi-coding-agent",
12
+ plan(ctx) {
13
+ const provider = {
14
+ name: PROVIDER_NAME,
15
+ baseUrl: ctx.apiBaseUrl,
16
+ api: "openai-completions",
17
+ apiKey: `$${KEY_ENV}`,
18
+ models: configModels(ctx).map((m) => ({
19
+ id: m.id,
20
+ name: m.name,
21
+ reasoning: m.reasoning,
22
+ input: m.images ? ["text", "image"] : ["text"],
23
+ contextWindow: m.contextLength,
24
+ maxTokens: m.maxOutput,
25
+ cost: { input: m.inputPerM, output: m.outputPerM, cacheRead: 0, cacheWrite: 0 },
26
+ })),
27
+ };
28
+ const extension = [
29
+ "// Generated by `reasonally pi` on every launch; edits here are overwritten.",
30
+ "export default function (pi) {",
31
+ ` pi.registerProvider(${JSON.stringify(PROVIDER_ID)}, ${JSON.stringify(provider, null, 2).replaceAll("\n", "\n ")});`,
32
+ "}",
33
+ "",
34
+ ].join("\n");
35
+ const file = join(ctx.dir, "reasonally-provider.js");
36
+ const plan = emptyPlan("pi", ctx);
37
+ plan.files.push({ path: file, content: extension });
38
+ plan.args = [
39
+ "-e",
40
+ file,
41
+ ...(ctx.model ? ["--provider", PROVIDER_ID, "--model", ctx.model.id] : []),
42
+ ...ctx.args,
43
+ ];
44
+ return plan;
45
+ },
46
+ };
@@ -0,0 +1,18 @@
1
+ import { agentModels } from "../catalog.js";
2
+ export const PROVIDER_ID = "reasonally";
3
+ export const PROVIDER_NAME = "Reasonally";
4
+ /** The child process reads the key from here, so generated configs never contain it. */
5
+ export const KEY_ENV = "REASONALLY_API_KEY";
6
+ /** Tool-capable models plus the picked one (even if the catalog says it can't call tools). */
7
+ export function configModels(ctx) {
8
+ const list = agentModels(ctx.models);
9
+ return ctx.model && !list.some((m) => m.id === ctx.model?.id) ? [...list, ctx.model] : list;
10
+ }
11
+ export const emptyPlan = (command, ctx) => ({
12
+ command,
13
+ args: [...ctx.args],
14
+ env: { [KEY_ENV]: ctx.apiKey },
15
+ files: [],
16
+ setup: [],
17
+ notes: [],
18
+ });
package/dist/index.js ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import { main } from "./cli.js";
3
+ main(process.argv.slice(2)).then((code) => process.exit(code));
package/dist/launch.js ADDED
@@ -0,0 +1,59 @@
1
+ import { spawn } from "node:child_process";
2
+ import { writePrivateFile } from "./config.js";
3
+ /** npm installs agents as `.cmd` shims on Windows, which need a shell to start. */
4
+ const useShell = process.platform === "win32";
5
+ class NotInstalledError extends Error {
6
+ }
7
+ function run(command, args, env, stdio) {
8
+ return new Promise((resolve, reject) => {
9
+ const child = spawn(command, args, {
10
+ stdio: stdio === "inherit" ? "inherit" : ["ignore", "pipe", "pipe"],
11
+ env: { ...process.env, ...env },
12
+ shell: useShell,
13
+ });
14
+ let output = "";
15
+ child.stdout?.on("data", (chunk) => (output += chunk));
16
+ child.stderr?.on("data", (chunk) => (output += chunk));
17
+ child.on("error", (error) => reject(error.code === "ENOENT" ? new NotInstalledError() : error));
18
+ child.on("exit", (code, signal) => resolve({ code: code ?? (signal ? 128 + signalNumber(signal) : 1), output }));
19
+ });
20
+ }
21
+ const signalNumber = (signal) => ({ SIGHUP: 1, SIGINT: 2, SIGQUIT: 3, SIGTERM: 15 })[signal] ?? 1;
22
+ /**
23
+ * Writes the plan's files, runs its setup commands, then hands the terminal to the agent and
24
+ * returns its exit code. Ctrl-C goes to the agent (same process group), not to us.
25
+ */
26
+ export async function launch(harness, plan, log) {
27
+ for (const file of plan.files)
28
+ await writePrivateFile(file.path, file.content);
29
+ for (const note of plan.notes)
30
+ log(`Note: ${note}`);
31
+ try {
32
+ for (const step of plan.setup) {
33
+ const result = await run(plan.command, step.args, step.env, "pipe");
34
+ if (result.code !== 0) {
35
+ log(`Couldn't configure ${harness.name} (\`${harness.bin} ${step.args[0]}\` failed):`);
36
+ log(result.output.trim());
37
+ return result.code;
38
+ }
39
+ }
40
+ const ignore = () => { };
41
+ process.on("SIGINT", ignore);
42
+ process.on("SIGTERM", ignore);
43
+ try {
44
+ return (await run(plan.command, plan.args, plan.env, "inherit")).code;
45
+ }
46
+ finally {
47
+ process.off("SIGINT", ignore);
48
+ process.off("SIGTERM", ignore);
49
+ }
50
+ }
51
+ catch (error) {
52
+ if (!(error instanceof NotInstalledError))
53
+ throw error;
54
+ log(`${harness.name} isn't installed (no \`${harness.bin}\` on your PATH). Install it with:`);
55
+ log(`\n ${harness.install}\n`);
56
+ log(`Then run \`reasonally ${harness.id}\` again.`);
57
+ return 127;
58
+ }
59
+ }