TOOL_NAME = "update_user_file"
TOOL_DESCRIPTION = """Append or prepend text to a file in output/ (e.g. user.md). Useful for saving session notes, user preferences, or learning insights that should persist across sessions. Returns bytes written."""
TOOL_ARGS = '{"name": {"type": "string", "description": "Path to the file to update (e.g. user.md)"}, "content": {"type": "string", "description": "New content to append to the file"}, "prepend": {"type": "boolean", "default": false, "description": "Prepend content instead of appending"}}'

import os
from tools._std import tool_ok, tool_error

def run(args):
    filename = args.get('name', 'user.md')
    content = args.get('content', '')
    prepend = args.get('prepend', False)
    
    filepath = f"output/{filename}" if not filename.startswith('/') else filename
    
    # Read existing content if file exists
    if os.path.exists(filepath):
        with open(filepath, 'r', encoding='utf-8') as f:
            existing = f.read()
    else:
        existing = ''
    
    # Combine content
    if prepend:
        new_content = content + existing
    else:
        new_content = existing + content
    
    # Write back
    with open(filepath, 'w', encoding='utf-8') as f:
        f.write(new_content)
    
    return tool_ok({"file": filename, "added_bytes": len(content), "total_bytes": len(new_content)}, f"Updated {filename}")
