Skip to content

Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More

3.6 KB
Raw Blame

import { logger } from '../utils/logger.js';
import type { Readable } from 'node:stream';

function isStdinAvailable(stdin: Readable & { isTTY?: boolean }): boolean {
  try {

    if (stdin.isTTY) {
      return false;
    }

    // eslint-disable-next-line @typescript-eslint/no-unused-expressions
    stdin.readable;
    return true;
  } catch (error) {
    logger.debug('HOOK', 'stdin not available (expected for some runtimes)', { error: error instanceof Error ? error.message : String(error) });
    return false;
  }
}

function tryParseJson(input: string): { success: true; value: unknown } | { success: false } {
  const trimmed = input.trim();
  if (!trimmed) {
    return { success: false };
  }

  try {
    const value = JSON.parse(trimmed);
    return { success: true, value };
  } catch (error) {
    logger.debug('HOOK', 'JSON parse attempt incomplete', { error: error instanceof Error ? error.message : String(error) });
    return { success: false };
  }
}

export const SAFETY_TIMEOUT_MS = 30000;

export interface ReadJsonFromStdinOptions {
  safetyTimeoutMs?: number;
  stdin?: Readable;
}

export async function readJsonFromStdin(options: ReadJsonFromStdinOptions = {}): Promise<unknown> {
  let stdin: Readable;
  try { stdin = options.stdin ?? process.stdin; } catch { return undefined; }
  if (!isStdinAvailable(stdin)) {
    return undefined;
  }

  const safetyTimeoutMs = options.safetyTimeoutMs ?? SAFETY_TIMEOUT_MS;

  return new Promise((resolve, reject) => {
    let input = '';
    let resolved = false;

    const cleanup = () => {
      try {
        stdin.removeListener('data', onData);
        stdin.removeListener('end', onEnd);
        stdin.removeListener('error', onError);
      } catch {
        // Ignore cleanup errors
      }
    };

    const resolveWith = (value: unknown) => {
      if (resolved) return;
      resolved = true;
      clearTimeout(safetyTimeoutId);
      cleanup();
      resolve(value);
    };

    const rejectWith = (error: Error) => {
      if (resolved) return;
      resolved = true;
      clearTimeout(safetyTimeoutId);
      cleanup();
      reject(error);
    };

    const tryResolveWithJson = () => {
      const result = tryParseJson(input);
      if (result.success) {
        resolveWith(result.value);
        return true;
      }
      return false;
    };

    const safetyTimeoutId = setTimeout(() => {
      if (!resolved) {
        if (!tryResolveWithJson()) {
          if (input.trim()) {
            rejectWith(new Error(`Incomplete JSON after ${safetyTimeoutMs}ms: ${input.slice(0, 100)}...`));
          } else {
            resolveWith(undefined);
          }
        }
      }
    }, safetyTimeoutMs);

    const onData = (chunk: Buffer | string) => {
      input += chunk;

      if (tryResolveWithJson()) {
        return;
      }
    };

    const onEnd = () => {
      if (!resolved) {
        if (!tryResolveWithJson()) {
          if (input.trim()) {
            rejectWith(new Error(`Malformed JSON at stdin EOF: ${input.slice(0, 100)}...`));
          } else {
            resolveWith(undefined);
          }
        }
      }
    };

    const onError = () => {
      if (!resolved) {
        resolveWith(undefined);
      }
    };

    try {
      stdin.setEncoding('utf8');
      stdin.on('data', onData);
      stdin.on('end', onEnd);
      stdin.on('error', onError);
    } catch (error) {
      logger.debug('HOOK', 'Failed to attach stdin listeners', { error: error instanceof Error ? error.message : String(error) });
      resolved = true;
      clearTimeout(safetyTimeoutId);
      cleanup();
      resolve(undefined);
    }
  });
}