From bf02eff6eaa8c4b0fe400608419a461c4b2addc5 Mon Sep 17 00:00:00 2001 From: Brent Larsen Date: Wed, 7 Oct 2026 09:27:20 -0500 Subject: [PATCH] v0.2.0 --- .gitignore | 5 ++ AGENTS.md | 121 +++++++++++++++++++++++++ README.md | 161 ++++++++++++++++++++++++++++++--- clean-text.js | 59 ++++++++++++ docs/history.md | 55 ++++++++++++ docs/ideas.md | 31 +++++++ docs/intentional-behavior.md | 84 ++++++++++++++++++ index.js | 82 ++++++++--------- lmstudio.js | 78 ++++++++++------ package.json | 9 +- test/lmstudio.test.js | 168 +++++++++++++++++++++++++++++++++++ test/perry.test.js | 46 ++++++++++ 12 files changed, 808 insertions(+), 91 deletions(-) create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 clean-text.js create mode 100644 docs/history.md create mode 100644 docs/ideas.md create mode 100644 docs/intentional-behavior.md create mode 100644 test/lmstudio.test.js create mode 100644 test/perry.test.js diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5a44f5f --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +node_modules/ +side-effects/ +migration/ +artifacts/ +*.zip \ No newline at end of file diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..46f3b4f --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,121 @@ +# Development Philosophy + +## Simplicity is the default + +Speculative architecture always has negative value. + +The cost of writing code is small compared with the cost of carrying it. Every abstraction, hook, compatibility layer, option, fallback, extension point, and anticipated future feature becomes something the project must understand and preserve. Worse, later work begins building on guesses about a future that has not arrived yet. + +If we understand A and B, partly understand C and D, and only imagine E, build A and B. Do not pour foundations for C, D, or E. When C becomes real, A and B will have taught us things we could not know beforehand. That evidence lets us build C once and integrate it with what actually exists. Premature preparation for E can occupy the very ground the real E eventually needs and can force A through D to depend on a mistaken future. + +The only reliable speculation is that simplicity will pay off. + +Build the smallest thing that fully serves the need we concretely understand. Do not future-proof by predicting the future. Preserve the future by refusing to obstruct it. + +## Discussion before action + +A problem report is information, not an instruction to patch the nearest code. + +When something breaks, first understand what happened, why it happened, which behavior was intentional, and what solution landscape the evidence supports. A clear path is not necessarily the right path. The right path tends to reveal itself when investigation and discussion converge on an obvious next step. + +This is not ceremony. The discussion may be brief. The rule is simply that action follows understanding rather than replacing it. + +Do not make meaningful behavioral or architectural changes merely because they appear straightforward. Surface the evidence, alternatives, and consequences first and agree on direction. + +## Beauty over perfection + +We are not building machinery to eliminate every imperfect judgment, irregular case, or possible mistake. Predictably good, useful, approachable work is more valuable than elaborate systems designed to force perfection. + +An occasional exception is allowed to remain an exception. Do not immediately turn anomalies into rules, validation systems, abstractions, fallbacks, or special cases. Forgive exceptions until repeated evidence shows that the exception is actually part of the shape of the problem. + +This applies to code and to the content these tools help produce. Complexity introduced to prevent every possible imperfection often damages the work more than the imperfection would have. + +## Follow evidence without an agenda + +Investigate the actual code, data, failures, and outputs rather than speculating about what they probably mean. Do not steer evidence toward a preferred architecture or conclusion. + +For translation and ancient-text work, the received text is the authority. Tradition is context, not a destination. We are not trying to reinforce tradition or tear it down, and we do not bend the text toward doctrine, dogma, skepticism, apologetics, or novelty. The aim is unbiased, approachable, useful, compelling translation of ancient wisdom. + +Not every participant in a creative or translation pipeline produces evidence. Explorers, philosophers, and literary voices may speculate, reach, or occasionally indulge wishful thinking when that is useful to their role. Be rigorous about what is called evidence and which roles have authority to alter the received text; do not turn the entire endeavor into an academic apparatus in pursuit of impossible perfection. + +## Perry is an external boundary; async is not the application architecture + +The project family intentionally uses synchronous blocking batch control flow. Provider transports may inherently expose asynchronous or streaming mechanics, but those mechanics should ultimately be isolated inside Perry and presented to applications as a blocking call with bounded timeout behavior. + +The current Perry implementation still exposes Promise/callback streaming behavior. Treat that as legacy plumbing awaiting a separate unwind, not as an architectural virtue and not as precedent for application code. Do not add new async abstractions, concurrency, queues, or callback-oriented control flow merely because Node examples normally do. + +# Perry + +Perry is an agent who does not do much. He has a knack for doing exactly enough to get the job done and avoid catastrophe. + +Perry is the LLM boundary for applications. Applications own who an agent is, why work happens, what work means, and what to do with the result. Perry owns the mechanics of forming and operating an LLM-backed conversational agent through a configured provider. + +## Scope + +Perry owns: + +- the provider-neutral Perry conversation/Lego shape; +- provider selection and provider-specific translation of Perry conversations; +- model selection exactly as requested by the consumer; +- provider-specific availability checks when the provider can offer certainty; +- provider transport of reasoning and final content (currently exposed through legacy callbacks pending the blocking-boundary unwind); +- conversation preparation, independent asks, and follow-up conversations; +- automatic continuation of incomplete responses; +- transport retry behavior; +- provider diagnostics and usage returned with replies; +- provider-specific catastrophe protection that has been proven necessary, such as LM Studio repetition-loop detection. + +Applications own: + +- agent personas and Lego content; +- which Lego pieces form an agent and in what order; +- pipeline orchestration and artifact meaning; +- application settings and any aliases that resolve to Perry settings; +- terminal, UI, or logging output; +- interpretation and validation of domain-specific model answers. + +## Intentional boundaries + +Perry is independent of Optimus. Do not add an Optimus adapter, Optimus settings lookup, or any other reciprocal dependency. An Optimus-based application may wrap Perry in its own module if that is convenient for that application. + +A Perry instance is lightweight. It is essentially provider/model settings plus behavior. It must be natural to create one Perry for an application, one per transformer, one per agent, or one per request. Do not introduce a meaningful instance lifecycle, singleton requirement, global model state, connection manager, or shared registry without discussion and concrete evidence. + +Current Perry settings are intentionally only `provider` and `model`. Both are required. Do not add configuration knobs because a provider happens to expose them. Add Perry settings only when actual consumers demonstrate that Perry needs to own them. + +Model identity is exact. Perry does not know that two model names are aliases, equivalent weights, variants, or interchangeable workers. If an application wants `gemma4-31b` to resolve to a particular provider model name, that abstraction belongs to the application before Perry is constructed. + +Perry never owns user-facing console output. Perry does not speak. Its current callback streaming surface is a legacy transport detail pending the blocking-boundary unwind; results and diagnostics belong to the caller, and consumers decide what humans see. + +A Perry Lego is not provider-specific data. Perry owns its known conversation shape and providers transform that shape into their own request format. A provider that happens to accept the same shape directly is an implementation coincidence, not permission to pass unknown provider-specific fields through Perry. + +Do not create provider frameworks, capability matrices, registries, cancellation abstractions, or shared provider behavior from one example. Let repeated implementations reveal a common interface before extracting one. + +## Current direction + +Perry 0.2 consolidates the behavior already proven by the project family while remaining deliberately small: + +- direct lightweight construction from `{ provider, model }`; +- LM Studio as the only currently implemented provider; +- fail-fast LM Studio warmup when the requested model is known to be unavailable; +- exact requested-model checks before work and exact response-model rejection when LM Studio explicitly reports a different model; +- silent operation with optional reasoning/content callbacks; +- preservation of the existing Lego, continuation, retry, diagnostics, and repetition-loop behavior. + +## Deliberately not doing yet + +- Ollama support. It existed historically, but no current implementation survived into this codebase and we are not rebuilding untested complexity in anticipation of future use. +- generalized remote-provider infrastructure; +- provider capability declarations; +- application or model alias registries; +- reasoning-effort, context-size, token-limit, temperature, or similar Perry settings without a demonstrated consumer need; +- retry/model-recovery redesign. See `docs/ideas.md` for the concrete observation already on the radar. + +## Lego formation: awareness before rules + +A Lego should help an agent understand one idea deeply enough to exercise judgment in the moment. Do not treat formation as a place to accumulate behavioral commandments. + +For an observed failure mode, explain clearly what happened, why the outcome was undesirable, and what feature of the situation seems to create the risk. Then let the agent reflect the problem back in its own words and carry that awareness into later judgment. Avoid turning the lesson into `do this / do not do that`, and avoid eliciting rigid promises such as `I will always...` or `I will never...` when understanding can do the work instead. + +**One exchange teaches one takeaway.** Even closely related observations should receive separate complete back-and-forth exchanges when each matters. Bundling several lessons into one exchange tends to dilute how fully the model incorporates each one. + +Rules remain appropriate when the task genuinely has a mechanical contract, but do not substitute rules for judgment merely because rules are easier to write. Repeated project evidence shows that agents often make better case-specific decisions when they understand the problem than when they are forced to obey an anticipated solution. diff --git a/README.md b/README.md index 5564ed3..9974882 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,160 @@ # Perry -Perry is a small utility for working with persistent conversational agents. +Perry is a small provider-neutral utility for forming and operating persistent conversational agents through LLMs. -It grew out of Chat2. Perry is not a scheduler, artifact graph, translation pipeline, or full-featured agent framework. Applications own why work happens and what the work means. Perry owns the conversational agent mechanics around a local model. +Perry is named for an agent who does not do much but has a knack for doing exactly enough to get the job done and avoid catastrophe. Applications own why work happens and what the work means. Perry owns the mechanics of talking to the requested LLM provider and maintaining the conversation needed to do it. -Current API: +## Where Lego Towers came from +Perry grew out of a simple question while building an Ollama chat client: what does an LLM need in order to persist a session that can be resumed, branched, or have information injected into it? + +The answer was already present in the chat API: conversation history. + +Persist the conversation history and the session is persistent. Copy it and the session branches. Compose useful subsets of history and those subsets become reusable Lego pieces. Stack the pieces in order and the result is a Lego Tower: a conversational history that forms an agent's awareness before repeated work is placed in front of it. + +Perry deliberately keeps that observation simple. A Lego is conversation data, not a framework object, registry entry, graph node, or special session type. + +## Provider-neutral conversations + +A Perry conversation has a Perry-defined shape. It is not an LM Studio message or any other provider's native request object. + +The basic message shape is: + +```js +{ role: "user", content: "..." } +``` + +Perry accepts the fields it understands and provider implementations transform that conversation into whatever their backend expects. A provider may happen to need little or no transformation, but consumers must not rely on provider-specific fields passing through Perry. + +Reasoning may be retained on replies for diagnostics, but it is not normally fed back into active conversation history. + +## Configuration + +Create a lightweight Perry instance with an explicit provider and exact model name: + +```js +const Perry = require("perry"); + +const perry = Perry({ + provider: "lm-studio", + model: "gemma-4-31b-it" +}); +``` + +Those are currently the only Perry settings. + +Perry instances are intentionally cheap and independent. An application can pass one instance around, create one per pipeline stage, create one per agent, or create one per request. Perry does not assume application-global LLM configuration. + +Current provider: `lm-studio`. + +Ollama was supported in the older Chat2 lineage, but no active Ollama implementation survived into the extracted Perry source. It is intentionally not being recreated until there is a real use for it again. + +## Preparing an agent + +```js +const agent = perry.prepare("Edith", systemPrompt, [ + identityLego, + valuesLego, + translatorLego +]); +``` + +Each Lego is simply a conversation subset. Perry assembles the system prompt and Lego histories into the agent's formative conversation. + +`prepare()` does not contact or load a model. + +## Asking for work + +```js +const reply = await perry.ask(agent, prompt, { + onReasoning(text) { + // The consumer decides whether and where to display this. + }, + onContent(text) { + // The consumer decides whether and where to display this. + } +}); + +console.log(reply.content); +``` + +Perry itself never writes user-facing output to the console. It streams through callbacks, returns replies and diagnostics, and throws errors. UI and logging belong to the consumer. + +A normal reply is shaped roughly like: + +```js +{ + role: "assistant", + content: "...", + reasoning: "...", // when available + provider: { + name: "lm-studio", + model: "gemma-4-31b-it", + continuationPages: 0, + pages: [/* provider diagnostics */] + } +} +``` + +## Follow-up conversations + +`ask()` starts from the agent's prepared formation each time. It does not mutate the prepared agent. + +For an intentional follow-up to a previous exchange: + +```js +const nextReply = await perry.followUp( + agent, + originalPrompt, + previousReply, + followUpPrompt +); +``` + +This keeps branching ordinary: conversation history is data, and a branch is simply a different history. + +## Optional text cleanup + +`Perry.cleanText(text)` is a pure opt-in helper for common LLM presentation artifacts. It does not run automatically and knows nothing about an application's envelopes, labels, artifacts, or document structure. + +It normalizes a small observed set of generic presentation habits into portable text / mini-markdown conventions, such as TeX `\text{...}` wrappers, common TeX arrow symbols, and ordinary Markdown emphasis. Unknown TeX is left visible rather than interpreted. + +Consumers decide whether a particular semantic text boundary should use it. + +## Availability and exact model identity + +`warmUp()` asks the configured provider to establish whatever certainty it can about the requested model. + +LM Studio can inspect and load models, so failure to make the exact requested model available is fatal. Perry does not silently choose a substitute model and does not understand application-level model aliases. + +`ask()` performs this check before each attempt. If LM Studio explicitly reports a response model and it differs from the exact configured model name, Perry rejects the response with `PERRY_MODEL_MISMATCH`. If a provider cannot supply model identity evidence, uncertainty by itself is not treated as failure. + +Applications that want friendly aliases such as `translator-large` should resolve those aliases to the exact provider/model settings before constructing Perry. + +## Continuation and retries + +Perry automatically continues LM Studio responses that explicitly end as incomplete. If an agent produces reasoning but no final answer and provider-native continuation is unavailable, Perry can continue through ordinary conversation history. + +Transient transport failures are retried up to ten times using the existing backoff policy. Partial failed responses are not appended to the agent's conversation. + +This retry policy is intentionally unchanged in 0.2. A better recovery sequence has been observed and is recorded in `docs/ideas.md`; it will be changed only after that behavior is discussed and deliberately implemented. + +## Repetition self-destruct + +The LM Studio provider watches reasoning and final-content streams independently for exact contiguous periodic repetition. If the tail becomes the same token sequence repeated seven complete times with no novel tokens between repetitions, it aborts that response and raises a retryable `PERRY_REPETITION_LOOP` error. + +The detector is deliberately literal. Similar ideas with changing token sequences are allowed to continue; Perry intervenes only after the stream locks into an exact repeated orbit. Pattern periods from one through 256 tokens are checked. + +This remains LM Studio-specific today because that is the implementation reality we have. It should not be generalized into a provider interface until repeated provider implementations demonstrate a real common shape. + +## API + +- `Perry({ provider, model })` +- `Perry.cleanText(text)` - `warmUp()` - `prepare(name, systemPrompt, segments)` - `ask(agent, input, options)` - `followUp(agent, originalInput, previousReply, input, options)` - `model()` -Current backend: LM Studio Responses API. The extracted source contained no active Ollama backend, so none was resurrected. - -## Repetition self-destruct - -Perry watches reasoning and final-content streams independently for exact contiguous periodic repetition. If the tail becomes the same token sequence repeated seven complete times with no novel tokens between repetitions, Perry aborts that response and raises a retryable `PERRY_REPETITION_LOOP` error. - -The detector is deliberately literal. Similar ideas with changing token sequences are allowed to continue; Perry intervenes only after the stream locks into an exact repeated orbit. Pattern periods from one through 256 tokens are checked. - -The normal retry layer then starts the response again without appending the pathological partial response to the conversation. +See `AGENTS.md` for development philosophy and scope, and `docs/` for intentional behavior, project history, and deferred ideas. diff --git a/clean-text.js b/clean-text.js new file mode 100644 index 0000000..356d201 --- /dev/null +++ b/clean-text.js @@ -0,0 +1,59 @@ +const TEX_SYMBOLS = Object.freeze({ + "\\rightarrow": "→", + "\\to": "→", + "\\leftarrow": "←", + "\\leftrightarrow": "↔", + "\\Rightarrow": "⇒", + "\\Leftarrow": "⇐", + "\\Leftrightarrow": "⇔", + "\\times": "×", + "\\cdot": "·", + "\\pm": "±", + "\\neq": "≠", + "\\ne": "≠", + "\\leq": "≤", + "\\le": "≤", + "\\geq": "≥", + "\\ge": "≥", + "\\ldots": "…", + "\\dots": "…", + "\\bullet": "•", +}); + +function cleanText(value) { + let text = String(value ?? ""); + + // The models commonly wrap ordinary words in TeX text commands, sometimes + // inside math delimiters. Convert the presentation intent, not the math language. + text = text.replace(/\$\\textbf\{([^{}]*)\}\$/g, "**$1**"); + text = text.replace(/\$\\(?:textit|emph)\{([^{}]*)\}\$/g, "//$1//"); + text = text.replace(/\$\\text\{([^{}]*)\}\$/g, "$1"); + + text = text.replace(/\\textbf\{([^{}]*)\}/g, "**$1**"); + text = text.replace(/\\(?:textit|emph)\{([^{}]*)\}/g, "//$1//"); + text = text.replace(/\\text\{([^{}]*)\}/g, "$1"); + + // Unwrap a TeX math span only when a known presentation command was actually + // converted. Unknown TeX remains visible rather than being guessed at. + text = text.replace(/\$([^$\n]+)\$/g, (whole, inner) => { + const converted = replaceKnownTexSymbols(inner); + return converted !== inner && !/\\[A-Za-z]+/.test(converted) ? converted : whole; + }); + text = replaceKnownTexSymbols(text); + + // Normalize common Markdown emphasis into the tiny inline dialect used by + // Cumorah renderers. Existing Cumorah **bold** and //italic// pass through. + text = text.replace(/__([^_\n]+)__/g, "**$1**"); + text = text.replace(/(? { - const settings = utils.getSettings("llm"); - const client = String(settings.client || "lm-studio").toLowerCase(); - if (client !== "lm-studio" && client !== "lmstudio") throw new Error(`Unsupported LLM client: ${settings.client}`); - const llm = lmStudio; - let warmupPromise = null; +function providerFor(name) { + switch (String(name || "").toLowerCase()) { + case "lm-studio": + return lmStudio; + default: + throw new Error(`Unsupported LLM provider: ${name}`); + } +} + +function validateSettings(settings) { + if (!settings || typeof settings !== "object") throw new Error("Perry settings are required."); + if (typeof settings.provider !== "string" || !settings.provider.trim()) throw new Error("Perry setting 'provider' is required."); + if (typeof settings.model !== "string" || !settings.model.trim()) throw new Error("Perry setting 'model' is required."); + + return { + provider: settings.provider.trim().toLowerCase(), + model: settings.model + }; +} + +function createPerry(settings) { + const configured = validateSettings(settings); + const llm = providerFor(configured.provider); function warmUp() { - if (!warmupPromise) warmupPromise = llm.warmUp(settings); - return warmupPromise; + return llm.warmUp(configured); } function prepare(name, systemPrompt, segments = []) { @@ -27,23 +44,6 @@ module.exports = utils => { return { name: name || "anonymous", conversation }; } - function liveOutput() { - let channel = null; - let wrote = false; - function switchTo(next) { - if (channel === next) return; - if (wrote) process.stdout.write("\n"); - process.stdout.write(` --- ${next} ---\n`); - channel = next; - wrote = true; - } - return { - reasoning(text) { switchTo("reasoning"); process.stdout.write(text); }, - content(text) { switchTo("response"); process.stdout.write(text); }, - end() { if (wrote) process.stdout.write("\n"); } - }; - } - function addFallbackContinuation(conversation, reply) { if (reply.reasoning?.trim()) { conversation.add({ @@ -59,29 +59,23 @@ module.exports = utils => { } async function askConversation(agent, conversation, options = {}) { - await warmUp(); - const callerOwnsOutput = typeof options.onReasoning === "function" || typeof options.onContent === "function"; const reasoning = []; let previousResponseId = null; let useStatefulContinuation = false; for (let continuation = 0; continuation <= MAX_CONTINUATIONS; continuation++) { for (let attempt = 1; attempt <= MAX_TRANSPORT_ATTEMPTS; attempt++) { - const output = !callerOwnsOutput && options.live !== false ? liveOutput() : null; - const sendOptions = { - ...options, - onReasoning: options.onReasoning || output?.reasoning, - onContent: options.onContent || output?.content - }; + const sendOptions = { ...options }; delete sendOptions.live; + if (useStatefulContinuation && previousResponseId) { sendOptions.previousResponseId = previousResponseId; sendOptions.continuationInput = CONTINUE_PROMPT; } try { - const reply = await llm.send(conversation, settings, sendOptions); - output?.end(); + await warmUp(); + const reply = await llm.send(conversation, configured, sendOptions); if (reply.reasoning?.trim()) reasoning.push(reply.reasoning.trim()); if (reply.content?.trim()) { delete reply.responseId; @@ -91,8 +85,7 @@ module.exports = utils => { if (continuation >= MAX_CONTINUATIONS) { throw Object.assign(new Error(`LLM returned no final response content for ${agent.name} after ${MAX_CONTINUATIONS} continuations.`), { retryable: false }); } - console.error(); - console.error(`LLM returned unfinished reasoning with no final response for ${agent.name}; continuing (${continuation + 1}/${MAX_CONTINUATIONS}).`); + if (reply.responseId) { previousResponseId = reply.responseId; useStatefulContinuation = true; @@ -103,15 +96,9 @@ module.exports = utils => { } break; } catch (error) { - output?.end(); const retryable = error.retryable !== false; - console.error(); - console.error(`LLM request failed for ${agent.name} (attempt ${attempt}/${MAX_TRANSPORT_ATTEMPTS}): ${error.message}`); - if (error.cause) console.error(` Cause: ${error.cause.code || error.cause.message || String(error.cause)}`); - if (error.partial) console.error(" Stream ended after partial output; retry will restart this response."); if (!retryable || attempt === MAX_TRANSPORT_ATTEMPTS) throw error; const delayMs = Math.min(attempt, 5) * 1000; - console.error(` Retrying in ${delayMs / 1000} second${delayMs === 1000 ? "" : "s"}...`); await new Promise(resolve => setTimeout(resolve, delayMs)); } } @@ -133,7 +120,12 @@ module.exports = utils => { return askConversation(agent, conversation, options); } - function model() { return settings.model; } + function model() { + return configured.model; + } return { warmUp, prepare, ask, followUp, model }; -}; +} + +createPerry.cleanText = cleanText; +module.exports = createPerry; diff --git a/lmstudio.js b/lmstudio.js index 17ef30e..ccabafc 100644 --- a/lmstudio.js +++ b/lmstudio.js @@ -1,5 +1,3 @@ -// api-wrappers/lmstudio.js - const http = require("node:http"); const Repetition = require("./repetition"); @@ -18,40 +16,47 @@ function instanceMatches(instance, configured) { .some(value => typeof value === "string" && value === configured); } +async function modelIsAvailable(model) { + const listResponse = await fetch(`http://${BASE_HOST}:${BASE_PORT}/api/v1/models`); + if (!listResponse.ok) throw new Error(`LM Studio model list returned ${listResponse.status}: ${await listResponse.text()}`); + + const list = await listResponse.json(); + const models = Array.isArray(list.models) ? list.models : []; + const installed = models.find(item => item.key === model); + const loadedInstance = models + .flatMap(item => item.loaded_instances || []) + .find(instance => instanceMatches(instance, model)); + + if (loadedInstance) return true; + if (installed?.loaded_instances?.length) return true; + if (installed) return false; + + const openAiList = await fetch(`http://${BASE_HOST}:${BASE_PORT}/v1/models`); + if (openAiList.ok) { + const loaded = await openAiList.json(); + if (loaded.data?.some(item => item.id === model)) return true; + } + + return false; +} + async function warmUp(settings) { try { - const listResponse = await fetch(`http://${BASE_HOST}:${BASE_PORT}/api/v1/models`); - if (!listResponse.ok) throw new Error(`LM Studio model list returned ${listResponse.status}: ${await listResponse.text()}`); - const list = await listResponse.json(); - const models = Array.isArray(list.models) ? list.models : []; - const installed = models.find(item => item.key === settings.model); - const loadedInstance = models.flatMap(item => item.loaded_instances || []).find(instance => instanceMatches(instance, settings.model)); + if (await modelIsAvailable(settings.model)) return; - if (loadedInstance || installed?.loaded_instances?.length) return; - - if (!installed) { - const openAiList = await fetch(`http://${BASE_HOST}:${BASE_PORT}/v1/models`); - if (openAiList.ok) { - const loaded = await openAiList.json(); - if (loaded.data?.some(item => item.id === settings.model)) return; - } - } - - const modelKey = installed?.key || settings.model; const response = await fetch(`http://${BASE_HOST}:${BASE_PORT}/api/v1/models/load`, { method: "POST", headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ model: modelKey }) + body: JSON.stringify({ model: settings.model }) }); - if (!response.ok) { - console.error(`Model warmup failed: LM Studio returned ${response.status}: ${await response.text()}`); - return; - } - + if (!response.ok) throw new Error(`LM Studio returned ${response.status}: ${await response.text()}`); await response.json(); } catch (error) { - console.error(`Model warmup failed: ${error.message}`); + const failure = new Error(`Model warmup failed for '${settings.model}': ${error.message}`); + failure.retryable = false; + failure.cause = error; + throw failure; } } @@ -96,11 +101,24 @@ function pageDiagnostic(page) { return { responseId: page.responseId || null, status: page.status || null, + model: page.model || null, incompleteDetails: page.incompleteDetails || null, usage: page.usage || null }; } +function assertResponseModel(page, settings) { + if (typeof page.model !== "string" || !page.model) return; + if (page.model === settings.model) return; + + const error = new Error(`LM Studio response model mismatch: requested '${settings.model}', received '${page.model}'.`); + error.code = "PERRY_MODEL_MISMATCH"; + error.retryable = false; + error.expectedModel = settings.model; + error.actualModel = page.model; + throw error; +} + function sendPage(conversation, settings, options = {}) { const body = { model: settings.model, @@ -109,7 +127,6 @@ function sendPage(conversation, settings, options = {}) { }; if (conversation.systemPrompt) body.instructions = conversation.systemPrompt; - if (settings.reasoning && settings.reasoning !== "off") body.reasoning = { effort: settings.reasoning }; if (options.previousResponseId) body.previous_response_id = options.previousResponseId; return new Promise((resolve, reject) => { @@ -263,6 +280,7 @@ function sendPage(conversation, settings, options = {}) { content: content || fallback.content, status: finalEventType === "response.incomplete" ? "incomplete" : finalResponse?.status || "completed", responseId: responseId || finalResponse?.id || null, + model: typeof finalResponse?.model === "string" ? finalResponse.model : null, incompleteDetails: finalResponse?.incomplete_details || null, usage: finalResponse?.usage || null }; @@ -306,6 +324,7 @@ async function send(conversation, settings, options = {}) { continuationInput }); + assertResponseModel(page, settings); lastReply = page; pages.push(pageDiagnostic(page)); if (page.reasoning) reasoning.push(page.reasoning); @@ -316,7 +335,8 @@ async function send(conversation, settings, options = {}) { if (reasoning.length > 0) reply.reasoning = reasoning.join(""); if (page.responseId) reply.responseId = page.responseId; reply.provider = { - name: "lmstudio", + name: "lm-studio", + model: page.model || null, continuationPages: pages.length - 1, pages }; @@ -334,7 +354,7 @@ async function send(conversation, settings, options = {}) { const error = new Error(`LM Studio response remained incomplete after ${MAX_INCOMPLETE_CONTINUATIONS} automatic continuations.`); error.retryable = false; error.partial = Boolean(content.length || reasoning.length); - error.provider = { name: "lmstudio", continuationPages: pages.length - 1, pages }; + error.provider = { name: "lm-studio", continuationPages: pages.length - 1, pages }; throw error; } diff --git a/package.json b/package.json index 6c9600a..1ffe508 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,10 @@ { "name": "perry", - "version": "0.1.0", - "private": true, - "description": "Small persistent conversational-agent utility for local LLM work. It doesn't do much.", + "version": "0.2.0", + "description": "Small provider-neutral conversational-agent utility for LLM work. It does not do much.", + "license": "BSD-3-Clause", "main": "index.js", "scripts": { "test": "node --test" - }, - "license": "UNLICENSED" + } } diff --git a/test/lmstudio.test.js b/test/lmstudio.test.js new file mode 100644 index 0000000..f817049 --- /dev/null +++ b/test/lmstudio.test.js @@ -0,0 +1,168 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const lmStudio = require("../lmstudio"); + +function jsonResponse(body, ok = true, status = 200, text = "") { + return { + ok, + status, + async json() { return body; }, + async text() { return text || JSON.stringify(body); } + }; +} + +test("warmUp accepts an exact loaded model key", async t => { + const originalFetch = global.fetch; + t.after(() => global.fetch = originalFetch); + + const calls = []; + global.fetch = async url => { + calls.push(String(url)); + return jsonResponse({ + models: [{ key: "gemma-4-31b-it", loaded_instances: [{ id: "instance-1" }] }] + }); + }; + + await lmStudio.warmUp({ model: "gemma-4-31b-it" }); + assert.equal(calls.length, 1); +}); + +test("warmUp accepts an exact loaded instance id", async t => { + const originalFetch = global.fetch; + t.after(() => global.fetch = originalFetch); + + global.fetch = async url => { + if (String(url).endsWith("/api/v1/models")) { + return jsonResponse({ + models: [{ key: "gemma-4-31b-it", loaded_instances: [{ id: "remote-instance" }] }] + }); + } + throw new Error(`Unexpected fetch ${url}`); + }; + + await lmStudio.warmUp({ model: "remote-instance" }); +}); + + +test("warmUp loads an exact installed model without requiring the compatibility model list", async t => { + const originalFetch = global.fetch; + t.after(() => global.fetch = originalFetch); + + const calls = []; + global.fetch = async (url, options = {}) => { + const target = String(url); + calls.push(target); + if (target.endsWith("/api/v1/models")) { + return jsonResponse({ models: [{ key: "gemma-4-31b-it", loaded_instances: [] }] }); + } + if (target.endsWith("/api/v1/models/load")) { + assert.deepEqual(JSON.parse(options.body), { model: "gemma-4-31b-it" }); + return jsonResponse({}); + } + throw new Error(`Unexpected fetch ${url}`); + }; + + await lmStudio.warmUp({ model: "gemma-4-31b-it" }); + assert.equal(calls.length, 2); +}); + +test("warmUp loads the exact requested model and fails fast when LM Studio refuses", async t => { + const originalFetch = global.fetch; + t.after(() => global.fetch = originalFetch); + + let loadBody = null; + global.fetch = async (url, options = {}) => { + const target = String(url); + if (target.endsWith("/api/v1/models")) return jsonResponse({ models: [] }); + if (target.endsWith("/v1/models")) return jsonResponse({ data: [] }); + if (target.endsWith("/api/v1/models/load")) { + loadBody = JSON.parse(options.body); + return jsonResponse({}, false, 500, "model not found"); + } + throw new Error(`Unexpected fetch ${url}`); + }; + + await assert.rejects( + () => lmStudio.warmUp({ model: "exact-model-name" }), + error => { + assert.equal(error.retryable, false); + assert.match(error.message, /exact-model-name/); + assert.match(error.message, /model not found/); + return true; + } + ); + assert.deepEqual(loadBody, { model: "exact-model-name" }); +}); + +function withFakeResponse(t, responseObject, inspectPayload = null) { + const http = require("node:http"); + const { EventEmitter } = require("node:events"); + const originalRequest = http.request; + t.after(() => http.request = originalRequest); + + http.request = (options, onResponse) => { + const request = new EventEmitter(); + request.destroy = () => {}; + request.write = payload => { + if (inspectPayload) inspectPayload(JSON.parse(payload)); + }; + request.end = () => { + const response = new EventEmitter(); + response.statusCode = 200; + response.setEncoding = () => {}; + response.destroy = () => {}; + onResponse(response); + process.nextTick(() => { + response.emit("data", `data: ${JSON.stringify({ type: "response.completed", response: responseObject })}\n\n`); + response.emit("end"); + }); + }; + return request; + }; +} + +test("LM Studio receives only Perry conversation fields and preserves exact model identity", async t => { + let body = null; + withFakeResponse(t, { + id: "response-1", + model: "exact-model", + status: "completed", + output: [{ type: "message", content: [{ text: "done" }] }], + usage: { total_tokens: 12 } + }, payload => body = payload); + + const reply = await lmStudio.send({ + systemPrompt: "system", + messages: [{ role: "user", content: "hello", reasoning: "do not send", providerField: "do not send" }] + }, { + model: "exact-model", + reasoning: "high" + }); + + assert.deepEqual(body.input, [{ role: "user", content: "hello" }]); + assert.equal(body.model, "exact-model"); + assert.equal(body.instructions, "system"); + assert.equal("reasoning" in body, false); + assert.equal(reply.content, "done"); + assert.equal(reply.provider.model, "exact-model"); +}); + +test("LM Studio rejects an explicitly different response model", async t => { + withFakeResponse(t, { + id: "response-2", + model: "different-model", + status: "completed", + output: [{ type: "message", content: [{ text: "wrong worker" }] }] + }); + + await assert.rejects( + () => lmStudio.send({ systemPrompt: null, messages: [] }, { model: "exact-model" }), + error => { + assert.equal(error.code, "PERRY_MODEL_MISMATCH"); + assert.equal(error.retryable, false); + assert.equal(error.expectedModel, "exact-model"); + assert.equal(error.actualModel, "different-model"); + return true; + } + ); +}); diff --git a/test/perry.test.js b/test/perry.test.js new file mode 100644 index 0000000..56c6043 --- /dev/null +++ b/test/perry.test.js @@ -0,0 +1,46 @@ +const test = require("node:test"); +const assert = require("node:assert/strict"); +const Perry = require(".."); + +test("Perry requires explicit provider and model settings", () => { + assert.throws(() => Perry(), /settings are required/); + assert.throws(() => Perry({ model: "gemma" }), /'provider' is required/); + assert.throws(() => Perry({ provider: "lm-studio" }), /'model' is required/); + assert.throws(() => Perry({ provider: "ollama", model: "gemma" }), /Unsupported LLM provider/); +}); + +test("Perry is a lightweight independently configured instance", () => { + const first = Perry({ provider: "lm-studio", model: "model-a" }); + const second = Perry({ provider: "lm-studio", model: "model-b" }); + + assert.equal(first.model(), "model-a"); + assert.equal(second.model(), "model-b"); +}); + +test("prepare assembles Perry-shaped conversation history", () => { + const perry = Perry({ provider: "lm-studio", model: "model-a" }); + const agent = perry.prepare("Perry", "system", [{ + messages: [ + { role: "user", content: "hello", providerSpecificThing: "discard me" }, + { role: "assistant", content: "hi", reasoning: "private" } + ] + }]); + + assert.equal(agent.name, "Perry"); + assert.deepEqual(agent.conversation, { + systemPrompt: "system", + messages: [ + { role: "user", content: "hello" }, + { role: "assistant", content: "hi" } + ], + add: agent.conversation.add + }); +}); + +test("cleanText converts common LLM presentation markup without understanding project structure", () => { + assert.equal(Perry.cleanText(String.raw`$\text{He}$ ($\text{ה}$)`), "He (ה)"); + assert.equal(Perry.cleanText(String.raw`left \rightarrow right`), "left → right"); + assert.equal(Perry.cleanText(String.raw`\textbf{bold} and \textit{italic}`), "**bold** and //italic//"); + assert.equal(Perry.cleanText("__bold__ and *italic*"), "**bold** and //italic//"); + assert.equal(Perry.cleanText(String.raw`unknown \mystery{thing}`), String.raw`unknown \mystery{thing}`); +});