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

clinical-ai-system

v1.0.1

Published

A **production‑grade, tri‑layer AI orchestration platform** designed for secure, privacy‑preserving, and clinically reliable medical workflows.

Readme

Clinical AI System (Pharma‑Integrated)

A production‑grade, tri‑layer AI orchestration platform designed for secure, privacy‑preserving, and clinically reliable medical workflows.

The system integrates seamlessly with Pharmacy Systems, EHRs, and Specialist APIs by proxying authentication, orchestrating reasoning workflows, and automating clinical documentation while maintaining strict security guarantees.


Table of Contents

  1. Overview
  2. Architecture Principles
  3. System Architecture
  4. Layer Responsibilities
  5. Backend‑for‑Frontend (BFF)
  6. Token Forwarding Pattern
  7. Clinical Reasoning Model
  8. Implementation Guide
  9. Configuration Reference
  10. Finalization & EHR Integration
  11. Security Guardrails
  12. Testing

1. Overview

Traditional AI integrations introduce security risks: - API keys exposed in browsers - Double authentication - Stateless reasoning - Clinical instability

The Clinical AI System solves this using a:

✅ Security‑First Proxy Architecture
✅ Stateful AI Orchestration
✅ Deterministic Clinical Reasoning
✅ Privacy‑Preserving Execution Model


2. Architecture Principles

Security First

Sensitive logic and credentials never exist in the browser.

Deterministic Clinical Reasoning

Diagnosis is not produced from a single prompt but from a controlled state machine.

Thin Client Philosophy

Frontend acts purely as an authenticated delivery surface.

Stateful Intelligence

Conversation and reasoning state persist across refreshes.


3. System Architecture

┌──────────────────────────────────────────────────────────┐
│                    Browser / Pharmacy App                │
│                                                          │
│   Clinical Plugin SDK (Edge Layer)                       │
│   - Detects JWT                                          │
│   - Injects Identity Headers                             │
│   - Sends Intent Requests                                │
└───────────────▲──────────────────────────────────────────┘
                │ Secure Authenticated Requests
                │
┌───────────────┴──────────────────────────────────────────┐
│                BFF (Backend‑for‑Frontend)                │
│                                                          │
│  • Auth Validation                                       │
│  • Identity Proxy                                        │
│  • Redis Session Memory                                  │
│  • Parallel Execution                                    │
│                                                          │
│        ┌───────────────┐      ┌───────────────┐          │
│        │ Intake Node   │      │ Scribe Node   │          │
│        └──────▲────────┘      └──────▲────────┘          │
│               │                      │                   │
│               └──── AI Graph ────────┘                   │
└───────────────▲──────────────────────────────────────────┘
                │ Server‑to‑Server Calls
                │
┌───────────────┴──────────────────────────────────────────┐
│        Specialist / Pharmacy / EHR APIs                  │
└──────────────────────────────────────────────────────────┘

4. Layer Responsibilities

Edge Layer --- Plugin SDK

Philosophy: Zero‑Config Security

Responsibilities: - Detect existing authentication tokens - Abstract API complexity - Standardize requests - Maintain stateless execution


Nexus Layer --- BFF

Philosophy: Secure Proxy & Orchestrator

Responsibilities: - Validate Plugin identity - Impersonate authenticated users - Maintain session memory - Coordinate reasoning workflow


Brain Layer --- AI Graph (LangGraph)

Philosophy: Clinical Stability & Determinism

Responsibilities: - Multi‑step reasoning - SOAP note generation - Intake validation - Specialist diagnosis control


5. Backend‑for‑Frontend (BFF)

Reducer‑Based Memory (Redis)

Each consultation is tracked using:

thread_id = sessionId

Capabilities: - State merging via reducers - Conversation resumption - Phase awareness (Intake → Specialist)

Idempotent Initialization

The BFF is designed to be "Refreshed-Safe."

First Call: If sessionId is not in Redis, it seeds patientContext and vitals, then triggers the proactive AI prompt.

Subsequent Calls: If sessionId exists, it ignores the seeding and returns the current state (Inflation). This prevents the AI from "re-starting" the conversation if the doctor refreshes the browser.

Identity Proxy Pattern

The BFF eliminates double login.

Flow: 1. Plugin sends x-specialist-token 2. BFF validates plugin key 3. BFF forwards credentials server‑side 4. Specialist API sees authenticated user

Browser never accesses sensitive endpoints.


Parallel Processing

User Input
     │
     ├── Intake Node → Next Question
     └── Scribe Node → SOAP Update

Result: - Faster interaction - Continuous documentation


6. Token Forwarding Pattern

Detection

SDK scans: - sessionStorage - localStorage

Encapsulation

Headers injected:

x-specialist-token
x-pharmacy-id

Proxying

BFF forwards credentials securely.

Audit trails remain intact.


7. Clinical Reasoning Model

Stability Algorithm

Diagnosis is released only when:

Domain Satisfaction

All domains completed: - Chief Complaint - Onset - Modifiers - Allergies - Medications - Confirmation

Snapshot Accumulation

Differential updated each turn.

Mathematical Completion

Stability:
Top diagnosis identical for 3 turns

Dominance:
P(top) ≥ 2 × P(second)

Prevents premature or hallucinated decisions.


8. Implementation Guide

Singleton Setup

import { ClinicalConsultationPlugin } from '@clinical/plugin';

export const clinicalAgent = new ClinicalConsultationPlugin({
  bffUrl: import.meta.env.VITE_BFF_URL,
  apiKey: import.meta.env.VITE_PLUGIN_API_KEY
});

Proactive Session Sync

const initializeConsultation = async (sessionId, patientData, vitals) => {
  const state = await clinicalAgent.sync(sessionId, {
    patientContext: {
      id: patientData.id,
      name: patientData.name,
      age: patientData.age,
      pastMedicalHistory: patientData.pmh
    },
    vitals: vitals, // Vitals are now part of the initial sync
    consultationId: sessionId
  });

  renderUI(state);
};

Dialogue Loop

const onUserReply = async (text) => {
  // Pass ONLY the sessionId and the string message.
  // The BFF retrieves context/vitals from Redis memory automatically.
  const response = await clinicalAgent.sendMessage(sessionId, text);

  updateChatHistory(response.askedItems);

  if (response.status === 'COMPLETE') {
    showSpecialistDiagnosis(response.differential, response.decisionRationale);
  }
};

9. Configuration Reference

BFF Environment

Variable Description


OPENAI_API_KEY GPT reasoning engine REDIS_URL Session memory PLUGIN_API_KEY Plugin validation PHARMA_API_URL Specialist API ECOSYSTEM_API_URL Final EHR destination VITE_PLUGIN_API_KEY Shared secret with BFF (Injected as x-api-key header).


Plugin Environment

Variable Description


VITE_BFF_URL BFF endpoint VITE_ACCESS_TOKEN_KEY JWT storage key VITE_PUBLIC_PHARMACY_COOKIE Pharmacy identifier


10. Finalization & EHR Integration

When:

plugin.finalize(sessionId)

Process: 1. Retrieve final SOAP note 2. Package structured vitals 3. POST to ecosystem API 4. Mark Redis session for cleanup

Ensures PHI lifecycle control.


11. Security Guardrails

  • Proxy‑only proprietary keys
  • Stateless frontend
  • Timing‑safe authentication
  • Server‑side credential forwarding
  • No PHI stored in SDK

12. Testing

Run full end‑to‑end simulation:

pnpm test:e2e

Simulates:

Initialization
 → Dialogue
 → Stability Achievement
 → Finalization

Production Characteristics

  • Horizontally scalable
  • Deterministic reasoning
  • Audit‑safe identity forwarding
  • HIPAA / NDPA aligned architecture
  • Pharmacy & EHR interoperable

State recovery

const state = await clinicalAgent.recover(sessionId);

Use recover() to fetch the full state (AskedItems, SOAP, Vitals) without moving the AI graph forward. This is ideal for "Read-Only" views or re-hydrating a UI after a crash.

Author: Clinical AI Platform
Architecture Style: Security‑First Stateful AI Orchestration