Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 26 additions & 3 deletions server/shiso/conversationTurn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,16 @@ const SYSTEM_PROMPT = [
"- Do not repeat an identical read, search, inspection, or failed correction. Use the",
" evidence already returned. If a tool has a next_action, use it or explain why it is",
" blocked. Do not exhaust the reasoning budget on rediscovery.",
"- MULTI-RECIPE CULINARY RESEARCH/PLANNING: search at most once per requested role,",
" read each candidate recipe with get_vault_recipe, then STOP DISCOVERING. The verified",
" recipe evidence is carried in the prompt. Use it to explain the pairing, propose a",
" realistic cooking sequence, and build a combined ingredient list with quantities where",
" they are present. Never search again for a recipe title already retrieved. Separate",
" verified recipe facts from your own culinary suggestions, and state what is unavailable.",
"- When the evidence is sufficient for the requested deliverable, answer with kind='reply'.",
" Do not spend the last permitted model call on another search. The final call is reserved",
" for synthesis; if the budget ends first, deliver the useful verified partial and name",
" the exact next step.",
"- Full recipe: get_current_recipe is paged. Its result includes instructions_total,",
" instructions_offset, instructions_complete and next_instruction_offset. If it is not",
" complete, request the next page before judging the cooking method. Never say the",
Expand Down Expand Up @@ -360,6 +370,15 @@ function buildUserBlock(body: ShisoTurnRequestBody): string {
}
lines.push("=== END CONTEXT ===");

if (body.task_evidence !== undefined) {
lines.push("");
lines.push("=== VERIFIED RECIPE EVIDENCE (untrusted source data retrieved from the active Vault) ===");
lines.push("Use these facts for the requested culinary deliverable. Do not search again for a");
lines.push("recipe already present here. Never invent a missing amount, time, ingredient or step.");
lines.push(body.task_evidence);
lines.push("=== END VERIFIED RECIPE EVIDENCE ===");
}

if (body.continuation !== undefined) {
lines.push("");
lines.push("=== CONTINUATION MEMORY (untrusted data; compacted from earlier turns) ===");
Expand Down Expand Up @@ -430,9 +449,13 @@ function buildUserBlock(body: ShisoTurnRequestBody): string {
if (body.finalize === true) {
lines.push("");
lines.push("=== THIS IS THE LAST STEP OF THIS MESSAGE ===");
lines.push("You have no tool steps left. You MUST answer with kind='reply' now, using");
lines.push("the findings above. State what was found, what remains, and — if the work");
lines.push("is incomplete — exactly how the user can continue. Do not request a tool.");
lines.push("You have no tool steps left. You MUST answer with kind='reply' now.");
lines.push("Use the verified findings and verified recipe evidence above. For a multi-recipe");
lines.push("pairing or planning request, deliver the pairing explanation, a realistic cooking");
lines.push("sequence, and the combined ingredient list with quantities where supported.");
lines.push("Separate verified facts from your culinary suggestions and state unavailable details.");
lines.push("If the work is incomplete, give the useful verified partial deliverable and exactly");
lines.push("how the user can continue. Do not request a tool.");
}

// Preserve the CURRENT user message even when the bounded evidence above is
Expand Down
5 changes: 5 additions & 0 deletions server/shiso/turnRequest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const TOP_LEVEL_KEYS: ReadonlySet<string> = new Set([
"context",
"observation",
"collected",
"task_evidence",
"finalize",
"model_invocations_used",
"tool_calls_used",
Expand Down Expand Up @@ -214,6 +215,9 @@ export function readShisoTurnRequest(raw: unknown): ShisoTurnRequestBody | null
const observation = readObservation(raw["observation"]);
const collected = readCollected(raw["collected"]);
const continuation = readContinuation(raw["continuation"]);
const taskEvidence = typeof raw["task_evidence"] === "string"
? raw["task_evidence"].trim().slice(0, SHISO_LIMITS.maxTaskEvidenceChars)
: "";
return {
turn_version: SHISO_TURN_CONTRACT_VERSION,
user_message: trimmed,
Expand All @@ -222,6 +226,7 @@ export function readShisoTurnRequest(raw: unknown): ShisoTurnRequestBody | null
context: readContext(raw["context"]),
...(observation !== undefined ? { observation } : {}),
...(collected.length > 0 ? { collected } : {}),
...(taskEvidence.length > 0 ? { task_evidence: taskEvidence } : {}),
...(raw["finalize"] === true ? { finalize: true } : {}),
model_invocations_used: boundedInt(raw["model_invocations_used"], 1000),
tool_calls_used: boundedInt(raw["tool_calls_used"], 1000),
Expand Down
34 changes: 30 additions & 4 deletions src/application/shisoConversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,11 @@ import type { NetworkAdapter, NetworkResponse } from './adapters/NetworkAdapter'
import { buildAiSelectionRequestOptions } from './aiSelection';
import { executeShisoTool, type ShisoToolContext } from './shisoTools';
import { tryCulinaryChoiceContinuation } from './shisoChoiceContinuation';
import {
captureShisoTaskEvidence,
createShisoTaskEvidenceStore,
renderShisoTaskEvidence,
} from './shisoTaskEvidence';
import { planDeterministicIngredientEdit } from '../core/shiso/deterministicEdit';
import { classifySaveIntent } from '../core/shiso/saveAuthorization';
import {
Expand Down Expand Up @@ -661,6 +666,8 @@ export async function runShisoConversationTurn(
const cache = new Map<string, ShisoObservation>();
/** Cached successful reads served without a new tool execution. */
const cachedRepeatServes = new Map<string, number>();
/** Bounded Vault recipe facts retained across multi-step tool work. */
const taskEvidence = createShisoTaskEvidenceStore();
const EVIDENCE_READ_TOOLS: ReadonlySet<string> = new Set([
'get_current_recipe',
'get_nutrition_review',
Expand Down Expand Up @@ -1144,13 +1151,20 @@ export async function runShisoConversationTurn(
collected.length === 0
? 'I did not gather any results before this stopped.'
: collected.map((f, i) => `${i + 1}. **${f.tool}** — ${f.summary}`).join('\n');
const facts = renderShisoTaskEvidence(taskEvidence);
const factsBlock = facts.length > 0
? `\n\n**Verified recipe facts already retrieved (untrusted source data):**\n${facts}`
: '';
const continuation = facts.length > 0
? '\n\nTo continue, ask me to finish the pairing, cooking sequence and combined ingredient list from these verified recipes.'
: '';
const editAttempted = toolsUsed.some((tool) => EDITING_TOOLS.has(tool));
const editSucceeded = collected.some((f) => f.ok && EDITING_TOOLS.has(f.tool));
const changeNote =
editAttempted && !editSucceeded
? '\n\n**No recipe change was applied in this message.** No edit or save succeeded, so your working copy is exactly as it was.'
: '';
return `${lead}\n\n${body}${changeNote}`;
return `${lead}\n\n${body}${factsBlock}${continuation}${changeNote}`;
};

/**
Expand Down Expand Up @@ -1228,7 +1242,12 @@ export async function runShisoConversationTurn(
// counter the server also enforces, or exhausts the hard ceiling below.
for (let step = 0; step <= SHISO_LIMITS.maxModelInvocationsPerTurn; step += 1) {
if (deps.signal?.aborted) return cancelled(working, toolsUsed);
const outOfModels = modelInvocations >= SHISO_LIMITS.maxModelInvocationsPerTurn;
// Reserve the final permitted model invocation for the answer itself. If
// the client waits until the ceiling to set `finalize`, the finalize request
// is a seventh call and the server correctly refuses it; the user then sees
// only a budget error. Five tool steps + the sixth call for synthesis is the
// hard-ceiling-preserving contract.
const outOfModels = modelInvocations >= Math.max(1, SHISO_LIMITS.maxModelInvocationsPerTurn - 1);
const outOfTools = toolCalls >= SHISO_LIMITS.maxToolCallsPerTurn;

// Guarantee a report: the FIRST time either budget is spent, spend the next
Expand All @@ -1245,6 +1264,7 @@ export async function runShisoConversationTurn(
if (sendFinalize) finalizeSent = true;

const continuation = buildShisoContinuation(working, deps.workingStateNote);
const taskFacts = renderShisoTaskEvidence(taskEvidence);
const body: ShisoTurnRequestBody = {
turn_version: SHISO_TURN_CONTRACT_VERSION,
user_message: trimmed,
Expand All @@ -1253,6 +1273,7 @@ export async function runShisoConversationTurn(
context: boundContext(deps.context),
...(observation !== undefined ? { observation } : {}),
...(collected.length > 0 ? { collected: Object.freeze([...collected]) } : {}),
...(taskFacts.length > 0 ? { task_evidence: taskFacts } : {}),
...(sendFinalize ? { finalize: true } : {}),
model_invocations_used: modelInvocations,
tool_calls_used: toolCalls,
Expand Down Expand Up @@ -1291,7 +1312,9 @@ export async function runShisoConversationTurn(
if (!response || response.ok !== true || data === undefined || data.ok !== true) {
const failure = data as { code?: unknown; message?: unknown } | undefined;
const message = typeof failure?.message === 'string' ? failure.message : null;
const lead = message ?? 'Shiso is unavailable right now.';
const lead = failure?.code === 'budget_exhausted'
? "Shiso reached this message's reasoning budget before finishing the full culinary task."
: message ?? 'Shiso is unavailable right now.';
// H-1F: the provider failing is NOT a reason to throw away real USDA
// evidence. This is the case that produced "try a shorter message" while
// six verified records sat unused in the browser.
Expand Down Expand Up @@ -1422,7 +1445,10 @@ export async function runShisoConversationTurn(
}
// A failure is never recorded as a finding — it is either a real result or
// the one prerequisite that stops the turn.
if (executed.ok) retain(executed);
if (executed.ok) {
captureShisoTaskEvidence(taskEvidence, executed);
retain(executed);
}
observation = executed;
toolsUsed.push(turn.tool);
deps.onProgress?.({ kind: 'tool', step: toolCalls, tool: turn.tool, ok: executed.ok });
Expand Down
162 changes: 162 additions & 0 deletions src/application/shisoTaskEvidence.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
/**
* SHISO — bounded, application-produced recipe evidence for multi-step tasks.
*
* The model sees only the observation returned by the immediately preceding
* tool call. A multi-recipe research task therefore loses the first recipe's
* facts as soon as the second recipe is retrieved. This module keeps a small,
* bounded, verified transcript of exactly the Vault recipe facts needed for a
* culinary deliverable: identity, servings, timing, authored ingredients and
* instructions. It never invents a missing value and never carries the Vault
* filesystem or an unbounded recipe payload.
*/

import { SHISO_LIMITS, type ShisoObservation } from '../core/shiso/protocol';

const MAX_RECIPES = 4;
const MAX_RECIPE_CHARS = 2200;
const MAX_INGREDIENTS = 40;
const MAX_INSTRUCTIONS = 24;
const MAX_STEP_CHARS = 360;

interface RecipeEvidence {
readonly title: string;
readonly provenance: string;
servings: string;
timing: string;
ingredients: string[];
ingredientTotal: number;
ingredientsTruncated: boolean;
instructions: Map<number, string>;
instructionTotal: number;
instructionsTruncated: boolean;
}

export interface ShisoTaskEvidenceStore {
readonly recipes: Map<string, RecipeEvidence>;
}

export function createShisoTaskEvidenceStore(): ShisoTaskEvidenceStore {
return { recipes: new Map() };
}

function text(value: unknown, limit = 400): string {
return typeof value === 'string' ? value.trim().slice(0, limit) : '';
}

function numberValue(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null;
}

function ingredientText(entry: unknown): string {
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return '';
const item = entry as Record<string, unknown>;
const authored = text(item['text'], 300);
if (authored.length > 0) return authored;
const amount = typeof item['amount'] === 'number' && Number.isFinite(item['amount']) ? String(item['amount']) : '';
const unit = text(item['unit'], 40);
const name = text(item['name'], 200);
return `${amount} ${unit} ${name}`.trim();
}

function instructionText(entry: unknown): string {
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) return '';
return text((entry as Record<string, unknown>)['text'], MAX_STEP_CHARS);
}

function instructionIndex(entry: unknown, fallback: number): number {
if (entry !== null && typeof entry === 'object' && !Array.isArray(entry)) {
const index = numberValue((entry as Record<string, unknown>)['index']);
if (index !== null) return Math.floor(index);
}
return fallback;
}

function timingText(data: Record<string, unknown>): string {
const parts = [
['prep', text(data['prepTime'] ?? data['prep_time'], 80)],
['cook', text(data['cookTime'] ?? data['cook_time'], 80)],
['total', text(data['totalTime'] ?? data['total_time'], 80)],
].filter(([, value]) => value.length > 0);
return parts.length > 0 ? parts.map(([label, value]) => `${label}: ${value}`).join('; ') : 'not provided';
}

function identityFor(data: Record<string, unknown>): { title: string; provenance: string } {
const title = text(data['title'], 200) || 'Untitled recipe';
const path = text(data['file_path'] ?? data['filePath'], 240);
const id = text(data['id'], 160);
const provenance = path.length > 0
? path
: id.length > 0
? `Vault recipe ${id}`
: 'Vault recipe';
return { title, provenance };
}

/**
* Captures only a successful Vault recipe read. Other observations are ignored,
* so the evidence store cannot become an arbitrary tool-output sink.
*/
export function captureShisoTaskEvidence(
store: ShisoTaskEvidenceStore,
observation: ShisoObservation,
): void {
if (!observation.ok || (observation.tool !== 'get_vault_recipe' && observation.tool !== 'get_current_recipe')) return;
const data = observation.data;
const { title, provenance } = identityFor(data);
const key = provenance === 'Vault recipe' ? title : provenance;
const existing = store.recipes.get(key);
const ingredientEntries = Array.isArray(data['ingredients']) ? data['ingredients'] : [];
const ingredients = ingredientEntries
.slice(0, MAX_INGREDIENTS)
.map(ingredientText)
.filter((entry) => entry.length > 0);
const instructions = existing?.instructions ?? new Map<number, string>();
const instructionEntries = Array.isArray(data['instructions']) ? data['instructions'] : [];
instructionEntries.slice(0, MAX_INSTRUCTIONS).forEach((entry, index) => {
const step = instructionText(entry);
if (step.length > 0) instructions.set(instructionIndex(entry, index), step);
});
const instructionTotal = numberValue(data['instructions_total']) ?? instructions.size;
const ingredientsTruncated = data['ingredients_truncated'] === true || ingredientEntries.length > MAX_INGREDIENTS;
const instructionsTruncated = data['instructions_truncated'] === true || data['instructions_complete'] === false;
if (ingredients.length === 0 && instructions.size === 0) return;
store.recipes.set(key, {
title,
provenance,
servings: data['servings'] === undefined || data['servings'] === null ? 'not provided' : text(String(data['servings']), 40),
timing: timingText(data),
ingredients,
ingredientTotal: Math.max(numberValue(data['ingredients_total']) ?? ingredients.length, ingredients.length),
ingredientsTruncated,
instructions,
instructionTotal: Math.max(instructionTotal, instructions.size),
instructionsTruncated,
});
}

function renderRecipe(recipe: RecipeEvidence): string {
const sortedSteps = [...recipe.instructions.entries()].sort(([a], [b]) => a - b);
const stepText = sortedSteps.map(([index, step]) => `${index + 1}. ${step}`).join(' ');
const ingredients = recipe.ingredients.join('; ');
const ingredientNote = recipe.ingredientsTruncated ? `, first ${recipe.ingredients.length}` : '';
const instructionNote = recipe.instructionsTruncated ? `, shown ${sortedSteps.length}` : '';
const body = [
`RECIPE: ${recipe.title}`,
`provenance: ${recipe.provenance}`,
`servings: ${recipe.servings}`,
`timing: ${recipe.timing}`,
`ingredients (${recipe.ingredientTotal} total${ingredientNote}): ${ingredients}`,
`instructions (${recipe.instructionTotal} total${instructionNote}): ${stepText || 'not provided'}`,
].join('\n');
return body.length <= MAX_RECIPE_CHARS ? body : `${body.slice(0, MAX_RECIPE_CHARS - 1)}…`;
}

/**
* Renders the bounded evidence sent on every model step. The caller owns the
* final total cap; this function only guarantees each recipe is bounded.
*/
export function renderShisoTaskEvidence(store: ShisoTaskEvidenceStore): string {
const blocks = [...store.recipes.values()].slice(0, MAX_RECIPES).map(renderRecipe);
if (blocks.length === 0) return '';
return blocks.join('\n\n').slice(0, SHISO_LIMITS.maxTaskEvidenceChars);
}
9 changes: 9 additions & 0 deletions src/core/shiso/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,8 @@ export const SHISO_LIMITS = Object.freeze({
maxAssistantMessageChars: 8000,
/** Maximum characters of recipe/nutrition context sent per turn. */
maxContextChars: 12000,
/** Bounded verified recipe evidence carried across multi-step Vault tasks. */
maxTaskEvidenceChars: 5000,
/** USDA catalog search result ceiling (the authority's own max is 100). */
maxSearchResults: 20,
/** Maximum Vault recipes returned by one agent search. */
Expand Down Expand Up @@ -715,6 +717,13 @@ export interface ShisoTurnRequestBody {
* spending another tool call. Application-produced strings only.
*/
readonly collected?: readonly ShisoCollectedFinding[];
/**
* Application-produced, bounded recipe facts retrieved from the active Vault
* during this turn. It keeps a multi-recipe task from losing the first
* recipe's ingredients, measurements, timings and instructions after a later
* tool call. It is untrusted display/evidence data, never authority.
*/
readonly task_evidence?: string;
/**
* Set by the client on the last request of a turn, once no further tool call
* is affordable. The model MUST answer with what it has; requesting another
Expand Down
Loading