HanaAgent Documentation

repository·main·Indexed 26 days ago

https://github.com/lilimozi/openhanako

Documentation for HanaAgent (version 0.421.24), a personal AI assistant with memory, personality, and autonomous computer action capabilities. This documentation details the provider compatibility layer, including the implementation of provider patches, thinking format declarations, reasoning replay contracts, output budget strategies, and audio input transport for various LLM providers.

Tokens
68.4K
Snippets
101
Records
288
Agent score
91%

What's inside hanako

  1. Overview of HanaAgent features

    main

    HanaAgent is a personal AI agent designed for autonomy and memory. Key features include:

    • Memory & Personality: Custom memory systems and personality templates for self-contained agents.
    • Tools & Skills: Built-in support for file I/O, web browsing, terminal sessions, and a community Skills ecosystem.
    • Multi-Agent Collaboration: Create multiple agents with independent memory that can collaborate via channel group chats.
    • Desk: A workspace for files and notes (Jian) with drag-and-drop and file-tree watching.
    • Sandbox: Two-layer isolation using PathGuard and OS-level sandboxing (macOS Seatbelt, Linux Bubblewrap, Windows restricted token).
    • Plugins: A convention-first architecture allowing users to add tools, skills, commands, and more via drag-and-drop.
    • Multi-Platform Bridge: Connect agents to Telegram, Feishu, QQ, and WeChat.
    • Mobile/LAN Access: Access the HanaAgent Server via a Mobile PWA or a secondary desktop frontend over LAN.
  2. Understand HanaAgent Architecture

    main

    HanaAgent is composed of several layers:

    • Core: Engine orchestration and Managers (Agent, Session, Model, etc.).
    • Lib: Core libraries for memory, tools, sandboxing, and Bridge adapters.
    • Server: A Hono-based HTTP + WebSocket service running in a separate Node.js process.
    • Hub: Handles scheduling, routing, event bus, and Agent-to-Agent communication.
    • Desktop: Electron application with a React frontend.
    • Shared: Cross-layer tools including config schemas and error buses.
    • Plugins: Built-in system plugins.

    Data Storage: User data is stored in the directory defined by the HANA_HOME environment variable (defaults to ~/.hanako in production and ~/.hanako-dev in development).

  3. Understand the Provider Compatibility Layer

    main

    The core/provider-compat directory serves as the unique compatibility layer for provider-specific payloads in Hana. It ensures that outgoing requests are correctly formatted for different LLM providers.

    Key Architecture Rules:

    • Single Entry Point: All outgoing payload compatibility must pass through normalizeProviderPayload(payload, model, options) in core/provider-compat.js.
    • Context Messages: Rules for replay/history or content projection that affect the model's view of messages should use normalizeContextMessages(messages, model, options).
    • Dispatcher Logic: The system uses a 'first-match-wins' strategy. The dispatcher iterates through a list of modules; the first module where matches(model) returns true is responsible for the transformation.
    • Separation of Concerns:
      • Pi SDK: Handles session lifecycle, model registry, and basic provider serialization.
      • Hana provider-compat: Handles final wire protocol translation (e.g., thinking, reasoning_effort, max_tokens, and reasoning history replay).
  4. Understand plugin error isolation and compatibility

    main

    The system is designed for forward compatibility and fault tolerance:

    • Forward Compatibility: The system ignores unknown directories and manifest fields. Old plugins run on new systems, and new plugins on old systems simply won't trigger new contribution types. For new WebView/iframe UIs using ui.hostCapabilities, it is recommended to set manifestVersion: 1 to align with SDK documentation.
    • Error Isolation:
      • A failure in a plugin's onload() method does not block other plugins or the system startup.
      • Syntax errors in individual tool, route, or command files only affect that specific file.
      • Failed plugins are marked with status: "failed" and display error messages on the plugin page.
  5. Quickstart: Create a simple Tool-only plugin

    main

    To create a basic plugin that adds tools for the Agent, follow these steps:

    1. Create a directory structure with a tools/ folder:
      my-plugin/
      └── tools/
          └── hello.js
    2. Implement the tool in tools/hello.js using the following export format:
      export const name = "hello";
      export const description = "Say hello to someone";
      export const parameters = {
        type: "object",
        properties: { name: { type: "string" } },
        required: ["name"],
      };
      export async function execute(input) {
        return `Hello, ${input.name}!`;
      }
    3. Install the plugin by dragging the folder or a .zip of the folder into the Settings → Plugins installation area in HanaAgent.
    4. Once installed, the Agent can immediately call the tool using the name my-plugin_hello (where my-plugin is your folder name).
    // tools/hello.js
    export const name = "hello";
    export const description = "Say hello to someone";
    export const parameters = {
      type: "object",
      properties: { name: { type: "string" } },
      required: ["name"],
    };
    export async function execute(input) {
      return `Hello, ${input.name}!`;
    }
  6. Access and Modify User Resources

    main

    Plugins should use ctx.resources to interact with user data (local files, mounts, SessionFile, or URLs) instead of using raw fs modules. You must declare required capabilities in your manifest.json.

    Capabilities:

    • resource.read: Covers stat, read, and list.
    • resource.search: Enables searching through resources.
    • resource.write: Covers write, edit, mkdir, delete, copy, rename, move, and trash.
    • resource.materialize: Converts a resource into a local machine path (use this for third-party libraries requiring local paths).
    • resource.watch: Subscribes to resource changes.

    Important Rules:

    • Security: ResourceIO is the only authorized entry point. Do not use absolute local paths or fs.writeFileSync for user resources.
    • Plugin Data: Use ctx.dataDir for files generated by the plugin itself. To deliver these to the user, use toolCtx.stageFile() to register them as a SessionFile.
    {
      "capabilities": ["resource.read", "resource.search", "resource.write"]
    }
    export async function execute(input, ctx) {
      const ref = { kind: "mount", mountId: input.mountId, path: input.path };
      const file = await ctx.resources.read(ref);
      await ctx.resources.write(ref, file.content.toString("utf-8") + "\nupdated\n");
      return "updated";
    }
  7. Use the Agent Dev Loop for plugin development

    main

    Instead of copying code into production directories, use the development workflow to keep source code in your workspace or ${HANA_HOME}/plugin-dev-sources/.

    Available Dev Commands:

    • plugin.dev.install: Copies source to ${HANA_HOME}/plugins-dev/<pluginId> and loads it.
    • plugin.dev.reload: Replaces the dev copy from the source.
    • plugin.dev.disable / plugin.dev.enable / plugin.dev.reset / plugin.dev.uninstall: Manages the dev slot.
    • plugin.dev.invokeTool: Runs a tool smoke test with explicit input.
    • plugin.dev.diagnostics: Returns load status, logs, and diagnostics.
    • plugin.dev.listSurfaces / plugin.dev.describeSurfaceDebug: Used for UI debugging.

    Note: To use these, the user must enable "Allow Agent plugin dev tools" in Settings -> Plugins. When controlling lifecycle, pass a devRunId to prevent stale tool calls from acting on newer dev runs.

  8. Configure the 'Ming' External Awareness Template

    main

    The ming.md template is designed to define an agent's 'External Awareness' (对外意识) when interacting with visitors who are not the primary user ({{userName}}). It establishes the agent's identity as a personal assistant, its personality traits, and its operational boundaries.

    Identity Configuration

    • Role: The agent acts as {{agentName}}, the personal assistant to {{userName}}.
    • Stance: The agent represents {{userName}} in all external communications.

    Personality and Tone Guidelines

    When using this template, the agent is instructed to follow these linguistic and cognitive patterns:

    • Tone: Calm, precise, and concise. Avoids fluff, excessive politeness, or filler phrases like "In summary" (总的来说), "Hope this helps" (希望对你有帮助), or "As you can see" (如你所见).
    • Cognitive Style: Focuses on decomposing complex issues, analyzing underlying principles rather than social consensus, and using analogies for abstract concepts.
    • Linguistic Constraints:
      • Minimize the use of dashes (——, -).
      • Avoid the sentence structure "It is not... but is..." (不是...是...) unless absolutely necessary.
      • Avoid ambiguity; if uncertain, state that you do not know.

    Boundary Rules

    • Privacy: Never disclose {{userName}}'s private information, personal habits, or private conversation content.
    • Honesty: If a visitor asks something unconfirmable, admit the need for verification rather than fabricating answers.
  9. Plugin development loop and Dev API

    main

    When developing plugins, use the development loop to avoid copying semi-finished code to the production directory.

    Setup:

    1. Place source code in the workspace or ${HANA_HOME}/plugin-dev-sources/.
    2. Enable "Allow Agent plugin development tools" in Settings → Plugins → Permissions.

    Dev Operations:

    • Install: Call plugin.dev.install or POST /api/plugins/dev/install to copy source to ${HANA_HOME}/plugins-dev/<pluginId>.
    • Reload: Call plugin.dev.reload or POST /api/plugins/dev/:id/reload after code changes.
    • Lifecycle: Use plugin.dev.disable, plugin.dev.enable, plugin.dev.reset, or plugin.dev.uninstall (or corresponding HTTP methods) to manage the dev instance.
    • Smoke Test: Use plugin.dev.invokeTool or POST /api/plugins/dev/:id/tools/:toolName/invoke to test tools. Use sessionId or sessionRef for the session identity.
    • Diagnostics: Use plugin.dev.diagnostics or GET /api/plugins/dev/diagnostics to debug.

    Note: Dev operations only affect the runtime copy in ${HANA_HOME}/plugins-dev/ and do not pollute the official ${HANA_HOME}/plugins/ directory.

  10. Configure Model Providers and Roles

    main

    HanaAgent uses different models for different tasks. You can configure these in Settings → Providers.

    Model Roles

    • Chat Model: The primary model for conversation and task execution.
    • Utility Model (Lightweight): Used for lightweight tasks like summarization and classification to save cost/time.
    • Utility Model (Heavyweight): Used for background tasks requiring high reasoning, such as memory compilation and deep analysis.
    • Vision Model: A multimodal model used to convert images into structured descriptions when the chat model does not support direct image input.

    Configuration Steps

    1. Go to Settings → Providers to add or adjust API Keys, Base URLs, OAuth accounts, local Ollama, or Coding Plan.
    2. To configure vision capabilities, ensure the "Vision / Supports Images" capability is enabled on the model card, the "Auxiliary Vision Switch" is ON at the bottom of Settings → Providers, and the "Vision Assistant Model" is set to a multimodal model.
    3. You can select a specific chat model for each assistant in Settings → Assistants.
    4. You can temporarily switch the model for the current session using the model capsule in the input box.
  11. Configure the Ming identity template

    main

    The ming identity template defines an agent persona characterized as a personal assistant that prioritizes reasoning, logic, and analysis. This template uses placeholders that should be populated during agent initialization:

    • {{agentName}}: The name of the agent.
    • {{userName}}: The name of the user this assistant belongs to.

    When applied, the persona is described as: "{{userName}}'s personal assistant. Reasoning first, deconstructing the world through logic and analysis."