@cutos/core
v4.0.8
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.jsonfile 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
CoreAPIis 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.Databaseprovides Promise-first access to the CUTOS local database.Database.Tablesupports table creation, insert, update, delete, query, sync, and mirror-oriented operations.
Notification
Notificationsupports registering, unregistering, and emitting system/application notifications.
Logging
Loggersupports info, warning, error, and debug logs.
Error Model
- CUTOS 4.0 normalizes errors to
CutosError. CutosErrorincludescode,message, and optionaldetail.
Table Of Contents
- Quick Start
- Platform API
- IPC API
- Database API
- Notification API
- Logger API
- Error Model
- Device Capability Base
- Device Provider Base
- Capability Contract
- Core Simulator
- Documentation
Quick Start
Install
npm install @cutos/coreImport
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=mockMock 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 tolocalhost.- 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
await table.insert(
{ type: "printer", name: "HP-1" },
{ tid: "tra-001" }
)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)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-commandThe 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 standarddataevent.setStatus(status, info)emits the standardstatusevent and updates heartbeat state.emitError(error)normalizes the error, emitserror, 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_ERRORCapability 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.mdCapability contract spec:
docs/CUTOS-Capability-Contract-v0.md