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

@notrealstudio/nr-ui-protocol

v0.12.1

Published

Универсальный протокол UI ⇄ бэкенд (v1): wire-типы + маппинг-хелперы, без движка. Модель сообщения ре-экспортируется из @notrealstudio/nr-chat-store.

Readme

@notrealstudio/nr-ui-protocol

Универсальный протокол UI ⇄ бэкенд (v1). Один провод между универсальным фронтом (dreams-web и наследники) и любым бэкендом: nr-engine/dreams, pi, opencode, будущие.

Канон: nr-engine/docs/specs/nr-ui-protocol-spec.md

Пакет содержит только типы + маппинг-хелперы. Без движка — адаптеры pi/opencode подключают его, не таща nr-engine (спека §10.7). Единственная зависимость — node builtins.

Установка

npm i @notrealstudio/nr-ui-protocol

Что внутри

Типы (спека §2–5)

  • Session: SessionInfo, Participant
  • Message: Message, Usage, MessageFlags, MessageMeta
  • Part (закрытое ядро + escape hatch custom): Part, TextPart, ThinkingPart, ToolUsePart, ToolResultPart, FilePart, ImagePart, ErrorPart, CustomPart; opaque-варианты AnyPart / UnknownPart
  • Модели (models-spec §2, capability models): ModelInfo, SessionModel (он же ModelSelection в nr-chat-store), SessionInfo.model, SessionCreateOpts.model, ModelsOps (list / set)
  • Пространство (workspace-spec §2, capability workspace): WorkspaceInfo, WorkspaceOps (current / list / switch), SessionInfo.workspace
  • Профили (profiles-spec §4, capability profiles, протокол v1.4): ProfileInfo, ProfilesOps (list / set), SessionInfo.profile, SessionCreateOpts.profile
  • Конструктор профилей (profile-editor-spec §2–3, протокол v1.5): ProfileDoc, ProfilesOps.get / save / delete / duplicate (capability profiles.edit); каталоги CatalogsOps (tools / skills / extensions, capability catalogs) — CatalogTool, CatalogSkill, CatalogExtension
  • Бот = сессия (bot-as-session-spec §1, протокол v1.6): встроенный профиль — SessionCreateOpts.profile и ProfilesOps.set принимают string | ProfileDoc, SessionInfo.profile: 'inline' + SessionInfo.profileDoc, INLINE_PROFILE_ID, isProfileDoc; MessageAppendOpts.role: 'user' | 'assistant' (гритинг без рана) и MessageAppendOpts.swipeOf (альтернатива сообщению, capability swipes). ProfileDoc теперь живёт в nr-chat-store и ре-экспортируется
  • Файлы пространства (workspace-files-spec §1, протокол v1.7): capability workspace.files {write?, watch?}, WorkspaceOps.files — WorkspaceFilesOps (list / read / stat; write / delete / rename — гейт write; watch(listener) → unsubscribe — гейт watch), FileEntry, FileContent, FileEncoding, FileReadOpts, FileWriteOpts, WorkspaceUpdateEvent (workspace_update {paths}, отдельный SSE-канал, не событие рана)
  • Capabilities: Capabilities
  • Envelope: Envelope<T>
  • Run: RunStartInput, RunEvent (run_start, message_start, part_start, part_delta, part_end, message_end, ask, activity, session_update, run_end); opaque-варианты AnyRunEvent / UnknownRunEvent

Хелперы

import {
  derivedText, matchToolPair,
  isKnownPart, isKnownRunEvent, isRunEvent,
  isTextPart, isToolUsePart, /* ... остальные guards */
  serializeRunEvent, parseRunEvent, parseSSEStream,
} from '@notrealstudio/nr-ui-protocol'
  • derivedText(message) — плоский текст = конкатенация text-parts (content в протоколе нет, считает клиент).
  • matchToolPair(parts) — матч tool_use ↔ tool_result по callId → ToolPair[].
  • Type guards для Part и RunEvent с сужением по type.
  • isKnownPart / isKnownRunEvent — распознавание ядра; неизвестное = opaque, рендерится fallback'ом, клиент не падает (§1.2 graceful degradation).

Файлы пространства — правила для бэкендов (workspace-files-spec §1)

Общие для backend-fs и memory-FS фикстуры, чтобы оба отвечали одинаково:

  • normalizeFilePath(path) — относительный POSIX-путь без .; корень — ''. .. в любом сегменте, абсолютный путь, \, NUL → FileBadRequestError (bad_request). Симлинки наружу проверяет бэкенд с диском.
  • fileContent({path, data, revision}) — UTF-8 без NUL текстом (BOM сохраняется), иначе base64; decodeFileContent(content, encoding) — обратно.
  • checkFileReadSize(path, size, maxBytes?) — лимит read (DEFAULT_FILE_READ_MAX_BYTES, 2 МБ), отказ с размером.
  • isIgnoredPath(path, isDir, rulesOf) + parseGitignore / matchGitignore — FileEntry.ignored: .git/node_modules на любой глубине, корзина .nr-trash в корне, дальше .gitignore каталогов (подмножество git).
  • FileNotFoundError (not_found), FileConflictError (conflict), fileMime, parentFilePath, isTrashPath, WORKSPACE_TRASH_DIR.
  • serializeWorkspaceEvent / parseWorkspaceEvent / isWorkspaceUpdateEvent — кадры GET /workspace/events. paths: [''] — «перечитай всё».

SSE-биндинг (§9)

Кадр event: <type>\ndata: {json}\n\n:

const frame = serializeRunEvent({ type: 'part_delta', runId: 'r1',
  messageId: 'm1', part: 0, delta: 'hello' })

const event  = parseRunEvent(frame)        // AnyRunEvent | null (null на битом кадре)
const events = parseSSEStream(sseText)      // AnyRunEvent[] — битые кадры отброшены

Транспорта (fetch/EventSource/сервер) здесь нет — только сериализация/парсинг.

Границы

  • Никакой реализации транспорта/сервера/клиента — только типы, guards, сериализация.
  • Маппинги dreams/pi/opencode/Marinara (спека §6–8b) — в будущих адаптерах, не здесь.

Разработка

npm test              # vitest
npm run build         # tsc → dist