Lucid Agents

repository·master·Indexed 41 days ago

https://github.com/daydreamsai/lucid-agents

A TypeScript runtime for machine commerce that enables developers to turn typed functions into discoverable, payable, and streamable services. It includes A2A (Agent-to-Agent) features for task runtimes, HTTP task routes, and agent discovery via agent cards, as well as integrated analytics and payment tracking.

Tokens
338.7K
Snippets
866
Records
1.4K
Agent score
49%

What's inside Lucid Agents

  1. Overview of Lucid Documentation Coverage and Roadmap

    master

    The Lucid documentation is organized into several functional families that guide users through the lifecycle of using the platform:

    • Home: High-level positioning and stack boundaries.
    • Start: Quickstart paths for sellers, buyers, existing apps, and coding agents.
    • Build: Implementation details for capabilities, payment models, tasks, and storefronts.
    • Buy: Guidance on paid calls, discovery, budgets, and wallet interoperability.
    • Operate: Production concerns including durable state, observability, security, and deployment runbooks.
    • Protocols: Technical specifications for x402, MPP, SIWX, A2A, ERC-8004, and AP2.
    • Packages: Reference for @lucid-agents core, extensions, adapters, and CLI.
    • Examples: A gallery of runnable patterns (A2A, MPP, Scheduler, etc.).
    • Products: Information on hosted platforms, routers, and agent creation.
    • Migration guides: Instructions for moving between runtimes (v3) and protocol versions (x402 v2).
    • Reference: Technical details on configuration, environment variables, errors, and telemetry.
  2. Overview of Lucid Agents example directories

    master

    The packages/examples/ directory contains various specialized examples. Use these as templates for your own implementation:

    DirectoryExample PurposeRequirements
    core/Full HTTP agent and local runtime-auth loopConfigured identity/payment services
    payment-methods/Every supported payment methodDeterministic smoke path (live rails need providers)
    payments/Paid service + outgoing/incoming policy agentsx402 facilitator and funded buyer
    mpp/Tempo charge server and custom provider referenceTempo/provider configuration
    analytics/Payment analytics endpointsPayment configuration
    catalog/YAML catalog generating MPP-paid routesTempo configuration
    kitchen-sink/Full composition (HTTP, A2A, AP2, payments, etc.)Local and free by default
    a2a/Multi-agent task flowLocal only
    scheduler/Leased scheduled paid callsPayment configuration
    identity/Read-only discovery and gated writesRPC/signer for opt-in writes
    wallet/Thirdweb Engine wallet operationsThirdweb credentials and network access
  3. Identify Documentation Gaps by Page Family

    master

    The following table summarizes the current completeness of the Lucid documentation across major functional areas. Use this to identify which sections may require more depth or verification before production use:

    FamilyCompleteness VerdictKey Missing Material
    HomeMostly complete positioning; channel risk.Per-claim status markers; external protocol specifications.
    StartSeller/buyer strong; remaining pages partial.Clean-room expected output; troubleshooting; fixture repo links.
    BuildGood conceptual skeleton; partial implementation depth.Authorization/failure state machines; streaming settlement semantics; executable recipes.
    BuyPartial.Durable budget backend recipes; malicious-challenge validation; receipt/reconciliation.
    OperateBroad but shallow.Deployment runbooks; crash-window recovery; threat models; tenant isolation; SLOs/alerts.
    Protocolsx402 strong; others incomplete.Versioned conformance profiles; wire examples; security/migration guides.
    PackagesUneven and not authoritative.Generated symbol/option tables; per-package errors; lifecycle/compatibility info.
    ExamplesPartial gallery.Repository source; prerequisites; exact package channel; expected response/test.
    ProductsBoundary placeholders.Verified endpoints; authentication; pricing; availability; limits; support contracts.
    MigrationsPartial.Package-by-package compatibility; deprecation windows; codemod recipes.
    ReferenceGood foundation; incomplete API contract.Generated API/type references; HTTP route/wire schemas; error retryability.
  4. Explore Lucid machine-commerce examples

    master

    The repository contains several specialized examples for different commerce and agentic patterns:

    • Paid seller and buyer: A clean-room-tested x402 transaction flow (Seller returns 402, Buyer signs and retries).
    • Core composition: Demonstrates HTTP, payments, wallets, identity, invoke, and streaming within a single runtime.
    • Lucid multi-service tasks: Agent Card-shaped discovery and Lucid-owned task routes.
    • x402 payment methods: Covers EVM/Solana, upto, batch settlement, SIWX, reconciliation, and Stripe destination mode.
    • MPP payment methods: Covers Tempo charge/session, Stripe, EVM, custom, and Lightning descriptors.
    • Scheduled calls: Leased, idempotent recurring A2A invocations.
    • Stripe destination mode: Provider-specific dynamic destination resolution.
    • Small MPP charge service: A compact Tempo charge server implementation.
  5. Understand the Lucid Payment Support Matrix

    master

    Lucid provides a multi-protocol payment surface covering EVM (Ethereum Virtual Machine), Solana, Tempo, Stripe, and Lightning networks.

    Key Concepts:

    • Built in: Lucid registers and coordinates the implementation. However, you still need to provide credentials, accounts, network access, and provider configuration.
    • Exact vs. Upto (x402):
      • exact schemes require the handler to return the specific amount requested.
      • upto schemes allow a ceiling; the handler must return a non-negative payment.actualAmount that is $\le$ the accepted ceiling.
    • Durability: By default, payment-policy accounting and challenge replay fences use process-local memory (intended for development). For production, you should use the provided SQLite or Postgres durable adapters to ensure state survives restarts.
    • Facilitator: For many x402 protocols, a facilitator is required for verification and settlement. For upto schemes, the /supported endpoint must include the facilitatorAddress.
  6. Integrate Lucid with Agent Frameworks and MCP

    master

    Lucid is designed to act as the paid application boundary. When integrating, you should keep model loops, memory, planning, evaluation, and tool selection within your existing agent framework.

    There are three primary integration patterns:

    1. Agent Frameworks: You can either expose work performed by your framework through Lucid, or call a paid Lucid service as a tool within your framework.
    2. MCP (Model Context Protocol): You can use the current HTTP-tool wrapper to interact with MCP, though note there is currently a native MCP gap.
    3. Framework Adapters: You can bind the canonical Lucid service runtime to web frameworks like Hono, Express, Next.js, or TanStack Start.

    Note on Compatibility: As of the current version, there are no official Lucid adapter packages for OpenAI Agents SDK, Vercel AI SDK, Mastra, LangGraph, AgentKit, or MCP. Integration with these is handled via the supported HTTP composition seam.

  7. Understand the Lucid layered protocol model

    master

    Lucid uses an extension architecture to compose a complete commerce runtime by layering different protocols. Developers should understand how these layers interact:

    1. Agent Discovery and Collaboration (A2A Layer): Handles agent advertising and defines interactions like messages, artifacts, tasks, streaming, and push notifications.
    2. Onchain Identity and Trust (ERC-8004 Layer): Handles identity registration and provides optional reputation or validation signals.
    3. Payment Negotiation and Execution (x402 & MPP Layer): Manages the challenge/payment transport, schemes, networks, and assets. Lucid-specific features like budgets, policies, and reservations are considered 'Lucid behavior' rather than core protocol features.
    4. Commerce Authorization and Evidence (AP2 Layer): Provides role metadata for commerce flows.

    Mental Model: No single protocol provides the full commerce runtime. Lucid acts as the orchestrator that integrates these specialized layers.

  8. Implement a Correlation Model for Payments and Fulfillment

    master

    To effectively observe commercial operations that span multiple HTTP attempts and systems, you should create one trace or business record per logical operation. This allows you to correlate challenges, denials, charges, and fulfillment states.

    Key fields to carry in your trace:

    • operation_id: A stable ID across unpaid, paid, and transport retries.
    • idempotency_key_ref: A hash or internal reference (do not expose raw sensitive keys).
    • attempt_id: A new ID for each network attempt.
    • trace_id / span_id: Preserve these through x402 protocol retries.
    • run_id: Returned in result/SSE envelopes.
    • task_id: Persist in a protected store with the secret access token.
    • settlement_ref: A sanitized transaction or receipt reference from the provider/chain.
    • accounting_settlement_id: Internal staged/committed accounting batch ID.

    Warning: Do not use a wallet address alone as a trace identifier, as it can be sensitive personal data and a single wallet may perform many operations.

    /* Recommended field mapping for correlation */
    {
      "operation_id": "stable_id",
      "idempotency_key_ref": "hash_ref",
      "attempt_id": "network_attempt_id",
      "trace_id": "otel_trace_id",
      "run_id": "lucid_run_id",
      "task_id": "lucid_task_id",
      "settlement_ref": "sanitized_provider_ref"
    }
  9. The x402 wire transaction lifecycle

    master

    A standard x402 payment transaction in Lucid follows these eight steps:

    1. Initial Call: Buyer calls the Lucid route without credentials.
    2. Challenge: Server returns a 402 status with PAYMENT-REQUIRED (specifying x402Version: 2).
    3. Retry: Buyer selects the requirement and retries the request with a PAYMENT-SIGNATURE.
    4. Verification: The Facilitator verifies the payer and the payment payload.
    5. Reservation: Lucid reserves capacity for the sender, total amount, rate, and idempotency.
    6. Execution: The application handler runs (or a task is durably reserved).
    7. Settlement: Lucid stages accounting, requests the facilitator to settle, and commits the transaction.
    8. Response: The application returns the final response containing PAYMENT-RESPONSE.
  10. How Lucid configuration and ownership works

    master

    Lucid uses a typed extension graph for configuration. Instead of a single global configuration object, each extension package owns its own configuration, runtime state, validation, and lifecycle. This ensures that concerns like payments, wallets, or HTTP routing are encapsulated within their respective packages.

    Ownership Map

    ConcernOwning packageConfiguration entrypoint
    Agent name, version, description@lucid-agents/corecreateAgent(meta)
    Entrypoints and handlers@lucid-agents/coreruntime.addEntrypoint(definition) or an adapter helper
    HTTP routes, landing page, base path, invoke idempotency@lucid-agents/httphttp(options)
    x402, SIWX, payment policy, payment accounting@lucid-agents/paymentspayments({ config })
    MPP challenge and credential verification@lucid-agents/mppmpp({ config })
    Agent and developer wallets@lucid-agents/walletwallets({ config })
    Lucid Agent Card, client, and task runtime@lucid-agents/a2aa2a(options)
    ERC-8004 initialization and trust metadata@lucid-agents/identityidentity(options) or createAgentIdentity(options)
    AP2 role metadata@lucid-agents/ap2ap2(config)
    Payment analytics@lucid-agents/analyticsanalytics(options)
    Scheduled Lucid task calls@lucid-agents/schedulercreateScheduler(options)
    Catalog-defined entrypoints@lucid-agents/catalogCatalog parser/registration APIs
    Framework bindingHono, Express, TanStack, or Next.jsAdapter-specific factory
  11. Configure durability and scaling for TanStack Start

    master

    The default Node server can be long-lived, but hosting presets may scale instances independently. Because in-memory state (payment/SIWX/idempotency/task/scheduler) is per instance, you must implement durable storage before horizontal scaling.

    Scaling Guidelines:

    • Use shared Postgres or custom stores for state.
    • If using SQLite, you need persistent local disk and a single-host topology.
    • Run scheduler and recoverable task execution in explicit long-lived workers.
    • Bound database pools and provider concurrency per instance.
    • Inject a shared Postgres MPP challenge store before scaling paid routes.

    Note: The package ships only memory stores for tasks and schedules. You must implement and test durable ports.

  12. Handle public versus internal error messages

    master

    When implementing error handling, distinguish between the automation surface and the debugging surface:

    • error.code: Use this as the primary automation surface. Public messages should be safe and actionable for the end-user. If your application introduces custom error codes, ensure they are namespaced and documented so clients can differentiate between Lucid transport errors and your specific business-domain failures.
    • Internal Details: Stack traces and raw provider responses should be kept in correlated server logs and never exposed as public messages.