This commit is contained in:
Brent Larsen
2026-10-07 09:27:20 -05:00
parent cf1ab0a7af
commit bf02eff6ea
12 changed files with 808 additions and 91 deletions
+5
View File
@@ -0,0 +1,5 @@
node_modules/
side-effects/
migration/
artifacts/
*.zip
+121
View File
@@ -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.
+149 -12
View File
@@ -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.
+59
View File
@@ -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(/(?<!\*)\*([^*\n]+)\*(?!\*)/g, "//$1//");
text = text.replace(/(?<![\w])_([^_\n]+)_(?![\w])/g, "//$1//");
return text;
}
function replaceKnownTexSymbols(value) {
let text = value;
for (const [source, target] of Object.entries(TEX_SYMBOLS)) text = text.split(source).join(target);
return text;
}
module.exports = cleanText;
+55
View File
@@ -0,0 +1,55 @@
# Perry history
This file records why Perry changed, not every mechanical code edit.
## Conversation history became the session
The original problem was practical: build a chat client around Ollama whose sessions could be persisted, branched, and have information injected into them.
No extra session architecture was necessary. The provider already accepted conversation history in a JSON-friendly shape. Persisting that history persisted the session. Copying the history created a branch. Inserting or composing portions of history altered what the model knew.
Reusable conversation subsets became "Legos." Ordered collections of them became "Lego Towers." The useful technique emerged from ordinary chat history rather than from a new agent/session framework.
That remains a foundational Perry decision.
## Chat2 became reusable infrastructure
Several application pipelines independently needed the same mechanics around local LLM calls: prepared conversational agents, streaming reasoning and content, transport retries, incomplete-response continuation, and persistent conversation history.
The repeated implementation became Chat2 and was later extracted as Perry so applications could own domain behavior while sharing the mechanics of operating an LLM-backed conversational agent.
## LM Studio became the surviving provider
The older lineage supported Ollama, but the code available when Perry was extracted contained only the active LM Studio Responses API implementation. Perry documented that fact instead of reconstructing an Ollama provider from memory.
This is intentional simplicity: provider-neutral scope does not require speculative provider implementations.
## Repetition self-destruct
Real LM Studio/model runs demonstrated a catastrophic failure mode where a generation could fall into an exact repeating token orbit indefinitely. A deliberately conservative detector was added to the LM Studio streaming implementation.
It checks the reasoning and final-content channels independently and aborts only after an exact token sequence has repeated seven complete times. The normal retry layer can then restart the response without adding the pathological partial response to conversation history.
The behavior is intentionally provider-specific until multiple provider implementations demonstrate that a shared abstraction is useful.
## Perry 0.2: consolidate lessons from the family
The application family continued evolving after Perry was extracted. A Coptic guide pipeline learned that LM Studio model warmup failures must be fatal: continuing after a requested model cannot load allows expensive downstream work to run under false assumptions.
At the same time, Perry itself had acquired repetition protection that the copied Chat2 implementations did not contain. The divergence demonstrated why LLM transaction mechanics should have one home.
Perry 0.2 consolidates those lessons and clarifies the boundary:
- Perry is provider-neutral, not "local-model" infrastructure.
- Perry is constructed directly from explicit `provider` and `model` settings and has no dependency on Optimus.
- Instances are lightweight and may be created freely.
- `client` was deliberately replaced by `provider`; no compatibility alias was retained while the family is being revisited together.
- LM Studio warmup now fails fast when the requested model cannot be made available.
- Availability is checked before each request attempt rather than cached for the life of a Perry instance.
- The exact model requested by the consumer is the model Perry requests. Application aliases belong upstream.
- If LM Studio explicitly identifies a different response model, the response is rejected rather than treated as equivalent.
- The unused reasoning-effort configuration lever was removed. Reasoning streaming remains supported.
- Perry no longer writes reasoning, content, retries, continuations, or other user-facing messages to the console. Consumers own their UI and logging.
- Existing continuation, retry, provider diagnostics, Lego formation, and LM Studio repetition behavior were retained.
The goal was consolidation, not redesign. Downstream applications can keep their current orchestration shape and wrap Perry locally if that minimizes change.
+31
View File
@@ -0,0 +1,31 @@
# Ideas and deferred work
These are observations worth retaining, not promises or roadmap commitments. Do not implement them merely because they are written here. Revisit them when real work makes them relevant.
## Retry and model recovery
Current Perry transport behavior allows up to ten retries before giving up.
A real failure pattern suggests a potentially better strategy: after roughly four consecutive failures, explicitly recover or reload the requested model, then allow another small group of attempts rather than blindly repeating the same failing request ten times.
This has not been implemented in Perry 0.2. The existing retry behavior is transparent to consumers and remains serviceable. Before changing it, inspect current failures and discuss what "recover/reload" means for the active provider rather than designing a provider-wide recovery framework in advance.
## Additional providers
Ollama existed in Perry's Chat2 ancestry and was useful when it was being used. No active implementation exists in the current repository, so it was not recreated.
If Ollama or another provider becomes useful again, implement the concrete provider required by that work. Do not pre-build generalized provider infrastructure first.
Likewise, a future Perry provider might not be a network client at all. A local Python-backed model runtime could still be a Perry provider if it satisfies the actual need. That possibility does not justify architecture today.
## Additional settings
Possible LLM controls include context size, output token limits, temperature, reasoning effort, provider endpoints, and many others.
None should be added to Perry merely because they exist. Add a setting when a real consumer needs to control it and the responsibility clearly belongs at the Perry boundary.
## Shared provider behavior
Some behavior currently lives inside the LM Studio provider, including exact repetition-loop detection and stream abortion.
Do not extract a generic interface after a second vaguely similar implementation. A useful working heuristic is to wait until about three real implementations reveal substantially the same shape, then decide whether there is actually a common concept worth naming.
+84
View File
@@ -0,0 +1,84 @@
# Intentional behavior
These are deliberate Perry behaviors and boundaries, not incidental implementation details. Do not remove, generalize, or substantially alter them during cleanup or refactoring without discussion.
## Perry is the LLM boundary, not the application
Perry handles LLM transaction mechanics. Consumers decide who agents are, which Legos form them, why a request exists, what an answer means, and what happens next.
Do not move pipeline stages, translation semantics, artifact logic, domain validation, or agent personas into Perry merely because they are adjacent to an LLM call.
## Perry is independent of Optimus
Perry must not import Optimus, read Optimus settings, or provide an Optimus-specific adapter. Optimus must not be required by Perry.
An Optimus application may create its own local module that reads application settings, constructs Perry, and exposes whatever interface is convenient to that application.
## Perry instances are cheap
Construction does not open an expensive persistent connection, load a model, register global state, or create a resource that needs special disposal.
Consumers may use one Perry instance or many. Do not introduce singleton assumptions or application-global model state.
## Settings are small and explicit
Current settings are exactly the concepts Perry has evidence to own:
- `provider`
- `model`
Both are required. `provider` replaced the older `client` name deliberately.
Do not add settings merely because an underlying provider exposes options. Provider capabilities do not automatically become Perry configuration.
## Exact model means exact model
Perry does not know model aliases or equivalence classes.
Before a request, an implemented provider should use any certainty it actually possesses to establish that the exact configured model can handle the work. If it can prove that model is unavailable or another model would be used, fail before inference. If the provider cannot know, ambiguity is allowed.
After a response, reject a model mismatch only when the provider explicitly supplies enough evidence to know the response came from a different model. Absence of model metadata is not itself failure.
Application-level aliases and model-selection policy belong before Perry construction.
## Lego shape is Perry-owned and provider-neutral
Conversation messages use Perry's known shape. Providers translate that shape into provider-native requests.
Do not pass arbitrary provider-specific message fields through Perry. A provider currently accepting Perry's shape directly does not make that provider's format Perry's public contract.
Conversation subsets are ordinary data. Lego Towers do not require registries, inheritance, graph objects, session managers, or special persistence machinery.
## Reasoning is observable, not conversational authority
When a provider exposes reasoning, Perry may stream it through `onReasoning` and retain it on returned replies for diagnostics.
Reasoning is not normally included when a prior Lego/conversation subset is added to a new active conversation. The model's ordinary conversation context remains role/content history.
## Perry does not speak
Perry does not own console or UI output.
No automatic response printing, reasoning headings, retry messages, continuation messages, warnings, or progress output should be added to Perry. Consumers can use callbacks, return values, errors, and provider diagnostics to decide what to display or log.
## Automatic continuation is intentional
Provider-native incomplete responses are continued automatically when it can be done safely. If provider-native continuation is unavailable and the model produced reasoning without final content, Perry may continue through explicit conversation history.
Partial failed responses are not silently appended as successful conversation turns.
## Retry behavior is intentionally conservative and currently imperfect
Transient transport failures currently retry up to ten times with the existing backoff. Non-retryable failures, including known model availability/identity failures, stop immediately.
The ten-attempt strategy is not considered perfected or permanent. It remains because changing it is a separate behavioral decision; see `ideas.md`.
## LM Studio repetition protection is intentionally local
Exact repetition-loop detection lives in the LM Studio implementation because LM Studio is the concrete provider where the failure has been observed and implemented.
Do not manufacture a provider-wide repetition/cancellation interface from this single example. Generalize only after repeated real implementations expose the same natural boundary.
## Blocking boundary is the intended direction
Applications in this project family are synchronous blocking batch tools. Perry may need to deal with provider-level asynchronous transport internally, but that should eventually be hidden behind a blocking application-facing boundary with bounded timeout behavior. Existing Promise/callback APIs are legacy plumbing, not a desired architecture to extend.
+37 -45
View File
@@ -1,5 +1,6 @@
const Conversation = require("./conversation");
const lmStudio = require("./lmstudio");
const cleanText = require("./clean-text");
const MAX_TRANSPORT_ATTEMPTS = 10;
const MAX_CONTINUATIONS = 10;
@@ -9,16 +10,32 @@ const CONTINUE_PROMPT = [
"Keep investigating as deeply as necessary. When you have actually finished, provide the final deliverable required by the original prompt."
].join("\n");
module.exports = utils => {
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;
+41 -21
View File
@@ -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 warmUp(settings) {
try {
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 === settings.model);
const loadedInstance = models.flatMap(item => item.loaded_instances || []).find(instance => instanceMatches(instance, settings.model));
const installed = models.find(item => item.key === model);
const loadedInstance = models
.flatMap(item => item.loaded_instances || [])
.find(instance => instanceMatches(instance, model));
if (loadedInstance || installed?.loaded_instances?.length) return;
if (loadedInstance) return true;
if (installed?.loaded_instances?.length) return true;
if (installed) return false;
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;
}
if (loaded.data?.some(item => item.id === model)) return true;
}
const modelKey = installed?.key || settings.model;
return false;
}
async function warmUp(settings) {
try {
if (await modelIsAvailable(settings.model)) return;
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;
}
+4 -5
View File
@@ -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"
}
}
+168
View File
@@ -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;
}
);
});
+46
View File
@@ -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}`);
});