@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.
@@ -0,0 +1,302 @@
1
+ import { ollamaRoot } from "./api.js";
2
+ const asObject = (input) => {
3
+ if (typeof input !== "string") {
4
+ return input ?? {};
5
+ }
6
+ try {
7
+ return JSON.parse(input);
8
+ }
9
+ catch {
10
+ return {};
11
+ }
12
+ };
13
+ /** A file part's bytes as base64, however the AI SDK hands them over. */
14
+ export function base64Of(data) {
15
+ if (data instanceof Uint8Array) {
16
+ return Buffer.from(data).toString("base64");
17
+ }
18
+ if (data && typeof data === "object" && data.type === "data") {
19
+ return base64Of(data.data);
20
+ }
21
+ if (typeof data !== "string") {
22
+ return undefined;
23
+ }
24
+ return data.startsWith("data:") ? data.slice(data.indexOf(",") + 1) : data;
25
+ }
26
+ /** The base64 of a picture in a tool's answer, when it is one. */
27
+ function pictureOf(piece) {
28
+ if (!piece.mediaType?.startsWith("image/")) {
29
+ return undefined;
30
+ }
31
+ return base64Of(piece.data);
32
+ }
33
+ /**
34
+ * The AI SDK's prompt as Ollama's messages. Pictures go along with the newest message of the
35
+ * person and what tools showed after it; an older message names its pictures instead, so they
36
+ * are not sent again each turn.
37
+ */
38
+ export function ollamaMessages(prompt) {
39
+ const messages = [];
40
+ const newest = prompt.findLastIndex((message) => message.role === "user");
41
+ for (const [at, message] of prompt.entries()) {
42
+ if (message.role === "system") {
43
+ messages.push({ role: "system", content: message.content });
44
+ }
45
+ else if (message.role === "user") {
46
+ const texts = [];
47
+ const images = [];
48
+ for (const part of message.content) {
49
+ if (part.type === "text") {
50
+ texts.push(part.text);
51
+ }
52
+ else if (part.type === "file" && part.mediaType.startsWith("image/")) {
53
+ const picture = at === newest ? base64Of(part.data) : undefined;
54
+ if (picture) {
55
+ images.push(picture);
56
+ }
57
+ else {
58
+ texts.push(`[picture: ${part.filename ?? "attached earlier"}]`);
59
+ }
60
+ }
61
+ }
62
+ messages.push({
63
+ role: "user",
64
+ content: texts.join("\n"),
65
+ ...(images.length ? { images } : {}),
66
+ });
67
+ }
68
+ else if (message.role === "assistant") {
69
+ const text = message.content.map((part) => (part.type === "text" ? part.text : "")).join("");
70
+ const calls = message.content
71
+ .filter((part) => part.type === "tool-call")
72
+ .map((part) => ({ function: { name: part.toolName, arguments: asObject(part.input) } }));
73
+ messages.push({
74
+ role: "assistant",
75
+ content: text,
76
+ ...(calls.length ? { tool_calls: calls } : {}),
77
+ });
78
+ }
79
+ else {
80
+ const shown = [];
81
+ for (const part of message.content) {
82
+ if (part.type !== "tool-result") {
83
+ continue;
84
+ }
85
+ const output = part.output;
86
+ let content;
87
+ if (output.type === "content") {
88
+ const texts = [];
89
+ for (const piece of output.value) {
90
+ const picture = piece.type === "text" ? undefined : pictureOf(piece);
91
+ if (piece.type === "text") {
92
+ texts.push(piece.text ?? "");
93
+ }
94
+ else if (picture && at > newest) {
95
+ shown.push(picture);
96
+ }
97
+ else if (picture) {
98
+ texts.push("[a picture shown earlier]");
99
+ }
100
+ }
101
+ content = texts.join("\n");
102
+ }
103
+ else {
104
+ content =
105
+ output.type === "text" || output.type === "error-text"
106
+ ? output.value
107
+ : "value" in output
108
+ ? JSON.stringify(output.value)
109
+ : "The tool call was not allowed.";
110
+ }
111
+ messages.push({ role: "tool", content, tool_name: part.toolName });
112
+ }
113
+ // Ollama takes pictures with a message of the person, not with a tool's answer.
114
+ if (shown.length) {
115
+ messages.push({ role: "user", content: "The pictures the tool showed.", images: shown });
116
+ }
117
+ }
118
+ }
119
+ return messages;
120
+ }
121
+ async function* lines(body) {
122
+ const decoder = new TextDecoder();
123
+ let buffer = "";
124
+ for await (const bytes of body) {
125
+ buffer += decoder.decode(bytes, { stream: true });
126
+ let newline = buffer.indexOf("\n");
127
+ while (newline >= 0) {
128
+ const line = buffer.slice(0, newline).trim();
129
+ buffer = buffer.slice(newline + 1);
130
+ if (line) {
131
+ yield JSON.parse(line);
132
+ }
133
+ newline = buffer.indexOf("\n");
134
+ }
135
+ }
136
+ if (buffer.trim()) {
137
+ yield JSON.parse(buffer);
138
+ }
139
+ }
140
+ /** A model of the Ollama at `setup.url`, streaming its answer, its tool calls and the usage. */
141
+ export function ollamaModel(setup) {
142
+ const doFetch = setup.fetch ?? fetch;
143
+ const root = ollamaRoot(setup.url);
144
+ let calls = 0;
145
+ async function doStream(options) {
146
+ const tools = setup.tools === false
147
+ ? []
148
+ : (options.tools ?? [])
149
+ .filter((tool) => tool.type === "function")
150
+ .map((tool) => ({
151
+ type: "function",
152
+ function: {
153
+ name: tool.name,
154
+ description: tool.description,
155
+ parameters: tool.inputSchema,
156
+ },
157
+ }));
158
+ const format = options.responseFormat?.type === "json"
159
+ ? (options.responseFormat.schema ?? "json")
160
+ : undefined;
161
+ const response = await doFetch(`${root}/api/chat`, {
162
+ method: "POST",
163
+ headers: { "content-type": "application/json" },
164
+ signal: options.abortSignal,
165
+ body: JSON.stringify({
166
+ model: setup.model,
167
+ messages: ollamaMessages(options.prompt),
168
+ ...(tools.length ? { tools } : {}),
169
+ ...(format ? { format } : {}),
170
+ stream: true,
171
+ // Thinking arrives beside the answer, as `message.thinking`, and is not read.
172
+ ...(setup.thinking === undefined ? {} : { think: setup.thinking }),
173
+ options: {
174
+ ...(setup.context ? { num_ctx: setup.context } : {}),
175
+ ...(options.maxOutputTokens ? { num_predict: options.maxOutputTokens } : {}),
176
+ ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),
177
+ ...(options.topP !== undefined ? { top_p: options.topP } : {}),
178
+ ...(options.topK !== undefined ? { top_k: options.topK } : {}),
179
+ ...(options.seed !== undefined ? { seed: options.seed } : {}),
180
+ ...(options.stopSequences?.length ? { stop: options.stopSequences } : {}),
181
+ },
182
+ }),
183
+ }).catch((error) => {
184
+ throw new Error(`Ollama at ${root} did not answer: ${error.message}`, {
185
+ cause: error,
186
+ });
187
+ });
188
+ if (!(response.ok && response.body)) {
189
+ throw new Error(`Ollama answered ${response.status}: ${(await response.text()).slice(0, 300)}`);
190
+ }
191
+ const body = response.body;
192
+ const stream = new ReadableStream({
193
+ async start(controller) {
194
+ controller.enqueue({ type: "stream-start", warnings: [] });
195
+ let textOpen = false;
196
+ let called = false;
197
+ try {
198
+ for await (const chunk of lines(body)) {
199
+ if (chunk.error) {
200
+ throw new Error(chunk.error);
201
+ }
202
+ if (chunk.message?.content) {
203
+ if (!textOpen) {
204
+ controller.enqueue({ type: "text-start", id: "0" });
205
+ }
206
+ textOpen = true;
207
+ controller.enqueue({ type: "text-delta", id: "0", delta: chunk.message.content });
208
+ }
209
+ for (const call of chunk.message?.tool_calls ?? []) {
210
+ called = true;
211
+ controller.enqueue({
212
+ type: "tool-call",
213
+ toolCallId: `call_${Date.now().toString(36)}_${++calls}`,
214
+ toolName: call.function.name,
215
+ input: JSON.stringify(call.function.arguments ?? {}),
216
+ });
217
+ }
218
+ if (chunk.done) {
219
+ if (textOpen) {
220
+ controller.enqueue({ type: "text-end", id: "0" });
221
+ }
222
+ textOpen = false;
223
+ const input = chunk.prompt_eval_count;
224
+ const output = chunk.eval_count;
225
+ controller.enqueue({
226
+ type: "finish",
227
+ finishReason: {
228
+ unified: called
229
+ ? "tool-calls"
230
+ : chunk.done_reason === "length"
231
+ ? "length"
232
+ : "stop",
233
+ raw: chunk.done_reason,
234
+ },
235
+ usage: {
236
+ inputTokens: {
237
+ total: input,
238
+ noCache: input,
239
+ cacheRead: undefined,
240
+ cacheWrite: undefined,
241
+ },
242
+ outputTokens: { total: output, text: output, reasoning: undefined },
243
+ },
244
+ });
245
+ }
246
+ }
247
+ }
248
+ catch (error) {
249
+ controller.enqueue({ type: "error", error });
250
+ }
251
+ controller.close();
252
+ },
253
+ });
254
+ return { stream };
255
+ }
256
+ return {
257
+ specificationVersion: "v3",
258
+ provider: "ollama",
259
+ modelId: setup.model,
260
+ supportedUrls: {},
261
+ doStream,
262
+ doGenerate: (options) => generateFrom(doStream, options),
263
+ };
264
+ }
265
+ /** A whole answer from a model that streams. */
266
+ export async function generateFrom(doStream, options) {
267
+ const { stream } = await doStream(options);
268
+ let text = "";
269
+ const content = [];
270
+ let finish;
271
+ for await (const part of stream) {
272
+ if (part.type === "text-delta") {
273
+ text += part.delta;
274
+ }
275
+ else if (part.type === "tool-call") {
276
+ content.push(part);
277
+ }
278
+ else if (part.type === "finish") {
279
+ finish = part;
280
+ }
281
+ else if (part.type === "error") {
282
+ throw part.error;
283
+ }
284
+ }
285
+ if (text) {
286
+ content.unshift({ type: "text", text });
287
+ }
288
+ return {
289
+ content,
290
+ finishReason: finish?.finishReason ?? { unified: "other", raw: undefined },
291
+ usage: finish?.usage ?? {
292
+ inputTokens: {
293
+ total: undefined,
294
+ noCache: undefined,
295
+ cacheRead: undefined,
296
+ cacheWrite: undefined,
297
+ },
298
+ outputTokens: { total: undefined, text: undefined, reasoning: undefined },
299
+ },
300
+ warnings: [],
301
+ };
302
+ }
@@ -0,0 +1,54 @@
1
+ import { type Client, type ClientId } from "./clients/index.js";
2
+ import { type InstalledModel } from "./ollama/api.js";
3
+ /**
4
+ * One short, real call per source of models: a tiny prompt, a timeout, and what came of it. A
5
+ * call costs a few tokens, so a host makes it when the person asks or once at setup, never on a
6
+ * timer. The result is a state and the source's own words; each host words it for the person.
7
+ */
8
+ /**
9
+ * - `ok`: it answered.
10
+ * - `absent`: the client is not installed, or Ollama does not answer at the address.
11
+ * - `signed_out`: the client is installed but not signed in.
12
+ * - `no_model`: Ollama runs but holds no model to talk with (or not the one named).
13
+ * - `too_big`: the model takes more of the computer's memory than the share allows.
14
+ * - `failed`: it was asked and did not answer; `detail` says what it said.
15
+ */
16
+ export type ProbeState = "ok" | "absent" | "signed_out" | "no_model" | "too_big" | "failed";
17
+ export interface ProbeResult {
18
+ state: ProbeState;
19
+ /** What the client or Ollama said, as it said it. */
20
+ detail?: string;
21
+ /** The model that was asked, or that would have been. */
22
+ model?: string;
23
+ /** It did not answer within the timeout. */
24
+ timedOut?: boolean;
25
+ }
26
+ export type ProbeSource = {
27
+ kind: "client";
28
+ /** A client by id, or one of the host's own. */
29
+ client: ClientId | Client;
30
+ /** The model by the client's own name; left out, the client picks. */
31
+ model?: string;
32
+ timeoutMs?: number;
33
+ } | {
34
+ kind: "ollama";
35
+ /** Ollama's address: its root or `…/v1`. */
36
+ url: string;
37
+ /** The model to ask; left out, the one a host would pick first (see `preferredModel`). */
38
+ model?: string;
39
+ /** The computer's memory and the share of it a model may take, in the model sizes' unit (bytes). */
40
+ memory?: number;
41
+ share?: number;
42
+ timeoutMs?: number;
43
+ fetch?: typeof fetch;
44
+ };
45
+ export declare const PROMPT = "Answer with the single word ok.";
46
+ export declare const CLIENT_TIMEOUT = 90000;
47
+ export declare const OLLAMA_TIMEOUT = 120000;
48
+ /** Whether the source answers a short call now. */
49
+ export declare function probe(source: ProbeSource): Promise<ProbeResult>;
50
+ /**
51
+ * The model a host asks first among Ollama's models that write text: one that takes tools, then
52
+ * the largest that fits the computer, then the smallest of those that do not.
53
+ */
54
+ export declare function preferredModel(models: InstalledModel[], memory?: number, share?: number): InstalledModel | undefined;
package/dist/probe.js ADDED
@@ -0,0 +1,190 @@
1
+ import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
2
+ import { tmpdir } from "node:os";
3
+ import { join } from "node:path";
4
+ import { createInterface } from "node:readline";
5
+ import spawn from "cross-spawn";
6
+ import { resolveEnv } from "./clients/env.js";
7
+ import { CLIENTS } from "./clients/index.js";
8
+ import { fits, installedModels, ollamaRoot, ollamaState, } from "./ollama/api.js";
9
+ export const PROMPT = "Answer with the single word ok.";
10
+ const SYSTEM = "You check whether you can answer. Answer with one word.";
11
+ export const CLIENT_TIMEOUT = 90_000;
12
+ export const OLLAMA_TIMEOUT = 120_000;
13
+ /** Whether the source answers a short call now. */
14
+ export function probe(source) {
15
+ return source.kind === "client" ? probeClient(source) : probeOllama(source);
16
+ }
17
+ async function probeClient(source) {
18
+ const client = typeof source.client === "string" ? CLIENTS[source.client] : source.client;
19
+ const timeout = source.timeoutMs ?? CLIENT_TIMEOUT;
20
+ let env;
21
+ try {
22
+ const resolved = await resolveEnv(client);
23
+ if (!(await client.version(resolved.env))) {
24
+ return { state: "absent" };
25
+ }
26
+ if (resolved.auth === "none") {
27
+ return { state: "signed_out" };
28
+ }
29
+ env = resolved.env;
30
+ }
31
+ catch (error) {
32
+ return { state: "failed", detail: error.message };
33
+ }
34
+ const dir = mkdtempSync(join(tmpdir(), "local-models-probe-"));
35
+ const call = {
36
+ system: SYSTEM,
37
+ message: PROMPT,
38
+ session: null,
39
+ dir,
40
+ model: source.model,
41
+ images: [],
42
+ };
43
+ // Cursor Agent reads its instructions from the workspace.
44
+ writeFileSync(join(dir, "AGENTS.md"), SYSTEM);
45
+ try {
46
+ const run = await new Promise((resolve) => {
47
+ const child = spawn(client.bin, client.args(call), {
48
+ cwd: dir,
49
+ env,
50
+ stdio: ["pipe", "pipe", "pipe"],
51
+ });
52
+ // Claude Code streams the text and then gives it whole; the whole message counts.
53
+ let answer = "";
54
+ let streamed = "";
55
+ let result = "";
56
+ let failed;
57
+ let stderr = "";
58
+ let timedOut = false;
59
+ const timer = setTimeout(() => {
60
+ timedOut = true;
61
+ child.kill("SIGTERM");
62
+ }, timeout);
63
+ child.stdin?.on("error", () => {
64
+ // The client went away before reading the prompt; `close` reports it.
65
+ });
66
+ child.stdin?.end(client.stdin(call));
67
+ if (child.stdout) {
68
+ createInterface({ input: child.stdout }).on("line", (line) => {
69
+ for (const event of client.events(line)) {
70
+ if (event.kind === "failure") {
71
+ failed = event.detail;
72
+ }
73
+ else if (event.kind === "text") {
74
+ answer += event.text;
75
+ }
76
+ else if (event.kind === "writing" && event.text) {
77
+ streamed += event.text;
78
+ }
79
+ else if (event.kind === "result") {
80
+ result = event.text;
81
+ }
82
+ }
83
+ });
84
+ }
85
+ child.stderr?.on("data", (chunk) => {
86
+ stderr = (stderr + chunk.toString()).slice(-4000);
87
+ });
88
+ child.on("error", (error) => {
89
+ clearTimeout(timer);
90
+ resolve({ failure: error.message, missing: error.code === "ENOENT" });
91
+ });
92
+ child.on("close", (code) => {
93
+ clearTimeout(timer);
94
+ if (timedOut) {
95
+ resolve({ failure: "", timedOut: true });
96
+ }
97
+ else if (failed !== undefined) {
98
+ resolve({ failure: failed });
99
+ }
100
+ else if ((answer || streamed || result).trim()) {
101
+ resolve({ answer: (answer || streamed || result).trim() });
102
+ }
103
+ else {
104
+ // Some failures reach only the error output, with a code or without.
105
+ resolve({ failure: stderr.trim() || `exit ${code}` });
106
+ }
107
+ });
108
+ });
109
+ if ("answer" in run) {
110
+ return { state: "ok", model: source.model, detail: run.answer };
111
+ }
112
+ if (run.missing) {
113
+ return { state: "absent", detail: run.failure };
114
+ }
115
+ if (run.timedOut) {
116
+ return { state: "failed", timedOut: true, model: source.model };
117
+ }
118
+ return {
119
+ state: client.signedOut(run.failure) ? "signed_out" : "failed",
120
+ detail: run.failure,
121
+ model: source.model,
122
+ };
123
+ }
124
+ finally {
125
+ rmSync(dir, { recursive: true, force: true });
126
+ }
127
+ }
128
+ /**
129
+ * The model a host asks first among Ollama's models that write text: one that takes tools, then
130
+ * the largest that fits the computer, then the smallest of those that do not.
131
+ */
132
+ export function preferredModel(models, memory = Number.POSITIVE_INFINITY, share = 1) {
133
+ const leavesRoom = (model) => fits(model, memory, share);
134
+ return models
135
+ .filter((m) => m.completion)
136
+ .sort((a, b) => Number(b.tools) - Number(a.tools) ||
137
+ Number(leavesRoom(b)) - Number(leavesRoom(a)) ||
138
+ (leavesRoom(a) ? b.size - a.size : a.size - b.size))[0];
139
+ }
140
+ async function probeOllama(source) {
141
+ const doFetch = source.fetch ?? fetch;
142
+ const root = ollamaRoot(source.url);
143
+ const timeout = source.timeoutMs ?? OLLAMA_TIMEOUT;
144
+ const state = await ollamaState(root, { fetch: doFetch });
145
+ if (!state.version) {
146
+ return { state: "absent" };
147
+ }
148
+ const models = await installedModels(root, { fetch: doFetch });
149
+ const sized = source.memory !== undefined && source.share !== undefined;
150
+ const model = source.model
151
+ ? models.find((m) => m.name === source.model || m.name === `${source.model}:latest`)
152
+ : preferredModel(models, source.memory, source.share);
153
+ if (!model) {
154
+ return { state: "no_model", model: source.model };
155
+ }
156
+ if (sized && !fits(model, source.memory, source.share)) {
157
+ return { state: "too_big", model: model.name };
158
+ }
159
+ try {
160
+ const response = await doFetch(`${root}/api/chat`, {
161
+ method: "POST",
162
+ headers: { "content-type": "application/json" },
163
+ body: JSON.stringify({
164
+ model: model.name,
165
+ messages: [{ role: "user", content: PROMPT }],
166
+ stream: false,
167
+ ...(model.thinking ? { think: false } : {}),
168
+ options: { num_predict: 16 },
169
+ }),
170
+ signal: AbortSignal.timeout(timeout),
171
+ });
172
+ const body = (await response.json().catch(() => ({})));
173
+ if (!response.ok || body.error) {
174
+ return {
175
+ state: "failed",
176
+ model: model.name,
177
+ detail: body.error ?? `status ${response.status}`,
178
+ };
179
+ }
180
+ return { state: "ok", model: model.name, detail: body.message?.content?.trim() };
181
+ }
182
+ catch (error) {
183
+ const timedOut = error.name === "TimeoutError";
184
+ return {
185
+ state: "failed",
186
+ model: model.name,
187
+ ...(timedOut ? { timedOut } : { detail: error.message }),
188
+ };
189
+ }
190
+ }
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@engenty/local-models",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.20.6",
4
+ "description": "The models on a person's own computer: Ollama (its models, what each can do, downloads, a model on its native chat API with the context length set) and the AI clients signed in on their subscription (Claude Code, Codex, Cursor Agent: found, signed in, run headless as a model or as a chat with one MCP server), and a short real call that says whether each answers.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/engenty/wizards.git",
9
+ "directory": "packages/local-models"
10
+ },
11
+ "type": "module",
12
+ "main": "./dist/index.js",
13
+ "types": "./dist/index.d.ts",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ },
19
+ "./ollama": {
20
+ "types": "./dist/ollama/index.d.ts",
21
+ "default": "./dist/ollama/index.js"
22
+ },
23
+ "./clients": {
24
+ "types": "./dist/clients/index.d.ts",
25
+ "default": "./dist/clients/index.js"
26
+ },
27
+ "./probe": {
28
+ "types": "./dist/probe.d.ts",
29
+ "default": "./dist/probe.js"
30
+ }
31
+ },
32
+ "typesVersions": {
33
+ "*": {
34
+ "ollama": [
35
+ "./dist/ollama/index.d.ts"
36
+ ],
37
+ "clients": [
38
+ "./dist/clients/index.d.ts"
39
+ ],
40
+ "probe": [
41
+ "./dist/probe.d.ts"
42
+ ]
43
+ }
44
+ },
45
+ "files": [
46
+ "dist",
47
+ "LICENSE"
48
+ ],
49
+ "dependencies": {
50
+ "cross-spawn": "7.0.6"
51
+ },
52
+ "peerDependencies": {
53
+ "ai": ">=7.0.0"
54
+ },
55
+ "publishConfig": {
56
+ "access": "public"
57
+ }
58
+ }