npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@agentdid/langchain

v0.1.0

Published

LangChain integration for Agent-DID identities with middleware and tools for LangChain JS 1.x agents.

Downloads

127

Readme

@agent-did/langchain

Integracion funcional de Agent-DID para LangChain JS 1.x.

Esta variante es la referencia original en JavaScript/TypeScript y ahora mantiene parity operativa con la integracion Python en superficies clave: middleware/contexto, tools opt-in, seguridad por defecto, observabilidad callback/logger/LangSmith y ejemplos de operacion.

La matriz de parity entre ambas integraciones vive en ../../docs/F1-03-LangChain-TS-Python-Integration-Parity-Matrix.md.

Compatibilidad objetivo

  • langchain ^1.2.35
  • @langchain/core ^1.1.34
  • @agent-did/sdk ^0.1.0
  • Node.js 20+

Estado

  • Estado actual: functional-mvp
  • Lenguaje objetivo: TypeScript / JavaScript
  • Rol actual: referencia JS de la integracion LangChain de Agent-DID
  • Parity objetivo: alineada con Python en README, ejemplos y observabilidad base

Instalacion

npm install @agent-did/sdk langchain @langchain/core zod

Para habilitar el adaptador opcional de LangSmith:

npm install langsmith

Si publicas este paquete por separado:

npm install @agent-did/langchain

Uso rapido

import { ethers } from "ethers";
import { createAgent } from "langchain";
import { AgentIdentity } from "@agent-did/sdk";
import { createAgentDidIntegration } from "@agent-did/langchain";

const signer = new ethers.Wallet(process.env.CREATOR_PRIVATE_KEY!);
const identity = new AgentIdentity({ signer, network: "polygon" });

const runtimeIdentity = await identity.create({
  name: "research_assistant",
  description: "Agente de investigacion con identidad verificable",
  coreModel: "gpt-4.1-mini",
  systemPrompt: "Eres un agente de investigacion preciso y trazable.",
  capabilities: ["research:web", "report:write"]
});

const integration = createAgentDidIntegration({
  agentIdentity: identity,
  runtimeIdentity,
  expose: {
    signHttp: true,
    verifySignatures: true,
    signPayload: false,
    rotateKeys: false,
    documentHistory: true
  }
});

const agent = createAgent({
  name: "research_assistant",
  model: "openai:gpt-4.1-mini",
  systemPrompt: "Responde con precision y usa herramientas cuando haga falta.",
  tools: integration.tools,
  middleware: [integration.middleware]
});

const result = await agent.invoke({
  messages: [
    {
      role: "user",
      content: "Muestrame tu DID actual y firma una solicitud POST a https://api.example.com/tasks"
    }
  ]
});

console.log(result.messages.at(-1)?.content);

Que agrega la integracion

  • Middleware que inyecta en el sistema el DID actual, controlador, capacidades y metodo de autenticacion activo.
  • Herramientas de consulta para identidad actual, resolucion DID y verificacion de firmas.
  • Herramientas opcionales para firma de payloads, firma HTTP, historial documental y rotacion de clave.
  • Observabilidad vendor-neutral via callback, logger estructurado y adaptador opcional de LangSmith con redaccion por defecto.

Compatibilidad de API

  • createAgentDidIntegration(...): nombre recomendado.
  • createAgentDidPlugin(...): alias mantenido por compatibilidad retroactiva.

Seguridad por defecto

  • signPayload y rotateKeys vienen deshabilitados por defecto.
  • signHttp tambien es opt-in y puede habilitarse para que el agente firme solicitudes salientes sin exponer la clave privada al modelo.
  • Los destinos HTTP privados, loopback o con credenciales embebidas se rechazan por defecto.
  • La clave privada nunca se inserta en mensajes, contexto ni estado del agente.

Observabilidad

La factory publica acepta instrumentacion opcional sin acoplar el paquete a un backend especifico:

const {
  composeEventHandlers,
  createAgentDidIntegration,
  createJsonLoggerEventHandler,
} = require("@agent-did/langchain");

const events = [];

const integration = createAgentDidIntegration({
  agentIdentity: identity,
  runtimeIdentity,
  expose: {
    signHttp: true,
    signPayload: true,
  },
  observabilityHandler: composeEventHandlers(
    (event) => events.push(event),
    createJsonLoggerEventHandler(console, {
      extraFields: { service: "agent-gateway" },
    })
  ),
});

Eventos emitidos:

  • agent_did.identity_snapshot.refreshed
  • agent_did.tool.started
  • agent_did.tool.succeeded
  • agent_did.tool.failed

Redaccion por defecto:

  • payload, body, signature y agent_private_key se reemplazan por metadatos de longitud.
  • Authorization, Signature, Signature-Input, Cookie, Set-Cookie y X-API-Key se redactan en headers.
  • Las URLs se serializan sin query string, fragmento ni credenciales embebidas.

Helpers publicos disponibles:

  • composeEventHandlers(...)
  • createJsonLoggerEventHandler(...)
  • createLangSmithRunTree(...)
  • createLangSmithEventHandler(...)
  • serializeObservabilityEvent(...)
  • sanitizeObservabilityAttributes(...)

Ejemplo de LangSmith local sin cambiar la factory principal:

const {
  createAgentDidIntegration,
  createLangSmithEventHandler,
  createLangSmithRunTree,
} = require("@agent-did/langchain");

const rootRun = createLangSmithRunTree({
  name: "agent_did_demo",
  inputs: { scenario: "local" },
  tags: ["agent-did", "demo"],
});

const integration = createAgentDidIntegration({
  agentIdentity: identity,
  runtimeIdentity,
  expose: { signHttp: true, signPayload: true },
  observabilityHandler: createLangSmithEventHandler(rootRun, {
    extraFields: { sink: "langsmith" },
    tags: ["local-demo"],
  }),
});

Archivos relevantes

  • src/agentDidLangChain.js: middleware, herramientas y helpers principales.
  • src/observability.js: callbacks, logging JSON y saneamiento de eventos.
  • examples/agentDidLangChain.example.js: ejemplo con createAgent() de LangChain 1.x.
  • examples/agentDidLangChain.observability.example.js: ejemplo de callback + JSON logging saneado.
  • examples/agentDidLangChain.langsmith.example.js: tracing local con RunTree de LangSmith y child runs saneados.
  • examples/agentDidLangChain.productionRecipe.example.js: receta con guardas de entorno para un flujo mas cercano a produccion.
  • tests/agentDidLangChain.test.js: pruebas de la integracion.
  • tests/agentDidLangChain.observability.test.js: pruebas de observabilidad saneada.