Compare commits

..
3 Commits
Author SHA1 Message Date
Chad Curtis fd04cc5eee 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-15 02:05:03 +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
9 changed files with 60 additions and 43 deletions

No files matched your search

-5
View File
@@ -1,10 +1,5 @@
# Changelog
## [9.16.4] - 2026-09-16
### Changed
- Published sites carry only the tags the nsite spec defines — the relay hints Shakespeare used to attach were read by nothing, and taking a site back no longer rewrites them
## [9.16.3] - 2026-09-14
### Added
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "shakespeare.diy",
"version": "9.16.4",
"version": "9.16.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "shakespeare.diy",
"version": "9.16.4",
"version": "9.16.2",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/app": "^8.1.0",
+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.4",
"version": "9.16.3",
"type": "module",
"author": {
"name": "shakespeare.diy",
-5
View File
@@ -1,10 +1,5 @@
# Changelog
## [9.16.4] - 2026-09-16
### Changed
- Published sites carry only the tags the nsite spec defines — the relay hints Shakespeare used to attach were read by nothing, and taking a site back no longer rewrites them
## [9.16.3] - 2026-09-14
### Added
@@ -145,7 +145,7 @@ export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMi
kind: NAMED_SITE_KIND,
content: claim.step.manifest.content,
created_at: Math.floor(Date.now() / 1000),
tags: republishTags(claim.step.manifest, claim.step.identifier, {
tags: republishTags(claim.step.manifest, claim.step.identifier, provider.relayUrls, {
title: claim.suggestedTitle,
description: claim.suggestedDescription,
}),
+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);
+5 -7
View File
@@ -250,8 +250,8 @@ async function runConcurrent<T>(
* - HEAD-checks each file on each Blossom server before uploading
* - PUTs files to Blossom servers with pre-signed auth headers
* - Publishes a single kind-15128 (root) or kind-35128 (named) site manifest event
* containing all ["path", "/path", sha256] tags and ["server", url] Blossom
* hints — no separate kind 10002 or kind 10063 published
* containing all ["path", "/path", sha256] tags, ["server", url] Blossom hints,
* and ["relay", url] relay hints — no separate kind 10002 or kind 10063 published
*
* Named sites (kind 35128, siteIdentifier set):
* URL = https://{base36pubkey}{siteIdentifier}.{gateway}
@@ -367,10 +367,8 @@ export class NsiteAdapter implements DeployAdapter {
pathTags.push(['path', '/404.html', indexFile.sha256]);
}
// NIP-5A defines no relay-hint tag for a manifest, so the relays a site was
// published to are not written into it. Where to find the event is the
// reader's problem and the author's kind 10002, not the manifest's.
const serverTags: string[][] = serverBases.map(url => ['server', url]);
const relayTags: string[][] = this.relayUrls.map(url => ['relay', url]);
const tags: string[][] = [];
@@ -379,7 +377,7 @@ export class NsiteAdapter implements DeployAdapter {
tags.push(['d', this.siteIdentifier]);
}
tags.push(...pathTags, ...serverTags);
tags.push(...pathTags, ...serverTags, ...relayTags);
if (this.siteTitle) {
tags.push(['title', this.siteTitle]);
@@ -401,7 +399,7 @@ export class NsiteAdapter implements DeployAdapter {
});
// ── Step 5: Publish manifest ──────────────────────────────────────────────
// Blossom server hints are embedded as tags in the manifest itself —
// Relay and server hints are embedded as tags in the manifest itself —
// no separate kind 10002 or kind 10063 events are published.
//
// Relay by relay, because the site is only as findable as the relays that
+7 -10
View File
@@ -154,15 +154,15 @@ describe('republishTags', () => {
const tags = republishTags(
{ ...manifest, tags: [...manifest.tags, ['relay', 'wss://gone.example']] },
'mysite',
['wss://relay.ditto.pub'],
{ title: 'My Site', description: 'What it is for.' },
);
expect(tags[0]).toEqual(['d', 'mysite']);
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
expect(tags).toContainEqual(['server', 'https://blossom.ditto.pub/']);
// NIP-5A has no relay-hint tag, so the archive's are dropped and none of
// ours take their place.
expect(tags.some(([name]) => name === 'relay' || name === 'r')).toBe(false);
expect(tags).toContainEqual(['relay', 'wss://relay.ditto.pub']);
expect(tags).not.toContainEqual(['relay', 'wss://gone.example']);
expect(tags.filter(([name]) => name === 'd')).toHaveLength(1);
// The archive's title was the hostname and its `alt` says the site is
@@ -180,7 +180,7 @@ describe('republishTags', () => {
// Roughly a third of these are shells that set their title from JavaScript.
// No title is what an nsite manifest without one has always meant, and is
// better than a domain wearing a name's clothes.
const tags = republishTags(manifest, 'mysite', {});
const tags = republishTags(manifest, 'mysite', [], {});
expect(tags.some(([name]) => name === 'title')).toBe(false);
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
@@ -188,7 +188,7 @@ describe('republishTags', () => {
});
describe('retitleTags', () => {
it('swaps the archive’s words, drops the tags NIP-5A never had, and passes the rest through', () => {
it('swaps the archive’s words and passes everything else through', () => {
const event = {
id: 'e'.repeat(64),
pubkey: PUBKEY,
@@ -208,13 +208,10 @@ describe('retitleTags', () => {
const tags = retitleTags(event, { title: 'My Site' });
expect(tags).toContainEqual(['d', 'mysite']);
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
// Built from the event as relays hold it, so a site redeployed since this
// migration ran keeps whatever it has become.
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
expect(tags).toContainEqual(['server', 'https://blossom.ditto.pub/']);
// Except the relay hints an older deploy wrote, which re-signing is the
// chance to stop carrying.
expect(tags.some(([name]) => name === 'relay')).toBe(false);
expect(tags).toContainEqual(['relay', 'wss://relay.ditto.pub']);
expect(tags).toContainEqual(['title', 'My Site']);
expect(tags.filter(([name]) => name === 'title')).toHaveLength(1);
});
+6 -12
View File
@@ -208,14 +208,13 @@ export function planClaim(
* called gets no title, which is what an nsite manifest without one has always
* meant and is more honest than a domain.
*
* The archive's relay hints are dropped and not replaced. NIP-5A gives a
* manifest no tag for saying where it was published, so the archive's `relay`
* and `r` tags are tags that were never part of the spec, and re-signing them
* under someone else's key would only spread them further.
* Relay hints are replaced for the same reason: the archive's say where the
* archive published, and this event is going somewhere else.
*/
export function republishTags(
manifest: NpanelClaimManifest,
identifier: string,
relayUrls: string[],
identity: SiteIdentity = {},
): string[][] {
const kept = manifest.tags.filter(
@@ -227,6 +226,7 @@ export function republishTags(
['d', identifier],
...kept,
...describeTags(identity),
...relayUrls.map((url) => ['relay', url]),
];
}
@@ -237,16 +237,10 @@ export function republishTags(
* holds, because the two are not always the same thing: a site republished by
* this migration and then redeployed normally has moved on, and rebuilding it
* out of the gateway's copy would quietly restore an older version of the site.
* Everything but the archive's own words and the relay hints NIP-5A never
* defined is passed through untouched; signing an event is the moment to stop
* carrying a tag that does not exist.
* Everything but the archive's own words is passed through untouched.
*/
export function retitleTags(event: NostrEvent, identity: SiteIdentity): string[][] {
const kept = event.tags.filter(
([name]) => name !== 'relay' && name !== 'r' && !ARCHIVE_TAGS.has(name),
);
return [...kept, ...describeTags(identity)];
return [...event.tags.filter(([name]) => !ARCHIVE_TAGS.has(name)), ...describeTags(identity)];
}
/**