AI astrologer chat

A streaming AI astrologer chat, ready to run

A chat page and a zero-dependency Node proxy for the AstroNode chat service: the user enters their birth details once, asks questions, and the astrologer's answer streams in as it is written - with follow-up suggestions, a stop button and clear errors when a quota is reached.

Updated

Download ai-astrologer-chat.zip14 files · runs on a Free-plan key

Run it

bash
unzip ai-astrologer-chat.zip && cd ai-astrologer-chat
cp .env.example .env   # put your key in ASTRONODE_API_KEY
npm run dev            # http://localhost:3000
Files (14)
  • .env.example1 KB
  • README.md7 KB
  • package.json1 KB
  • public/app.js8 KB
  • public/index.html5 KB
  • public/sse.js6 KB
  • server.js7 KB
  • src/chat.js11 KB
  • test/chat.test.js13 KB
  • test/fake-chat-service.js5 KB
  • test/fixtures/stream-error.sse2 KB
  • test/fixtures/stream-happy.sse3 KB
  • test/fixtures/stream-replace.sse1 KB
  • test/server.test.js5 KB

src/chat.js

javascript
"use strict";

/**
 * Chat proxy logic: validate what the browser sends, build the AstroNode
 * request, open the upstream stream and relay its events. The HTTP plumbing
 * lives in server.js; everything here takes injected `fetch` / sinks so it is
 * testable without a network or a key.
 */

const { formatSseEvent, readChatStream } = require("../public/sse.js");

const DEFAULT_CHAT_URL = "https://chatbot-api.astronode.dev";
const STREAM_PATH = "/v1/chat/respond/stream";

class InputError extends Error {
  constructor(message, field) {
    super(message);
    this.name = "InputError";
    this.field = field;
  }
}

// ---------------------------------------------------------------------------
// Time zone -> tz_offset_minutes (DST-correct for the birth moment)
// ---------------------------------------------------------------------------

const isValidTimeZone = (zone) => {
  if (typeof zone !== "string" || zone.length === 0 || zone.length > 64) return false;
  try {
    new Intl.DateTimeFormat("en-US", { timeZone: zone });
    return true;
  } catch {
    return false;
  }
};

const zoneOffsetMinutes = (instantMs, zone) => {
  const dtf = new Intl.DateTimeFormat("en-US", {
    timeZone: zone,
    hourCycle: "h23",
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit",
  });
  const p = {};
  for (const part of dtf.formatToParts(new Date(instantMs))) {
    if (part.type !== "literal") p[part.type] = part.value;
  }
  const asZoneUtc = Date.UTC(Number(p.year), Number(p.month) - 1, Number(p.day), Number(p.hour), Number(p.minute), Number(p.second));
  return Math.round((asZoneUtc - instantMs) / 60000);
};

/** UTC offset (minutes, east positive) in force at a local wall-clock time in `zone`. Two passes for DST. */
const offsetMinutesForLocalTime = (dateIso, timeHhmm, zone) => {
  const [y, mo, d] = dateIso.split("-").map(Number);
  const [hh, mm] = timeHhmm.split(":").map(Number);
  const wallAsUtc = Date.UTC(y, mo - 1, d, hh, mm, 0);
  const first = zoneOffsetMinutes(wallAsUtc, zone);
  return zoneOffsetMinutes(wallAsUtc - first * 60000, zone);
};

// ---------------------------------------------------------------------------
// Validation of the browser's request
// ---------------------------------------------------------------------------

const CONVERSATION_ID_RE = /^[A-Za-z0-9_\-:.]{3,120}$/;
const DATE_RE = /^(\d{4})-(\d{2})-(\d{2})$/;
const TIME_RE = /^(\d{2}):(\d{2})(?::(\d{2}))?$/;
const MAX_MESSAGE = 2000;

const isRealDate = (s) => {
  const m = DATE_RE.exec(s);
  if (!m) return false;
  const [y, mo, d] = [Number(m[1]), Number(m[2]), Number(m[3])];
  if (y < 1800 || y > 2100) return false;
  const t = new Date(Date.UTC(y, mo - 1, d));
  return t.getUTCFullYear() === y && t.getUTCMonth() === mo - 1 && t.getUTCDate() === d;
};

const isRealTime = (s) => {
  const m = TIME_RE.exec(s);
  return !!m && Number(m[1]) < 24 && Number(m[2]) < 60 && (m[3] === undefined || Number(m[3]) < 60);
};

const num = (v, field, limit) => {
  const n = typeof v === "string" && v.trim() !== "" ? Number(v) : v;
  if (typeof n !== "number" || !Number.isFinite(n) || n < -limit || n > limit) {
    throw new InputError(`${field} must be a number between -${limit} and ${limit}`, field);
  }
  return n;
};

/**
 * Validate the browser's JSON body and build the upstream request body.
 *
 * Browser body:
 *   { conversation_id, message,
 *     user: { date: "YYYY-MM-DD", time: "HH:MM[:SS]", lat, lng,
 *             tz: "Asia/Kolkata"  (or tz_offset_minutes: 330),
 *             time_certainty?: "exact" | "rough" | "unknown" } }
 *
 * Returns the AstroNode body: { conversation_id, user: {date,time,lat,lng,tz_offset_minutes[,time_certainty]}, message }.
 */
const buildChatRequest = (input) => {
  if (!input || typeof input !== "object" || Array.isArray(input)) throw new InputError("Body must be a JSON object", "body");
  const { conversation_id: conversationId, message, user } = input;

  if (typeof conversationId !== "string" || !CONVERSATION_ID_RE.test(conversationId)) {
    throw new InputError("conversation_id must be 3-120 characters of A-Z a-z 0-9 _ - : .", "conversation_id");
  }
  if (typeof message !== "string" || message.trim().length === 0) throw new InputError("message is required", "message");
  if (message.length > MAX_MESSAGE) throw new InputError(`message must be at most ${MAX_MESSAGE} characters`, "message");

  if (!user || typeof user !== "object") throw new InputError("user (birth details) is required", "user");
  if (typeof user.date !== "string" || !isRealDate(user.date)) throw new InputError("user.date must be a real date, YYYY-MM-DD", "user.date");
  if (typeof user.time !== "string" || !isRealTime(user.time)) throw new InputError("user.time must be HH:MM or HH:MM:SS (24-hour)", "user.time");
  const lat = num(user.lat, "user.lat", 90);
  const lng = num(user.lng, "user.lng", 180);

  let tzOffset;
  if (user.tz !== undefined && user.tz !== null && user.tz !== "") {
    if (!isValidTimeZone(user.tz)) throw new InputError("user.tz must be an IANA time zone such as Asia/Kolkata", "user.tz");
    tzOffset = offsetMinutesForLocalTime(user.date, user.time, user.tz);
  } else if (Number.isInteger(user.tz_offset_minutes) && Math.abs(user.tz_offset_minutes) <= 840) {
    tzOffset = user.tz_offset_minutes;
  } else {
    throw new InputError("user.tz (IANA zone) or an integer user.tz_offset_minutes (-840..840) is required", "user.tz");
  }

  const out = { date: user.date, time: user.time, lat, lng, tz_offset_minutes: tzOffset };
  if (user.time_certainty !== undefined && user.time_certainty !== "") {
    if (!["exact", "rough", "unknown"].includes(user.time_certainty)) {
      throw new InputError("user.time_certainty must be exact, rough or unknown", "user.time_certainty");
    }
    out.time_certainty = user.time_certainty;
  }
  return { conversation_id: conversationId, user: out, message };
};

// ---------------------------------------------------------------------------
// Upstream
// ---------------------------------------------------------------------------

/** A failure before the stream started: carries the status + error body to return to the browser. */
class UpstreamError extends Error {
  constructor(status, code, message, extra = {}) {
    super(message);
    this.name = "UpstreamError";
    this.status = status;
    this.code = code;
    this.details = extra.details;
    this.retryAfter = extra.retryAfter;
  }
}

/** Statuses the browser should see as-is; everything else becomes 502. */
const PASS_THROUGH = new Set([400, 401, 403, 413, 422, 429]);

/**
 * Open the upstream SSE stream. Resolves with the fetch Response once the
 * stream is open (status 2xx, text/event-stream); throws UpstreamError otherwise.
 * `connectTimeoutMs` bounds only the wait for response headers.
 */
const openUpstream = async ({ fetchImpl, chatUrl, apiKey, body, signal, connectTimeoutMs = 30_000 }) => {
  const ctrl = new AbortController();
  const onAbort = () => ctrl.abort();
  if (signal) {
    if (signal.aborted) ctrl.abort();
    else signal.addEventListener("abort", onAbort, { once: true });
  }
  const timer = setTimeout(() => ctrl.abort(new Error("connect timeout")), connectTimeoutMs);
  let res;
  try {
    res = await fetchImpl(`${chatUrl.replace(/\/+$/, "")}${STREAM_PATH}`, {
      method: "POST",
      headers: {
        authorization: `Bearer ${apiKey}`,
        "content-type": "application/json",
        accept: "text/event-stream",
        "user-agent": "astronode-ai-astrologer-chat-template",
      },
      body: JSON.stringify(body),
      signal: ctrl.signal,
    });
  } catch (err) {
    if (signal && signal.aborted) throw new UpstreamError(499, "CLIENT_CLOSED", "The browser closed the request");
    const timedOut = ctrl.signal.aborted;
    throw new UpstreamError(timedOut ? 504 : 502, timedOut ? "UPSTREAM_TIMEOUT" : "UPSTREAM_UNREACHABLE", timedOut ? "The chat service did not respond in time" : "Could not reach the chat service");
  } finally {
    clearTimeout(timer);
  }

  if (!res.ok) {
    let json = null;
    try {
      json = await res.json();
    } catch {
      json = null;
    }
    const e = (json && json.error) || {};
    const code = typeof e.code === "string" ? e.code : `HTTP_${res.status}`;
    const message = typeof e.message === "string" ? e.message : `Chat service returned HTTP ${res.status}`;
    throw new UpstreamError(PASS_THROUGH.has(res.status) ? res.status : 502, code, message, {
      details: e.details,
      retryAfter: res.headers.get("retry-after") || undefined,
    });
  }
  const type = res.headers.get("content-type") || "";
  if (!type.includes("text/event-stream") || !res.body) {
    throw new UpstreamError(502, "BAD_UPSTREAM_RESPONSE", "Chat service did not return an event stream");
  }
  // From here on, the caller's signal aborts the body read via the same controller.
  res.abort = () => ctrl.abort();
  return res;
};

/**
 * What the browser receives for each upstream event. Same event names and
 * payload shapes as the AstroNode stream, so one parser serves both sides.
 * `done` is trimmed to the parts a chat UI renders.
 */
const toBrowserEvent = (ev) => {
  switch (ev.type) {
    case "tool":
      return ["tool", ev];
    case "delta":
    case "replace":
      return [ev.type, { type: ev.type, text: ev.text }];
    case "done": {
      const env = ev.envelope && typeof ev.envelope === "object" ? ev.envelope : {};
      return [
        "done",
        {
          type: "done",
          envelope: { request_id: env.request_id, conversation_id: env.conversation_id, response: env.response || {} },
        },
      ];
    }
    case "error":
      return ["error", { type: "error", code: ev.code, message: ev.message }];
    default:
      return null;
  }
};

/**
 * Relay an open upstream stream to `write` (a function taking SSE text) as
 * events arrive. Always ends with exactly one terminal event: the upstream's
 * own done/error, or a synthesized `error` if the stream broke off.
 * Resolves with { terminal, count }.
 */
const relayStream = async (upstreamRes, write) => {
  let count = 0;
  let terminal = null;
  try {
    terminal = await readChatStream(upstreamRes.body, (ev) => {
      const out = toBrowserEvent(ev);
      if (!out) return;
      count++;
      write(formatSseEvent(out[0], out[1]));
    });
  } catch (err) {
    terminal = null;
  }
  if (!terminal) {
    terminal = { type: "error", code: "STREAM_INCOMPLETE", message: "The chat stream ended before the reply finished. Please try again." };
    write(formatSseEvent("error", terminal));
  }
  return { terminal, count };
};

module.exports = {
  DEFAULT_CHAT_URL,
  STREAM_PATH,
  InputError,
  UpstreamError,
  isValidTimeZone,
  offsetMinutesForLocalTime,
  buildChatRequest,
  openUpstream,
  toBrowserEvent,
  relayStream,
};

public/sse.js

javascript
/*
 * Server-Sent Events parsing for the AstroNode chat stream.
 *
 * One file used in two places: the Node server requires it to read the
 * upstream stream, and the browser loads it (as window.AstroSSE) to read the
 * relayed stream. No dependencies.
 *
 * Wire format of POST /v1/chat/respond/stream - one record per event,
 * records separated by a blank line, `:` lines are comments (keep-alives):
 *
 *   event: tool
 *   data: {"type":"tool","name":"analyze_house","phase":"start","label":"Reading your 7th house"}
 *
 *   event: delta
 *   data: {"type":"delta","text":"Hello "}
 *
 *   event: replace
 *   data: {"type":"replace","text":"<safety rewrite: discard what was streamed>"}
 *
 *   event: done
 *   data: {"type":"done","envelope":{ ...the full /v1/chat/respond response... }}
 *
 *   event: error
 *   data: {"code":"LLM_TIMEOUT","message":"..."}
 *
 * `done` and `error` are terminal.
 */
(function (root, factory) {
  if (typeof module === "object" && module.exports) module.exports = factory();
  else root.AstroSSE = factory();
})(typeof self !== "undefined" ? self : this, function () {
  "use strict";

  function findSeparator(buf) {
    var lf = buf.indexOf("\n\n");
    var crlf = buf.indexOf("\r\n\r\n");
    if (crlf !== -1 && (lf === -1 || crlf < lf)) return { index: crlf, length: 4 };
    if (lf !== -1) return { index: lf, length: 2 };
    return null;
  }

  /** Parse one record ("event: x\ndata: {...}") into { event, data }, or null for comments/empty records. */
  function parseRecord(record) {
    var trimmed = record.replace(/^\s+|\s+$/g, "");
    if (!trimmed) return null;
    var event = "message";
    var dataLines = [];
    var lines = trimmed.split(/\r?\n/);
    for (var i = 0; i < lines.length; i++) {
      var line = lines[i];
      if (line.charAt(0) === ":") continue;
      var idx = line.indexOf(":");
      var field = idx === -1 ? line : line.slice(0, idx);
      var val = idx === -1 ? "" : line.slice(idx + 1);
      if (val.charAt(0) === " ") val = val.slice(1);
      if (field === "event") event = val;
      else if (field === "data") dataLines.push(val);
    }
    if (dataLines.length === 0) return null;
    return { event: event, data: dataLines.join("\n") };
  }

  /**
   * Incremental parser. Feed it decoded text in chunks of any size (split
   * anywhere, even mid-line); it returns the complete records seen so far.
   */
  function createSseParser() {
    var buffer = "";
    return {
      push: function (text) {
        buffer += text;
        var out = [];
        var sep = findSeparator(buffer);
        while (sep) {
          var rec = parseRecord(buffer.slice(0, sep.index));
          buffer = buffer.slice(sep.index + sep.length);
          if (rec) out.push(rec);
          sep = findSeparator(buffer);
        }
        return out;
      },
      /** Flush a trailing record that had no final blank line. */
      end: function () {
        var rec = parseRecord(buffer);
        buffer = "";
        return rec ? [rec] : [];
      },
    };
  }

  /** Map a raw record onto a typed chat event, or null to skip it. Same rules as @astronode/chat-client. */
  function decodeStreamEvent(eventName, data) {
    var o;
    try {
      o = JSON.parse(data);
    } catch (e) {
      return null;
    }
    if (typeof o !== "object" || o === null) return null;
    var type = typeof o.type === "string" ? o.type : eventName;
    switch (type) {
      case "tool":
        if (typeof o.name !== "string" || (o.phase !== "start" && o.phase !== "result")) return null;
        var ev = { type: "tool", name: o.name, phase: o.phase, label: typeof o.label === "string" ? o.label : "" };
        if (typeof o.isError === "boolean") ev.isError = o.isError;
        return ev;
      case "delta":
      case "replace":
        return typeof o.text === "string" ? { type: type, text: o.text } : null;
      case "done":
        return "envelope" in o ? { type: "done", envelope: o.envelope } : null;
      case "error":
        return {
          type: "error",
          code: typeof o.code === "string" ? o.code : "INTERNAL_ERROR",
          message: typeof o.message === "string" ? o.message : "stream failed",
        };
      default:
        return null;
    }
  }

  /** Serialise one event as an SSE record. */
  function formatSseEvent(name, data) {
    return "event: " + name + "\ndata: " + JSON.stringify(data) + "\n\n";
  }

  /**
   * Read a fetch Response body as typed chat events. Calls onEvent for each;
   * stops after the first terminal (done/error) event. Resolves with the
   * terminal event, or null if the stream ended without one.
   */
  function readChatStream(body, onEvent) {
    var reader = body.getReader();
    var decoder = new TextDecoder();
    var parser = createSseParser();
    var terminal = null;
    function handle(records) {
      for (var i = 0; i < records.length && !terminal; i++) {
        var ev = decodeStreamEvent(records[i].event, records[i].data);
        if (!ev) continue;
        onEvent(ev);
        if (ev.type === "done" || ev.type === "error") terminal = ev;
      }
    }
    function step() {
      return reader.read().then(function (r) {
        if (r.done) {
          handle(parser.push(decoder.decode()));
          if (!terminal) handle(parser.end());
          return terminal;
        }
        handle(parser.push(decoder.decode(r.value, { stream: true })));
        if (terminal) {
          return Promise.resolve(reader.cancel()).then(
            function () { return terminal; },
            function () { return terminal; }
          );
        }
        return step();
      });
    }
    return step();
  }

  return {
    createSseParser: createSseParser,
    decodeStreamEvent: decodeStreamEvent,
    formatSseEvent: formatSseEvent,
    readChatStream: readChatStream,
  };
});

public/app.js

javascript
/*
 * Chat UI - no framework. Posts to /api/chat (this template's server) and
 * renders the Server-Sent Events it relays as they arrive. All text from the
 * API goes into the page with textContent.
 */
(function () {
  "use strict";

  var STORE_BIRTH = "astronode-chat:birth";
  var STORE_CONV = "astronode-chat:conversation";

  var $ = function (id) {
    return document.getElementById(id);
  };
  var birthForm = $("birth");
  var log = $("log");
  var composer = $("composer");
  var input = $("message");
  var sendBtn = $("send");
  var stopBtn = $("stop");
  var inflight = null;

  // ---------------------------------------------------------------- storage (best effort)

  function load(key) {
    try {
      return window.localStorage.getItem(key);
    } catch (e) {
      return null;
    }
  }
  function save(key, value) {
    try {
      if (value === null) window.localStorage.removeItem(key);
      else window.localStorage.setItem(key, value);
    } catch (e) {
      /* private mode etc. - the page still works */
    }
  }

  function newConversationId() {
    var rand = window.crypto && window.crypto.randomUUID ? window.crypto.randomUUID() : String(Date.now()) + Math.random().toString(16).slice(2);
    return "web-" + rand;
  }
  var conversationId = load(STORE_CONV) || newConversationId();
  save(STORE_CONV, conversationId);

  // ---------------------------------------------------------------- birth details

  function readBirth() {
    var f = new FormData(birthForm);
    var user = {
      date: String(f.get("date") || ""),
      time: String(f.get("time") || ""),
      lat: String(f.get("lat") || "").trim(),
      lng: String(f.get("lng") || "").trim(),
      tz: String(f.get("tz") || "").trim(),
      time_certainty: String(f.get("time_certainty") || "exact"),
    };
    if (user.time_certainty === "exact") delete user.time_certainty;
    return user;
  }

  (function restoreBirth() {
    var saved = null;
    try {
      saved = JSON.parse(load(STORE_BIRTH) || "null");
    } catch (e) {
      saved = null;
    }
    if (saved && typeof saved === "object") {
      ["date", "time", "lat", "lng", "tz", "time_certainty"].forEach(function (k) {
        if (typeof saved[k] === "string" && birthForm.elements[k]) birthForm.elements[k].value = saved[k];
      });
      if (birthForm.checkValidity()) $("birth-panel").open = false;
    }
    if (!birthForm.elements.tz.value) {
      try {
        birthForm.elements.tz.value = Intl.DateTimeFormat().resolvedOptions().timeZone || "";
      } catch (e) {
        /* leave empty */
      }
    }
  })();

  birthForm.addEventListener("input", function () {
    var f = new FormData(birthForm);
    var o = {};
    f.forEach(function (v, k) {
      o[k] = String(v);
    });
    save(STORE_BIRTH, JSON.stringify(o));
  });

  // ---------------------------------------------------------------- rendering

  function el(tag, className, text) {
    var n = document.createElement(tag);
    if (className) n.className = className;
    if (text !== undefined) n.textContent = text;
    return n;
  }

  function scrollToEnd() {
    window.scrollTo(0, document.body.scrollHeight);
  }

  function addUserMessage(text) {
    var empty = $("empty");
    if (empty) empty.remove();
    log.appendChild(el("div", "msg me", text));
    scrollToEnd();
  }

  /** An assistant bubble with a status line, the streamed text and room for errors/follow-ups. */
  function addBotMessage() {
    var box = el("div", "msg bot streaming");
    var status = el("div", "status", "Thinking…");
    var text = el("div", "text");
    box.appendChild(status);
    box.appendChild(text);
    log.appendChild(box);
    scrollToEnd();
    return {
      box: box,
      status: status,
      text: text,
      setText: function (s) {
        text.textContent = s;
        scrollToEnd();
      },
      setStatus: function (s) {
        status.textContent = s;
      },
      error: function (message) {
        box.classList.remove("streaming");
        status.textContent = "";
        box.appendChild(el("div", "err", message));
        scrollToEnd();
      },
      finish: function () {
        box.classList.remove("streaming");
        status.textContent = "";
      },
    };
  }

  function addFollowUps(bubble, followUps) {
    if (!Array.isArray(followUps) || followUps.length === 0) return;
    var wrap = el("div", "follow");
    followUps.slice(0, 4).forEach(function (q) {
      if (typeof q !== "string" || !q) return;
      var b = el("button", "", q);
      b.type = "button";
      b.addEventListener("click", function () {
        send(q);
      });
      wrap.appendChild(b);
    });
    bubble.box.appendChild(wrap);
  }

  function errorText(body, status) {
    var e = body && body.error;
    if (!e) return "Request failed (HTTP " + status + ").";
    if (e.code === "QUOTA_EXCEEDED" || e.code === "RATE_LIMITED") return e.message || "Limit reached. Try again later.";
    if (e.code === "INVALID_INPUT") return "Check your details: " + e.message;
    return e.message + " (" + e.code + ")";
  }

  function setBusy(busy) {
    sendBtn.disabled = busy;
    input.disabled = busy;
    stopBtn.hidden = !busy;
  }

  // ---------------------------------------------------------------- sending

  function send(message) {
    if (inflight) return;
    message = String(message || "").trim();
    if (!message) return;
    if (!birthForm.reportValidity()) {
      $("birth-panel").open = true;
      return;
    }
    addUserMessage(message);
    input.value = "";
    var bubble = addBotMessage();
    var ctrl = new AbortController();
    inflight = ctrl;
    setBusy(true);
    var text = "";

    fetch("/api/chat", {
      method: "POST",
      headers: { "content-type": "application/json", accept: "text/event-stream" },
      body: JSON.stringify({ conversation_id: conversationId, message: message, user: readBirth() }),
      signal: ctrl.signal,
    })
      .then(function (res) {
        var type = res.headers.get("content-type") || "";
        if (!res.ok || type.indexOf("text/event-stream") === -1) {
          return res
            .json()
            .catch(function () {
              return null;
            })
            .then(function (body) {
              bubble.error(errorText(body, res.status));
            });
        }
        return window.AstroSSE.readChatStream(res.body, function (ev) {
          switch (ev.type) {
            case "tool":
              if (ev.phase === "start") bubble.setStatus((ev.label || "Consulting your chart") + "…");
              else if (!text) bubble.setStatus("Writing…");
              break;
            case "delta":
              if (!text) bubble.setStatus("");
              text += ev.text;
              bubble.setText(text);
              break;
            case "replace":
              text = ev.text;
              bubble.setText(text);
              break;
            case "done":
              var r = (ev.envelope && ev.envelope.response) || {};
              if (typeof r.message === "string" && r.message) bubble.setText(r.message);
              bubble.finish();
              addFollowUps(bubble, r.follow_ups);
              break;
            case "error":
              bubble.error("The reply stopped: " + ev.message + " (" + ev.code + ")");
              break;
          }
        }).then(function (terminal) {
          if (!terminal) bubble.error("The connection closed before the reply finished.");
        });
      })
      .catch(function (err) {
        if (ctrl.signal.aborted) bubble.error("Stopped.");
        else bubble.error("Could not reach the server: " + (err && err.message ? err.message : "network error"));
      })
      .then(function () {
        inflight = null;
        setBusy(false);
        input.focus();
      });
  }

  composer.addEventListener("submit", function (e) {
    e.preventDefault();
    send(input.value);
  });
  input.addEventListener("keydown", function (e) {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault();
      send(input.value);
    }
  });
  stopBtn.addEventListener("click", function () {
    if (inflight) inflight.abort();
  });
  $("new-chat").addEventListener("click", function () {
    if (inflight) inflight.abort();
    conversationId = newConversationId();
    save(STORE_CONV, conversationId);
    log.textContent = "";
    log.appendChild(el("p", "empty", "New conversation. Ask away."));
    log.lastChild.id = "empty";
  });
})();

What it does

  • POST /api/chat validates the message and birth details, turns the IANA zone into the UTC offset at the birth moment, and opens the stream with your key.
  • Relays each event to the browser as soon as it is parsed, so the reply renders progressively; the final done event is trimmed to the reply and its ids.
  • Sends a heartbeat every 15 seconds, aborts the upstream call when the user presses Stop or leaves, and reports a stream that breaks off as an error rather than a short answer.
  • Passes quota and validation errors through with their code and Retry-After, so the page can say when the user can ask again.
  • Keeps the birth details in the browser's localStorage, and renders every value with textContent.

Endpoints and plan

API calls the template makes
EndpointUsed forPlan
POST /v1/chat/respond/streamThe answer as Server-Sent Events: tool, delta, replace, then done or errorFree

Everything it calls is on the Free plan, so a Free test key runs the whole template.

Where things live

FileWhat it holds
server.jsStatic files and POST /api/chat
src/chat.jsValidation, the upstream request, relaying events
public/sse.jsThe SSE parser, shared by the server and the browser
public/app.jsThe chat page
test/fake-chat-service.jsA local fake of the stream for development (npm run fake-chat)

Keys and deployment

  • The API key is read from the server's environment and sent as Authorization: Bearer <key>; it never reaches a browser or an app bundle.
  • npm run check runs 18 tests offline, including the stream parser fed byte by byte (through multi-byte Devanagari characters) and the whole proxy against a fake chat service in test/ - no key and no network.
  • Any Node host that does not buffer responses: behind nginx, turn proxy_buffering off for /api/chat, or the stream arrives all at once.
  • The chat service is at https://chatbot-api.astronode.dev (ASTRONODE_CHAT_URL). Each message is one call against your plan's monthly quota; the Free plan is also capped at five chat messages a day.
  • Put sign-in in front of a public deployment: every message spends your quota.

Questions

Does the AI astrologer chat work on the Free plan?
Yes, up to five messages a day on Free; paid plans have no daily chat cap, only the monthly quota shared with the other endpoints.
Why proxy the stream instead of calling the chat API from the browser?
The API key must stay on a server. The proxy adds the key and the birth details and relays the events unchanged, so the browser still sees tokens as they arrive.
Can I use it without a build step or framework?
Yes. The page is plain HTML and JavaScript and the server has no dependencies; the parser in public/sse.js drops into any front end.