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

@cutos/core

v4.3.3

Published

The CUTOS (CUT Operating System) Core API is a JavaScript library that provides essential functionalities for LWA (Local Web Application) edge computing and communication in the CUTOS ecosystem.

Readme

Introduction

@cutos/core is the TypeScript-friendly Core SDK for CUTOS 4.0. It provides the system-call API used by LWA applications, Node Providers, tools, and services running in the CUTOS ecosystem.

CUTOS 4.0 uses a Capability/Provider model:

  • Capability: a named CUTOS system ability consumed by an LWA, service, or AI agent.
  • Provider: a Node.js module or process that implements a Capability.
  • Contract: a capability.contract.json file that describes methods, events, errors, and permissions.

Hardware Device/Driver APIs remain available as the compatibility layer, but new CUTOS 4.0 applications should use Capability/Provider and Promise-first APIs.

Core API Module Components

Platform

  • CoreAPI is the main entry point for connecting to CUTOS runtime.
  • It provides Promise-first methods for reading platform, configuration, box, device, volume, proxy, and shell information.

IPC

  • IPC is a lower-level channel API for local and cross-device communication.
  • Prefer Capability/Provider for product APIs; use IPC for diagnostics, tools, and experimental services.

Database

  • CoreClass.Database provides Promise-first access to the CUTOS local database.
  • Database.Table supports local table creation, insert, update, delete, query and synchronization metadata.
  • table.create({ mirror: true }) enables automatic replication through the Node runtime while keeping normal local database operations.

Gateway

  • CoreAPI.getGateway() provides Promise-based remote service requests and message publication.
  • LWA applications share the Node Gateway connection; Node manages credentials and connection lifecycle.

Notification

  • Notification supports registering, unregistering, and emitting system/application notifications.

Logging

  • Logger supports info, warning, error, and debug logs.

Error Model

  • CUTOS 4.0 normalizes errors to CutosError.
  • CutosError includes code, message, and optional detail.

Table Of Contents

  1. Quick Start
  2. Platform API
  3. IPC API
  4. Database API
  5. Gateway API
  6. Notification API
  7. Logger API
  8. Error Model
  9. Device Capability Base
  10. Device Provider Base
  11. Capability Contract
  12. Core Simulator
  13. Documentation

Quick Start

Install

npm install @cutos/core

Import

import {
  CoreAPI,
  CoreClass,
  CoreSimulator,
  CutosError
} from "@cutos/core"

Initialize

await CoreAPI.init("localhost")

During development, connect to a target CUTOS device:

await CoreAPI.init("192.168.1.100")

Mock Dev

Use Mock Dev when developing an LWA without a local CUTOS Node.

import { CoreAPI, CutosMock } from "@cutos/core"

CutosMock.install({
  capabilities: {
    demo: {
      methods: {
        echo: params => ({ message: params.message })
      }
    }
  }
})

await CoreAPI.init("mock")

const demo = new CoreClass.Capability("demo")
const result = await demo.call("echo", { message: "hello" })

CutosMock.install() connects the existing Capability, Provider, DeviceCapabilityBase, and DeviceProviderBase classes to an in-memory transport. Capability names must match exactly. Device Base classes derive capability.device.<deviceType> automatically.

CutosMock.install()
await CoreAPI.init("mock")

class HelloProvider extends DeviceProviderBase {
  connect() {
    this.setStatus("online")
    return { connected: true }
  }

  disconnect() {
    this.setStatus("offline")
    return { connected: false }
  }

  readDeviceInfo() {
    return { deviceType: this.deviceType }
  }
}

const provider = new HelloProvider("hello")
const device = new DeviceCapabilityBase("hello")

await device.init()
await device.connect()

For simple UI development, set the CUTOS host to mock and keep application code unchanged:

VITE_CUTOS_BROKER_URL=mock

Mock Dev is intended for UI and SDK integration development. Real IPC, WebView host behavior, and Node Provider behavior should still be verified with a CUTOS Node before release.

Platform API

CoreAPI.init

Connect to CUTOS runtime.

await CoreAPI.init(host?: string | null)
  • host: CUTOS host address. Defaults to localhost.
  • Returns: Promise<string>.

Example:

await CoreAPI.init("localhost")

CoreAPI.connected

Check whether the SDK is connected.

const connected = CoreAPI.connected()

CoreAPI.getVersion

Get SDK version.

const version = CoreAPI.getVersion()

CoreAPI.getPlatform

Get platform information.

type PlatformInfo = {
  arch: string
  platform: string
  type: string
  release: string
}

const platform = await CoreAPI.getPlatform<PlatformInfo>()

CoreAPI.getConfig

Get CUTOS runtime configuration.

const config = await CoreAPI.getConfig<Record<string, unknown>>()

CoreAPI.getBoxInfo

Get host box information.

const box = await CoreAPI.getBoxInfo<Record<string, unknown>>()

CoreAPI.getDeviceInfo

Get registered CUTOS device identity information.

const deviceInfo = await CoreAPI.getDeviceInfo<Record<string, unknown>>()

CoreAPI.getVolume / CoreAPI.setVolume

const volume = await CoreAPI.getVolume<number>()
await CoreAPI.setVolume(70)

CoreAPI.setHttpProxy

Set a runtime HTTP proxy to avoid LWA cross-origin issues during development.

type ProxyResult = {
  path: string
  target: string
}

const proxy = await CoreAPI.setHttpProxy<ProxyResult>(
  "api",
  "https://www.cut-os.com"
)

CoreAPI.shell

Execute a shell command through CUTOS runtime.

const pwd = await CoreAPI.shell<string>("pwd")

Use this API carefully. It should not be exposed to untrusted LWA code without permissions.

IPC API

IPC is a lower-level channel API. Prefer Capability/Provider for product APIs.

CoreAPI.getIPC

const ipc = CoreAPI.getIPC()
const remote = CoreAPI.getIPC("192.168.1.149")

ipc.call

const result = await ipc.call<
  { left: number; right: number },
  { sum: number }
>("math.add", { left: 2, right: 2 })

ipc.callWithOptions

await ipc.callWithOptions(
  "math.add",
  { left: 2, right: 2 },
  { timeout: 3000 }
)

ipc.on

const off = ipc.on<{ left: number; right: number }, { sum: number }>(
  "math.add",
  (args, respond) => {
    respond({ sum: args.left + args.right })
  }
)

off?.()

ipc.sendTo

Fire-and-forget message.

ipc.sendTo("diagnostic.event", { time: Date.now() })

Database API

CUTOS database uses a key-value table model. Values can be arbitrary JSON objects.

Database

const database = new CoreClass.Database()
await database.connect()

database.run

const rows = await database.run<Array<Record<string, unknown>>>(
  "select * from device"
)

Database.Table

const table = new CoreClass.Database.Table("device", database)

table.create

await table.create({
  keyName: "id",
  keyType: "INTEGER"
})

table.insert

table.create({ mirror: true }) persists the table's Mirror switch in the updated Node runtime. mirror: false disables it; omitting mirror preserves an existing setting and defaults to false for a new table. The setting is stored in the connected database and survives Node restarts. Insert methods do not need to repeat the option. Node retains its existing single database connection behavior.

For an enabled table, the updated Node runtime saves each new inserted record and its Mirror task in one local transaction. A background worker reuses the Node Gateway connection, retries pending tasks after disconnects and restarts, and marks a record synchronized only after GW confirms its committed write. The GW update is required for these acknowledgements; MQTT QoS 1 alone does not confirm persistence.

After a Node restart, pending tasks resume when LWA calls db.connect(). Node does not automatically open a database before that call.

LWA still uses normal local database operations and does not import @cutos/mirror or configure a Gateway connection. The lwaName option selects the GW data namespace and defaults to "lwa". To use the application name, call table.create({ mirror: true, lwaName: config.name }). Node stores the name for subsequent inserts. Use the same name across releases; a different name sends new records to a different GW table.

Mirror supports table creation and new inserts, including insertById and insertByKey. Updates, deletes, raw SQL writes and pre-existing records are not replicated. Disabling Mirror pauses pending tasks and stops adding new tasks; enabling it resumes the retained tasks. Synchronization preserves original timestamps. The SDK alone cannot enable this on an old Node runtime.

await table.insert(
  { type: "printer", name: "HP-1" },
  { tid: "tra-001" }
)

The Mirror configuration regression suite (npm run test:database-mirror) uses Node.js 22.13+ with the built-in SQLite test engine. Production continues to use the Node runtime's existing sql.js storage adapter.

table.insertById / table.insertByKey

await table.insertById(1, { type: "printer", name: "HP-1" })
await table.insertByKey("printer-1", { type: "printer", name: "HP-1" })

table.update / table.updateByKey

await table.update(1, { type: "printer", name: "HP-2" })
await table.updateByKey("printer-1", { type: "printer", name: "HP-2" })

table.delete

await table.delete(1)

table.query APIs

const byId = await table.query<Array<Record<string, unknown>>>(1)
const byKey = await table.queryByKey<Array<Record<string, unknown>>>("printer-1")
const byTid = await table.queryByTid<Array<Record<string, unknown>>>("tra-001")
const all = await table.queryAll<Array<Record<string, unknown>>>()

table.queryUnsynced

const rows = await table.queryUnsynced<Array<Record<string, unknown>>>({ limit: 100 })

table.sync

await table.sync(1)

Gateway API

LWA applications reuse the Node Gateway connection through local MQTT. Gateway transport source is included in the Node runtime; neither LWA nor Core depends on a separate @cutos/gw-client package.

import { CoreAPI } from '@cutos/core'

await CoreAPI.init()
const face = CoreAPI.getGateway({
  gwi: '172B1F1E-91C3-450A-AEC2-CAC3091B1234',
  appService: 'ai-face2-app-svc@siptimes'
})

const response = await face.request({
  type: 'ai-face', data: { cmd: 'recognize', args: { image } }
}, { qos: 1, timeout: 10000 })

// Existing Face business contract; transport failures reject the Promise.
if (response.error) throw response.error
console.log(response.result)

const gateway = CoreAPI.getGateway()
await gateway.request('another-service', { command: 'read' })
await gateway.publish('value', { bloodFlow: 300 }, { qos: 0, retain: true })

getGateway({ gwi, appService }) returns a local facade bound to a service, with request(data, options?) and publish(channel, data, options?). getGateway() uses the Node's own GWI and exposes request(service, data, options?) and publish(channel, data, options?). Supplying only gwi selects a target group while keeping the service argument. Omitting gwi uses the Node's own group.

Core caches facades by GWI and appService; repeated equivalent options return the same instance. All facades share one Node connection. Both operations return Promises; handle failures with try/catch. TypeScript can specify the request result using face.request<Result>(...). Options accept QoS 0/1 and timeout (1-300000 ms, default 10000). Publications additionally accept retain.

The LWA does not supply a GW URL, token, routing scope or application context, and cannot connect or close the Node connection. Like Database, Gateway uses Core publishRequest(), maybePromise() and doCallback(). Core initialization waits for subscription acknowledgements before becoming ready. Gateway uses the existing Core MQTT request/reply framework: request IDs correlate replies on the shared callback topic. Node returns business responses unchanged. publish() completion confirms MQTT completion only. Remote GW disconnects reject calls; the local transport follows existing Core timeout behavior. Durable Mirror synchronization is not part of this API.

The Node connection is created on the first remote operation and reused. Connection state and reconnect handling stay in Node. Service requests use gw/<target-gwi>/app/<service>; publications use gw/<target-gwi>/lwa/<node-id>/<channel>. Target selection changes message routing; authentication and the reply address remain those of the Node. Cross-group calls require the GW broker to permit both the request and reply. The legacy Face endpoint's business body.gwi remains the Node GWI, independently of the target group.

Node configuration and access

The updated Node runtime requires Core 4.3 and includes its Gateway transport implementation. It obtains GW URL, instance, Node ID and license from existing Node settings. The SDK alone cannot enable this feature on an old Node runtime.

An optional Node-side settings.gatewayPolicy restricts services/channels and maps logical service names:

settings.gatewayPolicy = {
  services: ['face'],
  channels: ['value', 'device/status'],
  serviceAliases: { face: 'ai-face2-app-svc@siptimes' }
}

When lists are omitted, valid names are permitted under the existing Node GW credential. LWA cannot publish to the reserved state or mirror channel. Custom channels still need GW broker permissions and receivers. This implementation follows the current single-LWA Node model and does not introduce private per-client topics or Broker authorization rules.

The policy above is Node-wide. Per-application identity and message isolation remain a future Core transport concern.

In mock mode, supply an explicit facade with CutosMock.install({ gateway: mockGateway }), or a factory such as gateway: target => createMockGateway(target). The factory receives the normalized GWI and appService options. Without a mock, getGateway() raises GATEWAY_MOCK_NOT_CONFIGURED rather than pretending that remote service calls succeeded.

Notification API

CoreAPI.getNotification

const notification = CoreAPI.getNotification()

notification.register

notification.register(data => {
  console.log(data)
})

notification.unregister

notification.unregister()

notification.emit

notification.emit("notification-1", "msg-1")

System notification example:

type NetworkNotification = {
  event: "networkConnection"
  msg: boolean
}

Logger API

CoreAPI.getLogger

const logger = CoreAPI.getLogger()

logger.info / warning / error / debug

logger.info("hello-device", "provider started")
logger.warning("hello-device", "slow response")
logger.error("hello-device", "provider failed")
logger.debug("hello-device", "debug detail")

The third argument is optional and defaults to LWA.

logger.info("hello-provider", "started", "Provider")

Device Capability Base

DeviceCapabilityBase is the consumer-side base used by a Device Capability SDK. It derives the Capability identity from the raw deviceType and supplies the standard Device API:

  • init()
  • connect()
  • disconnect()
  • readDeviceInfo()
  • onData()
  • onStatus()
  • onError()

Concrete SDK classes add only device-specific extension methods:

class PrinterCapability extends DeviceCapabilityBase {
  constructor(options = {}) {
    super("printer", options)
  }

  printText(params) {
    return this.call("printText", params)
  }
}

const printer = new PrinterCapability()
await printer.init()
await printer.connect()

const info = await printer.readDeviceInfo()
const offData = printer.onData(data => console.log(data))
const offStatus = printer.onStatus(status => console.log(status))
const offError = printer.onError(error => console.error(error))

offData()
offStatus()
offError()

onStatus() receives both Provider status events and Runtime heartbeat status. Consumers should inspect the received payload rather than assuming every heartbeat message is a Device state transition.

Device Provider Base

DeviceProviderBase automatically registers the standard connect, disconnect, and readDeviceInfo Capability methods. A concrete device Provider overrides those methods and registers only its device-specific extensions:

Device Base constructors expose only the raw device type. CUTOS derives the internal Capability identity and transport type:

deviceType:   printer
capabilityId: capability.device.printer
transport:    device-channel-capability.device.printer-command

The legacy transport name and type are both set internally to the derived Capability id and cannot be overridden through Base options.

class PrinterProvider extends DeviceProviderBase {
  constructor(options) {
    super("printer", options)
  }

  connect(params) {
    // Connect hardware.
  }

  disconnect() {
    // Disconnect hardware.
  }

  readDeviceInfo() {
    return { manufacturer: "CUTOS", model: "printer" }
  }
}

The Base implementations throw DEVICE_CONNECT_NOT_IMPLEMENTED, DEVICE_DISCONNECT_NOT_IMPLEMENTED, and DEVICE_INFO_NOT_IMPLEMENTED. This makes an incomplete Provider fail explicitly instead of leaving a standard method unregistered.

Provider helpers map directly to Device Capability events and Runtime health reporting:

this.emitData({ paper: "ready" })
this.setStatus("online", { port: "COM3" })
this.emitError(new CutosError("PRINTER_ERROR", "Printer failed"))

this.setBeatInterval(3000)
this.startBeat()
  • emitData(data) emits the standard data event.
  • setStatus(status, info) emits the standard status event and updates heartbeat state.
  • emitError(error) normalizes the error, emits error, and marks heartbeat state as failed.
  • startBeat() registers and starts the Provider heartbeat. Calling it more than once is safe.

Error Model

CUTOS 4.0 normalizes SDK errors to CutosError.

try {
  await CoreAPI.getPlatform()
} catch (error) {
  if (error instanceof CutosError) {
    console.log(error.code)
    console.log(error.message)
    console.log(error.detail)
  }
}

Common error codes include:

CUTOS_TIMEOUT
CUTOS_CORE_ERROR
DRIVER_INIT_TIMEOUT
DRIVER_INIT_ERROR
METHOD_NOT_FOUND
PROVIDER_ERROR

Capability Contract

Capabilities should be described by capability.contract.json.

{
  "schemaVersion": "0.1",
  "name": "capability.device.hello",
  "version": "4.0.0",
  "type": "device",
  "methods": {},
  "events": {},
  "errors": {},
  "permissions": []
}

Contracts are the source of truth for future SDK generation, Provider stubs, documentation, tests, permissions, and AI tool schemas.

Core Simulator

CoreSimulator is a lightweight compatibility helper for testing legacy Driver initialization against an MQTT broker. It connects to ws://localhost:<port> and handles the default Device init command:

CoreSimulator.start({
  init(args) {
    console.log("Driver init", args)
  }
}, 1883)

Use CutosMock for normal LWA and Capability UI development. CoreSimulator requires a compatible MQTT broker and is not a replacement for full CUTOS Runtime verification.

Documentation

Full CUTOS 4.0 SDK API guide:

docs/CUTOS-4.0-SDK-API.md

Capability contract spec:

docs/CUTOS-Capability-Contract-v0.md