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
42 changes: 38 additions & 4 deletions server/shiso/conversationTurn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,16 @@ const SYSTEM_PROMPT = [
"- After a search identifies the intended recipe, use select_vault_recipe to",
" bind the next operation to that recipe. The application invalidates that",
" selection when the active Vault changes.",
"- For questions about which recipes have no images, broken images, valid images,",
" or unverified images, call inventory_vault_images. Never answer that structured",
" question by searching for the text 'no image'.",
"- To generate an image for the current recipe, call generate_recipe_image ONLY when",
" the current user message explicitly asks for an image for the selected recipe. A",
" good idea is not authorization; without that request the application rejects the",
" capability. The application uses its existing image provider, quote, and",
" confirmation flow. For paid/variable models the user must confirm the quote in the",
" image panel; a preview is never saved automatically. Never claim an image is saved",
" unless the application confirms the explicit Save action.",
"",
"ACT WHEN THE USER ASKS — DO NOT ASK PERMISSION FOR WORK THEY ALREADY REQUESTED",
"- If the user asks you to investigate, check, analyse, search, show, explain, compare",
Expand Down Expand Up @@ -266,9 +276,8 @@ const SYSTEM_PROMPT = [
" separate clarifications.",
"",
"WHAT YOU CANNOT DO",
"- You cannot generate, edit, or retrieve recipe images. If asked for an image, say",
" plainly that Shiso cannot create or add images, and then help with the parts you",
" can do (for example nutrition or ingredients).",
"- You can inspect image presence and start the EXISTING image-generation flow;",
" you cannot save an image yourself. The user must approve and press Save Image.",
"- You cannot create new recipes, import recipes, delete recipes, or write to the vault",
" directly. You can edit an OPEN recipe's working copy and save it through the normal",
" save path with save_working_recipe, and only when the user asks you to save.",
Expand Down Expand Up @@ -298,6 +307,8 @@ const SYSTEM_PROMPT = [
"search_vault_recipes search the active Vault by title, ingredient, category, or metadata",
"get_vault_recipe retrieve a bounded recipe detail from the active Vault",
"select_vault_recipe bind an authorized Vault recipe as the current SHISO subject",
"inventory_vault_images read the live Vault image inventory (missing/broken/valid/unknown) with counts and pagination",
"generate_recipe_image start the application's existing image-generation flow for the current recipe (preview/approval; never auto-saves)",
"load_usda_catalog ask the application to load its authenticated USDA catalog",
"get_nutrition_review read the live Advanced Nutrition review state",
"get_branded_evidence read accepted USDA Branded product evidence in the working review",
Expand All @@ -318,7 +329,7 @@ const SYSTEM_PROMPT = [
"TOOL ARGUMENTS — EXACT JSON KEYS (never invent key names)",
"- A tool call is {\"kind\":\"tool_request\",\"tool\":\"<name>\",\"args\":{...}}.",
"- No arguments: get_nutrition_review, get_branded_evidence, investigate_unresolved_ingredients,",
" get_vault_status, load_usda_catalog, run_nutrition_analysis, complete_nutrition, get_capability_status, apply_nutrition_review, save_working_recipe.",
" get_vault_status, load_usda_catalog, run_nutrition_analysis, complete_nutrition, get_capability_status, apply_nutrition_review, save_working_recipe, generate_recipe_image.",
"- {\"tool\":\"get_current_recipe\",\"instruction_offset\":0,\"instruction_limit\":20} (use next_instruction_offset until complete)",
"- {\"tool\":\"investigate_ingredient_amount\",\"line_ref\":\"<from get_current_recipe>\"}",
"- {\"tool\":\"search_usda_foods\",\"query\":\"...\"}",
Expand All @@ -327,6 +338,8 @@ const SYSTEM_PROMPT = [
"- {\"tool\":\"search_vault_recipes\",\"query\":\"chicken\",\"field\":\"ingredient\"}",
"- {\"tool\":\"get_vault_recipe\",\"recipe_id\":\"<id from search_vault_recipes>\"}",
"- {\"tool\":\"select_vault_recipe\",\"recipe_id\":\"<id from search_vault_recipes>\"}",
"- {\"tool\":\"inventory_vault_images\",\"status\":\"missing\",\"limit\":20,\"offset\":0}",
"- {\"tool\":\"generate_recipe_image\"}",
"- {\"tool\":\"apply_ingredient_edits\",\"edits\":[{\"line_ref\":\"<from get_current_recipe>\",\"new_name\":\"turkey\"}]}",
" Each edit object needs line_ref and AT LEAST ONE of: new_name (text), new_amount (number),",
" new_unit (text), new_preparation (text). Omit the fields you are not changing.",
Expand Down Expand Up @@ -500,6 +513,10 @@ function salvageToolArgs(tool: ShisoToolName): ShisoToolArgs {
return { tool, recipe_id: '' };
case 'select_vault_recipe':
return { tool, recipe_id: '' };
case 'inventory_vault_images':
return { tool, status: 'all', offset: 0, limit: 20 };
case 'generate_recipe_image':
return { tool };
case 'load_usda_catalog':
return { tool };
case 'get_nutrition_review':
Expand Down Expand Up @@ -609,6 +626,23 @@ function readToolArgs(tool: ShisoToolName, raw: unknown): ShisoToolArgs | null {
const trimmed = recipeId.trim().slice(0, SHISO_LIMITS.maxVaultRecipeIdChars);
return trimmed.length > 0 ? { tool, recipe_id: trimmed } : null;
}
case 'inventory_vault_images': {
const rawStatus = rec['status'];
const status = rawStatus === 'missing' || rawStatus === 'broken' || rawStatus === 'valid' || rawStatus === 'unknown' || rawStatus === 'all'
? rawStatus
: 'all';
const rawOffset = rec['offset'];
const offset = typeof rawOffset === 'number' && Number.isFinite(rawOffset) && rawOffset >= 0
? Math.min(100000, Math.floor(rawOffset))
: 0;
const rawLimit = rec['limit'];
const limit = typeof rawLimit === 'number' && Number.isFinite(rawLimit) && rawLimit > 0
? Math.max(1, Math.min(SHISO_LIMITS.maxImageInventoryResults, Math.floor(rawLimit)))
: 20;
return { tool, status, offset, limit };
}
case 'generate_recipe_image':
return { tool };
case 'load_usda_catalog':
return { tool };
case 'get_nutrition_review':
Expand Down
17 changes: 16 additions & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import { validateRecipeAssetReferences } from './utils/assetReferences';
import { createSessionAssetRunner } from './utils/sessionAssets';
import { VaultAssetScopeProvider } from './hooks/VaultAssetScopeContext';
import { getRecipeImage } from './utils/imageHelper';
import { assessRecipeImageHealth } from './core/recipeImage';
import { cleanRecipeTitle, parseObsidianRecipeMarkdown, serializeRecipeToObsidianMarkdown } from './utils/markdownParser';
import {
pickVaultDirectory,
Expand Down Expand Up @@ -3816,6 +3817,12 @@ export default function App({
return working?.base ?? shisoSelectedRecipeForReviewRef.current ?? selectedRecipeRef.current;
}, []);

// R2 image generation uses the canonical recipe, never an unsaved working copy.
// This keeps generation/save bound to the Markdown whose hash was previewed.
const getShisoImageRecipe = useCallback(() => {
return shisoSelectedRecipeForReviewRef.current ?? selectedRecipeRef.current;
}, []);

// SHISO agent foundation: one application-owned, read-only Vault capability
// object. It reads the live App refs, so a Vault transition is immediately
// reflected and any retained recipe selection is invalidated by session id.
Expand All @@ -3837,7 +3844,11 @@ export default function App({
setSelectedRecipe(recipe);
setVaultView('all');
},
}), [vaultStatus.accessType, vaultStatus.connectionState, vaultStatus.isConnected]);
assessImageHealth: async (recipe, signal) => {
if (signal?.aborted) return null;
return assessRecipeImageHealth({ image: recipe.image }, { asset: imageService.asset });
},
}), [vaultStatus.accessType, vaultStatus.connectionState, vaultStatus.isConnected, imageService]);
const handleShisoVaultRecipeSelected = useCallback((recipeId: string) => {
const selected = recipesRef.current.find((entry) => entry.id === recipeId) ?? (() => {
// The capability seam used by the real-App integration tests can
Expand Down Expand Up @@ -5572,6 +5583,10 @@ export default function App({
vaultCapabilities={shisoVaultCapabilityOverride ?? shisoVaultCapabilities}
onVaultRecipeSelected={handleShisoVaultRecipeSelected}
getSaveAuthorizationRecipe={getShisoSaveAuthorizationRecipe}
imageRecovery={recipeImageRecoverySupport}
imageRecoveryUnavailableReason={imageRecoveryUnavailableReason}
getImageRecipe={getShisoImageRecipe}
onRecipeImageSaved={handleRecipeImageSaved}
nutritionAuthority={{
enabled: nutritionAuthorityActive,
vaultScope: nutritionAuthorityScope,
Expand Down
1 change: 1 addition & 0 deletions src/application/shisoConversation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -679,6 +679,7 @@ export async function runShisoConversationTurn(
'get_vault_status',
'get_vault_recipe',
'select_vault_recipe',
'inventory_vault_images',
'get_capability_status',
'load_usda_catalog',
]);
Expand Down
92 changes: 92 additions & 0 deletions src/application/shisoTools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,16 @@ export interface ShisoAiNutritionOptions {
readonly nutrientGapFocus?: readonly ShisoNutrientGapFocus[];
}

export interface ShisoImageGenerationOutcome {
readonly ok: boolean;
readonly status: 'preview' | 'confirmation_required' | 'generating' | 'saved' | 'error';
readonly message: string;
readonly provider?: string;
readonly model?: string;
readonly costLabel?: string;
readonly requiresConfirmation?: boolean;
}

export interface ShisoExternalResearchOutcome {
readonly ok: boolean;
readonly contributions?: ReadonlyArray<AiNutrientContribution>;
Expand Down Expand Up @@ -220,6 +230,15 @@ export interface ShisoToolContext {
* message and the authenticated selected record label.
*/
readonly isTrustedNutritionSourceSelection?: ((lineRef: string, description: string) => boolean) | undefined;
/**
* R2. Starts the application's EXISTING image-recovery controller for the
* current canonical recipe. The controller owns the quote/confirmation,
* provider selection, preview, and explicit Save controls. This port never
* saves; absent means image generation is unavailable on this surface.
*/
readonly generateRecipeImage?: (() => Promise<ShisoImageGenerationOutcome>) | undefined;
/** Truthful reason image generation is unavailable on this surface. */
readonly imageGenerationUnavailableReason?: string | undefined;
}

function ok(
Expand Down Expand Up @@ -3070,6 +3089,69 @@ function getCapabilityStatus(ctx: ShisoToolContext): ShisoObservation {
* the server's closed schema, but they are RE-VALIDATED here: the browser is the
* authority boundary and never trusts that the check happened upstream.
*/
async function inventoryVaultImages(
ctx: ShisoToolContext,
status: 'all' | 'missing' | 'broken' | 'valid' | 'unknown',
offset: number,
limit: number,
signal?: AbortSignal,
): Promise<ShisoObservation> {
if (!ctx.vault?.inventoryImages) {
return fail(
'inventory_vault_images',
'vault_unavailable',
'The live Vault image inventory is not available on this surface. No image status was inferred.',
);
}
const result = await ctx.vault.inventoryImages({ status, offset, limit }, signal);
if (result.cancelled) {
return fail('inventory_vault_images', 'unsupported', 'The Vault image inventory was cancelled.');
}
const counts = result.counts;
const filterLabel = status === 'all' ? 'all image states' : `${status} images`;
return ok(
'inventory_vault_images',
`${counts.missing} missing, ${counts.broken} broken, ${counts.valid} valid, ${counts.unknown} unknown across ${result.total_recipes} Vault recipe(s). Showing ${result.entries.length} ${filterLabel} result(s) from offset ${result.offset}.`,
{
entries: result.entries,
counts,
total_recipes: result.total_recipes,
total_matches: result.total_matches,
offset: result.offset,
limit: result.limit,
has_more: result.has_more,
truncated: result.truncated,
status_filter: status,
},
);
}

async function generateRecipeImage(ctx: ShisoToolContext): Promise<ShisoObservation> {
if (ctx.recipe === null) {
return fail('generate_recipe_image', 'no_active_recipe', 'No recipe is currently active for image generation.');
}
if (!ctx.generateRecipeImage) {
return fail(
'generate_recipe_image',
'unsupported',
ctx.imageGenerationUnavailableReason
? `Image generation is not available: ${ctx.imageGenerationUnavailableReason}`
: 'Image generation is not available on this SHISO surface. Open a connected, writable Vault recipe.',
);
}
const result = await ctx.generateRecipeImage();
if (!result.ok) {
return fail('generate_recipe_image', 'unsupported', result.message);
}
return ok('generate_recipe_image', result.message, {
status: result.status,
...(result.provider !== undefined ? { provider: result.provider } : {}),
...(result.model !== undefined ? { model: result.model } : {}),
...(result.costLabel !== undefined ? { cost_label: result.costLabel } : {}),
...(result.requiresConfirmation !== undefined ? { requires_confirmation: result.requiresConfirmation } : {}),
});
}

export function executeShisoTool(
args: ShisoToolArgs,
ctx: ShisoToolContext,
Expand All @@ -3087,6 +3169,16 @@ export function executeShisoTool(
return getVaultRecipe(ctx, args.recipe_id);
case 'select_vault_recipe':
return selectVaultRecipe(ctx, args.recipe_id);
case 'inventory_vault_images':
return inventoryVaultImages(
ctx,
args.status ?? 'all',
args.offset ?? 0,
args.limit ?? 20,
signal,
);
case 'generate_recipe_image':
return generateRecipeImage(ctx);
case 'load_usda_catalog':
return loadUsdaCatalog(ctx, signal);
case 'get_nutrition_review':
Expand Down
Loading