Compare commits

..
3 Commits
Author SHA1 Message Date
Chad Curtis cf4f21f066 Merge branch 'fix/evict-stale-tool-outputs' into 'main'
Draft: Evict large tool outputs from old messages before sending to API

See merge request soapbox-pub/shakespeare!112
2026-09-14 00:52:56 +00:00
Chad Curtis 272e07795e Soften tool output eviction: keep prefix and require 2+ assistant turns
- Preserve the first 1 KiB of truncated tool output instead of replacing
  with a zero-information placeholder, so the model retains partial context
  and can decide whether to re-fetch.
- Only evict tool outputs that are at least 2 assistant turns old, not
  everything before the most recent assistant message. This prevents
  truncating outputs the model may still need on the immediately following
  turn in multi-step agentic workflows.
2026-04-10 19:44:19 -05:00
Chad Curtis ebd6fc9a10 Evict large tool outputs from old messages before sending to API
Add evictSeenToolOutputs following the same pattern as evictSeenImages. Tool
results larger than 1 KiB that the model has already seen and responded to are
replaced with a short placeholder at send time. This prevents multi-MB tool
output history from being re-sent on every subsequent turn in long agentic
sessions.
2026-04-10 19:29:28 -05:00
7 changed files with 51 additions and 104 deletions

No files matched your search

-5
View File
@@ -1,10 +1,5 @@
# Changelog
## [9.16.1] - 2026-09-13
### Fixed
- Deploying to a name you already own works again — names you took back in the migration were reported as taken by somebody else, and the Deploy button refused to publish to your own site
## [9.16.0] - 2026-09-13
### Added
+1 -1
View File
@@ -3,7 +3,7 @@
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
"homepage": "https://shakespeare.diy",
"license": "AGPL-3.0-or-later",
"version": "9.16.1",
"version": "9.16.0",
"type": "module",
"author": {
"name": "shakespeare.diy",
-5
View File
@@ -1,10 +1,5 @@
# Changelog
## [9.16.1] - 2026-09-13
### Fixed
- Deploying to a name you already own works again — names you took back in the migration were reported as taken by somebody else, and the Deploy button refused to publish to your own site
## [9.16.0] - 2026-09-13
### Added
+5 -16
View File
@@ -3,7 +3,6 @@ import { AlertCircle, Check, Loader2 } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { checkNameAvailable, type NameAvailability } from '@/lib/deploy/NpanelAdapter';
/** How long typing has to stop before the gateway is asked about a name. */
@@ -35,11 +34,6 @@ type NameState =
| { kind: 'unavailable'; message: string };
function describe(availability: NameAvailability, domain: string): NameState {
// A name the gateway recognises as this user's own. It is spoken for, and
// they are who it is spoken for by — deploying updates the site already
// there rather than taking anything.
if (availability.reason === 'mine') return { kind: 'mine' };
if (availability.available) return { kind: 'free' };
if (availability.reason === 'taken') {
@@ -62,7 +56,6 @@ export function NpanelDeployForm({
onSiteDescriptionChange,
onValidationChange,
}: NpanelDeployFormProps) {
const { user } = useCurrentUser();
const [subdomain, setSubdomain] = useState(savedSubdomain || projectId);
const [siteTitle, setSiteTitle] = useState(savedSiteTitle ?? projectName);
const [siteDescription, setSiteDescription] = useState(savedSiteDescription ?? '');
@@ -94,12 +87,12 @@ export function NpanelDeployForm({
// The name this project already deployed to is not "taken" — it is theirs,
// and asking the gateway would truthfully say taken and alarm them about
// their own site. Compared trimmed, since that is what gets deployed: a
// trailing space is not a different name.
const trimmed = subdomain.trim();
const isOwnName = Boolean(savedSubdomain) && trimmed === savedSubdomain;
// their own site.
const isOwnName = Boolean(savedSubdomain) && subdomain === savedSubdomain;
useEffect(() => {
const trimmed = subdomain.trim();
if (!trimmed) {
setNameState({ kind: 'empty' });
return;
@@ -113,14 +106,10 @@ export function NpanelDeployForm({
const controller = new AbortController();
const timer = setTimeout(async () => {
// Signed, where there is someone to sign: a name this user owns but this
// project has never deployed to — one they took back through the
// migration — is otherwise indistinguishable from a stranger's.
const availability = await checkNameAvailable(
dashboardHost,
`${trimmed}.${domain}`,
controller.signal,
user?.signer,
);
if (!controller.signal.aborted) setNameState(describe(availability, domain));
}, AVAILABILITY_DEBOUNCE_MS);
@@ -129,7 +118,7 @@ export function NpanelDeployForm({
controller.abort();
clearTimeout(timer);
};
}, [trimmed, isOwnName, dashboardHost, domain, user?.signer]);
}, [subdomain, isOwnName, dashboardHost, domain]);
// A name still being checked stays deployable: the gateway decides for real
// when the deploy runs, and blocking the button on an in-flight request would
+38
View File
@@ -396,6 +396,41 @@ export class SessionManager {
});
};
// Replace large tool result content with a truncated prefix for messages the
// model has already seen and responded to at least twice. Like evictSeenImages,
// this is a send-time transformation only — session.messages stays intact for
// the UI. We keep the first TOOL_OUTPUT_EVICTION_THRESHOLD bytes so the model
// retains partial context and can decide whether to re-fetch the full output.
const TOOL_OUTPUT_EVICTION_THRESHOLD = 1024; // 1 KiB
const TOOL_OUTPUT_MIN_ASSISTANT_TURNS = 2; // Only evict after 2+ assistant responses
const evictSeenToolOutputs = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
// Collect indices of all assistant messages.
const assistantIndices: number[] = [];
for (let i = 0; i < msgs.length; i++) {
if (msgs[i].role === 'assistant') {
assistantIndices.push(i);
}
}
// Need at least TOOL_OUTPUT_MIN_ASSISTANT_TURNS + 1 assistant messages:
// the ones that have "seen" the tool output, plus the current pending turn.
if (assistantIndices.length < TOOL_OUTPUT_MIN_ASSISTANT_TURNS + 1) return msgs;
// The eviction cutoff is the assistant message N turns back from the end.
// Tool results before this index have been processed by at least N assistant
// turns, so truncating them is safe.
const cutoffIdx = assistantIndices[assistantIndices.length - TOOL_OUTPUT_MIN_ASSISTANT_TURNS];
return msgs.map((msg, idx) => {
if (idx >= cutoffIdx) return msg;
if (msg.role !== 'tool') return msg;
if (typeof msg.content !== 'string') return msg;
if (msg.content.length <= TOOL_OUTPUT_EVICTION_THRESHOLD) return msg;
return { ...msg, content: msg.content.slice(0, TOOL_OUTPUT_EVICTION_THRESHOLD) + '\n\n[… truncated]' };
});
};
// Prepare messages for AI
// Note: User messages with image_url content parts are valid ChatCompletionMessageParam types
// The AIMessage type includes ChatCompletionMessageParam, so this cast is safe
@@ -403,6 +438,9 @@ export class SessionManager {
? [{ role: 'system', content: systemPrompt }, ...session.messages]
: session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[];
// Evict large tool outputs the model has already processed.
messages = evictSeenToolOutputs(messages);
// Evict images the model has already seen (all except the last user message).
// This is a send-time transformation only — session.messages stays intact for the UI.
messages = evictSeenImages(messages);
-48
View File
@@ -222,52 +222,4 @@ describe('checkNameAvailable', () => {
available: true,
});
});
it('asks again as the signer when a name comes back taken', async () => {
// "Taken" and "taken by you" are the same word to a stranger and opposite
// answers to the person about to deploy.
fetchMock
.mockResolvedValueOnce(
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
)
.mockResolvedValueOnce(
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: true, reason: 'mine' })),
);
await expect(
checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer),
).resolves.toMatchObject({ available: true, reason: 'mine' });
expect(fetchMock).toHaveBeenCalledTimes(2);
// The first ask carries nothing; only the second spends a signature.
const [, anonymous] = fetchMock.mock.calls[0];
expect((anonymous as RequestInit | undefined)?.headers).toBeUndefined();
const signed = fetchMock.mock.calls[1][0] as Request;
expect(signed.headers.get('Authorization')).toMatch(/^Nostr /);
expect(signed.url).toBe(`https://${DASHBOARD_HOST}/api/hosts/x.${DOMAIN}/available`);
});
it('spends no signature on a name that is free', async () => {
// Picking a new name is the common case, and a remote signer on the other
// end of every keystroke is not something to spend it on.
fetchMock.mockResolvedValue(new Response(JSON.stringify({ hostname: 'x', available: true })));
await checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('keeps the public answer when the gateway is too old to know better', async () => {
fetchMock
.mockResolvedValueOnce(
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
)
.mockResolvedValueOnce(new Response('nope', { status: 404 }));
await expect(
checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer),
).resolves.toMatchObject({ available: false, reason: 'taken' });
});
});
+7 -29
View File
@@ -10,13 +10,7 @@ const NAMED_SITE_KIND = 35128;
export interface NameAvailability {
hostname: string;
available: boolean;
/**
* Why it is not free, or — with `available` — that it is not free of somebody
* else. `mine` comes only from a signed request, and only from a gateway new
* enough to answer one; an older one says `taken` and is not wrong, just less
* use to the person who owns the name.
*/
reason?: 'taken' | 'invalid' | 'mine';
reason?: 'taken' | 'invalid';
/** Present when `reason` is `invalid`; written to be shown to whoever typed it. */
error?: string;
}
@@ -24,15 +18,9 @@ export interface NameAvailability {
/**
* Ask whether a name can still be claimed.
*
* Asked anonymously first, and deliberately so: someone choosing a name has not
* decided to make an account yet, and making them prove who they are to find out
* their first choice is taken would be a strange order to do things in.
*
* A name that comes back taken is then asked about again, signed, because
* "taken" and "taken by you" are the same answer to a stranger and opposite
* answers to the person about to deploy. Only on that branch: a free name is the
* common case while somebody is picking one, and signing every keystroke would
* put a remote signer on the other end of the typing.
* Unauthenticated, and deliberately so: someone choosing a name has not decided
* to make an account yet, and making them prove who they are to find out their
* first choice is taken would be a strange order to do things in.
*
* A network failure answers `available: true` rather than blocking the person.
* Being wrong that way costs a clear error at deploy time; being wrong the other
@@ -42,23 +30,13 @@ export async function checkNameAvailable(
dashboardHost: string,
hostname: string,
signal?: AbortSignal,
signer?: NostrSigner,
): Promise<NameAvailability> {
const path = `/api/hosts/${encodeURIComponent(hostname)}/available`;
const url = `https://${dashboardHost}/api/hosts/${encodeURIComponent(hostname)}/available`;
try {
const response = await fetch(`https://${dashboardHost}${path}`, {
signal: signal ?? AbortSignal.timeout(NPANEL_TIMEOUT_MS),
});
const response = await fetch(url, { signal: signal ?? AbortSignal.timeout(NPANEL_TIMEOUT_MS) });
if (!response.ok) return { hostname, available: true };
const availability = (await response.json()) as NameAvailability;
if (availability.available || availability.reason !== 'taken' || !signer) return availability;
const asOwner = await npanelRequest(dashboardHost, signer, 'GET', path, undefined, signal);
if (!asOwner.ok) return availability;
return (await asOwner.json()) as NameAvailability;
return (await response.json()) as NameAvailability;
} catch {
return { hostname, available: true };
}