@engenty/local-models 0.0.0-stage → 0.20.6

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Matthias Platzer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,42 @@
1
- # Temporary Holding Version
1
+ # @engenty/local-models
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
+ The models on a person's own computer. MIT.
4
+
5
+ - **Ollama** (`@engenty/local-models/ollama`). `ollamaRoot(url)` takes either way an address is
6
+ given: a root as OLLAMA_HOST names it (`http://127.0.0.1:11434`, `localhost`) or the
7
+ OpenAI-compatible `…/v1` as OLLAMA_URL names it. `ollamaState` says whether Ollama answers and
8
+ what it holds; `installedModels` describes each model (tools, vision, thinking, in memory),
9
+ asking Ollama once per digest; `fits(model, memory, share)` says whether a model leaves the
10
+ computer room, with the share the caller picks; `pullModel` downloads a model with the bytes
11
+ summed over its parts. `ollamaModel` is an AI SDK model on Ollama's own chat API, so a caller
12
+ sets the context length (`num_ctx`), thinking, tools and pictures.
13
+ - **Clients** (`@engenty/local-models/clients`). `CLIENTS` holds Claude Code, Codex and Cursor
14
+ Agent: how each is found and signed in (`detectClient`, cached for a minute), the environment
15
+ it runs in (the login shell's sign-in and PATH, no key of the host's: `resolveEnv`,
16
+ `clientEnv`, `stripKeys`), each as an AI SDK model that runs the client headless once per
17
+ call (`client.model(alias, options)`, the call's tools served over the host's MCP bridge), and
18
+ each as a chat turn with one MCP server, whose name and key variable the host gives
19
+ (`client.args(call)`, `client.events(line)`).
20
+ - **Probe** (`@engenty/local-models/probe`). `probe(source)` makes one short real call and
21
+ returns a state: `ok`, `absent`, `signed_out`, `no_model`, `too_big` or `failed`, with what the
22
+ source said. No words for people: each app words the states itself.
23
+
24
+ ```ts
25
+ import { CLIENTS } from "@engenty/local-models/clients";
26
+ import { installedModels, ollamaModel } from "@engenty/local-models/ollama";
27
+ import { probe } from "@engenty/local-models/probe";
28
+
29
+ const [first] = await installedModels("http://127.0.0.1:11434");
30
+ const model = ollamaModel({ url: "http://127.0.0.1:11434", model: first.name, context: 32_768 });
31
+
32
+ const args = CLIENTS.codex.args({
33
+ system: "…",
34
+ message: "Hello",
35
+ session: null,
36
+ dir: process.cwd(),
37
+ mcp: { name: "home", url: "http://127.0.0.1:4848/mcp", keyVar: "HOME_MCP_KEY" },
38
+ images: [],
39
+ });
40
+
41
+ const { state } = await probe({ kind: "client", client: "claude" });
42
+ ```
@@ -0,0 +1,89 @@
1
+ /**
2
+ * How an installed client answers one turn of a chat: the command line, what goes on stdin, and
3
+ * what its output lines mean. The client reaches only the host's MCP server, under the name the
4
+ * host gives it, and keeps the conversation itself; the host keeps the id it reports.
5
+ */
6
+ /** The host's MCP server for a turn. */
7
+ export interface ChatMcp {
8
+ /** The name the client knows the server by: its tools are `mcp__<name>__…` to Claude Code. */
9
+ name: string;
10
+ url: string;
11
+ /** Codex: the environment variable it reads the bearer key from; the host sets it for the turn. */
12
+ keyVar: string;
13
+ /** Claude Code: the MCP config file with the server and its key. */
14
+ configFile?: string;
15
+ }
16
+ /** What one turn hands the client. */
17
+ export interface ChatCall {
18
+ /** The instructions the client works by. */
19
+ system: string;
20
+ message: string;
21
+ /** The conversation to continue, as the client named it last time. */
22
+ session: string | null;
23
+ /** The folder the client runs in: Claude's MCP config, Cursor's workspace. */
24
+ dir: string;
25
+ /** The model the client runs, by its own name: left out, the client picks. */
26
+ model?: string;
27
+ /** The host's MCP server. Left out, the turn has no tools at all: a call that only writes text. */
28
+ mcp?: ChatMcp;
29
+ /** The pictures pasted with the message: base64 for Claude, files for Codex. */
30
+ images: {
31
+ mime: string;
32
+ base64: string;
33
+ file: string;
34
+ }[];
35
+ }
36
+ /** What one line of the client's output says. */
37
+ export type ChatEvent = {
38
+ kind: "text";
39
+ text: string;
40
+ } | {
41
+ kind: "tool";
42
+ name: string;
43
+ args: Record<string, unknown>;
44
+ started: boolean;
45
+ }
46
+ /** A tool has answered; `issues` is how many it found, if its answer speaks of them. */
47
+ | {
48
+ kind: "toolDone";
49
+ issues?: number;
50
+ }
51
+ /**
52
+ * The model is writing text this client hands over whole later on: for the turn's clock, and
53
+ * the piece itself where the client streams it.
54
+ */
55
+ | {
56
+ kind: "writing";
57
+ text?: string;
58
+ } | {
59
+ kind: "thinkingStart";
60
+ }
61
+ /** `whole`: the client gives its reasoning once that is done, not as it streams. */
62
+ | {
63
+ kind: "thinking";
64
+ text: string;
65
+ whole?: boolean;
66
+ } | {
67
+ kind: "session";
68
+ id: string;
69
+ } | {
70
+ kind: "failure";
71
+ detail: string;
72
+ }
73
+ /** The client's own summary of the answer, used where no text came before it. */
74
+ | {
75
+ kind: "result";
76
+ text: string;
77
+ };
78
+ /** A client as a chat: its command line and how to read it. */
79
+ export interface ChatClient {
80
+ args(call: ChatCall): string[];
81
+ stdin(call: ChatCall): string;
82
+ events(line: string): ChatEvent[];
83
+ /** Whether a failure the client reports means its sign-in is missing or expired. */
84
+ signedOut(detail: string): boolean;
85
+ }
86
+ export declare function parseLine(line: string): any;
87
+ export declare const record: (v: unknown) => Record<string, unknown>;
88
+ /** How many issues a tool's answer names; nothing where the answer does not speak of them. */
89
+ export declare function issuesIn(text: unknown): number | undefined;
@@ -0,0 +1,22 @@
1
+ /**
2
+ * How an installed client answers one turn of a chat: the command line, what goes on stdin, and
3
+ * what its output lines mean. The client reaches only the host's MCP server, under the name the
4
+ * host gives it, and keeps the conversation itself; the host keeps the id it reports.
5
+ */
6
+ export function parseLine(line) {
7
+ try {
8
+ return JSON.parse(line);
9
+ }
10
+ catch {
11
+ return null;
12
+ }
13
+ }
14
+ export const record = (v) => v && typeof v === "object" ? v : {};
15
+ /** How many issues a tool's answer names; nothing where the answer does not speak of them. */
16
+ export function issuesIn(text) {
17
+ if (typeof text !== "string" || !text.includes('"issues"')) {
18
+ return undefined;
19
+ }
20
+ const issues = parseLine(text)?.issues;
21
+ return Array.isArray(issues) ? issues.length : undefined;
22
+ }
@@ -0,0 +1,32 @@
1
+ import type { Client } from "./client.js";
2
+ import { type ClientAnswer } from "./model.js";
3
+ /**
4
+ * Claude Code: `claude -p` answers on the person's sign-in — the client's keychain, or the key
5
+ * or token their login shell sets. Tools go over MCP; structured output is validated by the
6
+ * client (`--json-schema`); web search is its own tool.
7
+ */
8
+ export declare const CLAUDE_BIN: string;
9
+ /** What the client prints last with `--output-format json`. */
10
+ export interface ClaudeResult {
11
+ type?: string;
12
+ /** On a failure: why, e.g. error_max_turns, error_during_execution. */
13
+ subtype?: string;
14
+ is_error?: boolean;
15
+ /** On a failure: what went wrong, where the client says. */
16
+ errors?: unknown[];
17
+ result?: unknown;
18
+ structured_output?: unknown;
19
+ session_id?: string;
20
+ stop_reason?: string;
21
+ total_cost_usd?: number;
22
+ num_turns?: number;
23
+ usage?: {
24
+ input_tokens?: number;
25
+ output_tokens?: number;
26
+ cache_read_input_tokens?: number;
27
+ cache_creation_input_tokens?: number;
28
+ };
29
+ }
30
+ /** The client's result as the model call wants it: text (or the structured output as JSON) and usage. */
31
+ export declare function claudeAnswer(event: ClaudeResult): ClientAnswer;
32
+ export declare const claude: Client;
@@ -0,0 +1,238 @@
1
+ import { issuesIn, parseLine, record } from "./chat.js";
2
+ import { probeVersion, resolveEnv, run } from "./env.js";
3
+ import { clientFailure } from "./failure.js";
4
+ import { ClientModel } from "./model.js";
5
+ import { lastJson, runClient } from "./run.js";
6
+ /**
7
+ * Claude Code: `claude -p` answers on the person's sign-in — the client's keychain, or the key
8
+ * or token their login shell sets. Tools go over MCP; structured output is validated by the
9
+ * client (`--json-schema`); web search is its own tool.
10
+ */
11
+ export const CLAUDE_BIN = process.env.CLAUDE_BIN?.trim() || "claude";
12
+ const spec = {
13
+ id: "claude",
14
+ passThrough: /^(ANTHROPIC_|CLAUDE_CODE_OAUTH_TOKEN$|CLAUDE_CODE_USE_|CLAUDE_CONFIG_DIR$|AWS_(PROFILE|REGION|DEFAULT_REGION|ACCESS_KEY_ID|SECRET_ACCESS_KEY|SESSION_TOKEN)$|GOOGLE_APPLICATION_CREDENTIALS$|CLOUD_ML_REGION$)/,
15
+ keyVars: ["ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN"],
16
+ async auth(env) {
17
+ try {
18
+ const { stdout } = await run(CLAUDE_BIN, ["auth", "status", "--json"], {
19
+ timeout: 15_000,
20
+ env,
21
+ });
22
+ const status = JSON.parse(stdout.trim());
23
+ if (!status.loggedIn) {
24
+ return "none";
25
+ }
26
+ return status.authMethod === "api_key" ? "api_key" : "subscription";
27
+ }
28
+ catch {
29
+ return "none";
30
+ }
31
+ },
32
+ };
33
+ /** The client's result as the model call wants it: text (or the structured output as JSON) and usage. */
34
+ export function claudeAnswer(event) {
35
+ const u = event.usage ?? {};
36
+ const cacheRead = u.cache_read_input_tokens ?? 0;
37
+ const cacheWrite = u.cache_creation_input_tokens ?? 0;
38
+ return {
39
+ text: event.structured_output !== undefined
40
+ ? JSON.stringify(event.structured_output)
41
+ : typeof event.result === "string"
42
+ ? event.result
43
+ : JSON.stringify(event.result ?? ""),
44
+ usage: {
45
+ input: (u.input_tokens ?? 0) + cacheRead + cacheWrite,
46
+ cacheRead,
47
+ cacheWrite,
48
+ output: u.output_tokens ?? 0,
49
+ },
50
+ meta: { costUsd: event.total_cost_usd ?? 0, turns: event.num_turns ?? 1 },
51
+ sessionId: event.session_id,
52
+ stopReason: event.stop_reason,
53
+ };
54
+ }
55
+ class ClaudeCodeModel extends ClientModel {
56
+ provider = "claude-code";
57
+ nativeSchema = true;
58
+ async invoke(call) {
59
+ const builtin = [];
60
+ if (call.files.length) {
61
+ builtin.push("Read");
62
+ }
63
+ if (call.webSearch) {
64
+ builtin.push("WebSearch");
65
+ }
66
+ const args = [
67
+ "-p",
68
+ "--output-format",
69
+ "json",
70
+ "--model",
71
+ this.modelId,
72
+ "--tools",
73
+ builtin.join(","),
74
+ "--strict-mcp-config",
75
+ "--setting-sources",
76
+ "",
77
+ "--disable-slash-commands",
78
+ "--no-session-persistence",
79
+ ];
80
+ if (call.system) {
81
+ args.push("--system-prompt", call.system);
82
+ }
83
+ if (call.effort) {
84
+ args.push("--effort", call.effort);
85
+ }
86
+ if (call.schema) {
87
+ // The CLI checks the schema with no dialects loaded: one that names its own is refused.
88
+ const { $schema: _dialect, ...schema } = call.schema;
89
+ args.push("--json-schema", JSON.stringify(schema));
90
+ }
91
+ if (call.bridgeUrl) {
92
+ args.push("--mcp-config", JSON.stringify({ mcpServers: { step: { type: "http", url: call.bridgeUrl } } }));
93
+ }
94
+ const allowed = [...builtin, ...(call.bridgeUrl ? ["mcp__step"] : [])];
95
+ if (allowed.length) {
96
+ args.push("--allowedTools", allowed.join(","));
97
+ }
98
+ if (call.files.length) {
99
+ args.push("--add-dir", call.dir);
100
+ }
101
+ const { stdout, stderr, code } = await runClient(CLAUDE_BIN, args, {
102
+ cwd: call.dir,
103
+ env: (await resolveEnv(spec)).env,
104
+ signal: call.signal,
105
+ stdin: call.prompt,
106
+ });
107
+ const event = lastJson(stdout);
108
+ if (!event) {
109
+ throw clientFailure(this.client, stderr.trim() || `exit ${code}`);
110
+ }
111
+ if (event.is_error) {
112
+ // A failed run carries no result, only why (subtype) and sometimes what (errors).
113
+ const why = [
114
+ typeof event.result === "string" ? event.result : "",
115
+ event.subtype ?? "",
116
+ ...(event.errors ?? []).map((e) => (typeof e === "string" ? e : JSON.stringify(e))),
117
+ event.num_turns ? `after ${event.num_turns} turns` : "",
118
+ ].filter(Boolean);
119
+ throw clientFailure(this.client, why.join(" – ") || "error", JSON.stringify(event).slice(0, 2000));
120
+ }
121
+ return claudeAnswer(event);
122
+ }
123
+ }
124
+ export const claude = {
125
+ ...spec,
126
+ id: "claude",
127
+ name: "Claude Code",
128
+ bin: CLAUDE_BIN,
129
+ version: (env) => probeVersion(CLAUDE_BIN, env, (stdout) => stdout.trim().split(/\s+/)[0] || stdout.trim()),
130
+ login: { args: ["auth", "login"], interactive: false },
131
+ model: (alias, options) => new ClaudeCodeModel(claude, alias || "sonnet", options),
132
+ args: (call) => [
133
+ // The message comes on stdin, so pictures can go with it.
134
+ "-p",
135
+ "--input-format",
136
+ "stream-json",
137
+ "--output-format",
138
+ "stream-json",
139
+ "--verbose",
140
+ // Names a tool as it starts and streams the thinking; whole messages still follow.
141
+ "--include-partial-messages",
142
+ // No built-in tools: `--allowedTools` alone would not take them away.
143
+ "--tools",
144
+ "",
145
+ "--strict-mcp-config",
146
+ ...(call.mcp
147
+ ? ["--mcp-config", call.mcp.configFile ?? "", "--allowedTools", `mcp__${call.mcp.name}`]
148
+ : []),
149
+ "--disable-slash-commands",
150
+ "--setting-sources",
151
+ "",
152
+ "--append-system-prompt",
153
+ call.system,
154
+ ...(call.model ? ["--model", call.model] : []),
155
+ ...(call.session ? ["--resume", call.session] : []),
156
+ ],
157
+ stdin: (call) => `${JSON.stringify({
158
+ type: "user",
159
+ message: {
160
+ role: "user",
161
+ content: [
162
+ { type: "text", text: call.message },
163
+ ...call.images.map((i) => ({
164
+ type: "image",
165
+ source: { type: "base64", media_type: i.mime, data: i.base64 },
166
+ })),
167
+ ],
168
+ },
169
+ })}\n`,
170
+ events(line) {
171
+ const event = parseLine(line);
172
+ if (!event) {
173
+ return [];
174
+ }
175
+ if (event.type === "stream_event") {
176
+ const e = event.event ?? {};
177
+ if (e.type === "content_block_start" && e.content_block?.type === "tool_use") {
178
+ return [
179
+ { kind: "tool", name: String(e.content_block.name ?? ""), args: {}, started: false },
180
+ ];
181
+ }
182
+ if (e.type === "content_block_start" && e.content_block?.type === "thinking") {
183
+ return [{ kind: "thinkingStart" }];
184
+ }
185
+ if (e.type === "content_block_delta" && e.delta?.type === "thinking_delta") {
186
+ return [{ kind: "thinking", text: e.delta.thinking ?? "" }];
187
+ }
188
+ if (e.type === "content_block_delta" && e.delta?.type === "text_delta") {
189
+ return [{ kind: "writing", text: String(e.delta.text ?? "") }];
190
+ }
191
+ return [];
192
+ }
193
+ if (event.type === "user") {
194
+ const out = [];
195
+ for (const block of event.message?.content ?? []) {
196
+ if (block.type === "tool_result") {
197
+ const text = Array.isArray(block.content)
198
+ ? block.content.find((c) => c.type === "text")?.text
199
+ : block.content;
200
+ out.push({ kind: "toolDone", issues: issuesIn(text) });
201
+ }
202
+ }
203
+ return out;
204
+ }
205
+ if (event.type === "assistant") {
206
+ const out = [];
207
+ for (const block of event.message?.content ?? []) {
208
+ if (block.type === "text" && block.text) {
209
+ out.push({ kind: "text", text: block.text });
210
+ }
211
+ else if (block.type === "tool_use") {
212
+ out.push({
213
+ kind: "tool",
214
+ name: String(block.name ?? ""),
215
+ args: record(block.input),
216
+ started: true,
217
+ });
218
+ }
219
+ }
220
+ return out;
221
+ }
222
+ if (event.type === "result") {
223
+ const out = [];
224
+ if (event.session_id) {
225
+ out.push({ kind: "session", id: String(event.session_id) });
226
+ }
227
+ if (event.is_error) {
228
+ out.push({ kind: "failure", detail: String(event.result ?? "error") });
229
+ }
230
+ else if (typeof event.result === "string") {
231
+ out.push({ kind: "result", text: event.result });
232
+ }
233
+ return out;
234
+ }
235
+ return [];
236
+ },
237
+ signedOut: (detail) => /authenticat|log ?in|oauth|credential/i.test(detail),
238
+ };
@@ -0,0 +1,29 @@
1
+ import type { ChatClient } from "./chat.js";
2
+ import type { EnvSpec } from "./env.js";
3
+ import type { ClientMeta } from "./failure.js";
4
+ import type { ClientModel, ClientModelOptions } from "./model.js";
5
+ /** The AI clients a person signs in to with their own subscription. */
6
+ export declare const CLIENT_IDS: readonly ["claude", "codex", "cursor"];
7
+ export type ClientId = (typeof CLIENT_IDS)[number];
8
+ /**
9
+ * An AI client installed on this computer that answers on the person's own subscription or
10
+ * sign-in: how it is found and signed in, how it runs headless as a model, and how it answers a
11
+ * chat turn with the host's MCP server. Nothing of the host's process reaches it: no key of the
12
+ * host's, no session of a parent client.
13
+ */
14
+ export interface Client extends EnvSpec, ChatClient, ClientMeta {
15
+ id: ClientId;
16
+ bin: string;
17
+ /** Null: not installed. Throws ProbeUndecided when the probe could not finish on a busy machine. */
18
+ version(env: NodeJS.ProcessEnv): Promise<string | null>;
19
+ /**
20
+ * What a terminal runs to sign the client in. `interactive`: the client's own app opens and the
21
+ * person ends it.
22
+ */
23
+ login: {
24
+ args: string[];
25
+ interactive: boolean;
26
+ };
27
+ /** The client as a model; `alias` is the model by the client's own name. */
28
+ model(alias: string, options?: ClientModelOptions): ClientModel;
29
+ }
@@ -0,0 +1,2 @@
1
+ /** The AI clients a person signs in to with their own subscription. */
2
+ export const CLIENT_IDS = ["claude", "codex", "cursor"];
@@ -0,0 +1,35 @@
1
+ import type { Client } from "./client.js";
2
+ import { type ClientAnswer } from "./model.js";
3
+ /**
4
+ * Codex: `codex exec` answers on the ChatGPT sign-in kept in CODEX_HOME. The person's own
5
+ * config is left out so none of their MCP servers start for a call; tools go over MCP through
6
+ * a config override; structured output is validated by the client (`--output-schema`).
7
+ */
8
+ export declare const CODEX_BIN: string;
9
+ /** One line of `codex exec --json`. */
10
+ export interface CodexEvent {
11
+ type?: string;
12
+ item?: {
13
+ type?: string;
14
+ text?: string;
15
+ };
16
+ usage?: {
17
+ input_tokens?: number;
18
+ cached_input_tokens?: number;
19
+ cache_write_input_tokens?: number;
20
+ output_tokens?: number;
21
+ };
22
+ error?: {
23
+ message?: string;
24
+ } | string;
25
+ message?: string;
26
+ thread_id?: string;
27
+ }
28
+ /** The events of one run as the model call wants them: the last agent message and the usage. */
29
+ export declare function codexAnswer(stdout: string): {
30
+ answer: ClientAnswer | null;
31
+ failure: string | null;
32
+ };
33
+ /** The arguments every headless `codex exec` starts with: read-only, no approvals, nothing of the person's config. */
34
+ export declare function codexExecArgs(dir: string, webSearch: boolean): string[];
35
+ export declare const codex: Client;