reasonally 0.0.0-stage → 0.1.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,3 +1,52 @@
1
- # Temporary Holding Version
1
+ # reasonally
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Run the coding agents you already use on Reasonally models, billed to your Reasonally workspace.
4
+
5
+ ```bash
6
+ npm install -g reasonally
7
+ reasonally login # approve this computer in your browser
8
+ reasonally opencode --model anthropic/claude-sonnet-4.5
9
+ ```
10
+
11
+ Needs Node.js 20 or later.
12
+
13
+ ## Agents
14
+
15
+ | Command | Agent |
16
+ | --------------------- | ----------------------------------------------------- |
17
+ | `reasonally opencode` | [OpenCode](https://opencode.ai) |
18
+ | `reasonally crush` | [Crush](https://github.com/charmbracelet/crush) |
19
+ | `reasonally cline` | [Cline](https://cline.bot) CLI |
20
+ | `reasonally pi` | [Pi](https://pi.dev) |
21
+ | `reasonally hermes` | [Hermes Agent](https://hermes-agent.nousresearch.com) |
22
+
23
+ Each agent keeps its own interface. Anything after the agent's name, except `--model`, is passed
24
+ to it unchanged. Without `--model`, pick a Reasonally model in the agent's own model picker
25
+ (Cline and Hermes need one to start; the last one you used is remembered).
26
+
27
+ The CLI points each agent at Reasonally for that launch without editing the agent's own config:
28
+
29
+ - **OpenCode**: inline config through `OPENCODE_CONFIG_CONTENT`.
30
+ - **Crush**: a generated `crushrc` (via `CRUSH_GLOBAL_CONFIG`) that loads your own crushrc first.
31
+ - **Cline**: a separate data directory (`CLINE_DATA_DIR`) configured with `cline auth`.
32
+ - **Pi**: a generated provider extension loaded with `-e`.
33
+ - **Hermes**: `hermes chat --provider custom` for that launch; `~/.hermes` is untouched.
34
+
35
+ Generated files live in `~/.config/reasonally/harness/`.
36
+
37
+ ## Other commands
38
+
39
+ ```bash
40
+ reasonally models [search] # models you can use, with context and price
41
+ reasonally whoami # account and balance
42
+ reasonally logout # log out and revoke this computer's key
43
+ reasonally login --no-browser # print the approval link instead of opening it
44
+ ```
45
+
46
+ ## Environment
47
+
48
+ | Variable | Use |
49
+ | -------------------- | ------------------------------------------------------------ |
50
+ | `REASONALLY_API_KEY` | Use an existing API key instead of logging in (CI, servers). |
51
+ | `REASONALLY_URL` | Dashboard URL (default `https://app.reasonally.ai`). |
52
+ | `REASONALLY_API_URL` | API base URL (default `https://api.reasonally.ai/v1`). |
package/dist/api.js ADDED
@@ -0,0 +1,50 @@
1
+ import { parseCatalog } from "./catalog.js";
2
+ /** A failed call to Reasonally, carrying the server's OpenAI-shaped error message. */
3
+ export class ApiError extends Error {
4
+ status;
5
+ code;
6
+ constructor(message, status, code) {
7
+ super(message);
8
+ this.status = status;
9
+ this.code = code;
10
+ }
11
+ }
12
+ async function call(url, init = {}) {
13
+ let res;
14
+ try {
15
+ res = await fetch(url, { ...init, signal: AbortSignal.timeout(30_000) });
16
+ }
17
+ catch (error) {
18
+ throw new ApiError(`Couldn't reach ${new URL(url).host}: ${error.message}`, 0, null);
19
+ }
20
+ const body = (await res.json().catch(() => null));
21
+ if (!res.ok) {
22
+ const message = body?.error?.message ?? `Request failed with HTTP ${res.status}.`;
23
+ throw new ApiError(message, res.status, body?.error?.code ?? null);
24
+ }
25
+ if (body === null)
26
+ throw new ApiError("The server sent an unreadable response.", res.status, null);
27
+ return body;
28
+ }
29
+ const bearer = (apiKey) => ({ authorization: `Bearer ${apiKey}` });
30
+ export function exchangeCode(appUrl, body) {
31
+ return call(`${appUrl}/api/cli/token`, {
32
+ method: "POST",
33
+ headers: { "content-type": "application/json" },
34
+ body: JSON.stringify(body),
35
+ });
36
+ }
37
+ export function fetchAccount(appUrl, apiKey) {
38
+ return call(`${appUrl}/api/cli/me`, {
39
+ headers: bearer(apiKey),
40
+ });
41
+ }
42
+ export function revokeKey(appUrl, apiKey) {
43
+ return call(`${appUrl}/api/cli/logout`, {
44
+ method: "POST",
45
+ headers: bearer(apiKey),
46
+ });
47
+ }
48
+ export async function fetchModels(apiBaseUrl, apiKey) {
49
+ return parseCatalog(await call(`${apiBaseUrl}/models`, { headers: bearer(apiKey) }));
50
+ }
@@ -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,214 @@
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
+
18
+ Agents:
19
+ ${HARNESSES.map((h) => ` ${h.id.padEnd(10)} ${h.name}`).join("\n")}
20
+
21
+ Anything after the agent's name (except --model) is passed to it unchanged.
22
+ Set REASONALLY_API_KEY to use an existing key instead of logging in.`;
23
+ /** Pulls our `--model` out of an agent's arguments; everything else passes through. */
24
+ export function splitModelFlag(args) {
25
+ const rest = [];
26
+ let model = null;
27
+ for (let i = 0; i < args.length; i++) {
28
+ const arg = args[i];
29
+ if (arg === "--") {
30
+ rest.push(...args.slice(i));
31
+ break;
32
+ }
33
+ if (model === null && arg === "--model" && i + 1 < args.length) {
34
+ model = args[++i];
35
+ }
36
+ else if (model === null && arg.startsWith("--model=")) {
37
+ model = arg.slice("--model=".length);
38
+ }
39
+ else {
40
+ rest.push(arg);
41
+ }
42
+ }
43
+ return { model, rest };
44
+ }
45
+ async function requireSession() {
46
+ const session = resolveSession(process.env, await readCredentials());
47
+ if (!session)
48
+ throw new UsageError("You're not logged in. Run `reasonally login` first.");
49
+ return session;
50
+ }
51
+ class UsageError extends Error {
52
+ }
53
+ async function login(args) {
54
+ const previous = await readCredentials();
55
+ const appUrl = appUrlFrom(process.env, previous);
56
+ const token = await browserLogin(appUrl, log, { open: !args.includes("--no-browser") });
57
+ await writeCredentials({
58
+ appUrl,
59
+ apiBaseUrl: token.api_base_url,
60
+ apiKey: token.api_key,
61
+ keyId: token.key_id,
62
+ email: token.email,
63
+ });
64
+ // Retire the key from the previous login so repeat logins don't pile up keys.
65
+ if (previous && previous.apiKey !== token.api_key) {
66
+ await revokeKey(previous.appUrl, previous.apiKey).catch(() => { });
67
+ }
68
+ log(`Logged in as ${token.email}.`);
69
+ if (process.env.REASONALLY_API_KEY) {
70
+ log("Note: REASONALLY_API_KEY is set in your environment and takes precedence over this login.");
71
+ }
72
+ log(`Start an agent, e.g. \`reasonally ${HARNESSES[0].id}\`.`);
73
+ return 0;
74
+ }
75
+ async function logout() {
76
+ const creds = await readCredentials();
77
+ if (!creds) {
78
+ log("You're not logged in.");
79
+ return 0;
80
+ }
81
+ try {
82
+ await revokeKey(creds.appUrl, creds.apiKey);
83
+ }
84
+ catch (error) {
85
+ // An already-revoked key is fine; anything else leaves a key the user should revoke.
86
+ if (!(error instanceof ApiError && error.status === 401)) {
87
+ log(`Couldn't revoke this computer's key (${error.message}).`);
88
+ log("Revoke it on the API keys page of your dashboard.");
89
+ }
90
+ }
91
+ await deleteCredentials();
92
+ log("Logged out.");
93
+ return 0;
94
+ }
95
+ async function whoami() {
96
+ const session = await requireSession();
97
+ const account = await fetchAccount(session.appUrl, session.apiKey);
98
+ console.log(`${account.email} · ${account.workspace}`);
99
+ console.log(`Balance: ${account.balance}`);
100
+ if (session.fromEnv)
101
+ console.log("(using the key in REASONALLY_API_KEY)");
102
+ return 0;
103
+ }
104
+ const formatK = (tokens) => tokens >= 1_000_000 ? `${+(tokens / 1_000_000).toFixed(2)}M` : `${Math.round(tokens / 1000)}K`;
105
+ export function formatModels(models) {
106
+ const rows = models.map((m) => [
107
+ m.id,
108
+ formatK(m.contextLength),
109
+ `$${m.inputPerM} / $${m.outputPerM}`,
110
+ [m.tools && "tools", m.images && "images", m.reasoning && "reasoning"]
111
+ .filter(Boolean)
112
+ .join(", "),
113
+ ]);
114
+ const header = ["MODEL", "CONTEXT", "PRICE PER 1M (IN / OUT)", "SUPPORTS"];
115
+ const widths = header.map((h, i) => Math.max(h.length, ...rows.map((r) => r[i].length)));
116
+ return [header, ...rows]
117
+ .map((r) => r
118
+ .map((cell, i) => cell.padEnd(widths[i]))
119
+ .join(" ")
120
+ .trimEnd())
121
+ .join("\n");
122
+ }
123
+ async function models(search) {
124
+ const session = await requireSession();
125
+ const all = await fetchModels(session.apiBaseUrl, session.apiKey);
126
+ const words = search.join(" ").toLowerCase().split(/\s+/).filter(Boolean);
127
+ const matches = all.filter((m) => words.every((w) => `${m.id} ${m.name}`.toLowerCase().includes(w)));
128
+ if (matches.length === 0) {
129
+ log(words.length ? `No models match "${search.join(" ")}".` : "No models are available.");
130
+ return 1;
131
+ }
132
+ console.log(formatModels(matches));
133
+ return 0;
134
+ }
135
+ async function runAgent(harness, args) {
136
+ const session = await requireSession();
137
+ const { model: requested, rest } = splitModelFlag(args);
138
+ const catalog = await fetchModels(session.apiBaseUrl, session.apiKey);
139
+ const wanted = requested ?? (harness.needsModel ? await readLastModel(harness.id) : null);
140
+ let model = null;
141
+ if (wanted) {
142
+ const match = findModel(catalog, wanted);
143
+ if (!match.ok) {
144
+ log(`Unknown model "${wanted}".`);
145
+ if (match.suggestions.length)
146
+ log(`Did you mean:\n ${match.suggestions.join("\n ")}`);
147
+ log("See all models with `reasonally models`.");
148
+ return 1;
149
+ }
150
+ model = match.model;
151
+ }
152
+ if (harness.needsModel && !model) {
153
+ log(`${harness.name} needs a model to start. Pick one (it's remembered for next time):`);
154
+ log(`\n reasonally ${harness.id} --model <id>\n`);
155
+ log("See all models with `reasonally models`.");
156
+ return 1;
157
+ }
158
+ if (model && harness.needsModel)
159
+ await writeLastModel(harness.id, model.id);
160
+ const plan = harness.plan({
161
+ apiBaseUrl: session.apiBaseUrl,
162
+ apiKey: session.apiKey,
163
+ models: catalog,
164
+ model,
165
+ dir: harnessDir(harness.id),
166
+ args: rest,
167
+ });
168
+ return launch(harness, plan, log);
169
+ }
170
+ export async function main(argv) {
171
+ const [command, ...args] = argv;
172
+ try {
173
+ switch (command) {
174
+ case undefined:
175
+ case "help":
176
+ case "--help":
177
+ case "-h":
178
+ console.log(HELP);
179
+ return 0;
180
+ case "--version":
181
+ case "-v":
182
+ console.log(createRequire(import.meta.url)("../package.json").version);
183
+ return 0;
184
+ case "login":
185
+ return await login(args);
186
+ case "logout":
187
+ return await logout();
188
+ case "whoami":
189
+ return await whoami();
190
+ case "models":
191
+ return await models(args);
192
+ }
193
+ const harness = findHarness(command);
194
+ if (!harness) {
195
+ log(`Unknown command "${command}".\n\n${HELP}`);
196
+ return 1;
197
+ }
198
+ return await runAgent(harness, args);
199
+ }
200
+ catch (error) {
201
+ if (error instanceof UsageError) {
202
+ log(error.message);
203
+ return 1;
204
+ }
205
+ if (error instanceof ApiError) {
206
+ log(error.status === 401
207
+ ? "Your login was rejected (the key may have been revoked). Run `reasonally login` again."
208
+ : error.message);
209
+ return 1;
210
+ }
211
+ log(error.message);
212
+ return 1;
213
+ }
214
+ }
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
+ }
package/dist/login.js ADDED
@@ -0,0 +1,113 @@
1
+ import { spawn } from "node:child_process";
2
+ import { createServer } from "node:http";
3
+ import { hostname } from "node:os";
4
+ import { exchangeCode } from "./api.js";
5
+ import { createPkce } from "./pkce.js";
6
+ /** How long to wait for the user to approve in the browser. */
7
+ const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
8
+ export function authorizeUrl(appUrl, params) {
9
+ const query = new URLSearchParams({
10
+ redirect_uri: params.redirectUri,
11
+ code_challenge: params.challenge,
12
+ code_challenge_method: "S256",
13
+ state: params.state,
14
+ device: params.device,
15
+ });
16
+ return `${appUrl}/cli/authorize?${query}`;
17
+ }
18
+ /** Interprets a request to the loopback server. Only `/callback` with our `state` counts. */
19
+ export function readCallback(requestUrl, state) {
20
+ const url = new URL(requestUrl, "http://127.0.0.1");
21
+ if (url.pathname !== "/callback")
22
+ return { kind: "ignore" };
23
+ if (url.searchParams.get("state") !== state)
24
+ return { kind: "invalid" };
25
+ if (url.searchParams.get("error") === "access_denied")
26
+ return { kind: "denied" };
27
+ const code = url.searchParams.get("code");
28
+ return code ? { kind: "code", code } : { kind: "invalid" };
29
+ }
30
+ const page = (title, body) => `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${title}</title><style>body{font:16px/1.5 system-ui,sans-serif;display:grid;place-items:center;min-height:100vh;margin:0;padding:0 16px;color:#111;background:#fafafa}@media(prefers-color-scheme:dark){body{color:#eee;background:#111}}main{max-width:28rem;text-align:center}h1{font-size:1.25rem}</style></head><body><main><h1>${title}</h1><p>${body}</p></main></body></html>`;
31
+ function openBrowser(url) {
32
+ const [command, args] = process.platform === "darwin"
33
+ ? ["open", [url]]
34
+ : process.platform === "win32"
35
+ ? ["cmd", ["/c", "start", '""', url.replaceAll("&", "^&")]]
36
+ : ["xdg-open", [url]];
37
+ try {
38
+ const child = spawn(command, args, { stdio: "ignore", detached: true });
39
+ child.on("error", () => { }); // no browser: the printed URL still works
40
+ child.unref();
41
+ }
42
+ catch {
43
+ // same
44
+ }
45
+ }
46
+ /** Waits for the browser to come back to the loopback server with a code (or a refusal). */
47
+ function waitForCallback(server, state) {
48
+ return new Promise((resolve, reject) => {
49
+ const timer = setTimeout(() => reject(new Error("Timed out waiting for approval in the browser. Run the login again.")), LOGIN_TIMEOUT_MS);
50
+ server.on("request", (req, res) => {
51
+ const result = readCallback(req.url ?? "/", state);
52
+ const reply = (status, title, body) => {
53
+ res.writeHead(status, { "content-type": "text/html; charset=utf-8", connection: "close" });
54
+ res.end(page(title, body));
55
+ };
56
+ if (result.kind === "ignore")
57
+ return reply(404, "Not found", "Nothing to see here.");
58
+ clearTimeout(timer);
59
+ if (result.kind === "code") {
60
+ reply(200, "You're logged in", "You can close this tab and go back to your terminal.");
61
+ resolve(result.code);
62
+ }
63
+ else if (result.kind === "denied") {
64
+ reply(200, "Login cancelled", "You can close this tab.");
65
+ reject(new Error("Login was cancelled in the browser."));
66
+ }
67
+ else {
68
+ reply(400, "Login failed", "This response didn't match the login in your terminal.");
69
+ reject(new Error("The browser returned an unexpected response. Run the login again."));
70
+ }
71
+ });
72
+ });
73
+ }
74
+ /**
75
+ * Browser login: opens the approval page, receives the code on a one-shot loopback server and
76
+ * exchanges it (with the PKCE verifier) for an API key.
77
+ */
78
+ export async function browserLogin(appUrl, log, { open = true } = {}) {
79
+ const pkce = createPkce();
80
+ const server = createServer();
81
+ await new Promise((resolve, reject) => {
82
+ server.once("error", reject);
83
+ server.listen(0, "127.0.0.1", () => resolve());
84
+ });
85
+ try {
86
+ const { port } = server.address();
87
+ const redirectUri = `http://127.0.0.1:${port}/callback`;
88
+ const url = authorizeUrl(appUrl, {
89
+ redirectUri,
90
+ challenge: pkce.challenge,
91
+ state: pkce.state,
92
+ device: hostname().replace(/\.local$/, ""),
93
+ });
94
+ if (open) {
95
+ log("Opening your browser to approve this computer…");
96
+ log(`If it doesn't open, visit:\n\n ${url}\n`);
97
+ openBrowser(url);
98
+ }
99
+ else {
100
+ log(`Open this link in the browser where you're signed in, on this computer:\n\n ${url}\n`);
101
+ }
102
+ const code = await waitForCallback(server, pkce.state);
103
+ return await exchangeCode(appUrl, {
104
+ code,
105
+ code_verifier: pkce.verifier,
106
+ redirect_uri: redirectUri,
107
+ });
108
+ }
109
+ finally {
110
+ server.closeAllConnections();
111
+ server.close();
112
+ }
113
+ }
package/dist/pkce.js ADDED
@@ -0,0 +1,10 @@
1
+ import { createHash, randomBytes } from "node:crypto";
2
+ /** A PKCE pair (RFC 7636, S256) and a `state` value for one browser login. */
3
+ export function createPkce() {
4
+ const verifier = randomBytes(32).toString("base64url");
5
+ return {
6
+ verifier,
7
+ challenge: createHash("sha256").update(verifier).digest("base64url"),
8
+ state: randomBytes(16).toString("base64url"),
9
+ };
10
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "reasonally",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Run the coding agents you already use on Reasonally models.",
5
+ "type": "module",
6
+ "bin": {
7
+ "reasonally": "dist/index.js"
8
+ },
9
+ "files": [
10
+ "dist"
11
+ ],
12
+ "engines": {
13
+ "node": ">=20"
14
+ },
15
+ "scripts": {
16
+ "build": "tsc -p tsconfig.build.json",
17
+ "prepublishOnly": "npm run build"
18
+ },
19
+ "keywords": [
20
+ "llm",
21
+ "cli",
22
+ "coding-agent",
23
+ "opencode",
24
+ "crush",
25
+ "cline",
26
+ "pi",
27
+ "hermes"
28
+ ],
29
+ "license": "UNLICENSED"
30
+ }