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

@agent-diaries/core

v2.3.4

Published

Stop your AI agents from doing the same work twice. Exactly-once execution, deduplication, and distributed coordination for multi-agent systems.

Readme

Agent Diaries Core

npm version License: MIT

Agent Diaries Core is a TypeScript toolkit for recording agent work and coordinating repeated tasks. It helps applications reuse completed results, keep task history, and coordinate callers through storage-backed locks.

The library is framework independent. Use it with the agents, tools, and model providers you already have. Agent Diaries does not make model calls on your behalf.

Contents

When to use it

Agent Diaries is useful when the same work can arrive more than once: a queue redelivers a message, multiple agents research the same topic, or a workflow retries after part of its work has completed.

It provides:

  • Task history and result reuse through AgentDiary
  • Local file, memory, SQLite, MongoDB, Redis, and PostgreSQL storage adapters
  • Workflow coordination with per-step checkpoints and resume support
  • Runtime cancellation, concurrency limits, and estimated-cost limits
  • Integrations for LangChain, MCP tools, and OpenTelemetry tracing

Install

npm install @agent-diaries/core

The package targets TypeScript and modern Node.js. Backend clients such as ioredis, pg, mongodb, and better-sqlite3 are optional peer dependencies. Install the client for the backend you choose.

Quick start

The default AgentDiary storage writes JSON files to .agent-diaries in the current working directory.

import { AgentDiary } from "@agent-diaries/core";

const diary = new AgentDiary({ agentId: "researcher" });

async function fetchArticle(url: string): Promise<string> {
  const response = await fetch(url);
  if (!response.ok) {
    throw new Error(`Request failed: ${response.status}`);
  }
  return response.text();
}

const article = await diary.executeOnce(
  "fetch:example.com/article-123",
  () => fetchArticle("https://example.com/article-123"),
);

console.log(article);

executeOnce checks for a saved result using the task key. If it finds a result that has not expired, it returns that result. Otherwise, it runs the function and saves its result. Calls using the same diary and storage are coordinated by the storage lock.

Choose keys that identify the work, including any inputs that should make it a different task. For example, fetch:article-123 and fetch:article-456 are separate tasks.

Set an expiration time

Use a TTL when the result becomes stale. TTL values are in milliseconds. The per-call value overrides defaultTtlMs.

const diary = new AgentDiary({
  agentId: "market-researcher",
  defaultTtlMs: 60 * 60 * 1000, // one hour
});

const headlines = await diary.executeOnce(
  "headlines:technology",
  () => fetchTechnologyHeadlines(),
  { ttlMs: 5 * 60 * 1000 }, // refresh this result after five minutes
);

Common use cases

1. Process a webhook or queue message once per event

Queue systems may deliver the same message more than once. Use the event ID as the diary key so a redelivery can reuse the completed result.

import { AgentDiary } from "@agent-diaries/core";

const diary = new AgentDiary({ agentId: "invoice-worker" });

interface InvoiceEvent {
  id: string;
  invoiceId: string;
}

async function handleInvoiceEvent(event: InvoiceEvent) {
  return diary.executeOnce(`invoice-event:${event.id}`, async () => {
    const invoice = await loadInvoice(event.invoiceId);
    const message = await draftInvoiceSummary(invoice);

    // Use the same key with the email provider's idempotency feature if it has one.
    await sendInvoiceEmail(invoice.customerEmail, message, {
      idempotencyKey: `invoice-event:${event.id}`,
    });

    return `Sent invoice email for ${event.invoiceId}`;
  });
}

This is useful for payment events, email notifications, and background jobs. For an external side effect, also use the provider's idempotency support when available. The diary writes its result after the function completes, so a process can stop after the provider acts but before the result is saved.

2. Avoid repeating research across agents

Several workers may be asked to research the same topic. Use one shared key for the research task and a TTL that matches how quickly the answer gets stale.

const diary = new AgentDiary({ agentId: "research-swarm" });

async function research(topic: string): Promise<string> {
  const key = `research:${topic.trim().toLowerCase()}`;

  const summary = await diary.executeOnce(
    key,
    async () => {
      const sources = await searchWeb(topic);
      return summarizeSources(sources);
    },
    { ttlMs: 30 * 60 * 1000 }, // research can be refreshed after 30 minutes
  );

  return summary ?? "No summary was returned";
}

const topics = ["battery recycling", "grid storage"];
const summaries = await Promise.all(topics.map(research));

If agents run in different processes or machines, give each instance a shared Redis or PostgreSQL adapter. Separate in-memory or local-file stores do not coordinate across hosts.

3. Deduplicate repeated support-ticket analysis

For queue redelivery, key by ticket ID so retries of the same ticket share a result. If the goal is instead to reuse a general answer for similar issues, build a normalized key from the issue category and relevant text, and make sure that grouping is safe for your product.

interface SupportTicket {
  id: string;
  message: string;
  category: string;
}

const diary = new AgentDiary({
  agentId: "support-triage",
  maxHistory: 2_000,
});

async function triage(ticket: SupportTicket): Promise<string> {
  const result = await diary.executeOnce(
    `ticket:${ticket.id}:triage-v1`,
    () => classifyAndDraftReply(ticket),
    { ttlMs: 24 * 60 * 60 * 1000 },
  );

  return result ?? "Ticket was not analyzed";
}

Version the key (for example, triage-v2) when a prompt or business rule change should cause work to run again.

4. Filter a batch before scheduling work

For a queue or scheduled job that manages claims itself, filterNewTasks can remove items already recorded in the diary. If multiple workers may claim the same item, use claimTask as the atomic claim step.

const diary = new AgentDiary({ agentId: "document-indexer" });

const documents = [
  { title: "document:101", url: "https://example.com/101" },
  { title: "document:102", url: "https://example.com/102" },
];

const unseen = await diary.filterNewTasks(documents);

for (const document of unseen) {
  const claimed = await diary.claimTask(document.title);
  if (!claimed) continue;

  try {
    const text = await fetchArticle(document.url);
    await indexDocument(text);
    await diary.writeTaskResult(document.title, "indexed");
  } catch (error) {
    await diary.failTask(
      document.title,
      error instanceof Error ? error.message : String(error),
    );
  }
}

filterNewTasks is a convenience filter, not a reservation. The later claimTask call is what attempts to claim an item under the configured storage lock.

5. Cache a LangChain tool result

The LangChain integration wraps tools with the same diary-based result reuse. This is useful for searches and other read-only tools where repeating the same input should return the same recent result.

import { DeduplicatedTool } from "@agent-diaries/core/langchain";

const cachedSearch = new DeduplicatedTool(searchTool, {
  agentId: "product-research",
  ttlMs: 10 * 60 * 1000,
});

const results = await cachedSearch.invoke("current pricing for product X");

For tools with side effects, use a key that identifies the operation and rely on the target service's idempotency mechanisms as well.

Storage options

The default local-file adapter is useful for development or a single machine. Use shared storage when separate processes need to see the same task records and coordinate through a shared lock.

Redis

Install the optional client:

npm install ioredis
import Redis from "ioredis";
import { AgentDiary, RedisStorage } from "@agent-diaries/core";

const redis = new Redis(process.env.REDIS_URL);
const diary = new AgentDiary({
  agentId: "researcher",
  storage: new RedisStorage({
    redis,
    prefix: "my-app:",
    globalTtlMs: 7 * 24 * 60 * 60 * 1000, // optional: expire stored diary data after a week
  }),
});

PostgreSQL

Install the optional client:

npm install pg
npm install --save-dev @types/pg
import { Pool } from "pg";
import { AgentDiary, PostgresStorage } from "@agent-diaries/core";

const pool = new Pool({ connectionString: process.env.DATABASE_URL });
const diary = new AgentDiary({
  agentId: "researcher",
  storage: new PostgresStorage({ pool }),
});

// Close the pool during application shutdown.
await pool.end();

SQLite and MongoDB adapters are also available. Their database drivers are optional peer dependencies. See src/adapters and the runnable examples for details.

Workflow checkpoints

WorkflowCoordinator.executeWorkflowSteps saves each successful step result. If you retry the workflow with the same workflow ID and step IDs, completed steps are skipped and their results are passed to later steps.

import {
  DiaryRepository,
  MetricsRepository,
  ProviderRepository,
  StorageManager,
  TimelineRepository,
  TraceRepository,
  WorkflowCoordinator,
  WorkflowRepository,
} from "@agent-diaries/core/core";

// Share the same storage manager across the workflow repositories.
const storage = new StorageManager();
const coordinator = new WorkflowCoordinator(
  new WorkflowRepository(storage),
  new DiaryRepository(storage),
  new TraceRepository(storage),
  new TimelineRepository(storage),
  new MetricsRepository(storage),
  new ProviderRepository(),
);

const workflow = await coordinator.submitWorkflow("prepare-report", {
  reportId: "monthly-2026-11",
});

const result = await coordinator.executeWorkflowSteps(
  workflow.id,
  "report-worker-1",
  [
    {
      id: "load-data",
      run: async (input: { reportId: string }) => loadReportData(input.reportId),
    },
    {
      id: "write-report",
      run: async (_input, previous) => {
        const rows = previous["load-data"];
        return renderReport(rows);
      },
    },
  ],
  { reportId: "monthly-2026-11" },
);

Keep step IDs stable between attempts. Configure a persistence provider that supports workflow checkpoints if the results need to survive process restarts. A checkpoint is written after a step finishes, so use idempotency keys for external side effects inside a step too.

Integrations

MCP tools

Adapt tool definitions from an MCP server and register them with AgentRuntime:

import { AgentRuntime } from "@agent-diaries/core/runtime";
import { adaptMcpTools } from "@agent-diaries/core/adapters/mcp";

const runtime = new AgentRuntime();
for (const tool of adaptMcpTools(mcpClient, serverTools)) {
  runtime.registerTool(tool);
}

await runtime.warmup();
// Register an agent that uses these tools, then call runtime.run(...).

The adapter forwards cancellation signals and returns structured MCP content when available. Provide permission scopes in the tool definitions if your runtime uses permission checks.

Runtime limits and cancellation

The runtime can cap concurrent runs and reject a run when the agent's estimated cost exceeds a configured limit.

import { AgentRuntime } from "@agent-diaries/core/runtime";

const runtime = new AgentRuntime({
  maxConcurrentRuns: 8,
  maxEstimatedCostPerRunUSD: 0.05,
  maxEstimatedSessionCostUSD: 2,
});

const controller = new AbortController();
const pending = runtime.run("support-agent", ticket, {
  signal: controller.signal,
});

// Call this when the request is cancelled by the caller.
// controller.abort();

const result = await pending;

Cost limits use the agent's estimate; they do not read actual provider billing data. The runtime session limit is local to that runtime instance.

OpenTelemetry

The OpenTelemetry bridge forwards recorded spans to the OpenTelemetry API without making it a required dependency of the package. Install @opentelemetry/api in your application, then connect the bridge to the event bus and dispose it during shutdown. See the tracing guide for setup details.

Operational notes

  • Use stable, namespaced task keys. Include IDs and input versions where they affect the result.
  • Set a TTL for data that becomes stale, such as search results or current pricing.
  • Use the same shared storage configuration across workers that need to coordinate.
  • executeOnce records a result after the function completes. A crash between an external side effect and that write can allow the side effect to happen again on a later attempt.
  • Avoid storing secrets or unnecessary personal data in diary results. Treat stored data according to your application's retention and access policies.
  • Configure database and Redis connection lifecycle in the host application and close clients during shutdown.

Documentation and examples

Development

npm install
npm test
npm run build

License

MIT. See LICENSE.