Skip to content

AI-native design editor. Open-source Figma alternative.

AI chat: debug log with tool loop detection, prompt caching, system prompt tuning

Anton A S94160168eca8
diff --git a/Caddyfile.dev b/Caddyfile.dev
new file mode 100644
index 000000000..56e1f7645
--- /dev/null
+++ b/Caddyfile.dev
@@ -0,0 +1,20 @@
+{
+ admin off
+}
+
+:9100 {
+ header {
+ Access-Control-Allow-Origin *
+ Access-Control-Allow-Methods "GET, POST, OPTIONS"
+ Access-Control-Allow-Headers "Content-Type, Authorization, x-api-key, anthropic-version, anthropic-beta"
+ }
+
+ @options method OPTIONS
+ handle @options {
+ respond 204
+ }
+
+ reverse_proxy https://ai-proxy.soldatov.dev {
+ header_up Host ai-proxy.soldatov.dev
+ }
+}
diff --git a/packages/core/src/index.ts b/packages/core/src/index.ts
index 60b464b97..c59e152e0 100644
--- a/packages/core/src/index.ts
+++ b/packages/core/src/index.ts
@@ -52,8 +52,8 @@ export {
} from './scene-graph'
export { FigmaAPI, FigmaNodeProxy, computeImageHash, type FigmaFontName } from './figma-api'
-export { ALL_TOOLS, defineTool, toolsToAI } from './tools'
-export type { ToolDef, ParamDef, ParamType } from './tools'
+export { ALL_TOOLS, defineTool, toolsToAI, buildDebugLog } from './tools'
+export type { ToolDef, ParamDef, ParamType, ToolLogEntry, ToolDebugLog, AIAdapterOptions } from './tools'
export { executeRpcCommand, ALL_RPC_COMMANDS } from './rpc'
export { queryByXPath, matchByXPath } from './xpath'
export type { XPathQueryOptions } from './xpath'
diff --git a/packages/core/src/tools/ai-adapter.ts b/packages/core/src/tools/ai-adapter.ts
index adc33e438..44af77c58 100644
--- a/packages/core/src/tools/ai-adapter.ts
+++ b/packages/core/src/tools/ai-adapter.ts
@@ -9,11 +9,40 @@ import type { FigmaAPI } from '../figma-api'
import type { ToolDef, ParamDef, ParamType } from './schema'
import type * as valibot from 'valibot'
+export interface ToolLogEntry {
+ tool: string
+ args: Record<string, unknown>
+ result: unknown
+ error?: string
+ timestamp: number
+ durationMs: number
+ mutates: boolean
+ /** For mutating tools: snapshot of target node props before execution */
+ nodeBefore?: Record<string, unknown>
+ /** For mutating tools: snapshot of target node props after execution */
+ nodeAfter?: Record<string, unknown>
+ /** Props that didn't change despite the tool reporting success */
+ unchangedProps?: string[]
+ /** True when this exact tool+args combo was already called in the session */
+ isDuplicate?: boolean
+}
+
+export interface ToolDebugLog {
+ entries: ToolLogEntry[]
+ /** Detect repeated tool calls with identical args */
+ duplicates: Array<{ tool: string; args: Record<string, unknown>; count: number }>
+ /** Entries where mutating tool succeeded but node didn't change */
+ noopMutations: ToolLogEntry[]
+ /** Total bytes of tool results sent to model (rough token proxy) */
+ totalResultBytes: number
+}
+
export interface AIAdapterOptions {
getFigma: () => FigmaAPI
onBeforeExecute?: (def: ToolDef) => void
onAfterExecute?: (def: ToolDef) => void
onFlashNodes?: (nodeIds: string[]) => void
+ onToolLog?: (entry: ToolLogEntry) => void
}
function extractIdsFromArray(arr: unknown[]): string[] {
@@ -36,6 +65,53 @@ function extractNodeIds(result: unknown): string[] {
return ids
}
+function captureNodeSnapshot(
+ figma: FigmaAPI,
+ args: Record<string, unknown>
+): Record<string, unknown> | undefined {
+ const targetId = args.id as string | undefined
+ if (!targetId) return undefined
+ const raw = figma.graph.getNode(targetId)
+ if (!raw) return undefined
+ return structuredClone(raw) as unknown as Record<string, unknown>
+}
+
+function emitToolLog(
+ options: AIAdapterOptions,
+ def: ToolDef,
+ args: Record<string, unknown>,
+ startTime: number,
+ figma: FigmaAPI,
+ nodeBefore: Record<string, unknown> | undefined,
+ execResult: unknown,
+ error?: string
+): void {
+ if (!options.onToolLog) return
+
+ let nodeAfter: Record<string, unknown> | undefined
+ let unchangedProps: string[] | undefined
+
+ if (def.mutates && !error) {
+ nodeAfter = captureNodeSnapshot(figma, args)
+ if (nodeBefore && nodeAfter) {
+ unchangedProps = detectUnchangedProps(args, nodeBefore, nodeAfter)
+ }
+ }
+
+ options.onToolLog({
+ tool: def.name,
+ args,
+ result: execResult,
+ error,
+ timestamp: startTime,
+ durationMs: Date.now() - startTime,
+ mutates: !!def.mutates,
+ nodeBefore,
+ nodeAfter,
+ unchangedProps: unchangedProps?.length ? unchangedProps : undefined
+ })
+}
+
export function toolsToAI(
tools: ToolDef[],
options: AIAdapterOptions,
@@ -63,6 +139,11 @@ export function toolsToAI(
// eslint-disable-next-line typescript-eslint/no-explicit-any -- valibot v.object() requires typed ObjectEntries, but shape is built dynamically
inputSchema: valibotSchema(v.object(shape as Record<string, any>)),
execute: async (args: Record<string, unknown>) => {
+ const startTime = Date.now()
+ const figma = options.getFigma()
+ const nodeBefore =
+ def.mutates && options.onToolLog ? captureNodeSnapshot(figma, args) : undefined
+
options.onBeforeExecute?.(def)
try {
const execResult = await def.execute(options.getFigma(), args)
@@ -70,9 +151,12 @@ export function toolsToAI(
const ids = extractNodeIds(execResult)
if (ids.length > 0) options.onFlashNodes(ids)
}
+ emitToolLog(options, def, args, startTime, figma, nodeBefore, execResult)
return execResult
} catch (err) {
- return { error: err instanceof Error ? err.message : String(err) }
+ const errorMsg = err instanceof Error ? err.message : String(err)
+ emitToolLog(options, def, args, startTime, figma, nodeBefore, null, errorMsg)
+ return { error: errorMsg }
} finally {
options.onAfterExecute?.(def)
}
@@ -98,6 +182,84 @@ export function toolsToAI(
return result
}
+/**
+ * Map from tool arg names to the SceneNode property they affect.
+ * Only needed where the arg name differs from the node prop name.
+ */
+const ARG_TO_NODE_PROP: Record<string, string> = {
+ color: 'fills',
+ corner_radius: 'cornerRadius',
+ font_size: 'fontSize',
+ font_weight: 'fontWeight',
+ text: 'text',
+ visible: 'visible',
+ opacity: 'opacity',
+ direction: 'layoutMode',
+ spacing: 'itemSpacing',
+ name: 'name',
+ rotation: 'rotation',
+ value: 'opacity',
+ mode: 'blendMode'
+}
+
+function detectUnchangedProps(
+ args: Record<string, unknown>,
+ before: Record<string, unknown>,
+ after: Record<string, unknown>
+): string[] {
+ const unchanged: string[] = []
+ for (const [argKey, argVal] of Object.entries(args)) {
+ if (argKey === 'id' || argVal === undefined) continue
+ const nodeProp = ARG_TO_NODE_PROP[argKey] ?? argKey
+ const beforeVal = before[nodeProp]
+ const afterVal = after[nodeProp]
+ if (beforeVal !== undefined && afterVal !== undefined) {
+ const bStr = JSON.stringify(beforeVal)
+ const aStr = JSON.stringify(afterVal)
+ if (bStr === aStr) {
+ unchanged.push(nodeProp)
+ }
+ }
+ }
+ return unchanged
+}
+
+export function buildDebugLog(entries: ToolLogEntry[]): ToolDebugLog {
+ const callCounts = new Map<
+ string,
+ { args: Record<string, unknown>; count: number; mutates: boolean }
+ >()
+ const noopMutations: ToolLogEntry[] = []
+ let totalResultBytes = 0
+
+ for (const entry of entries) {
+ totalResultBytes += JSON.stringify(entry.result ?? '').length
+
+ const key = `${entry.tool}:${JSON.stringify(entry.args)}`
+ const existing = callCounts.get(key)
+ if (existing) {
+ existing.count++
+ if (entry.mutates) entry.isDuplicate = true
+ } else {
+ callCounts.set(key, { args: entry.args, count: 1, mutates: entry.mutates })
+ }
+
+ if (entry.mutates && !entry.error && entry.unchangedProps?.length) {
+ noopMutations.push(entry)
+ }
+ }
+
+ const duplicates: ToolDebugLog['duplicates'] = []
+ for (const [key, { args, count, mutates }] of callCounts) {
+ if (count > 1 && mutates) {
+ const tool = key.split(':')[0]
+ duplicates.push({ tool, args, count })
+ }
+ }
+
+ return { entries, duplicates, noopMutations, totalResultBytes }
+}
+
function paramToValibot(v: typeof valibot, param: ParamDef): unknown {
const typeMap: Record<ParamType, () => unknown> = {
string: () => (param.enum ? v.picklist(param.enum as [string, ...string[]]) : v.string()),
diff --git a/packages/core/src/tools/index.ts b/packages/core/src/tools/index.ts
index 72d19d0c0..8dd5be2ce 100644
--- a/packages/core/src/tools/index.ts
+++ b/packages/core/src/tools/index.ts
@@ -1,4 +1,5 @@
export { ALL_TOOLS } from './registry'
export { defineTool, nodeToResult, nodeSummary } from './schema'
export type { ToolDef, ParamDef, ParamType } from './schema'
-export { toolsToAI } from './ai-adapter'
+export { toolsToAI, buildDebugLog } from './ai-adapter'
+export type { ToolLogEntry, ToolDebugLog, AIAdapterOptions } from './ai-adapter'
diff --git a/src/ai/chat-debug.ts b/src/ai/chat-debug.ts
index 29eaff477..910e1e033 100644
--- a/src/ai/chat-debug.ts
+++ b/src/ai/chat-debug.ts
@@ -1,3 +1,7 @@
+import { getStepUsages, getToolLogEntries } from '@/ai/tools'
+import { buildDebugLog } from '@open-pencil/core'
+
+import type { ToolDebugLog, ToolLogEntry } from '@open-pencil/core'
import type { UIMessage } from 'ai'
function formatToolPart(part: Record<string, unknown>): string {
@@ -18,11 +22,224 @@ function formatToolPart(part: Record<string, unknown>): string {
return lines.join('\n')
}
+function formatLogEntry(entry: ToolLogEntry, index: number): string {
+ const time = new Date(entry.timestamp).toISOString().slice(11, 23)
+ const lines = [` #${index + 1} [${time}] ${entry.tool} (${entry.durationMs}ms)`]
+ lines.push(` args: ${JSON.stringify(entry.args)}`)
+
+ if (entry.error) {
+ lines.push(` ERROR: ${entry.error}`)
+ } else {
+ lines.push(` result: ${JSON.stringify(entry.result)}`)
+ }
+
+ if (entry.isDuplicate) {
+ lines.push(` ⚠ DUPLICATE: same tool+args called earlier in session`)
+ }
+
+ if (entry.unchangedProps?.length) {
+ lines.push(` ⚠ NO-OP PROPS: ${entry.unchangedProps.join(', ')}`)
+ if (entry.nodeBefore) {
+ for (const prop of entry.unchangedProps) {
+ const val = entry.nodeBefore[prop]
+ lines.push(` ${prop} stayed: ${JSON.stringify(val)}`)
+ }
+ }
+ }
+
+ if (entry.nodeBefore && entry.nodeAfter) {
+ const changed = diffNodeSnapshots(entry.nodeBefore, entry.nodeAfter)
+ if (changed.length > 0) {
+ lines.push(
+ ` changed: ${changed.map((c) => `${c.prop}: ${JSON.stringify(c.before)} → ${JSON.stringify(c.after)}`).join(', ')}`
+ )
+ }
+ }
+
+ return lines.join('\n')
+}
+
+function diffNodeSnapshots(
+ before: Record<string, unknown>,
+ after: Record<string, unknown>
+): Array<{ prop: string; before: unknown; after: unknown }> {
+ const SKIP = new Set(['childIds', 'parentId', 'id'])
+ const changed: Array<{ prop: string; before: unknown; after: unknown }> = []
+ const allKeys = new Set([...Object.keys(before), ...Object.keys(after)])
+ for (const key of allKeys) {
+ if (SKIP.has(key)) continue
+ const bStr = JSON.stringify(before[key])
+ const aStr = JSON.stringify(after[key])
+ if (bStr !== aStr) {
+ changed.push({ prop: key, before: before[key], after: after[key] })
+ }
+ }
+ return changed
+}
+
+function formatDiagnostics(log: ToolDebugLog): string {
+ const sections: string[] = []
+
+ sections.push(`Total tool calls: ${log.entries.length}`)
+ sections.push(`Total result payload: ${(log.totalResultBytes / 1024).toFixed(1)} KB`)
+
+ const mutatingCalls = log.entries.filter((e) => e.mutates)
+ const errorCalls = log.entries.filter((e) => e.error)
+ sections.push(`Mutating calls: ${mutatingCalls.length}`)
+ if (errorCalls.length > 0) {
+ sections.push(`Errors: ${errorCalls.length}`)
+ }
+
+ if (log.duplicates.length > 0) {
+ sections.push('')
+ sections.push('⚠ DUPLICATE CALLS (potential loops):')
+ for (const dup of log.duplicates) {
+ sections.push(` ${dup.tool} ×${dup.count} — args: ${JSON.stringify(dup.args)}`)
+ }
+ }
+
+ if (log.noopMutations.length > 0) {
+ sections.push('')
+ sections.push('⚠ NO-OP MUTATIONS (tool succeeded but node unchanged):')
+ for (const entry of log.noopMutations) {
+ sections.push(` ${entry.tool} on ${String(entry.args.id)}`)
+ sections.push(` unchanged: ${entry.unchangedProps!.join(', ')}`)
+ if (entry.nodeBefore) {
+ for (const prop of entry.unchangedProps!) {
+ sections.push(` ${prop} = ${JSON.stringify(entry.nodeBefore[prop])}`)
+ }
+ }
+ }
+ }
+
+ const largeResults = log.entries
+ .map((e, i) => ({ index: i, tool: e.tool, size: JSON.stringify(e.result ?? '').length }))
+ .filter((r) => r.size > 2048)
+ .sort((a, b) => b.size - a.size)
+ .slice(0, 5)
+
+ if (largeResults.length > 0) {
+ sections.push('')
+ sections.push('⚠ LARGE RESULTS (potential token waste):')
+ for (const r of largeResults) {
+ sections.push(` #${r.index + 1} ${r.tool}: ${(r.size / 1024).toFixed(1)} KB`)
+ }
+ }
+
+ return sections.join('\n')
+}
+
+function formatMessageStats(messages: UIMessage[]): string {
+ let userMessages = 0
+ let assistantMessages = 0
+ let toolCalls = 0
+ let totalTextLength = 0
+
+ for (const msg of messages) {
+ if (msg.role === 'user') userMessages++
+ else if (msg.role === 'assistant') assistantMessages++
+ for (const part of msg.parts) {
+ const p = part as Record<string, unknown>
+ if (p.type === 'text') {
+ totalTextLength += String(p.text ?? '').length
+ } else if (
+ p.type === 'tool-invocation' ||
+ p.type === 'dynamic-tool' ||
+ p.toolInvocation ||
+ (typeof p.type === 'string' && p.type.startsWith('tool-'))
+ ) {
+ toolCalls++
+ totalTextLength += JSON.stringify(p).length
+ }
+ }
+ }
+
+ const lines = [
+ `Messages: ${messages.length} (${userMessages} user, ${assistantMessages} assistant)`,
+ `Tool invocations in messages: ${toolCalls}`,
+ `Total text content: ${(totalTextLength / 1024).toFixed(1)} KB (~${Math.ceil(totalTextLength / 4)} tokens approx)`
+ ]
+ return lines.join('\n')
+}
+
+function formatTokenUsage(): string {
+ const steps = getStepUsages()
+ if (steps.length === 0) return ' (no usage data — provider may not report it)'
+
+ let totalInput = 0
+ let totalOutput = 0
+ let totalCacheRead = 0
+ let totalCacheWrite = 0
+
+ const lines: string[] = []
+ for (let i = 0; i < steps.length; i++) {
+ const s = steps[i]
+ totalInput += s.inputTokens
+ totalOutput += s.outputTokens
+ totalCacheRead += s.cacheReadTokens
+ totalCacheWrite += s.cacheWriteTokens
+
+ let cacheInfo = ' NO CACHE'
+ if (s.cacheReadTokens > 0) {
+ cacheInfo = ` cache_read=${s.cacheReadTokens}`
+ } else if (s.cacheWriteTokens > 0) {
+ cacheInfo = ` cache_write=${s.cacheWriteTokens}`
+ }
+ lines.push(` Step ${i + 1}: in=${s.inputTokens} out=${s.outputTokens}${cacheInfo}`)
+ }
+
+ const cacheHitRate = totalInput > 0 ? ((totalCacheRead / totalInput) * 100).toFixed(1) : '0.0'
+ const savedTokens = totalCacheRead > 0 ? totalCacheRead - Math.round(totalCacheRead * 0.1) : 0
+
+ lines.unshift(
+ `Total: in=${totalInput} out=${totalOutput} cache_read=${totalCacheRead} cache_write=${totalCacheWrite}`,
+ `Cache hit rate: ${cacheHitRate}% (saved ~${savedTokens} uncached input tokens, 90% cost reduction on cached)`,
+ `Steps: ${steps.length}`,
+ totalCacheRead === 0 && totalCacheWrite === 0
+ ? '⚠ NO CACHING DETECTED — system prompt + tools are re-processed every step'
+ : ''
+ )
+
+ return lines.filter(Boolean).join('\n')
+}
+
export function serializeChatLog(messages: UIMessage[]): string {
const sections: string[] = []
+ const toolLog = getToolLogEntries()
+ const debugLog = buildDebugLog(toolLog)
+
+ sections.push('╔══════════════════════════════════════╗')
+ sections.push('║ OPEN PENCIL AI DEBUG LOG ║')
+ sections.push(`║ ${new Date().toISOString()} ║`)
+ sections.push('╚══════════════════════════════════════╝')
+ sections.push('')
+
+ sections.push('=== TOKEN USAGE & CACHING ===')
+ sections.push(formatTokenUsage())
+ sections.push('')
+
+ sections.push('=== DIAGNOSTICS ===')
+ sections.push(formatDiagnostics(debugLog))
+ sections.push('')
+
+ sections.push('=== MESSAGE STATS ===')
+ sections.push(formatMessageStats(messages))
+ sections.push('')
+
+ sections.push('=== TOOL EXECUTION LOG ===')
+ if (toolLog.length === 0) {
+ sections.push(' (no tool calls recorded)')
+ } else {
+ for (let i = 0; i < toolLog.length; i++) {
+ sections.push(formatLogEntry(toolLog[i], i))
+ }
+ }
+ sections.push('')
+
+ sections.push('=== CONVERSATION ===')
for (const msg of messages) {
- const header = `=== ${msg.role.toUpperCase()} (${msg.id}) ===`
+ const header = `--- ${msg.role.toUpperCase()} (${msg.id}) ---`
const parts: string[] = []
for (const part of msg.parts) {
diff --git a/src/ai/system-prompt.md b/src/ai/system-prompt.md
index ddf43f1be..bbe8cdab1 100644
--- a/src/ai/system-prompt.md
+++ b/src/ai/system-prompt.md
@@ -1,4 +1,6 @@
-You are a design assistant inside a vector design editor. You create and modify designs using tools. Be direct, use design terminology, describe what you did after each action.
+You are a design assistant inside a vector design editor. You create and modify designs using tools. Be direct, use design terminology.
+
+After completing a design, give a **2–3 line** summary: frame size, accent color hex, and any remaining layout issues. Do NOT list every section — the user can see the canvas. No markdown headers, no bullet lists of what you built.
# Rendering
@@ -81,31 +83,35 @@ Dividers replace vertical space — don't add a full gap on both sides of a divi
Split into **2–3 render calls**, not 10. Example for a movie card:
1. **Skeleton** — outer frame + empty section containers:
+
```
<Frame name="Card" w={380} flex="col" bg="#0F0F1A" rounded={20} overflow="hidden">
<Frame name="Poster" w="fill" h={220} bg="#1A1A2E" overflow="hidden" />
<Frame name="Content" w="fill" flex="col" gap={20} p={20} />
</Frame>
```
+
2. **Poster content** — render into Poster (decorations, badges, title overlay)
3. **Main content** — render into Content (all text blocks, details, ratings, buttons)
That's it — 3 renders total, not one per element. Each render fills a major section. Call `describe` on the root after each to verify.
+**Sizing rule for skeleton sections:** When a section uses `grow={1}` to fill remaining space, its children that should expand must also use `grow={1}` — not `h="fill"`. And critically: give the **fixed-height** child an explicit `h={N}` that leaves enough room. If the root is 844px and header=72, actions=116, tabbar=87, then card area = 844−72−116−87 = 569px. If photo=420 that leaves only 149px for content — too little. Plan the math before rendering.
+
## Typography
### Type scale
Pick 6–8 sizes from a consistent scale, not arbitrary numbers. Good base scales (ratio ~1.25):
-| Role | Size | Weight |
-|---|---|---|
-| Display | 32–40 | bold |
-| H1 | 24–28 | bold |
-| H2 | 20–22 | bold |
-| H3 | 17–18 | bold/medium |
-| Body | 14–15 | regular |
-| Caption | 12–13 | regular/medium |
+| Role | Size | Weight |
+| -------- | ----- | --------------- |
+| Display | 32–40 | bold |
+| H1 | 24–28 | bold |
+| H2 | 20–22 | bold |
+| H3 | 17–18 | bold/medium |
+| Body | 14–15 | regular |
+| Caption | 12–13 | regular/medium |
| Overline | 10–11 | bold, UPPERCASE |
Use at most 2–3 weights per design. Regular (400) for body, medium (500) for labels, bold (700) for headings.
@@ -147,6 +153,7 @@ No style={{}}, className, CSS. No named colors or rgb(). No percentage values. N
## Common patterns
**Progress bar / rating bar:**
+
```
<Frame name="Bar" flex="row" w="fill" gap={10} items="center">
<Text w={80} size={13} color="#6B7280">Label</Text>
@@ -156,6 +163,7 @@ No style={{}}, className, CSS. No named colors or rgb(). No percentage values. N
<Text w={36} size={13} weight="bold" textAlign="right" color="#111827">8.8</Text>
</Frame>
```
+
Key rules: bar background uses `grow={1}` (no fixed `w`), `overflow="hidden"` to clip the fill. Fill width is a fraction of the bar — calculate from the score. Label is plain Text with `w`, not a Frame wrapper. Never set `h` on label containers to match the row — let items="center" handle vertical alignment.
**Decorative vs content layers:** Background effects (gradients, bokeh circles, glows, star patterns) must be absolutely positioned with x/y — they are decoration, not content. Only actual content (text, buttons, badges) goes into flex layout. Never put 10+ tiny decorative shapes into a flex container — they eat up all the gap space and squash real content.
@@ -166,6 +174,7 @@ Key rules: bar background uses `grow={1}` (no fixed `w`), `overflow="hidden"` to
**Dividers between columns (vertical dividers):**
A vertical divider (`w={1} h={N}`) must be a sibling inside the same `flex="row"` container as the columns it separates. Use `h="fill"` instead of fixed height so it matches the row height. Example:
+
```
<Frame flex="row" items="center">
<Frame grow={1}>…</Frame>
@@ -173,6 +182,7 @@ A vertical divider (`w={1} h={N}`) must be a sibling inside the same `flex="row"
<Frame grow={1}>…</Frame>
</Frame>
```
+
Never place vertical dividers outside their row container. Horizontal dividers (`h={1} w="fill"`) go between sections in a `flex="col"` parent.
## Icons and shapes
diff --git a/src/ai/tools.ts b/src/ai/tools.ts
index 879443a87..eccd1b28f 100644
--- a/src/ai/tools.ts
+++ b/src/ai/tools.ts
@@ -6,7 +6,36 @@ import { makeFigmaFromStore } from '@/automation/figma-factory'
import { ALL_TOOLS, computeAllLayouts, toolsToAI } from '@open-pencil/core'
import type { EditorStore } from '@/stores/editor'
-import type { SceneNode } from '@open-pencil/core'
+import type { SceneNode, ToolLogEntry } from '@open-pencil/core'
+
+let _toolLogEntries: ToolLogEntry[] = []
+
+export interface StepUsage {
+ inputTokens: number
+ outputTokens: number
+ cacheReadTokens: number
+ cacheWriteTokens: number
+ timestamp: number
+}
+
+let _stepUsages: StepUsage[] = []
+
+export function getToolLogEntries(): ToolLogEntry[] {
+ return _toolLogEntries
+}
+
+export function getStepUsages(): StepUsage[] {
+ return _stepUsages
+}
+
+export function recordStepUsage(usage: StepUsage): void {
+ _stepUsages.push(usage)
+}
+
+export function clearToolLogEntries(): void {
+ _toolLogEntries = []
+ _stepUsages = []
+}
export function createAITools(store: EditorStore) {
let beforeSnapshot: Map<string, SceneNode> | null = null
@@ -38,6 +67,9 @@ export function createAITools(store: EditorStore) {
},
onFlashNodes: (nodeIds) => {
store.flashNodes(nodeIds)
+ },
+ onToolLog: (entry) => {
+ _toolLogEntries.push(entry)
}
},
{ v, valibotSchema, tool }
diff --git a/src/components/ChatPanel.vue b/src/components/ChatPanel.vue
index ca67a80a5..104d46af4 100644
--- a/src/components/ChatPanel.vue
+++ b/src/components/ChatPanel.vue
@@ -3,6 +3,7 @@ import { ScrollAreaRoot, ScrollAreaScrollbar, ScrollAreaThumb, ScrollAreaViewpor
import { computed, markRaw, nextTick, ref, watch } from 'vue'
import { copyChatLog } from '@/ai/chat-debug'
+import { clearToolLogEntries } from '@/ai/tools'
import ChatInput from '@/components/chat/ChatInput.vue'
import ChatMessage from '@/components/chat/ChatMessage.vue'
import ProviderSetup from '@/components/chat/ProviderSetup.vue'
@@ -54,6 +55,7 @@ async function handleCopyDebug() {
function handleClearChat() {
chat.value = null
resetChat()
+ clearToolLogEntries()
}
</script>
diff --git a/src/components/chat/ChatInput.vue b/src/components/chat/ChatInput.vue
index 68a5c0e5b..efbfcf767 100644
--- a/src/components/chat/ChatInput.vue
+++ b/src/components/chat/ChatInput.vue
@@ -35,7 +35,9 @@ const emit = defineEmits<{
const input = ref('')
const isStreaming = computed(() => status === 'streaming' || status === 'submitted')
-const isCustomProvider = computed(() => providerID.value === 'openai-compatible')
+const isCustomProvider = computed(
+ () => providerID.value === 'openai-compatible' || providerID.value === 'anthropic-compatible'
+)
const selectedModelName = computed(() => {
if (isCustomProvider.value) return customModelID.value || 'No model'
diff --git a/src/composables/use-chat.ts b/src/composables/use-chat.ts
index 1f23f6037..23ba0b667 100644
--- a/src/composables/use-chat.ts
+++ b/src/composables/use-chat.ts
@@ -5,11 +5,10 @@ import { Chat } from '@ai-sdk/vue'
import { createOpenRouter } from '@openrouter/ai-sdk-provider'
import { useLocalStorage } from '@vueuse/core'
import { DirectChatTransport, ToolLoopAgent } from 'ai'
-
import { computed, ref, watch } from 'vue'
-import { createAITools } from '@/ai/tools'
import SYSTEM_PROMPT from '@/ai/system-prompt.md?raw'
+import { createAITools, recordStepUsage } from '@/ai/tools'
import { useEditorStore } from '@/stores/editor'
import { AI_PROVIDERS, DEFAULT_AI_MODEL, DEFAULT_AI_PROVIDER } from '@open-pencil/core'
@@ -159,17 +158,44 @@ let overrideTransport: (() => any) | null = null
let chat: Chat<UIMessage> | null = null
+const ANTHROPIC_CACHE_CONTROL = {
+ anthropic: { cacheControl: { type: 'ephemeral' } }
+} as const
+
+function supportsAnthropicCaching(): boolean {
+ return (
+ providerID.value === 'anthropic' ||
+ providerID.value === 'anthropic-compatible' ||
+ (providerID.value === 'openrouter' && modelID.value.startsWith('anthropic/'))
+ )
+}
+
function createTransport() {
if (overrideTransport) return overrideTransport()
const tools = createAITools(useEditorStore())
+ const cacheProviderOptions = supportsAnthropicCaching() ? ANTHROPIC_CACHE_CONTROL : undefined
const agent = new ToolLoopAgent({
model: createModel(),
instructions: SYSTEM_PROMPT,
tools,
maxOutputTokens: maxOutputTokens.value,
- prepareCall: (options) => ({ ...options, maxOutputTokens: maxOutputTokens.value })
+ providerOptions: cacheProviderOptions,
+ prepareCall: (options) => ({
+ ...options,
+ maxOutputTokens: maxOutputTokens.value,
+ providerOptions: cacheProviderOptions
+ }),
+ onStepFinish: ({ usage }) => {
+ recordStepUsage({
+ inputTokens: usage.inputTokens ?? 0,
+ outputTokens: usage.outputTokens ?? 0,
+ cacheReadTokens: usage.inputTokenDetails?.cacheReadTokens ?? 0,
+ cacheWriteTokens: usage.inputTokenDetails?.cacheWriteTokens ?? 0,
+ timestamp: Date.now()
+ })
+ }
})
return new DirectChatTransport({ agent })