On this page
The npm package exposes a Node.js ESM control plane, the portable
arcane-os/event-manager, arcane-os/logging, arcane-os/mail,
arcane-os/preference-store, arcane-os/speech-playback, arcane-os/websocket-client,
arcane-os/speech-text, arcane-os/ai/tool-text-stream, arcane-os/ai/twin-cloud, and arcane-os/browser-device entrypoints, and the browser-only
arcane-os/pwa, arcane-os/ai/browser-wasm, and
arcane-os/ai/browser-decisions entrypoints. The
arcane-os/ai/browser-speech entrypoint includes local and native browser
providers plus a cloud TTS adapter usable in Node with Fetch and Blob.
The arcane-os/modules/<filename> and arcane-os/entities/<filename> paths
resolve directly to the existing runtime files, with their actual extension.
They are public Node package exports and managed browser keys, without a wrapper.
For example, import.meta.resolve('arcane-os/modules/WaitForComponent.js')
retains the module directory needed to resolve ../components/modal.html.
Lowercase runtime subpaths also expose existing module namespaces through both
Node package exports and managed browser imports, as listed below. Established
browser names such as arcane/AIProviderRuntime, arcane/AIRuntimeState, and
arcane/ThemeBootstrap remain compatibility names in physical/nested maps;
direct-installed root maps use the package namespace instead. Applications call globalThis.Arcane for capability-gated host
behavior.
This page documents the focused package APIs. The same binding can appear at
the root and a focused subpath; those entrypoints are listed together. Direct
runtime-module aliases and filename patterns expose the complete namespaces in
the runtime module and entity
catalogs. The root workspace discoverApps and low-level packager
discoverApps are separate functions with separate records.
Import map
This table is the Node package.json#exports map: it defines package
entrypoints for SDK/tooling code. It is distinct from the generated browser
import map that resolves application-facing arcane-os/* names for root/direct
layouts and arcane/* compatibility names for physical/nested layouts.
See browser runtime delivery
for the shared browser destinations used by installed-package and physical
runtime layouts.
| Specifier | Purpose |
|---|---|
arcane-os |
Complete high-level SDK surface. |
arcane-os/toolchain |
Headless application operations. |
arcane-os/events |
CLI/event reporter. |
arcane-os/websocket |
Node HTTP/1.1 WebSocket Upgrade, complete messages and accepted connection lifecycle. |
arcane-os/websocket-client |
Shared native client WS, one managed-connection observer and current connection snapshots through published ws-share. |
arcane-os/testing |
Isolated test registration and execution. |
arcane-os/targets |
Target adapters and dispatch. |
arcane-os/native |
Native plan and builder protocol. |
arcane-os/native-provider |
SDK portable/Windows/macOS defaults and registered explicit checkout provider loader. |
arcane-os/native/portable-provider |
Node-only portable payload provider and explicit app-service composition; not an executable host. |
arcane-os/native/windows-provider |
Selected Windows x64 executable assembly and host-owned run/drain lifecycle. |
arcane-os/native/macos-provider |
Architecture-selected Mac application bundle composition and host-owned run/drain lifecycle. |
arcane-os/core/client |
Browser-safe Core RPC client, application facade, readiness and request cancellation. |
arcane-os/core/contracts |
Shared Core protocol, frame, method and diagnostic error contracts. |
arcane-os/core/classic-source |
Node generator for the canonical classic-script Core client projection. |
arcane-os/core/runtime |
App-neutral native Core dispatcher and service lifecycle. |
arcane-os/core/model-observation |
Passive observation of an existing Core and its actual native model service owners. |
arcane-os/ai/model-observation |
Attach existing renderer model owners and subscribe through an existing Core client. |
arcane-os/document-acquisition |
Acquire complete document and redirect bodies through the selected native Core service. |
arcane-os/core/document-acquisition |
Native HTTP(S) GET service, application-owned destination predicate and acquisition lifecycle. |
arcane-os/core/development |
App-service composition and document-owned Core transport during source development, independently of local AI. |
arcane-os/core/stdio |
Framed Node stdio transport with graceful runtime drain. |
arcane-os/core/host |
Node-only reusable Core host lifecycle, app-selected native launch defaults and shared native location resolution. |
arcane-os/core/app-control |
Explicit connection to an existing native window for background document inspection, capture and DOM actions. |
arcane-os/codex/app-server |
Explicit native Codex App Server session, complete live turns, server requests and recovery. |
arcane-os/mcp/stdio |
Node MCP STDIO server for app-owned tools and static resources. |
arcane-os/core/repositories |
Native persistent ArcaneData paths, connected working repositories and scoped non-secret Git identity configuration. |
arcane-os/core/packaged-web |
Core-owned packaged web listener with a persisted loopback origin and ready/failure events. |
arcane-os/core/preferences |
Existing preference RPC methods with an application-selected file, ordered writes and owned drain. |
arcane-os/core/diarization |
Lazy native speaker-diarization service, explicit stream methods and lifecycle/result events. |
arcane-os/diarization |
Retained Nemotron model helper and independent caller-fed audio streams. |
arcane-os/diarization/build |
First-party helper compilation against explicitly installed NeMo-Speech.cpp libraries. |
arcane-os/core/local-ai |
Native llama.cpp, Ollama and ONNX Core service, model readiness, complete responses and owned lifecycle. See local AI through Core. |
arcane-os/local-ai |
Official runtime installation and native artifact bundling for selected llama.cpp/Ollama/ONNX/image requirements and NeMo libraries. |
arcane-os/local-ai/onnx |
Retained native ONNX worker sessions with explicit graph loading and complete tensor inference. |
arcane-os/local-ai/decisions |
Explicit native Laya FP32/FP16 and Julia FP32 decisions using the existing ONNX owner and a tokenizer Worker. |
arcane-os/core/decisions |
Renderer-independent typed-decision service composed with existing local-AI and model-assets owners. |
arcane-os/ai/core-onnx |
Optional browser access to system ONNX through an existing Core connection. |
arcane-os/local-ai/image |
Retained native stable-diffusion.cpp context, complete PNG generation and owned worker lifetime. |
arcane-os/ai/core-image |
Browser image lifecycle and complete PNG Blobs through an available Core service. |
arcane-os/core/image |
Native image Core service with independent runtime preparation and retained model ownership. |
arcane-os/core/speech |
Independent injected STT/TTS engine loading, request cancellation and joined Core service lifetime. |
arcane-os/local-ai/nemotron |
Retained native streaming recognition with complete timed words and optional diarization. |
arcane-os/local-ai/nemotron/build |
First-party ASR helper build against a prepared NeMo runtime. |
arcane-os/local-ai/magpie |
Retained native Magpie/NanoCodec synthesis with complete audio or ordered PCM. |
arcane-os/local-ai/magpie/build |
First-party TTS helper build against a prepared NeMo runtime. |
arcane-os/local-ai/whisper |
Retained native Whisper model, complete recordings and joined helper lifetime. |
arcane-os/local-ai/kokoro |
Retained native Kokoro synthesis using the existing ONNX/model-resource owners and a compiled phonemization/Opus helper. |
arcane-os/local-ai/whisper/build |
First-party persistent helper build against selected installed Whisper headers and libraries. |
arcane-os/local-ai/whisper/openvino-build |
Optional Windows x64 Intel NPU encoder runtime producer using selected installed sources and toolchain. |
arcane-os/ai/core-model-assets |
Complete stored browser model members projected through Core into native working files. |
arcane-os/core/model-assets |
Native working-file preparation, engine retain handles and joined cleanup. |
arcane-os/integrated-provider |
Fixed integrated shared-development provider. |
arcane-os/packager |
Low-level browser app packager. |
arcane-os/release-bundle |
Deterministic external release bundles. |
arcane-os/event-manager |
Central synchronous events, complete time-travel history, playback, and optional DOM instrumentation. |
arcane-os/modules/<filename> |
Direct existing runtime module, including its .js or .mjs extension. |
arcane-os/entities/<filename> |
Direct existing runtime entity, including its extension. |
arcane-os/logging |
Shared console diagnostics controlled by the existing user.developer preference. |
arcane-os/preference-store |
Portable preference records and injected storage adapters. |
arcane-os/ai |
Existing AI.js provider-neutral inference and speech namespace. |
arcane-os/ai-preference-tuple |
Existing AIPreferenceTuple.js module namespace. |
arcane-os/ai-preference-runtime |
Existing AIPreferenceRuntime.js module namespace. |
arcane-os/ai-provider-runtime |
Existing AIProviderRuntime.js provider selection and lifecycle namespace. |
arcane-os/ai-runtime-state |
Existing AIRuntimeState.js state and event namespace. |
arcane-os/model-definition |
Existing ModelDefinition.js module namespace. |
arcane-os/conversation-timebox |
Existing ConversationTimebox.js module namespace. |
arcane-os/conversation-action-items |
Existing ConversationActionItems.js module namespace. |
arcane-os/conversation-closing-report |
Existing ConversationClosingReport.js module namespace. |
arcane-os/chat-records |
Existing ChatRecords.js module namespace. |
arcane-os/app-data-scope |
Existing AppDataScope.js application storage scope namespace. |
arcane-os/core-local-model-catalog |
Existing CoreLocalModelCatalog.js local model catalog namespace. |
arcane-os/dbopfs-document-library |
Existing DBOPFSDocumentLibrary.js document storage namespace. |
arcane-os/local-ai-readiness |
Existing LocalAIReadiness.js local AI readiness namespace. |
arcane-os/ollama-model-identifier |
Existing OllamaModelIdentifier.js model identifier namespace. |
arcane-os/speech-playback |
Portable speech preparation, playback state, and injected media adapters. |
arcane-os/speech-text |
Speech-input formatting cleanup for complete text and streamed chunks. |
arcane-os/browser-device |
Synchronous mobile or desktop identity hints for application-owned settings. |
arcane-os/pwa |
Nonblocking PWA registration, worker updates, native installation state and a dismissible installation component. |
arcane-os/ai/browser-wasm |
Caller-selected browser-local Wllama inference, complete DBOPFS model storage, streaming, cancellation, and structural tool-call results. |
arcane-os/ai/core-local |
Browser llama.cpp provider through an available Core connection; browser-local Wllama and ONNX remain independently available. |
arcane-os/ai/browser-decisions |
Explicit-load Laya and Julia-1 typed decisions with caller-selected precision through the shared Transformers.js Worker owner. |
arcane-os/ai/tool-text-stream |
Shared selected tool-argument text observer for provider integration. |
arcane-os/ai/twin-cloud |
Stateless chat, System One state/questions and image generation with explicit key/model, complete results and operation-specific retry/cancellation. |
arcane-os/ai/browser-speech |
Caller-selected Whisper/Kokoro, native browser recognition/synthesis, cloud TTS, upstream assets, role lifecycle and cancellation. |
arcane-os/mail |
Portable Mail runtime, durable outbox, complete transport responses, and provider-neutral acceptance contracts. |
These lowercase runtime-module entrypoints expose their existing exports; they
do not duplicate the module implementations or change their platform and
lifecycle requirements. Node resolves them inside the installed package, while
the managed browser map resolves the same names to the selected runtime URLs.
Node package resolution does not make browser-only operations available in
Node: a module still needs its documented browser globals, storage, media,
Worker, or host capabilities when its initialization or operation uses them.
Use arcane-os/mail for the existing Mail aggregation rather than importing a
private runtime file. Its package facade and managed browser entry both expose
the canonical MailApi.mjs aggregation and the same Mail, outbox, and transport
bindings.
Eight JSON schemas and package.json are data-only export subpaths. In Node ESM, import JSON with with {type: 'json'}, or resolve and read it explicitly.
Managed AI narration
Root applications import AI through arcane-os/ai in the managed browser map.
ai.prepareTTSPlayback(payload,signal) silently prepares real Blob audio or a
native speech descriptor for playback. Native browser voices expose no audio
file; use this path or shared streaming/SpeechPlayback for native output.
ai.prepareTTS({parts,storage,identity,textFormat,signal,onState}) prepares complete
punctuation segments without playing them and optionally saves/reuses their
audio through application-owned DBOPFS. Its immediate handle exposes ordered
segments, preparation state, ready, getAudio(index), and cancel().
ai.playPreparedTTS(prepared,{signal,onState}) attaches ordered playback and
returns state, error, finished, pause(), resume(), and stop().
Each preparation owns its pending activation interest. Cancelling the final
interest aborts that activation; other preparation, playback or joining direct
TTS-load interests preserve it. Cancelling after readiness leaves the model
loaded, and complete cache hits start no model. Actual cleanup is provider-owned.
Each AI has one playback lane; replacing playback preserves independent
preparation. Fully cached replay does not load the speech
model. See prepared narration
for complete inputs, storage ownership, progress, errors, and cancellation,
and AI.js for the managed runtime contract.
These are AI instance methods, not new npm export names.
Complete synthesis calls can select textFormat:'plain' to preserve supplied
speech text, including repeated formatting marks and surrounding whitespace.
This applies to ai.fetchTTS(payload,signal), audio-file preparation through
ai.prepareTTSPlayback(payload,signal), durable ai.prepareTTS(...), provider
runtime TTS requests and direct Kokoro synthesis. The SDK consumes the control
before engine dispatch; durable preparation retains the existing punctuation
segmentation. Omitted or other values retain automatic speech cleanup.
Streaming streamTTS, finishTTS and shared SpeechPlayback retain their
automatic cleanup; this option does not change upstream engine capacity.
See exact complete synthesis input.
Shared operation contract
High-level operations accept one options object. Common fields are workspaceRoot, appId, target, signal, and onEvent; only fields meaningful to that operation are consumed. Long work acknowledges first, owns its child tasks, keeps event delivery ordered and backpressured, emits progress or heartbeats, observes cancellation where safe, and rejects with ArcaneError on failure.
One invocation selects one workspace, app, operation, target, architecture, format, and output root. No API silently loops over all apps or targets.
Protocol mechanics are intentionally kept in the deep protocol guide. The compact availability and normalization sentence beneath each member is the normal application-facing view.
Canonical member inventory
memberCount in inventory/package-api.json
counts the authored focused API records below. Shared bindings retain their
entrypoints together. Runtime aliases and filename patterns are documented in
Runtime modules and Runtime entities.
The remaining data-only subpaths are eight JSON Schemas and package metadata.
| Member | Kind | Import | Group | Availability |
|---|---|---|---|---|
acceptWebSocket() |
function | arcane-os, arcane-os/websocket |
WebSocket protocol | Node; browser-native client interoperability |
WS |
class | arcane-os, arcane-os/websocket-client |
Shared WebSocket clients | Node and native-WebSocket browser hosts |
createBrowserDecisionModel() |
function | arcane-os/ai/browser-decisions |
Browser typed decisions | Browser module Workers and the caller-selected inference backend |
createNativeDecisionModel() |
function | arcane-os/local-ai/decisions |
Native typed decisions | Node with an existing native ONNX owner and selected Laya FP32/FP16 or Julia FP32 files |
createNativeDecisionService() |
function | arcane-os/core/decisions |
Native typed decisions | Node Core with existing local-AI and model-assets services |
createNativeDecisionService default export |
function | arcane-os/core/decisions |
Native typed decisions | Same native decision service factory |
fetchRequest() |
function | arcane-os/ai/twin-cloud |
TWiN Cloud requests | Node and Browser; remote HTTPS provider |
fetchSystemOneRequest() |
function | arcane-os/ai/twin-cloud |
TWiN Cloud state-and-questions requests | Node and Browser; remote HTTPS provider |
generateImages() |
function | arcane-os/ai/twin-cloud |
TWiN Cloud image generation | Node and Browser with Fetch and Blob; remote HTTPS provider |
createBrowserSpeechSynthesisProvider() |
function | arcane-os/ai/browser-speech |
Native browser speech | Browser with speechSynthesis and SpeechSynthesisUtterance |
fetchHTTPResponse() |
function | arcane-os/ai/twin-cloud |
Shared AI transport integration | Node and Browser |
fetchJSONResponse() |
function | arcane-os/ai/twin-cloud |
Shared AI transport integration | Node and Browser |
structuredOutputFormat() |
function | arcane-os/ai/twin-cloud |
Shared AI transport integration | Node and Browser |
openAIResponseFormat() |
function | arcane-os/ai/twin-cloud |
Shared AI transport integration | Node and Browser |
isAIRequestAbort() |
function | arcane-os/ai/twin-cloud |
Shared AI transport integration | Node and Browser |
normalizeAIRequestAbort() |
function | arcane-os/ai/twin-cloud |
Shared AI transport integration | Node and Browser |
APP_BUNDLE_DESCRIPTOR_NAME |
constant | arcane-os |
Packaging and release bundles | Node |
APP_BUNDLE_EXTENSION |
constant | arcane-os |
Packaging and release bundles | Node |
APP_BUNDLE_FORMAT |
constant | arcane-os |
Packaging and release bundles | Node |
APP_BUNDLE_KIND |
constant | arcane-os |
Packaging and release bundles | Node |
APP_BUNDLE_MANIFEST_NAME |
constant | arcane-os |
Packaging and release bundles | Node |
APP_BUNDLE_RELEASE_PATH |
constant | arcane-os |
Packaging and release bundles | Node |
APP_BUNDLE_SCHEMA_VERSION |
constant | arcane-os |
Packaging and release bundles | Node |
APP_BUNDLE_SUPPORTED_SDK_VERSIONS |
constant | arcane-os/release-bundle |
Packaging and release bundles | Node |
APP_CONFIG_NAME |
constant | arcane-os/packager |
Packaging and release bundles | Node |
APP_DESCRIPTOR_NAME |
constant | arcane-os |
Runtime and app descriptors | Node |
APP_DESCRIPTOR_SCHEMA_VERSION |
constant | arcane-os |
Runtime and app descriptors | Node |
ARCANE_INTEGRATED_PROVIDER_RELATIVE_PATH |
constant | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
ARCANE_MACHINE_BUNDLE_VERSION |
constant | arcane-os |
Identity and protocol constants | Node |
ARCANE_NATIVE_PROVIDER_PATHS |
constant | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
ARCANE_PROTOCOL |
constant | arcane-os |
Identity and protocol constants | Node |
ARCANE_UPSTREAM_REPOSITORY |
constant | arcane-os |
Identity and protocol constants | Node |
ArcaneError |
class | arcane-os |
Errors | Node |
adaptV1LlmProvider() |
function | arcane-os/ai/browser-wasm |
Browser-WASM local AI | Browser; the wrapped provider retains its own WebGPU, storage, model, and lifecycle requirements |
assertIntegratedNativeToolchain() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
assessArcaneOllama() |
function | arcane-os |
Workspace, doctor, repository, and server | Node; Microsoft NT managed-service assessment |
buildApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
buildTarget() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
BROWSER_SPEECH_ARTIFACT_GRAPH_PROTOCOL |
constant | arcane-os/ai/browser-speech |
Browser speech providers | Browser metadata; graph construction starts no fetch, cache, Worker, provider, or event operation |
BROWSER_SPEECH_ARTIFACT_PROTOCOL |
constant | arcane-os/ai/browser-speech |
Browser speech providers | Browser metadata; model/runtime use requires caller-selected sources plus the selected DBOPFS, Web Locks, and Worker capabilities |
BROWSER_WASM_RUNTIME_AUTHORITY |
constant | arcane-os/ai/browser-wasm |
Browser-WASM local AI | Browser metadata; no model or DBOPFS required to inspect |
bumpVersion() |
function | arcane-os/packager |
Packaging and release bundles | Node |
bundleApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
checkApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
CLI_EVENT_PROTOCOL |
constant | arcane-os |
Identity and protocol constants | Node |
CLI_NAME |
constant | arcane-os |
Identity and protocol constants | Node |
completeValueText() |
function | arcane-os/ai/browser-wasm |
Browser-WASM local AI | Compatible JavaScript module host; no browser capability required |
createApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
createArcaneAI() |
function | arcane-os/ai/browser-wasm |
Browser-WASM local AI | Browser; compatible LLM provider or controller required |
createAppReleaseBundle() |
function | arcane-os |
Packaging and release bundles | Node |
createBrowserKokoroProvider() |
function | arcane-os/ai/browser-speech |
Browser speech providers | Browser with Workers, object URLs, caller-selected Kokoro runtime/model artifacts, and an SDK DBOPFS speech store |
createBrowserModelSource() |
function | arcane-os/ai/browser-wasm |
Browser-WASM local AI | Browser Fetch with a readable response body |
createBrowserSpeechArtifactGraph() |
function | arcane-os/ai/browser-speech |
Browser speech providers | Browser metadata; construction starts no fetch, cache, Worker, provider, or event operation |
createBrowserSpeechAuthority() |
function | arcane-os/ai/browser-speech |
Browser speech providers | Browser descriptor construction; use requires the selected storage and provider Web APIs |
createBrowserWasmLlmProvider() |
function | arcane-os/ai/browser-wasm |
Browser-WASM local AI | Browser context with WebAssembly and OPFS/DBOPFS; WebGPU by default or explicit CPU with gpuLayers:0 |
createBrowserWhisperProvider() |
function | arcane-os/ai/browser-speech |
Browser speech providers | Browser with Workers, object URLs, caller-selected Whisper runtime/model artifacts, and an SDK DBOPFS speech store |
createBrowserSpeechRecognitionProvider() |
function | arcane-os/ai/browser-speech |
Browser speech providers | Browser or WebView with native SpeechRecognition; construction and catalog remain available on unsupported hosts |
createCanonicalUstarHeader() |
function | arcane-os |
Packaging and release bundles | Node |
createDbopfsModelStore() |
function | arcane-os/ai/browser-wasm |
Browser-WASM local AI | Browser with a ready DBOPFS instance and OPFS |
getBrowserDeviceClass() |
function | arcane-os/browser-device |
Browser device settings | Node and Browser; synchronous identity hint with no model, storage, or GPU operation |
PWA_STATE_EVENT |
constant | arcane-os/pwa |
Progressive web applications | Browser lifecycle event name; importable without registration |
registerPwa() |
function | arcane-os/pwa |
Progressive web applications | Browser service workers; synchronous unsupported state when unavailable |
PWA_INSTALL_STATE_EVENT |
constant | arcane-os/pwa |
Progressive web applications | Browser installation event name; importable without starting observation |
getPwaInstall() |
function | arcane-os/pwa |
Progressive web applications | Browser native installation events; waiting state while no prompt is available |
mountPwaInstallPrompt() |
function | arcane-os/pwa |
Progressive web applications | Browser document and managed HTML import; resolves to null without a document |
createDbopfsSpeechArtifactStore() |
function | arcane-os/ai/browser-speech |
Browser speech providers | Browser with ready DBOPFS, Web Locks, Fetch, File/Blob, and object URLs |
createDigitalOceanFalTTSProvider() |
function | arcane-os/ai/browser-speech |
Browser speech providers | Compatibility name for createTwinCloudTTSProvider() |
createTwinCloudTTSProvider() |
function | arcane-os/ai/browser-speech |
Browser speech providers | Browser or Node with Fetch, Blob, and an application-supplied inference key |
removeBrowserSpeechModelCache() |
function | arcane-os/ai/browser-speech |
Browser speech providers | Browser CacheStorage; explicit removal of one selected upstream model |
createNativeBuildPlan() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
createNativeTargetAdapter() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
createReporter() |
function | arcane-os |
Events, processes, and testing | Node |
createToolchain() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
createToolTextObserver() |
function | arcane-os/ai/tool-text-stream |
AI provider integration | Compatible JavaScript module host; no browser capability required |
createWorkspace() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
default() |
function | arcane-os/testing |
Events, processes, and testing | Node |
DEFAULT_TEST_TIMEOUT_MS |
constant | arcane-os |
Events, processes, and testing | Node |
describeTargets() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
developApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
discoverPackagerApps() |
function | arcane-os |
Packaging and release bundles | Node |
doctorApplication() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
doctorNativeTarget() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
ERROR_CODES |
constant | arcane-os |
Errors | Node |
errorRecord() |
function | arcane-os |
Errors | Node |
executeNativeBuildPlan() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
executeOperation() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
fail() |
function | arcane-os |
Errors | Node |
generateDocumentImportMaps() |
function | arcane-os |
Runtime and app descriptors | Node; explicit documents and an existing materialized runtime |
getSdkBrowserRuntimeRoot() |
function | arcane-os |
Runtime and app descriptors | Node |
getSdkRoot() |
function | arcane-os |
Runtime and app descriptors | Node |
getTargetAdapter() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
incrementSemver() |
function | arcane-os/packager |
Packaging and release bundles | Node |
initializeApplication() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
initWorkspace() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
inspectApp() |
function | arcane-os |
Packaging and release bundles | Node |
inspectWorkspaceProfile() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
INTEGRATED_TOOLCHAIN_PROTOCOL |
constant | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
listRuntimeFiles() |
function | arcane-os |
Runtime and app descriptors | Node |
listSdkBrowserRuntimeFiles() |
function | arcane-os |
Runtime and app descriptors | Node |
listTargets() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
loadAppDescriptor() |
function | arcane-os |
Runtime and app descriptors | Node |
loadArcaneIntegratedProvider() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
loadArcaneNativeProvider() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
loadRuntimeRelease() |
function | arcane-os |
Runtime and app descriptors | Node |
loadSdkBrowserRuntimeRelease() |
function | arcane-os |
Runtime and app descriptors | Node |
materializeInstalledSdkRuntime() |
function | arcane-os |
Runtime and app descriptors | Node |
materializeWorkspaceRuntimeContent() |
function | arcane-os |
Runtime and app descriptors | Node |
MarkdownSpeech |
class | arcane-os/speech-text |
Portable runtime modules | Node and browser |
NATIVE_BUILD_PLAN_PROTOCOL |
constant | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
NATIVE_BUILDER_PROTOCOL |
constant | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
normalizeError() |
function | arcane-os |
Errors | Node |
normalizeRelativePath() |
function | arcane-os/packager |
Packaging and release bundles | Node |
OUTPUT_MODES |
constant | arcane-os |
Identity and protocol constants | Node |
packageApp() |
function | arcane-os |
Packaging and release bundles | Node |
packageApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
PACKAGER_VERSION |
constant | arcane-os/packager |
Packaging and release bundles | Node |
packager.discoverApps() |
function | arcane-os/packager |
Packaging and release bundles | Node |
parseSemver() |
function | arcane-os/packager |
Packaging and release bundles | Node |
planApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
prepareNativeTarget() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
PreferenceStore default export |
class | arcane-os/preference-store |
Portable runtime modules | Node with injected adapters, or browser/native WebView storage |
PREFERENCE_STORE_ERROR_CODES |
constant | arcane-os/preference-store |
Portable runtime modules | Node and browser |
PREFERENCE_STORE_EVENT_TYPES |
constant | arcane-os/preference-store |
Portable runtime modules | Node and browser |
Preference |
class | arcane-os/preference-store |
Portable runtime modules | Node and browser |
preferenceSchema() |
function | arcane-os/preference-store |
Portable runtime modules | Node and browser |
projectNativeDescriptor() |
function | arcane-os |
Runtime and app descriptors | Node |
projectPackageManifest() |
function | arcane-os |
Runtime and app descriptors | Node |
readRuntimeFile() |
function | arcane-os |
Runtime and app descriptors | Node |
readSdkBrowserRuntimeFile() |
function | arcane-os |
Runtime and app descriptors | Node |
registeredTestCount() |
function | arcane-os |
Events, processes, and testing | Node |
RELEASE_MANIFEST_NAME |
constant | arcane-os/packager |
Packaging and release bundles | Node |
repositoryApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
repositoryPull() |
function | arcane-os |
Workspace, doctor, repository, and server | Node; network-assisted Git |
repositoryPush() |
function | arcane-os |
Workspace, doctor, repository, and server | Node; network-assisted Git |
repositoryStatus() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
resolveNativeBuildOutputRoot() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
resolvePwaRetirementResponse() |
function | arcane-os |
Workspace, doctor, repository, and server | Node; browser service-worker lifecycle remains browser-owned |
resolveWorkspace() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
ROOT_CONFIG_NAME |
constant | arcane-os/packager |
Packaging and release bundles | Node |
discoverApps() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
runApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
runDoctor() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
runProcess() |
function | arcane-os |
Events, processes, and testing | Node |
createGitTextSnapshot() |
function | arcane-os |
Workspace, doctor, repository, and server | Node with Git |
runRegisteredTests() |
function | arcane-os |
Events, processes, and testing | Node |
runRepositoryAction() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
runTarget() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
RUNTIME_ROOT |
constant | arcane-os |
Identity and protocol constants | Node |
SDK_NAME |
constant | arcane-os |
Identity and protocol constants | Node |
SDK_ROOT |
constant | arcane-os |
Identity and protocol constants | Node |
SDK_VERSION |
constant | arcane-os |
Identity and protocol constants | Node |
selectApp() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
SpeechPlayback default export |
class | arcane-os/speech-playback |
Portable runtime modules | Node with injected media adapters, or browser/native WebView media |
SPEECH_PLAYBACK_STATE_EVENT |
constant | arcane-os/speech-playback |
Portable runtime modules | Node and browser |
SPEECH_VOICE_ALIASES |
constant | arcane-os/speech-playback |
Portable runtime modules | Node and browser |
SPEECH_VOICE_OPTIONS |
constant | arcane-os/speech-playback |
Portable runtime modules | Node and browser |
SpeechPlayback |
class | arcane-os/speech-playback |
Portable runtime modules | Node with injected media adapters, or browser/native WebView media |
splitSpeechText() |
function | arcane-os/speech-playback |
Portable runtime modules | Node and browser |
stripSpeechFormatting() |
function | arcane-os/speech-text |
Portable runtime modules | Node and browser |
startDevServer() |
function | arcane-os |
Workspace, doctor, repository, and server | Node control plane; browser data plane |
startSourceExampleServer() |
function | arcane-os |
Workspace, doctor, repository, and server | Node control plane; browser data plane |
TARGET_ADAPTER_PROTOCOL |
constant | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
TARGET_IDS |
constant | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
test() |
function | arcane-os |
Events, processes, and testing | Node |
testApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
throwIfAborted() |
function | arcane-os |
Errors | Node |
upgradeApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
validateAppBundlePath() |
function | arcane-os |
Packaging and release bundles | Node |
validateAppConfig() |
function | arcane-os/packager |
Packaging and release bundles | Node |
validateAppDescriptor() |
function | arcane-os |
Runtime and app descriptors | Node |
validateNativeBuilder() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
validateRootConfig() |
function | arcane-os/packager |
Packaging and release bundles | Node |
validateWorkspace() |
function | arcane-os |
Workspace, doctor, repository, and server | Node |
verifyApp() |
function | arcane-os |
Packaging and release bundles | Node |
verifyApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
verifyAppReleaseBundle() |
function | arcane-os |
Packaging and release bundles | Node |
verifyBundleApplication() |
function | arcane-os |
Headless toolchain operations | Node; selected operation may produce browser or native output |
verifyNativeArtifact() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
verifyTarget() |
function | arcane-os |
Targets, native plans, and providers | Node; selected browser/native target or provider as documented |
SDK_UPDATE_REGISTRY |
constant | arcane-os |
Explicit SDK update checks | Node; on-demand CLI or maintainer check only |
SDK_UPDATE_TIMEOUT_MS |
constant | arcane-os |
Explicit SDK update checks | Node; on-demand CLI or maintainer check only |
checkForSdkUpdate() |
function | arcane-os |
Explicit SDK update checks | Node; on-demand CLI or maintainer check only |
checkSdkUpdate() |
function | arcane-os |
Explicit SDK update checks | Node; on-demand CLI or maintainer check only |
compareSdkVersions() |
function | arcane-os |
Explicit SDK update checks | Node; on-demand CLI or maintainer check only |
updateTagForVersion() |
function | arcane-os |
Explicit SDK update checks | Node; on-demand CLI or maintainer check only |
validateUpdateRegistry() |
function | arcane-os |
Explicit SDK update checks | Node; on-demand CLI or maintainer check only |
ARCANE_EVENT_AUTHORITY_BRAND |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
ARCANE_EVENT_AUTHORITY_KIND |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
ARCANE_EVENT_AUTHORITY_PROTOCOL |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
ARCANE_EVENT_ERROR_CODES |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
ARCANE_EVENT_LISTENER_ERROR_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
ARCANE_EVENT_OCCURRENCE_PROTOCOL |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
ARCANE_EVENT_SOURCE_DISPOSED_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
ARCANE_EVENT_SOURCE_KIND |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
ARCANE_EVENT_SOURCE_PROTOCOL |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
ARCANE_EVENT_STACK_PROTOCOL |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
DEFAULT_DOM_EVENT_TYPES |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler; meaningful to browser DOM instrumentation |
DOM_INTERACTION_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Browser DOM or a DOM-compatible test host; constant imports in Node |
DOM_MUTATION_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Browser DOM or a DOM-compatible test host; constant imports in Node |
DOM_OBSERVATION_STARTED_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Browser DOM or a DOM-compatible test host; constant imports in Node |
DOM_OBSERVATION_STOPPED_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Browser DOM or a DOM-compatible test host; constant imports in Node |
EventManager |
class | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler; DOM capture requires a compatible DOM |
PLAYBACK_CANCELLED_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
PLAYBACK_COMPLETED_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
PLAYBACK_FAILED_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
PLAYBACK_RECORD_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
PLAYBACK_STARTED_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
TIME_TRAVEL_SEEK_EVENT |
constant | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
arcaneEvents |
singleton | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler; DOM capture requires a compatible DOM |
createArcaneEventSource() |
function | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
createDOMInstrumentation() |
function | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Browser DOM or a DOM-compatible test host |
createEventManager() |
function | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler; DOM capture requires a compatible DOM |
describeDOMTarget() |
function | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Browser DOM or DOM-compatible objects; importable in Node |
domSelector() |
function | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Browser DOM or DOM-compatible objects; importable in Node |
isArcaneEventOccurrence() |
function | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
parseEventStack() |
function | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Node and browser/bundler |
projectArcaneDOMEvent() |
function | arcane-os/event-manager |
Central events, time travel, and DOM instrumentation | Browser DOM or a DOM-compatible test host |
CORE_PROTOCOL |
constant | arcane-os/core/contracts |
Core protocol contracts | Node and browser/bundler |
CORE_READY_EVENTS |
constant | arcane-os/core/contracts |
Core protocol contracts | Node and browser/bundler |
CORE_FRAME_CONTRACTS |
constant | arcane-os/core/contracts |
Core protocol contracts | Node and browser/bundler |
CORE_METHOD_CONTRACTS |
constant | arcane-os/core/contracts |
Core protocol contracts | Node and browser/bundler |
CoreError |
class | arcane-os/core/contracts |
Core protocol contracts | Node and browser/bundler |
serializeCoreError() |
function | arcane-os/core/contracts |
Core protocol contracts | Node and browser/bundler |
createCoreClient() |
function | arcane-os/core/client |
Core browser client | Browser and native WebView JavaScript hosts |
createCoreFacade() |
function | arcane-os/core/client |
Core browser client | Browser and native WebView JavaScript hosts |
installCoreClient() |
function | arcane-os/core/client |
Core browser client | Browser and native WebView JavaScript hosts |
getInstalledCoreClient() |
function | arcane-os/core/client |
Core browser client | Browser and native WebView JavaScript hosts |
subscribeCoreClient() |
function | arcane-os/core/client |
Core browser client | Browser and native WebView JavaScript hosts |
createDevelopmentCore() |
function | arcane-os/core/development, arcane-os |
Core source development | Node on Windows, Linux and macOS; Android requires host adaptation |
createCodexAppServerSession() |
function | arcane-os/codex/app-server |
Native Codex sessions | Node with an explicitly selected Codex App Server executable |
openCodexAppServerSession() |
function | arcane-os/codex/app-server |
Native Codex sessions | Node with an explicitly selected Codex App Server executable |
createMcpStdioServer() |
function | arcane-os/mcp/stdio |
MCP STDIO | Node streams on Windows, Linux and macOS; Android needs host adaptation |
MCP_PROTOCOL_VERSION |
constant | arcane-os/mcp/stdio |
MCP STDIO | Node |
McpProtocolError |
class | arcane-os/mcp/stdio |
MCP STDIO | Node |
createCoreClassicSource() |
function | arcane-os/core/classic-source |
Core classic client projection | Node; generated source runs in browser and native WebView renderers |
createCoreRuntime() |
function | arcane-os/core/runtime |
Native Core runtime | Node on Windows, Linux and macOS native hosts; Android requires host adaptation |
createModelObservationService() |
function | arcane-os/core/model-observation |
Existing model observation | Node with an existing Core runtime and optional existing native model services |
attachModelObservation() |
function | arcane-os/ai/model-observation |
Existing model observation | JavaScript with an existing Core client and optional existing renderer owners |
subscribeModelObservation() |
function | arcane-os/ai/model-observation |
Existing model observation | JavaScript with an existing Core client and composed observation service |
acquireCoreDocument() |
function | arcane-os/document-acquisition |
Native document acquisition | Browser or native WebView with an existing Core client and selected document service |
createDocumentAcquisitionService() |
function | arcane-os/core/document-acquisition |
Native document acquisition | Node Core on Windows, Linux and macOS; Android requires host adaptation |
encodeCoreFrame() |
function | arcane-os/core/stdio |
Native Core stdio transport | Node |
createCoreFrameDecoder() |
function | arcane-os/core/stdio |
Native Core stdio transport | Node |
startCoreStdio() |
function | arcane-os/core/stdio |
Native Core stdio transport | Node |
createPortableNativeProvider() |
function | arcane-os/native/portable-provider |
Portable native provider | Node; produces a portable payload rather than an executable host |
arcaneNativeBuilderProvider |
singleton | arcane-os/native/portable-provider |
Portable native provider | Node; produces a portable payload rather than an executable host |
arcaneNativeBuilderProvider default export |
singleton | arcane-os/native/portable-provider |
Portable native provider | Node; produces a portable payload rather than an executable host |
startCoreHost() |
function | arcane-os/core/host |
Native Core host composition | Node with readable input and writable output streams |
startCoreListener() |
function | arcane-os/core/host |
Shared Core host | Node local IPC attached to an existing runtime |
startSharedCoreHost() |
function | arcane-os/core/host |
Shared Core host | Node local IPC on Windows, Linux and macOS |
connectSharedCoreHost() |
function | arcane-os/core/host |
Shared Core host | Node local IPC and optional explicit headless startup |
connectAppControl() |
function | arcane-os/core/app-control |
Native application control | Node local IPC; current window adapter is Windows WebView2 |
runSharedCoreHost() |
function | arcane-os/core/host |
Shared Core host | Node headless entry and optional parent startup IPC |
startSharedCoreBridge() |
function | arcane-os/core/host |
Shared Core host | Node readable/writable streams and local IPC |
readCoreLaunchContext() |
function | arcane-os/core/host |
Native Core host composition | Node; combines packaged defaults, host state and explicitly selected launch JSON |
resolveNativeLaunchContext() |
function | arcane-os/core/host |
Native Core host composition | Node native paths; Android supplies its adapted state root |
resolveArcaneDataPaths() |
function | arcane-os/core/repositories |
Native repository workspaces | Node on Windows, Linux and macOS; Android supplies its data root |
createRepositoryWorkspace() |
function | arcane-os/core/repositories |
Native repository workspaces | Node with Git; Android requires host process adaptation |
readGitIdentity() |
function | arcane-os/core/repositories |
Native repository workspaces | Node with Git; Android requires host process adaptation |
createWindowsNativeProvider() |
function | arcane-os/native/windows-provider |
Windows native provider | Node assembly; Windows x64/WebView2 execution |
arcaneNativeBuilderProvider |
singleton | arcane-os/native/windows-provider |
Windows native provider | Node assembly; Windows x64/WebView2 execution |
arcaneNativeBuilderProvider default export |
singleton | arcane-os/native/windows-provider |
Windows native provider | Node assembly; Windows x64/WebView2 execution |
createMacOSNativeProvider() |
function | arcane-os/native/macos-provider |
macOS native provider | Node assembly; matching Darwin architecture and selected host asset |
arcaneNativeBuilderProvider |
singleton | arcane-os/native/macos-provider |
macOS native provider | Node assembly; matching Darwin architecture and selected host asset |
arcaneNativeBuilderProvider default export |
singleton | arcane-os/native/macos-provider |
macOS native provider | Node assembly; matching Darwin architecture and selected host asset |
createPackagedWebService() |
function | arcane-os/core/packaged-web |
Native packaged web serving | Node Core lifetime; actual listener readiness before navigation |
createPreferencesService() |
function | arcane-os/core/preferences |
Core preference persistence | Node Core runtime with an application-selected file |
createPreferencesService default export |
function | arcane-os/core/preferences |
Core preference persistence | Same Core service factory |
createDiarization() |
function | arcane-os/diarization |
Native speaker diarization | Node with a built helper, selected NeMo libraries and caller-selected model |
buildDiarizationHelper() |
function | arcane-os/diarization/build |
Native speaker diarization | Node with installed CMake/C++17 toolchain and selected runtime |
createDiarizationService() |
function | arcane-os/core/diarization |
Native speaker diarization | Node Core runtime with explicitly selected helper, runtime and model |
createDiarizationService default export |
function | arcane-os/core/diarization |
Native speaker diarization | Same Core service factory |
createCoreLocalAIProvider() |
function | arcane-os/ai/core-local |
Core local AI | Browser/native WebView with an available Core connection |
createLocalAIService() |
function | arcane-os/core/local-ai |
Core local AI | Node with selected llama.cpp/Ollama/ONNX runtimes |
createONNXRuntime() |
function | arcane-os/local-ai/onnx |
Core local AI | Node with prepared Microsoft ONNX runtime |
createCoreONNXRuntime() |
function | arcane-os/ai/core-onnx |
Core local AI | Browser with an available Core ONNX service |
createImageRuntime() |
function | arcane-os/local-ai/image |
Core local images | Node with a prepared native image runtime and caller-selected model |
createCoreImageRuntime() |
function | arcane-os/ai/core-image |
Core local images | Browser with an available Core image service |
createLocalImageService() |
function | arcane-os/core/image |
Core local images | Node Core with selected stable-diffusion.cpp requirements |
createLocalImageService default export |
function | arcane-os/core/image |
Core local images | Same native image service factory |
createSpeechService() |
function | arcane-os/core/speech |
Core native speech | Node Core with explicitly supplied speech engines |
createNativeKokoroRuntime() |
function | arcane-os/local-ai/kokoro |
Core native speech | Node with matching prepared helper/data, selected model resources and an existing ONNX owner |
createNativeKokoroRuntime default export |
function | arcane-os/local-ai/kokoro |
Core native speech | Same retained native Kokoro factory |
KOKORO_MODEL |
constant | arcane-os/local-ai/kokoro |
Core native speech | Selected upstream model identifier |
KOKORO_REVISION |
constant | arcane-os/local-ai/kokoro |
Core native speech | Selected upstream model revision |
KOKORO_SAMPLE_RATE |
constant | arcane-os/local-ai/kokoro |
Core native speech | Native PCM sample rate |
KOKORO_VOICES |
constant | arcane-os/local-ai/kokoro |
Core native speech | Complete 28-voice US/GB selection |
createNemotronRuntime() |
function | arcane-os/local-ai/nemotron |
Core native speech | Node with a matching first-party helper, selected NeMo ASR runtime and models; Windows/Linux/macOS source, Android host adaptation |
NEMO_SPEECH_MODELS |
constant | arcane-os/local-ai/nemotron |
Core native speech | Node; selected upstream model catalog, no acquisition at import |
prepareNemotronModels() |
function | arcane-os/local-ai/nemotron |
Core native speech | Node with the shared model-assets service |
prepareMagpieModels() |
function | arcane-os/local-ai/nemotron |
Core native speech | Node with the shared model-assets service |
createNemotronRuntime default export |
function | arcane-os/local-ai/nemotron |
Core native speech | Same named function |
buildNemotronHelper() |
function | arcane-os/local-ai/nemotron/build |
Core native speech | Node with CMake 3.26+, C++17 toolchain and platform-matching public NeMo ASR headers/libraries/CMake package |
buildNemotronHelper default export |
function | arcane-os/local-ai/nemotron/build |
Core native speech | Same named function |
createMagpieRuntime() |
function | arcane-os/local-ai/magpie |
Core native speech | Node with a matching first-party helper, selected NeMo TTS runtime, Magpie/tokenizer and NanoCodec assets; Windows/Linux/macOS source, Android host adaptation |
createMagpieRuntime default export |
function | arcane-os/local-ai/magpie |
Core native speech | Same named function |
buildMagpieHelper() |
function | arcane-os/local-ai/magpie/build |
Core native speech | Node with CMake 3.26+, C++17 toolchain, platform threads and matching public NeMo TTS headers/libraries/CMake package |
buildMagpieHelper default export |
function | arcane-os/local-ai/magpie/build |
Core native speech | Same named function |
createWhisperRuntime() |
function | arcane-os/local-ai/whisper |
Core native speech | Node with a prepared matching helper, runtime, decoder and selected model |
createWhisperRuntime default export |
function | arcane-os/local-ai/whisper |
Core native speech | Same retained native engine factory |
buildWhisperHelper() |
function | arcane-os/local-ai/whisper/build |
Core native speech | Node with installed CMake/C++17 toolchain and matching Whisper source/runtime |
buildWhisperOpenVinoRuntime() |
function | arcane-os/local-ai/whisper/openvino-build |
Core native speech | Windows x64 Node with installed matching Whisper/OpenVINO sources and CMake/MSVC toolchain |
createSpeechService default export |
function | arcane-os/core/speech |
Core native speech | Same shared speech service factory |
prepareCoreModelAssets() |
function | arcane-os/ai/core-model-assets |
Core model assets | Browser with complete Blob/File members and available Core service |
discoverCoreModelAssets() |
function | arcane-os/ai/core-model-assets |
Core model assets | Browser with an available model-assets Core service |
openExistingCoreModelAssets() |
function | arcane-os/ai/core-model-assets |
Core model assets | Browser with an available model-assets Core service |
downloadCoreModelAssets() |
function | arcane-os/ai/core-model-assets |
Core model assets | Browser with an available model-assets Core service |
createModelAssetService() |
function | arcane-os/core/model-assets |
Core model assets | Node Core with an application-selected working directory |
createModelAssetService default export |
function | arcane-os/core/model-assets |
Core model assets | Same native working-file service factory |
createLocalAIService default export |
function | arcane-os/core/local-ai |
Core local AI | Same native service factory |
ensureLocalAIRuntimes() |
function | arcane-os/local-ai |
Core local AI | Node; selected upstream platform assets |
bundleLocalAIRuntimes() |
function | arcane-os/local-ai |
Core local AI | Node; complete native runtime assembly |
MAIL_OUTBOX_IDEMPOTENCY_WINDOW_MS |
constant | arcane-os/mail |
Portable Mail | Node and browser metadata |
MAIL_OUTBOX_PROTOCOL |
constant | arcane-os/mail |
Portable Mail | Node and browser metadata |
MAIL_OUTBOX_STATES |
constant | arcane-os/mail |
Portable Mail | Node and browser metadata |
MAIL_OUTBOX_TABLE |
constant | arcane-os/mail |
Portable Mail | Node and browser metadata |
Mail |
class | arcane-os/mail |
Portable Mail | Node with injected host adapters, or browser/native WebView with durable storage and Web Locks |
MailOutbox |
class | arcane-os/mail |
Portable Mail | Node or browser with injected DBOPFS-compatible storage and a Web Locks-compatible lock manager |
MailTransportError |
class | arcane-os/mail |
Portable Mail | Node and browser |
createMailOutbox() |
function | arcane-os/mail |
Portable Mail | Node or browser with the required injected outbox adapters |
Mail default export |
class | arcane-os/mail |
Portable Mail | Node with injected host adapters, or browser/native WebView with durable storage and Web Locks |
normalizeMailEndpoint() |
function | arcane-os/mail |
Portable Mail | Node and browser with URL support; relative endpoints require an explicit or global base URL |
resolveMailConfig() |
function | arcane-os/mail |
Portable Mail | Node with explicit configuration, or browser/native WebView with optional document and location defaults |
sendMailReport() |
function | arcane-os/mail |
Portable Mail | Node and browser with Fetch and AbortController, or an explicit fetch implementation |
serializeMailReport() |
function | arcane-os/mail |
Portable Mail | Node and browser |
arcaneLogging |
singleton | arcane-os/logging |
Shared logging | Node and browser |
readArcaneDeveloperMode() |
function | arcane-os/logging |
Shared logging | Node and browser |
Packaging and release bundles
APPBUNDLEDESCRIPTOR_NAME
Overview
Canonical descriptor filename stored in an external application release bundle.
Value and import
const APP_BUNDLE_DESCRIPTOR_NAME
Import it from arcane-os or arcane-os/release-bundle. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {APP_BUNDLE_DESCRIPTOR_NAME} from 'arcane-os';
console.log(APP_BUNDLE_DESCRIPTOR_NAME);
APPBUNDLEEXTENSION
Overview
Required filename extension for deterministic external application release bundles.
Value and import
const APP_BUNDLE_EXTENSION
Import it from arcane-os or arcane-os/release-bundle. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {APP_BUNDLE_EXTENSION} from 'arcane-os';
console.log(APP_BUNDLE_EXTENSION);
APPBUNDLEFORMAT
Overview
Canonical archive encoding used by external application release bundles.
Value and import
const APP_BUNDLE_FORMAT
Import it from arcane-os or arcane-os/release-bundle. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {APP_BUNDLE_FORMAT} from 'arcane-os';
console.log(APP_BUNDLE_FORMAT);
APPBUNDLEKIND
Overview
Stable manifest kind identifying an Arcane application release bundle.
Value and import
const APP_BUNDLE_KIND
Import it from arcane-os or arcane-os/release-bundle. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {APP_BUNDLE_KIND} from 'arcane-os';
console.log(APP_BUNDLE_KIND);
APPBUNDLEMANIFEST_NAME
Overview
Canonical bundle-envelope manifest filename.
Value and import
const APP_BUNDLE_MANIFEST_NAME
Import it from arcane-os or arcane-os/release-bundle. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {APP_BUNDLE_MANIFEST_NAME} from 'arcane-os';
console.log(APP_BUNDLE_MANIFEST_NAME);
APPBUNDLERELEASE_PATH
Overview
Canonical path of the packaged release manifest inside a bundle payload.
Value and import
const APP_BUNDLE_RELEASE_PATH
Import it from arcane-os or arcane-os/release-bundle. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {APP_BUNDLE_RELEASE_PATH} from 'arcane-os';
console.log(APP_BUNDLE_RELEASE_PATH);
APPBUNDLESCHEMA_VERSION
Overview
Current immutable bundle-envelope schema version.
Value and import
const APP_BUNDLE_SCHEMA_VERSION
Import it from arcane-os or arcane-os/release-bundle. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {APP_BUNDLE_SCHEMA_VERSION} from 'arcane-os';
console.log(APP_BUNDLE_SCHEMA_VERSION);
APPBUNDLESUPPORTEDSDKVERSIONS
Overview
Exact SDK generations accepted by this bundle verifier.
Value and import
const APP_BUNDLE_SUPPORTED_SDK_VERSIONS
Import it from arcane-os/release-bundle. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {APP_BUNDLE_SUPPORTED_SDK_VERSIONS} from 'arcane-os/release-bundle';
console.log(APP_BUNDLE_SUPPORTED_SDK_VERSIONS);
APPCONFIGNAME
Overview
Canonical schema-1 application package configuration filename used by the packager.
Value and import
const APP_CONFIG_NAME
Import it from arcane-os/packager. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {APP_CONFIG_NAME} from 'arcane-os/packager';
console.log(APP_CONFIG_NAME);
bumpVersion()
Overview
Updates the authored arcane-package.json version for one selected application.
This is a development-time metadata operation. It never updates the Arcane SDK,
the synchronized runtime, an installed application, or an Arcane OS host.
Signature, parameters, and result
async bumpVersion(options)
Import it from arcane-os/packager. options.workspaceRoot and options.appId
select one configured app. Supply exactly one of bump ("major", "minor",
"patch", or "prerelease") and exactVersion; preid customizes a
prerelease bump and defaults to "rc". dryRun defaults to false.
The promise resolves to
{app, currentVersion, version, bump, dryRun}. bump is null when an exact
version was selected. A dry run validates and calculates the result without
writing or acquiring the operation lock. A non-dry run acquires the selected
app's packager lock under dist/, then atomically replaces only its
arcane-package.json version through temporary and backup files.
This function has no signal, onEvent, or receipt parameter: once started it
has no public cancellation or progress-event contract. It rejects invalid or
unchanged versions, conflicting bump/exactVersion inputs, an invalid
workspace/app, an active or stale packager lock, and filesystem failures. The
lock is released in finally; an unrecoverable replacement failure can leave
the documented backup file for manual recovery.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {bumpVersion} from 'arcane-os/packager';
async function previewNextPrerelease(workspaceRoot) {
const result = await bumpVersion({
workspaceRoot,
appId: 'example-app',
bump: 'prerelease',
preid: 'beta',
dryRun: true
});
console.log(`${result.currentVersion} -> ${result.version}`);
return result;
}
createAppReleaseBundle()
Overview
Writes one deterministic USTAR+gzip external application bundle from the selected
authored release state. Long or non-ASCII filenames use per-file POSIX PAX path
extensions, preserving their complete UTF-8 spelling and file content. Ordinary
USTAR entries remain unchanged. Metadata framing is excluded from the manifest's
logical file inventory. Existing portable-path rules, schema 1, and the
ustar+gzip format identifier remain unchanged.
Signature and result
async createAppReleaseBundle({releaseRoot, appDescriptor, outputPath, overwrite=false, signal, onEvent}={})
Import it from arcane-os or arcane-os/release-bundle. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {createAppReleaseBundle} from 'arcane-os';
async function usecreateAppReleaseBundle(...arguments_) {
return createAppReleaseBundle(...arguments_);
}
createCanonicalUstarHeader()
Overview
Builds the exact 512-byte canonical USTAR header for one validated bundle entry.
This low-level helper remains a single regular-file header with the USTAR field
limits. Use createAppReleaseBundle() to encode complete long or Unicode paths;
the bundle writer supplies PAX framing where needed.
Signature and result
createCanonicalUstarHeader(entryPath, size)
Import it from arcane-os or arcane-os/release-bundle. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {createCanonicalUstarHeader} from 'arcane-os';
async function usecreateCanonicalUstarHeader(...arguments_) {
return createCanonicalUstarHeader(...arguments_);
}
discoverPackagerApps()
Overview
Root-entry alias for the packager-specific application discovery function.
Signature and result
async discoverPackagerApps({workspaceRoot:requestedWorkspaceRoot})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {discoverPackagerApps} from 'arcane-os';
async function usediscoverPackagerApps(...arguments_) {
return discoverPackagerApps(...arguments_);
}
incrementSemver()
Overview
Returns a validated semantic version incremented by the requested bump and optional prerelease id.
Signature and result
incrementSemver(value, bump, preid)
Import it from arcane-os/packager. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {incrementSemver} from 'arcane-os/packager';
console.log(incrementSemver('1.2.3', 'minor'));
inspectApp()
Overview
Loads one validated packager app plan, including the shared directly navigable descriptor-selected browser document inventory.
Signature and result
async inspectApp({workspaceRoot, appId, signal, target, outputDirectory}={})
Import it from arcane-os or arcane-os/packager. The result includes the
configured entry, include, and exclude values, the optional documents
declaration when authored, and browserDocuments, the entry-first ordered
.html/.htm paths shared by import-map refresh, development and packaging.
package.documents in an authored descriptor, or documents in a schema-1
package, selects literal app-root-relative paths already included and not
excluded. Other selected paths follow the entry in deterministic lexical order
without duplicates. The authored documents declaration remains as supplied,
including [], which selects only the entry. Omitting the property retains
automatic discovery of the entry and included secondary pages with an active <base>. App identity
meta tags do not select documents.
Selected pages retain their existing base requirements. Explicit selection leaves other included HTML documents unchanged, including iframe-referenced originals, while preserving package, serving and offline resource membership. Component processing and shared runtime-resource traversal retain their existing behavior. See application document selection.
entry and each app browser document's path stay relative to the app
directory. Each browser document also reports packagePath, the emitted path
such as apps/hello-world/index.html. The complete files inventory uses
package-relative paths and includes the root index.html. Shared
files retain their configured route destinations.
target defaults to 'browser'. A selected nonbrowser target adds the app's
explicit nativeResources to files, without adding those native-only paths
to browserDocuments. The optional normalized nativeResources record is
returned when authored. This inspection copies or executes no resources.
output is the selected workspace-relative final package directory. An explicit
operation outputDirectory wins. Otherwise, a nonbrowser target with a nonempty
native include list uses dist/.native/<target>/<app-id>; the app's saved browser
destination remains separate. Browser selection, omitted native resources and
an empty native include list use the app's saved outputDirectory or
dist/<app-id>. The SDK appends no app ID to an explicit destination. See
native-only application resources.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {inspectApp} from 'arcane-os';
const plan=await inspectApp({workspaceRoot:process.cwd(),appId:'hello-world'});
console.log(plan.browserDocuments);
normalizeRelativePath()
Overview
Normalizes one portable repository-relative path and rejects traversal, aliases, links, and unsafe names.
Signature and result
normalizeRelativePath(value, label='path')
Import it from arcane-os/packager. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {normalizeRelativePath} from 'arcane-os/packager';
console.log(normalizeRelativePath('apps/example/index.html'));
packageApp()
Overview
Builds one complete selected application release through the low-level packager API, with browser selection by default. It does not run tests or checks automatically; verification occurs only when explicitly requested or when required for this selected release output.
Signature and result
async packageApp(options)
Import it from arcane-os or arcane-os/packager. Packaging consumes the saved
source and managed import maps. Refresh maps through arcane import-map or
ordinary arcane dev startup before selecting output that needs updated maps.
The package preserves the complete selected content, applying the documented
asset-version and enabled browser-PWA transformations to resource references.
Malformed configuration or descriptors fail while preserving the prior output.
target defaults to 'browser'; supported target names are browser,
portable, windows-x64, linux-x64, linux-arm64 and android-arm64.
A nonbrowser target adds the app's explicit nativeResources selection and
sets the effective browserPwa value to false. It does not compile or launch
that platform. Browser calls preserve the existing browserPwa default and
explicit setting. The app adapter's buildArcanePackage() context receives
the actual target and effective browserPwa alongside its existing fields.
copyBase() retains the browser/shared selection; native-only resources are
copied afterward, outside browser rewriting and PWA processing.
moduleFormat controls browser module representation independently of target.
In particular, moduleFormat:'native' alone remains a browser package and does
not add native resources. The complete selection and separate-output rules are
documented under native-only application resources.
moduleFormat defaults to 'import-map', preserving the ordinary browser
package. Select 'native' to resolve saved document import maps into native
module URLs in the package stage and emit executable inline scripts as external
files. Static imports, re-exports, string-literal dynamic imports and
string-literal import.meta.resolve() retain exact/prefix/scoped mappings.
Imported HTML components use the shared HTMLImport externally executable
script path, retaining their host binding and asynchronous lifecycle. No
application-owned module loader is needed. Source HTML, saved data and the
ordinary browser output remain unchanged. See
native-module package output
for resource handling and the static transformation boundary.
browserDecisions defaults to false. Explicit browserDecisions: true
acquires the bundled Transformers.js 4.3.0 entry, matching ONNX Runtime
1.31.0-dev.20260914-8d85527a0 asyncify module/WASM and both licenses into
the package stage beside the selected SDK ai/browser-decisions.mjs, under
decisions-runtime/. Installed-package routes retain their configured
dependency path, including aliases; source and installed dependencies remain
unchanged, with no workspace-root arcane/ projection. The selected SDK decision
module must be included in the package. Acquisition happens after native-module
and asset rewriting, preserving upstream content unchanged in both module
formats. The distribution joins the returned and release-manifest inventories
and any enabled PWA's ordinary offline selection. The default and dry runs
perform no optional acquisition; dry runs report selected inputs. Repeat this
option on each package build that should acquire the closure. Cancellation and
HTTP or observer failures abort/join acquisition before stage cleanup and
preserve previous output. The existing workspace.decisions.started and
workspace.decisions.progress events report file progress. See the
extension-local decision guide
for runtime.local: true, upstream versions and complete error details.
An operation may override outputDirectory without changing the saved app
configuration. For example, package a complete application beneath an
application-owned extension manifest and launcher:
const release = await packageApp({
workspaceRoot,
appId: 'moon-dashboard',
outputDirectory: 'dist/extension/app',
moduleFormat: 'native',
browserPwa: false
});
The override uses the same workspace-relative destination and staged replacement
rules as the saved field. It replaces only dist/extension/app, leaving its
extension-root siblings and an existing browser output intact. browserPwa:false
omits generated PWA artifacts and removes their active references from selected
output documents before native-module processing. This removes SDK-marked
data-arcane-pwa scripts and manifest relationships resolving to the package's
arcane.webmanifest, preserving unrelated authored links and inactive HTML.
It does not change source documents or the app's saved PWA configuration.
The app owns extension metadata, permissions and toolbar
launch behavior. This API builds the application directory, not an extension
manifest or an operating-system launcher. Native-mode dry runs report selected
input files; generated script/context files are included in the completed
package's full returned inventory.
For browser selection, the app's optional schema-1 outputDirectory selects the
final workspace-relative destination. For example, "ai" emits directly into
<workspace>/ai; omission retains dist/<app-id>. The selected directory is
wholly replaced through the existing staged swap, not merged. Changing the
destination preserves the former output and siblings. Conflicting source,
selected input, or required control paths fail before output writes. Source
layout, app identity, OPFS scope, and internal package paths remain unchanged.
See app-selected package output.
For a nonbrowser target with a nonempty native include list, the default is
instead dist/.native/<target>/<app-id>, preserving a separately emitted browser
output even when its saved destination is custom. An explicit operation
outputDirectory still wins; choose a dedicated destination because packaging
replaces that selected directory. Omitted or empty native resources retain the
existing destination rules.
Root app files retain their paths at the output root; explicitly nested apps
retain their apps/<id>/ paths. Shared files retain their configured route
destinations. When the selected content supplies no root index.html, the SDK
generates one that opens the selected app page. The result
contains outputRoot, manifest, and the complete files inventory.
manifest.app.entry stays app-relative, while manifest.app.start
is the package launch URL, such as ./index.html for a root app or
./apps/hello-world/index.html for a nested app. Only when selected records
supply an authored output-root index does the release add
manifest.app.rootDocument: "./index.html". Preview serves that explicit
document at /; without the field, older releases and generated-launcher
packages retain the 302 redirect to app.start or the older app.entry
fallback with the request query preserved. This generated release fact adds no
app configuration or API option, changes no app.start, and requires no HTML
content inference. Release
schema 1, kind arcane-app-release, and packager identity
arcane-app-packager-v1 remain unchanged. A dry run returns the planned output
and file inventory without writing source or output.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {packageApp} from 'arcane-os';
const packaged = await packageApp({
workspaceRoot: process.cwd(),
appId: 'hello-world'
});
console.log(packaged.manifest.app.start, packaged.files);
PACKAGER_VERSION
Overview
Builder identity written into schema-1 application release manifests.
Value and import
const PACKAGER_VERSION
Import it from arcane-os/packager. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {PACKAGER_VERSION} from 'arcane-os/packager';
console.log(PACKAGER_VERSION);
packager.discoverApps()
Overview
Discovers packager application configurations and release boundaries beneath one workspace root.
Signature and result
async discoverApps({workspaceRoot:requestedWorkspaceRoot})
Import it from arcane-os/packager. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {discoverApps} from 'arcane-os/packager';
async function usediscoverApps(...arguments_) {
return discoverApps(...arguments_);
}
parseSemver()
Overview
Parses one strict three-part semantic version with optional prerelease metadata.
Signature and result
parseSemver(value)
Import it from arcane-os/packager. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {parseSemver} from 'arcane-os/packager';
console.log(parseSemver('1.2.3'));
RELEASEMANIFESTNAME
Overview
Canonical packaged application release manifest filename.
Value and import
const RELEASE_MANIFEST_NAME
Import it from arcane-os/packager. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {RELEASE_MANIFEST_NAME} from 'arcane-os/packager';
console.log(RELEASE_MANIFEST_NAME);
ROOTCONFIGNAME
Overview
Canonical root packager configuration filename.
Value and import
const ROOT_CONFIG_NAME
Import it from arcane-os/packager. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {ROOT_CONFIG_NAME} from 'arcane-os/packager';
console.log(ROOT_CONFIG_NAME);
validateAppBundlePath()
Overview
Validates and normalizes one portable path selected inside an external app bundle.
Signature and result
validateAppBundlePath(value, label='bundle path')
Import it from arcane-os or arcane-os/release-bundle. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {validateAppBundlePath} from 'arcane-os';
console.log(validateAppBundlePath('payload/apps/example/index.html'));
validateAppConfig()
Overview
Validates one schema-1 packager app configuration and its relationship to the root config.
Optional nativeResources contains a required literal-path include array
(which may be empty) and optional exclude array (default []). It selects
additional app-owned resources only for a nonbrowser packaging target. Ordinary
include, exclude, shared routes and document selection remain unchanged.
Optional outputDirectory is the saved workspace-relative browser package
directory; omission preserves dist/<app-id>. Nonempty native selection uses
the separate target-selected default described above. It is an app package
field, not a change to the root configuration's distRoot or the schema-2 app identity. Packaging
reports conflicting output/input selections with ARCANE_PACKAGE_INVALID
before output writes. Authored-descriptor comparison treats the destination
as package-local, and descriptor refresh preserves the existing setting.
Signature and result
validateAppConfig(value, appId, rootConfig, configPath=`apps/${appId}/${APP_CONFIG_NAME}`)
Import it from arcane-os/packager. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {validateAppConfig} from 'arcane-os/packager';
async function usevalidateAppConfig(...arguments_) {
return validateAppConfig(...arguments_);
}
validateRootConfig()
Overview
Validates one root packager mapping and its fixed shared-route boundaries.
The schema-1 arcane-packager.json uses appsRoot: "." for standalone apps:
each app's root is its repository root. Managed-map refresh, development
serving, inspection and packaging use root app files and direct npm package
paths without generated nested app redirects or duplicate PWA files.
Installation identity and authored file selection remain unchanged.
Explicit appsRoot: "apps" supports real multi-app workspaces. See
standalone root applications.
Signature and result
validateRootConfig(value, configPath=ROOT_CONFIG_NAME)
Import it from arcane-os/packager. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {validateRootConfig} from 'arcane-os/packager';
async function usevalidateRootConfig(...arguments_) {
return validateRootConfig(...arguments_);
}
verifyApp()
Overview
Reads one existing application release and compares its complete file inventory with its release manifest through the low-level packager API.
Signature and result
async verifyApp({workspaceRoot, appId, outputDirectory, signal, onEvent})
Import it from arcane-os or arcane-os/packager. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Optional outputDirectory selects the same workspace-relative override accepted
by packageApp, without changing the app's saved destination.
For a target-selected native input release, pass the returned release.output
as this override. verifyApp has no target option and does not infer the native
directory or execute the application, its services or a platform host.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {verifyApp} from 'arcane-os';
// release is the result of packageApp() for this app and workspace.
const inspected = await verifyApp({
workspaceRoot,
appId: 'moon-dashboard',
outputDirectory: release.output
});
console.log(inspected.files);
verifyAppReleaseBundle()
Overview
Parses one deterministic app bundle without extraction and checks its structural
manifest and complete logical file inventory. It supports ordinary USTAR entries
and per-file POSIX PAX path extensions. The complete extended path is used by
files and readFile(); the metadata and regular-header placeholder are not
payload files. Malformed or orphaned PAX records produce ARCANE_BUNDLE_INVALID.
Other PAX attributes and archive member types remain unsupported. The existing
same-SDK-version condition remains unchanged. An older reader without PAX support
must be updated before importing a bundle that requires these path extensions.
Signature and result
async verifyAppReleaseBundle({bundlePath, signal, onEvent}={})
Import it from arcane-os or arcane-os/release-bundle. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. Normalized SDK validation with complete canonical archive and release content. Deep protocol: SDK packager and deterministic bundle contract.
Example
import {verifyAppReleaseBundle} from 'arcane-os';
async function useverifyAppReleaseBundle(...arguments_) {
return verifyAppReleaseBundle(...arguments_);
}
Runtime and app descriptors
APPDESCRIPTORNAME
Overview
Canonical schema-2 application descriptor filename.
Value and import
const APP_DESCRIPTOR_NAME
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {APP_DESCRIPTOR_NAME} from 'arcane-os';
console.log(APP_DESCRIPTOR_NAME);
APPDESCRIPTORSCHEMA_VERSION
Overview
Current authored application descriptor schema version.
Value and import
const APP_DESCRIPTOR_SCHEMA_VERSION
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {APP_DESCRIPTOR_SCHEMA_VERSION} from 'arcane-os';
console.log(APP_DESCRIPTOR_SCHEMA_VERSION);
generateDocumentImportMaps()
Overview
Writes SDK-managed inline browser import maps into explicitly selected HTML
documents. Hosts can keep their existing page layout and use an already
materialized Arcane runtime without an app descriptor, app discovery, or an
apps/<id>/ directory. The existing app-scoped arcane import-map operation
continues to own descriptor-selected application pages and its map artifact.
Signature and result
async generateDocumentImportMaps({
documentRoot,
runtimeRoot = path.join(documentRoot, 'arcane'),
documents,
version = SDK_VERSION,
deploymentUrl,
signal,
onEvent
} = {})
Import it from arcane-os.
| Input | Contract |
|---|---|
documentRoot |
Required filesystem directory containing the selected documents. Returned root paths are absolute. |
runtimeRoot |
Existing materialized runtime directory containing modules/, entities/, sdk/, and its other selected content. Defaults to arcane/ under documentRoot. Pass an absolute path when selecting another directory; relative root arguments resolve from the current working directory. |
documents |
Required nonempty array of document-root-relative file paths, such as ['shell/home.html', 'settings.html']. Use forward slashes and normalized paths without a leading ./ or parent traversal. Duplicate paths are processed once, in first-selected order. |
version |
Retained argument with default SDK_VERSION; generated local URLs stay clean and retired arcaneVersion fields are removed regardless of this value. Other authored query values and fragments remain unchanged. |
deploymentUrl |
Optional absolute directory URL ending in / that corresponds to documentRoot, such as https://example.com/control/. Required when a selected document has an absolute or root-relative base URL, or a relative base that traverses above documentRoot. |
signal |
Optional AbortSignal, observed during inventory, document preparation, and before each write. |
onEvent |
Optional named callback receiving the ordered events below. An asynchronous callback is awaited before the operation continues. |
The resolved result contains:
{
documentRoot,
runtimeRoot,
documentPaths,
documentCount,
documents: [{path, filePath, imports, scopes?}],
committed: true
}
documentPaths and each filePath are absolute filesystem paths. Each path
is relative to documentRoot; imports contains the global bindings rendered
for that document. Optional scopes contains dependency-specific bindings;
scope URLs and their targets are rebased with the same document base as global
imports. The operation inventories the runtime once, builds the shared map
once, and reads the selected documents with up to four concurrent readers.
It renders every document before writing any of them, then writes in selected
order. committed: true means all selected writes completed; the batch is not
an atomic filesystem transaction.
Document URLs and authored content
The first <base> with an href determines each document's effective base.
A target-only base, such as <base target="_blank">, does not change URL
resolution. With no base, shell/home.html resolves the default runtime through
../arcane/. With <base href="../">, the same page resolves it through
./arcane/. Generated local URLs stay clean regardless of the retained
version argument.
The host serves the runtime at the same relative location as runtimeRoot
has to documentRoot. deploymentUrl supplies that directory's public URL
when an authored base needs an origin or deployment path to resolve correctly.
For example, https://example.com/control/ corresponds to documentRoot, so
its default runtime is served at https://example.com/control/arcane/.
Cross-origin bases produce absolute runtime map URLs. Without deploymentUrl,
an absolute or root-relative base causes a TypeError before any document is
written. A relative base that traverses above documentRoot also requires
deploymentUrl, even if later path segments return into the physical directory:
the filesystem's parent names do not establish public deployment paths.
The two filesystem roots must share a volume.
The generator replaces only SDK-marked <script type="importmap" data-arcane-import-map> ranges, consolidating multiple SDK blocks into one.
It preserves complete authored HTML around those ranges, including whitespace,
resource URLs, custom import maps, and the attributes and order of classic,
module, async, and defer scripts. Custom maps remain separate and are not
merged into the SDK map. The managed block follows the effective base and
precedes executable scripts and module preloads. An authored base that follows
one of those loads is reported as ARCANE_IMPORT_MAP_INVALID before writes.
This operation writes only the selected HTML files. The caller owns runtime materialization, document selection, serving, and coordination with other document writers. It creates no map sidecar, copies no runtime content, and starts no build or browser.
Events, errors, and cancellation
| Event | Fields |
|---|---|
import-map.documents.started |
documentRoot, runtimeRoot, and the complete documentPaths selection. |
import-map.write.progress |
paths: all absolute document paths successfully written so far. |
import-map.documents.completed |
The successful result fields, including committed: true. |
If an event callback throws or rejects, generation continues. A successful
return additionally reports eventDelivery: {status: 'degraded', errorCode: 'ARCANE_EVENT_DELIVERY_FAILED', message} for the first callback failure.
Invalid options can throw TypeError; document/map structure failures use
ARCANE_IMPORT_MAP_INVALID, runtime inventory failures use
ARCANE_RUNTIME_INVALID, and filesystem failures propagate. All started
preparation reads settle before rejection; multiple failures are
reported together in an AggregateError. Cancellation
rejects with the signal's error reason when supplied, otherwise an operation
cancellation error; an error lacking a code receives ARCANE_CANCELLED.
Preparation failures occur before writes. Cancellation or a filesystem failure
during writing can leave earlier completed files updated; the operation does
not roll those files back. An in-flight filesystem write completes before the
next cancellation boundary.
Availability and normalization
Node on Windows, Linux, and macOS. Filesystem paths are resolved with the host path API; browser import URLs use forward slashes and URL encoding. Deep protocol: Explicit host documents.
Example
A dragon observatory keeps its control page at shell/home.html, settings at
settings.html, and its selected Arcane runtime at arcane/. Run this from
that document root after materializing the runtime:
import {generateDocumentImportMaps} from 'arcane-os';
const controller = new AbortController();
function reportImportMapEvent(event) {
console.log(event);
}
const result = await generateDocumentImportMaps(
{
documentRoot: process.cwd(),
documents: ['shell/home.html', 'settings.html'],
signal: controller.signal,
onEvent: reportImportMapEvent
}
);
for (const document of result.documents) {
console.log(document.path, document.imports['arcane/AI']);
}
Change the explicit document list to update another host page. If either page
uses <base href="/control/">, add
deploymentUrl: 'https://example.com/control/' to the options. Both pages keep
their authored layout and receive map URLs appropriate to their own base.
getSdkBrowserRuntimeRoot()
Overview
Returns the absolute SDK browser-runtime root selected by the installed package.
Signature and result
getSdkBrowserRuntimeRoot()
Import it from arcane-os. The return value is the default root accepted by the
browser-runtime inventory and reader functions.
Availability and normalization
Node. Returns one absolute directory path. Deep protocol: Node ESM.
Example
import {getSdkBrowserRuntimeRoot} from 'arcane-os';
console.log(getSdkBrowserRuntimeRoot());
getSdkRoot()
Overview
Returns the absolute installed SDK package root.
Signature and result
getSdkRoot()
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {getSdkRoot} from 'arcane-os';
console.log(getSdkRoot());
loadAppDescriptor()
Overview
Loads an authored schema-2 descriptor or a complete package/registry projection with its source label.
Signature and result
async loadAppDescriptor({workspaceRoot, appRoot, appId, packageManifest})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {loadAppDescriptor} from 'arcane-os';
async function useloadAppDescriptor(...arguments_) {
return loadAppDescriptor(...arguments_);
}
listRuntimeFiles()
Overview
Lists every regular file beneath one selected SDK runtime root as an ordered, slash-normalized relative path.
Signature and result
async listRuntimeFiles({runtimeRoot=path.join(sdkRoot, 'runtime'),signal}={})
The function traverses the selected directory, observes signal, and returns
the complete sorted path list.
Availability and normalization
Node. Complete relative-path inventory. Deep protocol: Node ESM.
Example
import {listRuntimeFiles} from 'arcane-os';
const files=await listRuntimeFiles();
listSdkBrowserRuntimeFiles()
Overview
Lists every regular file beneath one selected SDK browser-runtime root as an ordered, slash-normalized relative path.
Signature and result
async listSdkBrowserRuntimeFiles({browserRuntimeRoot=defaultRoot,signal}={})
The function traverses the selected directory, observes signal, and returns
the complete sorted path list.
Availability and normalization
Node. Complete relative-path inventory. Deep protocol: Node ESM.
Example
import {listSdkBrowserRuntimeFiles} from 'arcane-os';
const files=await listSdkBrowserRuntimeFiles();
loadRuntimeRelease()
Overview
Returns the selected runtime root, SDK version, and complete current file inventory derived directly from that directory.
Signature and result
async loadRuntimeRelease({runtimeRoot=path.join(sdkRoot, 'runtime'),signal}={})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {loadRuntimeRelease} from 'arcane-os';
async function useloadRuntimeRelease(...arguments_) {
return loadRuntimeRelease(...arguments_);
}
loadSdkBrowserRuntimeRelease()
Overview
Returns the selected browser-runtime root, SDK version, and complete current file inventory derived directly from that directory.
Signature and result
async loadSdkBrowserRuntimeRelease({browserRuntimeRoot=defaultRoot,signal}={})
Import it from arcane-os. The mutable result contains sdkVersion,
browserRuntimeRoot, and ordered files.
Availability and normalization
Node. SDK-normalized inputs, errors, and documented result. Deep protocol: Node ESM.
Example
import {loadSdkBrowserRuntimeRelease} from 'arcane-os';
const release=await loadSdkBrowserRuntimeRelease();
materializeInstalledSdkRuntime()
Overview
Materializes the complete installed SDK runtime and browser-runtime content.
After full runtime replacement, it writes or replaces semantic
arcane.lock.json from the actual installed dependency name, package name,
package version, alias source, and projected roots.
This operation remains available for physical workspace projections. External
applications using installed-package routes
read directly from their installed dependency and do not need to call it or
create arcane.lock.json before serving, refreshing app import maps, or packaging.
Signature and result
async materializeInstalledSdkRuntime({workspaceRoot,sdkPackageSource,browserDecisions=false,workspaceOperationLease,signal,onEvent}={})
Import it through the exact dependency key declared by the workspace: normally
arcane-os, or the alias name such as arcane-sdk when the declaration is
npm:arcane-os@<version>. It resolves that declaration under the shared
workspace-operation lock and replaces the complete projection by staged
whole-tree replacement. The mutable result includes the installed-package
location, materialized workspace runtime paths, and workspaceLock path and
document. It does not install dependencies or merge application source.
Explicit browserDecisions: true also acquires the bundled Transformers.js
4.3.0 entry and matching ONNX Runtime 1.31.0-dev.20260914-8d85527a0 asyncify
module/WASM and license files from their upstream distributions into
arcane/sdk/ai/decisions-runtime/. It returns their directory,
transformersVersion, onnxRuntimeVersion and files under
workspaceRuntime.browserDecisions. The default false performs no optional
acquisition. Select this option on each refresh that should retain those files.
For applications with installed-package routes, use
packageApp({workspaceRoot, appId, browserDecisions: true}) to place the
distribution beside the actual deployed SDK module. This physical materializer
continues to own only the separate arcane/ projection; it does not populate or
modify node_modules.
The extension-local decision guide
describes runtime.local: true, complete resource ownership and MV3 usage.
Ordinary acquisition automatically recovers a workspace-operation lock when
the recorded owner process is confirmed absent, without waiting solely for its
six-hour expiry. Retry this public operation normally; workspaceOperationLease
is for active nested SDK work and cannot be reconstructed from the lock JSON.
Live or indeterminate owners remain ARCANE_WORKSPACE_BUSY; an indeterminate
process-probe error is retained as the cause. Existing published lock documents
remain readable. Recovery rechecks cancellation, the captured nonce and PID,
and owner presence after asynchronous observation, preserving a replacement
detected there. This cooperative read-then-remove protocol does not provide an
atomic compare-and-delete across competing processes.
Replacement removes files absent from the selected runtime content and restores
the prior tree if commit fails. signal and
onEvent remain caller-owned before commit. Once the atomic replacement starts,
it completes replacement or rollback without observing cancellation or invoking
callbacks.
Availability and normalization
Node. Complete installed runtime content and a mutable materialization result. Deep protocol: Installed SDK runtime materialization.
Example
import {materializeInstalledSdkRuntime} from 'arcane-os';
// If package.json declares the SDK under the arcane-sdk alias, import from
// 'arcane-sdk' instead.
const result=await materializeInstalledSdkRuntime({workspaceRoot});
materializeWorkspaceRuntimeContent()
Overview
Replaces one workspace's complete projected runtime and browser-runtime content
from selected source roots. It does not resolve a package declaration or write
the installed-package lock document owned by materializeInstalledSdkRuntime().
Signature and result
async materializeWorkspaceRuntimeContent({workspaceRoot,runtimeRoot=path.join(getSdkRoot(), 'runtime'),browserRuntimeRoot=getSdkBrowserRuntimeRoot(),sdkVersion=SDK_VERSION,browserDecisions=false,signal,onEvent}={})
The operation stages the complete projection, replaces the prior tree at the commit boundary, restores it if commit fails, and removes paths absent from the selected sources.
browserDecisions: true acquires the same upstream executable closure described
by materializeInstalledSdkRuntime() before replacement. Its result is at
result.browserDecisions because this lower-level operation returns the
workspace runtime directly. Full downloaded content remains unchanged; model
and tokenizer data are not materialized. workspace.decisions.started and
workspace.decisions.progress report completed files and the fixed total.
Cancellation, HTTP failures and throwing/rejecting observers abort and join
pending acquisitions before returning; the prior runtime remains in place.
An HTTP failure retains its complete response in error.response, or in the
corresponding member of AggregateError.errors when several operations fail.
Availability and normalization
Node. Complete workspace runtime content and a mutable materialization result. Deep protocol: Installed SDK runtime materialization.
Example
import {materializeWorkspaceRuntimeContent} from 'arcane-os';
const result=await materializeWorkspaceRuntimeContent({workspaceRoot});
PreferenceStore default export
Overview
Default binding for the canonical PreferenceStore runtime class. The static
specifier arcane-os/preference-store works in Node package consumers and is
mapped to the same runtime module in managed browsers. arcane/PreferenceStore
is the direct browser runtime name generated into the managed import map.
Signature and result
default class PreferenceStore extends EventTarget
Availability and normalization
Node with injected adapters, or browser/native WebView storage. The package subpath and managed browser key both resolve directly to the canonical runtime module. Deep protocol: Browser runtime delivery.
The default adapter recognizes an absent optional preferences namespace only
from the exact Core lookup tuple code:'METHOD_NOT_ALLOWED',
reason:'core-namespace-unavailable', namespace:'preferences', and the
matching method:'preferences.<operation>'. Single get, set, and delete
operations then retry once through the existing app-scoped local adapter after
checking disposal and cancellation, preserving complete values and operation
context. The existing Android unsupported-capability route is unchanged.
An advertised setMany batch rejected for that exact absence retains its
original rejection and performs no serial retry; subsequent operations use the
selected local adapter.
Partial-service, permission, persistence, transport and cancellation failures
remain errors. Explicit adapters retain their own behavior. See the
complete PreferenceStore contract.
Example
import PreferenceStore from 'arcane-os/preference-store';
const store=new PreferenceStore({schema,adapter});
PREFERENCESTOREERROR_CODES
Overview
Frozen stable error-code vocabulary emitted by PreferenceStore.
Signature and result
const PREFERENCE_STORE_ERROR_CODES
Availability and normalization
Node and browser. Exact immutable values from the canonical runtime module.
Example
import {PREFERENCE_STORE_ERROR_CODES} from 'arcane-os/preference-store';
console.log(PREFERENCE_STORE_ERROR_CODES.disposed);
PREFERENCESTOREEVENT_TYPES
Overview
Frozen semantic event names published by PreferenceStore.
Signature and result
const PREFERENCE_STORE_EVENT_TYPES
Availability and normalization
Node and browser. Exact load, change, and reset names from the canonical runtime.
Example
import {PREFERENCE_STORE_EVENT_TYPES} from 'arcane-os/preference-store';
console.log(PREFERENCE_STORE_EVENT_TYPES.change);
Preference
Overview
Canonical Preference entity re-exported with the store namespace.
Signature and result
new Preference(data={})
Availability and normalization
Node and browser. Entity validation and serialization remain owned by the canonical runtime entity.
Example
import {Preference} from 'arcane-os/preference-store';
const record=new Preference({key:'theme',value:'system'});
preferenceSchema()
Overview
Builds the canonical Preference strong-type schema for a supplied definition set.
Signature and result
preferenceSchema(definitions=[])
Availability and normalization
Node and browser. Returns the canonical runtime schema for the supplied definitions.
Example
import {preferenceSchema} from 'arcane-os/preference-store';
const schema=preferenceSchema([]);
SpeechPlayback default export
Overview
Default binding for the canonical SpeechPlayback runtime class. The static
specifier arcane-os/speech-playback works in Node package consumers and maps
to the same runtime module in managed browsers. Physical/nested maps also
retain the arcane/SpeechPlayback compatibility name.
When the supplied speech client has prepareTTSPlayback or fetchTTS and reports a positive
providerRuntime.status('tts', {execution:true}).execution.maxConcurrentRequests,
prepare() submits every complete part immediately. The provider owns its
bounded FIFO queue (browser Kokoro defaults to four), while Blob audio or native
playback descriptors remain in exact input order. Preparation prefers
prepareTTSPlayback when available. Native playback owns pause, resume, stop
and release without creating an audio-file URL. A native or custom client without that
advertised capacity stays serialized with one lookahead. Replay keeps completed
URLs and pending requests while retrying failed missing provider segments.
The optional constructor onState(detail) callback runs synchronously after
the canonical state occurrence is dispatched; callback failures are reported
without replacing playback settlement.
prepare() keeps every nonblank stored part exact. At synthesis time,
SpeechPlayback copies the part and automatically removes repeated formatting
marks from only that outbound speech input. It passes SDK-internal preparation
metadata so a downstream SDK speech boundary does not apply the filter again;
applications do not supply that metadata. Original part objects, displayed or
stored content, and every non-input payload field remain unchanged.
Signature and result
default class SpeechPlayback
Availability and normalization
Node with injected media adapters, or browser/native WebView media. The package subpath and managed browser key both resolve directly to the canonical runtime module; provider and media availability remain host-owned.
Example
import SpeechPlayback from 'arcane-os/speech-playback';
const audio=document.body.appendChild(document.createElement('audio'));
const playback=new SpeechPlayback({
audio,
speech:globalThis.ai,
onState(detail) {
console.log(detail.state);
}
});
const button=document.body.appendChild(document.createElement('button'));
button.textContent='Speak';
button.addEventListener('click',async function speakCompleteSegments(){
await globalThis.ai.setSpeechMuted(false);
await playback.prepare({
parts:['First complete segment.','Second complete segment.'],
autoplay:true
});
});
SPEECHPLAYBACKSTATE_EVENT
Overview
Canonical semantic event name for SpeechPlayback state transitions.
Signature and result
const SPEECH_PLAYBACK_STATE_EVENT
Availability and normalization
Node and browser. Exact immutable speech-playback-state name.
Example
import {SPEECH_PLAYBACK_STATE_EVENT} from 'arcane-os/speech-playback';
console.log(SPEECH_PLAYBACK_STATE_EVENT);
SPEECHVOICEALIASES
Overview
Mutable compatibility membership for the ten shared voice identifiers used by
existing speech controls. SpeechPlayback does not select a voice from this
set, and membership does not promise support from the selected provider.
Signature and result
const SPEECH_VOICE_ALIASES
Availability and normalization
Node and browser. Ordinary mutable Set, derived once in
SPEECH_VOICE_OPTIONS order, containing alloy, ash, ballad, coral,
echo, fable, nova, onyx, sage, and shimmer.
Example
import {SPEECH_VOICE_ALIASES} from 'arcane-os/speech-playback';
console.log(SPEECH_VOICE_ALIASES.has('alloy')); // true
SPEECHVOICEOPTIONS
Overview
Mutable ordered compatibility records for existing speech voice controls.
Each record has a lowercase value and matching title-case label. Provider
support and voice selection remain caller-owned.
Signature and result
const SPEECH_VOICE_OPTIONS
Availability and normalization
Node and browser. Ordinary mutable array and mutable {value,label}
records ordered as Alloy, Ash, Ballad, Coral, Echo, Fable, Nova, Onyx, Sage,
and Shimmer.
Example
import {SPEECH_VOICE_OPTIONS} from 'arcane-os/speech-playback';
console.log(SPEECH_VOICE_OPTIONS[0]); // {value: 'alloy', label: 'Alloy'}
SpeechPlayback
Overview
Named binding for the same capability-aware, exact-order canonical class exposed
as the speech-playback default. prepare() preserves each nonblank part's exact
input string without trimming, splitting, or freezing that content. An optional
onState(detail) constructor callback receives every state synchronously after
the canonical occurrence is dispatched. Both surfaces expose the same public
field values at dispatch time; object identity is not promised. Callback
failures are reported through globalThis.reportError when available,
otherwise console.error, and do not replace playback settlement.
Only the outbound synthesis copy receives automatic repeated-formatting-mark
cleanup; the original part and stored preparation record stay exact.
Signature and result
new SpeechPlayback({
audio,
speech?,
model?,
voice?,
responseFormat?,
speed=1,
onState=()=>{},
createObjectURL?,
revokeObjectURL?,
delay?,
messages?
})
Availability and normalization
Node with injected media adapters, or browser/native WebView media. Binding identity equals the default export. Provider-advertised capacity enables eager submission while that provider owns its bound; native and custom speech stays serialized, and media availability remains host-owned.
Example
import SpeechPlayback,{SpeechPlayback as NamedSpeechPlayback} from 'arcane-os/speech-playback';
const audio=document.body.appendChild(document.createElement('audio'));
const playback=new NamedSpeechPlayback({
audio,
onState(detail) {
console.log(detail.state);
}
});
console.log(playback instanceof SpeechPlayback); // true
splitSpeechText()
Overview
Returns the caller's exact nonblank speech text as one segment.
Signature and result
splitSpeechText(value='')
Availability and normalization
Node and browser. Uses trimming only to detect blank input. A nonblank value is returned with its exact whitespace and content intact in one mutable array; it is not trimmed, split, or frozen. Blank or whitespace-only input returns an empty array.
Example
import {splitSpeechText} from 'arcane-os/speech-playback';
console.log(splitSpeechText('Hello world.'));
MarkdownSpeech
Overview
Streams the SDK's speech formatting cleanup across input chunk
boundaries. append() removes runs of two or more identical *, #, _,
backtick, or ~ marks while retaining single marks and every other character.
It is a narrow speech filter, not a Markdown parser. Normal SDK TTS calls use
this cleanup automatically; applications do not need to construct this class
or opt in.
Signature and result
new MarkdownSpeech()
append(text='',end=false) returns only newly available narration. It retains
one trailing candidate formatting mark across calls so a repeated run split
between chunks is still removed. A terminal end:true append flushes any
single pending mark and resets the instance. reset() discards pending state.
Availability and normalization
Node and browser. The implementation has no runtime dependency. Caller
strings remain unchanged. Non-string input throws TypeError.
Example
import {MarkdownSpeech} from 'arcane-os/speech-text';
const speechText=new MarkdownSpeech();
console.log(speechText.append('*')); // '' (held for the next chunk)
console.log(speechText.append('*Hello.',true)); // 'Hello.'
stripSpeechFormatting()
Overview
Removes repeated same formatting marks from one complete speech text value. Single marks, ordinary punctuation, links, code contents, and every other character remain literal. Normal SDK TTS calls already apply this function to an outbound copy; the public helper is available when another speech-text owner needs the same one-pass result.
Signature and result
stripSpeechFormatting(text='')
Availability and normalization
Node and browser. Calls the supplied value's replace() method and returns
its filtered result without modifying the supplied value. Pass a string;
values without a callable replace() fail with the native TypeError.
Example
import {stripSpeechFormatting} from 'arcane-os/speech-text';
console.log(stripSpeechFormatting('**Hello**')); // 'Hello'
projectNativeDescriptor()
Overview
Projects the canonical app descriptor into the native registry shape consumed by paired builders.
Signature and result
projectNativeDescriptor(descriptor, {source}={})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {projectNativeDescriptor} from 'arcane-os';
async function useprojectNativeDescriptor(...arguments_) {
return projectNativeDescriptor(...arguments_);
}
projectPackageManifest()
Overview
Projects a schema-2 descriptor into the compatible schema-1 application package contract.
Optional package.documents becomes top-level documents. Omission stays
omitted and an authored empty list stays [], so projection preserves automatic
discovery versus entry-only selection. See
application document selection.
Optional package.nativeResources becomes top-level nativeResources.
Omission remains omitted, an empty include remains [], and an omitted exclude
becomes []. Package-only descriptor synthesis preserves the same selection.
This is a packaging contract; projectNativeDescriptor() keeps its existing
registry shape and ordinary include list. See
native-only application resources.
Signature and result
projectPackageManifest(descriptor)
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {projectPackageManifest} from 'arcane-os';
async function useprojectPackageManifest(...arguments_) {
return projectPackageManifest(...arguments_);
}
readRuntimeFile()
Overview
Reads one complete contained file from a selected SDK runtime root.
Signature and result
async readRuntimeFile({runtimeRoot=path.join(sdkRoot, 'runtime'),relativePath,signal}={})
The relative path must identify a regular file contained by the selected root.
The result is the complete file Buffer.
Availability and normalization
Node. Contained runtime file access with cancellation. Deep protocol: Node ESM.
Example
import {readRuntimeFile} from 'arcane-os';
const content=await readRuntimeFile({relativePath:'arcane/modules/AI.js'});
readSdkBrowserRuntimeFile()
Overview
Reads one complete contained file from a selected SDK browser-runtime root.
Signature and result
async readSdkBrowserRuntimeFile({browserRuntimeRoot=defaultRoot,relativePath,signal}={})
The relative path must identify a regular file contained by the selected root.
The result is the complete file Buffer.
Availability and normalization
Node. Contained browser-runtime file access with cancellation. Deep protocol: Node ESM.
Example
import {readSdkBrowserRuntimeFile} from 'arcane-os';
const content=await readSdkBrowserRuntimeFile({relativePath:'ai/browser-wasm.mjs'});
validateAppDescriptor()
Overview
Strictly validates and freezes one schema-2 app descriptor, including runtime-only cross-field rules.
Signature and result
validateAppDescriptor(value, {appId}={})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {validateAppDescriptor} from 'arcane-os';
async function usevalidateAppDescriptor(...arguments_) {
return validateAppDescriptor(...arguments_);
}
Targets, native plans, and providers
ARCANEINTEGRATEDPROVIDERRELATIVEPATH
Overview
Frozen repository-relative path of Arcane OS's integrated shared-development provider.
Value and import
const ARCANE_INTEGRATED_PROVIDER_RELATIVE_PATH
Import it from arcane-os or arcane-os/integrated-provider. Treat arrays and records as immutable public values.
Availability and normalization
Node; selected browser/native target or provider as documented. Exact immutable SDK value. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {ARCANE_INTEGRATED_PROVIDER_RELATIVE_PATH} from 'arcane-os';
console.log(ARCANE_INTEGRATED_PROVIDER_RELATIVE_PATH);
ARCANENATIVEPROVIDER_PATHS
Overview
Target-to-provider path registry for explicitly selected Arcane OS checkout providers. The package-owned portable default resolves directly from the SDK module location and leaves this existing registry unchanged.
Value and import
const ARCANE_NATIVE_PROVIDER_PATHS
Import it from arcane-os or arcane-os/native-provider. The exported path arrays
are ordinary copies; changing them does not change the loader's fixed paths.
Availability and normalization
Node. Checkout provider path metadata; it does not load a provider or report runtime readiness. Deep protocol: native provider protocols.
Example
import {ARCANE_NATIVE_PROVIDER_PATHS} from 'arcane-os';
console.log(ARCANE_NATIVE_PROVIDER_PATHS);
assertIntegratedNativeToolchain()
Overview
Requires an integrated workspace and explicitly selected checkout provider to use the same canonical Arcane checkout. The SDK-owned portable pairing uses its installed package root instead; other targets retain the existing requirement.
Signature and result
assertIntegratedNativeToolchain({workspaceMode, workspaceRoot, toolchainRoot, target, providerSource='arcane-checkout'}={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {assertIntegratedNativeToolchain} from 'arcane-os';
async function useassertIntegratedNativeToolchain(...arguments_) {
return assertIntegratedNativeToolchain(...arguments_);
}
buildTarget()
Overview
Invokes one target adapter build with explicit app, target, and artifact inputs.
Signature and result
async buildTarget(options={})
Import it from arcane-os or arcane-os/targets. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {buildTarget} from 'arcane-os';
async function usebuildTarget(...arguments_) {
return buildTarget(...arguments_);
}
createNativeBuildPlan()
Overview
Creates a native plan carrying the complete selected app release, dependency
releases, toolchain, target request and output roots. Release inputs use
{files, ...releaseFields} records; dependency inputs use
{appId,releaseRoot,release}. Selected-file readers return the complete contents.
Both nested CLI signing:{mode,profileId} and existing flat
signing/signingProfileId inputs normalize to the same flat plan request.
Optional selectedSdk:{packageRoot,packageSource} carries the app's actual
installed SDK source through the plan and builder request. The high-level
toolchain reads this from the workspace's existing installed SDK layout once
per build. Direct callers composing services over a partial direct SDK
projection supply the actual source; the builder does not infer it from the
browser file inventory or substitute its own version.
Signature and result
async createNativeBuildPlan({ nativeBuilder, toolchainRoot, toolchain, appReleaseRoot, release, appDescriptor, selectedSdk, dependencyReleases, minimumCoreVersion, protectedRoots=[], outputRoot, targetRequest, signal, onEvent }={})
Import it from arcane-os or arcane-os/native. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {createNativeBuildPlan} from 'arcane-os';
async function usecreateNativeBuildPlan(...arguments_) {
return createNativeBuildPlan(...arguments_);
}
createNativeTargetAdapter()
Overview
Adapts one validated native builder to the common target-adapter contract.
Signature and result
createNativeTargetAdapter({targetId, nativeBuilder}={})
Import it from arcane-os or arcane-os/targets. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {createNativeTargetAdapter} from 'arcane-os';
async function usecreateNativeTargetAdapter(...arguments_) {
return createNativeTargetAdapter(...arguments_);
}
doctorNativeTarget()
Overview
Loads and diagnoses one explicit native provider and target without building an application.
Signature and result
async doctorNativeTarget(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {doctorNativeTarget} from 'arcane-os';
async function usedoctorNativeTarget(...arguments_) {
return doctorNativeTarget(...arguments_);
}
executeNativeBuildPlan()
Overview
Invokes the plan's selected builder with complete app/dependency release records, their file readers, the flat target request and event/cancellation lifecycle.
Signature and result
async executeNativeBuildPlan(plan, { expectedNativeBuilder, expectedTarget, signal, onEvent }={})
Import it from arcane-os or arcane-os/native. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {executeNativeBuildPlan} from 'arcane-os';
async function useexecuteNativeBuildPlan(...arguments_) {
return executeNativeBuildPlan(...arguments_);
}
getTargetAdapter()
Overview
Returns the registered adapter for one exact target id or fails for an unknown target.
Signature and result
getTargetAdapter(targetId)
Import it from arcane-os or arcane-os/targets. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {getTargetAdapter} from 'arcane-os';
async function usegetTargetAdapter(...arguments_) {
return getTargetAdapter(...arguments_);
}
INTEGRATEDTOOLCHAINPROTOCOL
Overview
Protocol required from the fixed integrated shared-development provider.
Value and import
const INTEGRATED_TOOLCHAIN_PROTOCOL
Import it from arcane-os or arcane-os/integrated-provider. Treat arrays and records as immutable public values.
Availability and normalization
Node; selected browser/native target or provider as documented. Exact immutable SDK value. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {INTEGRATED_TOOLCHAIN_PROTOCOL} from 'arcane-os';
console.log(INTEGRATED_TOOLCHAIN_PROTOCOL);
listTargets()
Overview
Returns the frozen target descriptors without running an operation lifecycle.
Signature and result
listTargets()
Import it from arcane-os or arcane-os/targets. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {listTargets} from 'arcane-os';
console.table(listTargets());
loadArcaneIntegratedProvider()
Overview
Loads and authenticates the fixed Arcane-owned integrated development provider generation.
Signature and result
loadArcaneIntegratedProvider({ arcaneRoot, signal, onEvent, run=runProcess }={})
Import it from arcane-os or arcane-os/integrated-provider. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {loadArcaneIntegratedProvider} from 'arcane-os';
async function useloadArcaneIntegratedProvider(...arguments_) {
return loadArcaneIntegratedProvider(...arguments_);
}
loadArcaneNativeProvider()
Overview
Loads the package-owned provider when arcaneRoot is omitted and target is
portable or windows-x64. Portable produces a non-executable payload; Windows
assembles the matching precompiled SDK host. An explicit root retains the fixed
Arcane OS checkout provider route, including its errors; there is no silent
fallback. Other native targets still require that root. Normal Node module
resolution owns imports.
Signature and result
async loadArcaneNativeProvider({ arcaneRoot, target, inspect=lstat, canonicalize=realpath, importModule=specifier=>import(specifier), signal, onEvent }={})
The result retains arcaneRoot, toolchainRoot, providerPath and
nativeBuilder, and adds providerSource. Package pairing returns
providerSource:'sdk-package', arcaneRoot:null and the installed SDK root as
toolchainRoot. Explicit checkout pairing returns
providerSource:'arcane-checkout' with the selected root. Load completion means
the builder interface was loaded, not that an app, native host or service is ready.
For explicit service composition and host lifecycle, use the separate
arcane-os/native/portable-provider and arcane-os/core/host guide.
Import it from arcane-os or arcane-os/native-provider. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {loadArcaneNativeProvider} from 'arcane-os';
async function useloadArcaneNativeProvider(...arguments_) {
return loadArcaneNativeProvider(...arguments_);
}
NATIVEBUILDPLAN_PROTOCOL
Overview
Protocol identifier for native plans with complete selected release inputs.
Value and import
const NATIVE_BUILD_PLAN_PROTOCOL
Import it from arcane-os or arcane-os/native. Treat arrays and records as immutable public values.
Availability and normalization
Node; selected browser/native target or provider as documented. Exact immutable SDK value. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {NATIVE_BUILD_PLAN_PROTOCOL} from 'arcane-os';
console.log(NATIVE_BUILD_PLAN_PROTOCOL);
NATIVEBUILDERPROTOCOL
Overview
Protocol identifier required from injected native builders.
Value and import
const NATIVE_BUILDER_PROTOCOL
Import it from arcane-os or arcane-os/native. Treat arrays and records as immutable public values.
Availability and normalization
Node; selected browser/native target or provider as documented. Exact immutable SDK value. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {NATIVE_BUILDER_PROTOCOL} from 'arcane-os';
console.log(NATIVE_BUILDER_PROTOCOL);
prepareNativeTarget()
Overview
Runs one provider toolchain preparation and returns its process-owned result.
Signature and result
async prepareNativeTarget(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {prepareNativeTarget} from 'arcane-os';
async function useprepareNativeTarget(...arguments_) {
return prepareNativeTarget(...arguments_);
}
resolveNativeBuildOutputRoot()
Overview
Resolves and validates one native output root, including integrated-checkout non-overlap.
Signature and result
resolveNativeBuildOutputRoot({target, workspaceMode, workspaceRoot, outputRoot}={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {resolveNativeBuildOutputRoot} from 'arcane-os';
async function useresolveNativeBuildOutputRoot(...arguments_) {
return resolveNativeBuildOutputRoot(...arguments_);
}
runTarget()
Overview
Invokes one target adapter run method and fails honestly when the artifact kind is not runnable.
For the browser adapter, optional releaseRoot selects an existing packaged
directory directly. Omission keeps the direct adapter's dist/<app-id>
default, including callers with only a release workspace. The high-level
runApplication() supplies the app-configured destination automatically.
Signature and result
async runTarget(options={})
Import it from arcane-os or arcane-os/targets. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {runTarget} from 'arcane-os';
async function userunTarget(...arguments_) {
return runTarget(...arguments_);
}
TARGETADAPTERPROTOCOL
Overview
Protocol required from target adapter descriptors and implementations.
Value and import
const TARGET_ADAPTER_PROTOCOL
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node; selected browser/native target or provider as documented. Exact immutable SDK value. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {TARGET_ADAPTER_PROTOCOL} from 'arcane-os';
console.log(TARGET_ADAPTER_PROTOCOL);
TARGET_IDS
Overview
Frozen list of currently exposed target identifiers.
Value and import
const TARGET_IDS
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node; selected browser/native target or provider as documented. Exact immutable SDK value. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {TARGET_IDS} from 'arcane-os';
console.log(TARGET_IDS);
validateNativeBuilder()
Overview
Validates a native builder's protocol and required describe/doctor/prepare/build/verify/run methods.
Signature and result
validateNativeBuilder(provider)
Import it from arcane-os or arcane-os/native. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {validateNativeBuilder} from 'arcane-os';
async function usevalidateNativeBuilder(...arguments_) {
return validateNativeBuilder(...arguments_);
}
verifyNativeArtifact()
Overview
Explicitly verifies one selected target artifact through the prepared provider and toolchain state.
Signature and result
async verifyNativeArtifact(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {verifyNativeArtifact} from 'arcane-os';
async function useverifyNativeArtifact(...arguments_) {
return verifyNativeArtifact(...arguments_);
}
verifyTarget()
Overview
Invokes one target adapter's artifact verification boundary.
Signature and result
async verifyTarget(options={})
Import it from arcane-os or arcane-os/targets. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected browser/native target or provider as documented. Normalized complete plan and result; target-specific artifact detail preserved. Deep protocol: arcane-target-adapter/1, arcane-native-build-plan/1, or provider protocol.
Example
import {verifyTarget} from 'arcane-os';
async function useverifyTarget(...arguments_) {
return verifyTarget(...arguments_);
}
Identity and protocol constants
ARCANEMACHINEBUNDLE_VERSION
Overview
Exact Arcane machine-bundle generation paired with this SDK runtime.
Value and import
const ARCANE_MACHINE_BUNDLE_VERSION
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {ARCANE_MACHINE_BUNDLE_VERSION} from 'arcane-os';
console.log(ARCANE_MACHINE_BUNDLE_VERSION);
ARCANE_PROTOCOL
Overview
Application-facing Arcane bridge protocol required by this SDK.
Value and import
const ARCANE_PROTOCOL
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {ARCANE_PROTOCOL} from 'arcane-os';
console.log(ARCANE_PROTOCOL);
ARCANEUPSTREAMREPOSITORY
Overview
Canonical upstream Arcane OS repository URL.
Value and import
const ARCANE_UPSTREAM_REPOSITORY
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {ARCANE_UPSTREAM_REPOSITORY} from 'arcane-os';
console.log(ARCANE_UPSTREAM_REPOSITORY);
CLIEVENTPROTOCOL
Overview
Version identifier for normalized CLI JSON and NDJSON event envelopes.
Value and import
const CLI_EVENT_PROTOCOL
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {CLI_EVENT_PROTOCOL} from 'arcane-os';
console.log(CLI_EVENT_PROTOCOL);
CLI_NAME
Overview
Primary command name presented by the SDK.
Value and import
const CLI_NAME
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {CLI_NAME} from 'arcane-os';
console.log(CLI_NAME);
OUTPUT_MODES
Overview
Frozen supported CLI output modes: human, JSON, and NDJSON.
Value and import
const OUTPUT_MODES
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {OUTPUT_MODES} from 'arcane-os';
console.log(OUTPUT_MODES);
RUNTIME_ROOT
Overview
Absolute installed SDK runtime directory for the current process.
Value and import
const RUNTIME_ROOT
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {RUNTIME_ROOT} from 'arcane-os';
console.log(RUNTIME_ROOT);
SDK_NAME
Overview
Published npm package name.
Value and import
const SDK_NAME
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {SDK_NAME} from 'arcane-os';
console.log(SDK_NAME);
SDK_ROOT
Overview
Absolute installed package root for the current process.
Value and import
const SDK_ROOT
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {SDK_ROOT} from 'arcane-os';
console.log(SDK_ROOT);
SDK_VERSION
Overview
Exact SDK package version.
Value and import
const SDK_VERSION
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {SDK_VERSION} from 'arcane-os';
console.log(SDK_VERSION);
Errors
ArcaneError
Overview
Normalized SDK error class carrying a stable code, human message, optional resolution details, cause, and exit status.
Signature and result
new ArcaneError(code, message, {details, cause, exitCode}={})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. ArcaneError and JSON-safe error normalization. Deep protocol: Node ESM.
Example
import {ArcaneError, ERROR_CODES} from 'arcane-os';
const error = new ArcaneError(
ERROR_CODES.usage,
'Choose one documented target.'
);
console.log(error.code, error.message);
ERROR_CODES
Overview
Frozen registry of stable SDK error-code strings.
ERROR_CODES.updateCheckFailed is exactly
'ARCANE_UPDATE_CHECK_FAILED'. It identifies an update-check validation,
registry, timeout, HTTP, or response failure; caller cancellation remains the
separate ERROR_CODES.cancelled value.
The import-map operation also reports the stable operation-specific strings
ARCANE_IMPORT_MAP_INVALID, ARCANE_IMPORT_MAP_UNRESOLVED, and
ARCANE_IMPORT_MAP_COLLISION; package assembly can additionally report
ARCANE_IMPORT_MAP_CLEANUP_FAILED. They are normalized ArcaneError.code
values, but are not properties added to this general registry in SDK 0.5.14.
Value and import
const ERROR_CODES
Import it from arcane-os. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM.
Example
import {ERROR_CODES} from 'arcane-os';
console.log(ERROR_CODES.updateCheckFailed); // ARCANE_UPDATE_CHECK_FAILED
errorRecord()
Overview
Projects an error into the JSON-safe normalized public error record.
Signature and result
errorRecord(error)
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. ArcaneError and JSON-safe error normalization. Deep protocol: Node ESM.
Example
import {errorRecord} from 'arcane-os';
console.log(errorRecord(new Error('Example failure.')));
fail()
Overview
Synchronously throws an ArcaneError with the supplied code, message, and
optional diagnostic context. It never returns a value or a promise.
Signature, parameters, and error
fail(code, message, options)
Import it from arcane-os. code is normally one of ERROR_CODES; a falsy
code becomes ARCANE_OPERATION_FAILED. message is the public error message.
options can contain details, cause, and exitCode. details is preserved
for structured recovery, cause is attached through the standard Error
cause, and an integer exitCode is preserved; otherwise the exit code is 1.
Calling fail() has no filesystem, event, cancellation, or receipt side
effect. Catch the thrown ArcaneError synchronously, or let it reject the
surrounding asynchronous operation naturally. Do not wrap it merely to make it
look asynchronous.
Availability and normalization
Node. ArcaneError and JSON-safe error normalization. Deep protocol: Node ESM.
Example
import {ERROR_CODES, fail} from 'arcane-os';
function requireSelectedApp(appId) {
if (typeof appId !== 'string' || appId.length === 0) {
fail(ERROR_CODES.usage, 'Select one application.', {
details: {field: 'appId'}
});
}
return appId;
}
normalizeError()
Overview
Converts an unknown thrown value into an ArcaneError while preserving an existing normalized error.
Signature and result
normalizeError(error, fallbackCode=ERROR_CODES.operationFailed)
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. ArcaneError and JSON-safe error normalization. Deep protocol: Node ESM.
Example
import {normalizeError} from 'arcane-os';
console.log(normalizeError(new Error('Example failure.')));
throwIfAborted()
Overview
Throws the signal reason or a normalized cancellation error when an AbortSignal is already aborted.
Signature and result
throwIfAborted(signal)
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. ArcaneError and JSON-safe error normalization. Deep protocol: Node ESM.
Example
import {throwIfAborted} from 'arcane-os';
const controller = new AbortController();
throwIfAborted(controller.signal);
Workspace, doctor, repository, and server
assessArcaneOllama()
Overview
Performs a read-only Microsoft NT assessment of the managed ArcaneOllama service and reports unsupported hosts honestly.
Signature and result
async assessArcaneOllama({ signal, onEvent, platform=process.platform, run=runProcess, fileExists=exists }={})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; Microsoft NT managed-service assessment. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {assessArcaneOllama} from 'arcane-os';
async function useassessArcaneOllama(...arguments_) {
return assessArcaneOllama(...arguments_);
}
createWorkspace()
Overview
Scaffolds one new external repository-shaped workspace and one selected application.
Signature and result
async createWorkspace({ targetPath, appId, displayName, target='browser', initializeGit=false, signal, onEvent })
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {createWorkspace} from 'arcane-os';
async function usecreateWorkspace(...arguments_) {
return createWorkspace(...arguments_);
}
doctorApplication()
Overview
Runs the read-only SDK/runtime/workspace and optional local-AI diagnostic operation.
Signature and result
async doctorApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {doctorApplication} from 'arcane-os';
async function usedoctorApplication(...arguments_) {
return doctorApplication(...arguments_);
}
initializeApplication()
Overview
Initializes missing Arcane files for one app in an existing external or integrated workspace.
Signature and result
async initializeApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {initializeApplication} from 'arcane-os';
async function useinitializeApplication(...arguments_) {
return initializeApplication(...arguments_);
}
initWorkspace()
Overview
Adds one application scaffold to an existing workspace without overwriting incompatible files.
Signature and result
async initWorkspace({ workspaceRoot=process.cwd(), appId, displayName, target='browser', signal, onEvent })
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {initWorkspace} from 'arcane-os';
async function useinitWorkspace(...arguments_) {
return initWorkspace(...arguments_);
}
inspectWorkspaceProfile()
Overview
Classifies one canonical workspace as external or integrated and reports its fixed layout.
Signature and result
async inspectWorkspaceProfile(workspaceRoot=process.cwd())
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {inspectWorkspaceProfile} from 'arcane-os';
async function useinspectWorkspaceProfile(...arguments_) {
return inspectWorkspaceProfile(...arguments_);
}
repositoryPull()
Overview
Runs one fast-forward-only pull after proving the selected repository worktree is clean.
Signature and result
async repositoryPull({ workspaceRoot=process.cwd(), target, signal, onEvent, run=runProcess }={})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Optional target:{remote,ref,remoteBase?} captures the exact nonempty
native-representable remote and ref strings before any wait and selects
git pull --ff-only -- <remote> <ref>:.
The current clean branch receives a fast-forward-only integration; the SDK
never switches branches, resets or changes configuration. Without a target,
the existing configured pull and result remain unchanged. Targeted results
add target, complete stdout and stderr to the existing pull result.
Supplying target.remoteBase explicitly selects a local filesystem locator:
only the Git remote argument becomes path.resolve(remoteBase, remote), captured
once at acceptance before status work. Relative bases, including '', use the
working directory at that moment. The returned target retains the original
remote, ref and supplied base text. Omission preserves Git remote names,
URLs, SCP-like addresses and remote-helper strings without guessed parsing.
Unrepresentable base text reports TypeError without transformation.
See checkout configuration and selected targets.
Availability and normalization
Node; network-assisted Git. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {repositoryPull} from 'arcane-os';
async function userepositoryPull(...arguments_) {
return repositoryPull(...arguments_);
}
repositoryPush()
Overview
Pushes the selected attached branch through the repository's configured remote and credentials.
Signature, parameters, and result
async repositoryPush({ workspaceRoot=process.cwd(), target, signal, onEvent, run=runProcess }={})
Import it from arcane-os. workspaceRoot selects the Git worktree. signal
cancels the owned Git process tree. The awaited onEvent callback receives the
ordered process.* events for the three status probes and the push. run is an
injectable process runner intended for deterministic tests; ordinary callers
should keep the default.
Before pushing, the SDK runs git rev-parse --show-toplevel,
git branch --show-current, and git status --short --branch in order. It rejects a
detached HEAD, then, without target, runs plain git push; the repository's current branch,
configured upstream/remote, Git credentials, hooks, and server policy remain
authoritative. Unlike repositoryPull(), this function does not require a
clean worktree. It does not create a commit or choose an application destination.
Optional target:{remote,ref,remoteBase?} captures the original nonempty
native-representable remote and ref strings before any wait and runs
git push --no-follow-tags -- <remote> HEAD:<ref>. This publishes current HEAD
to the caller-selected ref without force or implicit configured tag following.
It changes no branch or Git configuration; credentials, URL interpretation,
hooks and remote rejection remain Git-owned.
Supplying target.remoteBase explicitly selects a local filesystem locator:
only the Git remote argument becomes path.resolve(remoteBase, remote), captured
once at acceptance before status work. Relative bases, including '', use the
working directory at that moment. Later directory or target-object changes do
not redirect accepted work. Omission preserves Git remote names, URLs, SCP-like
addresses and remote-helper strings without guessed parsing. Unrepresentable
base text reports TypeError without transformation.
The promise resolves to
{action:'push', repositoryRoot, branch, output}. output is trimmed stdout,
or trimmed stderr when stdout is empty. A missing Git executable, failed status
probe, rejected/nonzero push, cancellation, or event-callback failure rejects
with the normalized process error. Cancellation stops the local process tree;
it cannot prove that a remote accepted no objects before the interruption.
Targeted results also contain the captured target, retaining original
remote, ref and any supplied remoteBase, and complete
stdout/stderr; omitting the target preserves the existing result shape.
See checkout configuration and selected targets.
Availability and normalization
Node; network-assisted Git. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {repositoryPush} from 'arcane-os';
// Call only after the user has chosen to publish the attached branch.
async function pushAttachedBranch(workspaceRoot, signal) {
const result = await repositoryPush({
workspaceRoot,
signal,
onEvent(event) {
if (event.type === 'process.stderr') console.error(event.message);
}
});
console.log(`Pushed ${result.branch} from ${result.repositoryRoot}`);
return result;
}
repositoryStatus()
Overview
Reads one repository's branch and short worktree status through an owned child process.
Signature and result
async repositoryStatus({ workspaceRoot=process.cwd(), signal, onEvent, run=runProcess }={})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {repositoryStatus} from 'arcane-os';
async function userepositoryStatus(...arguments_) {
return repositoryStatus(...arguments_);
}
resolveWorkspace()
Overview
Resolves one workspace profile and selected app into canonical SDK paths.
Signature and result
async resolveWorkspace({workspaceRoot=process.cwd(), appId}={})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {resolveWorkspace} from 'arcane-os';
async function useresolveWorkspace(...arguments_) {
return resolveWorkspace(...arguments_);
}
discoverApps()
Overview
Discovers application ids in one external or integrated workspace without selecting one.
Signature and result
async discoverApps(workspaceRoot=process.cwd())
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {discoverApps} from 'arcane-os';
async function usediscoverApps(...arguments_) {
return discoverApps(...arguments_);
}
runDoctor()
Overview
Runs the underlying read-only doctor checks and returns their normalized report.
Signature and result
async runDoctor({ workspaceRoot, appId, arcaneRoot, requireLocalAI=false, signal, onEvent, platform=process.platform, run=runProcess }={})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {runDoctor} from 'arcane-os';
async function userunDoctor(...arguments_) {
return runDoctor(...arguments_);
}
runRepositoryAction()
Overview
Selects and runs one repository action by name.
Signature and result
async runRepositoryAction(action, options={})
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {runRepositoryAction} from 'arcane-os';
async function userunRepositoryAction(...arguments_) {
return runRepositoryAction(...arguments_);
}
selectApp()
Overview
Selects one exact app id, or requires an unambiguous single discovered application.
Signature and result
async selectApp(workspaceRoot=process.cwd(), appId)
Import it from arcane-os. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {selectApp} from 'arcane-os';
async function useselectApp(...arguments_) {
return selectApp(...arguments_);
}
WS
Import WS as the default or named binding from arcane-os/websocket-client,
or as a named binding from the Node root arcane-os. new WS(uri,protocols?)
returns the exact native socket from published ws-share, sharing a connecting
or open socket for the same exact URI string and ordered protocol list.
await WS.observe() exposes one event-pubsub observer with
created/open/error/close lifecycle records; WS.getConnections() returns
current managed-connection snapshots. Each physical connection has its own ID,
including replacements at the same address.
The shared-client guide covers complete record fields,
subscribe-then-snapshot ordering, listener cleanup, shared close ownership,
native per-socket behavior and the per-loaded-module/realm boundary. This
client entry does not change the server-side acceptWebSocket contract.
acceptWebSocket()
Overview
Accepts one caller-selected RFC6455 HTTP/1.1 Upgrade using Node's native
duplex stream. The caller owns HTTP routing, TLS, listeners, application
messages and shutdown. Use the raw server returned by startDevServer, or
the public .server / .secureServer of node-http-server. There is no
listener creation, default port, application envelope, message persistence,
client sharing, reconnect loop or third-party WebSocket runtime.
Clients may use native WebSocket directly or the separate shared
WS client. Node's global WebSocket is also a client,
not a server. This server adapter supports version 13 over an
HTTP/1.1 upgrade event, including HTTP/1.1 negotiated on an HTTPS listener.
It does not implement HTTP/2 extended CONNECT or negotiate extensions such as
compression. TLS setup remains with the existing server owner.
Signature, modes, and result
acceptWebSocket({request,socket,head,protocol,signal})
Import from arcane-os/websocket or arcane-os. Supply the exact request,
socket and head from the selected Node upgrade event. Do not substitute
request.socket for that event's stream. head defaults to an empty buffer.
Optional protocol is one exact client-offered token; the default empty string
selects no subprotocol. A browser that offers subprotocols expects one to be
selected. Optional signal owns this connection's lifetime.
The synchronous result is a native EventTarget with:
| Member | Contract |
|---|---|
readyState |
1 open, 2 closing, 3 closed. Acceptance queues the handshake before any messages. |
protocol |
Selected subprotocol, or the empty string. |
send(data) |
Promise<void> for a complete string, ArrayBuffer, or view. A view sends only its selected region. Input is snapshotted at submission; writes stay in submission order. The promise waits for the native write callback and any required drain; it is not a peer/application acknowledgement. |
close(code=1000,reason='') |
Starts the close handshake after already accepted sends; returns closed. Repeated calls return the same promise. A peer Close rejects unsent application messages and retains the close reply. |
terminate(reason?) |
Destroys only this connection's stream immediately, rejects pending sends and returns closed. An optional reason is reported as an error. |
closed |
Resolves once the stream closes to {code,reason,wasClean,error}. It never rejects. Code/reason come from the peer Close; without one, code is 1006. An empty peer Close reports 1005. wasClean requires both close frames and no recorded failure. |
Register listeners synchronously after acceptance. The handshake write and
initial head processing begin in a microtask so those listeners receive
buffered messages. head is processed once, before later stream chunks.
| Native event | Payload |
|---|---|
message |
MessageEvent.data: complete text as a string, or complete binary as Uint8Array. Fragment boundaries never replace message boundaries. |
error |
CustomEvent.detail: the complete original transport Error or coded protocol/abort Error. |
close |
CustomEvent.detail: the same result as closed. |
These are transport-local native events, not an application bus or retained
event history. Native EventTarget owns listener exceptions; an async listener
must observe its own promises. Listen for errors or inspect closed.error.
Ping receives a matching Pong internally; Pong is not an application message.
Text decoding preserves a leading U+FEFF and validates UTF-8 across the complete
fragmented message. Binary data is never interpreted or wrapped as JSON.
Errors and cancellation
Before changing the socket, an invalid handshake throws
ARCANE_WEBSOCKET_HANDSHAKE_INVALID with statusCode:400,headers:{};
an unsupported WebSocket version throws ARCANE_WEBSOCKET_VERSION_UNSUPPORTED
with statusCode:426 and headers:{'Sec-WebSocket-Version':'13'}. The host
owns sending that HTTP response and ending the rejected stream. Invalid socket,
data or close arguments report TypeError / RangeError; a failed send
rejects its promise without changing the payload.
An unpaired UTF-16 surrogate cannot be represented as UTF-8: sending such text
rejects with ARCANE_WEBSOCKET_TEXT_INVALID, and using it as a close reason
throws that error before changing connection state. Valid strings remain exact.
After acceptance, invalid framing reports ARCANE_WEBSOCKET_PROTOCOL_INVALID
and close status 1002; invalid text reports ARCANE_WEBSOCKET_TEXT_INVALID
and 1007. Complete platform errors remain observable. Framing lengths,
masking, the handshake's SHA-1 accept calculation and control-frame bounds are
RFC transport requirements only. There are no application message limits,
byte progress, content identities, or optional security controls.
A pre-aborted signal throws before taking ownership. Later abort destroys the
stream with an AbortError coded ARCANE_WEBSOCKET_ABORTED, preserving the
signal reason as its cause. Closing rejects new sends with
ARCANE_WEBSOCKET_CONNECTION_CLOSED (or the existing failure).
No timer silently terminates a slow close handshake; use the caller's signal or
terminate() when that owner decides to stop. Server listener closure alone,
including Node closeAllConnections(), does not own upgraded sockets. Track
connections or provide a shared lifetime signal, then await their closed
promises separately. None of this changes chat storage or persist:false.
Example
This example attaches to an already-owned listener and returns a separate
connection cleanup function. Its route and echo policy belong to the caller.
Call it with publicServer.server, publicServer.secureServer, or an SDK
development server's returned server; it creates no additional HTTP server.
import {acceptWebSocket} from 'arcane-os/websocket';
function attachEcho(server,signal){
const connections=new Set();
function upgrade(request,socket,head){
if(request.url!=='/socket'){
socket.end('HTTP/1.1 404 Not Found\r\nConnection: close\r\n\r\n');
return;
}
let connection;
try{connection=acceptWebSocket({request,socket,head,signal});}
catch(error){
console.error(error);
const status=error.statusCode??400;
const version=status===426?'Sec-WebSocket-Version: 13\r\n':'';
socket.end(`HTTP/1.1 ${status} Upgrade rejected\r\n${version}Connection: close\r\n\r\n`);
return;
}
connections.add(connection);
connection.addEventListener('error',function failed(event){console.error(event.detail);});
connection.addEventListener('message',function echo(event){
connection.send(event.data).catch(function sendFailed(error){console.error(error);});
});
connection.addEventListener('close',function remove(){connections.delete(connection);});
}
server.on('upgrade',upgrade);
return async function detach(){
server.off('upgrade',upgrade);
await Promise.all([...connections].map(function stop(connection){return connection.terminate();}));
};
}
// In browser code, after the host has selected its ws: or wss: URL:
function connectEcho(url){
const client=new WebSocket(url);
client.addEventListener('open',function greet(){client.send('The moon needs a coffee break.');});
client.addEventListener('message',function received(event){console.log(event.data);});
return client;
}
Protocol references: RFC6455,
Node upgrade event, and
native browser WebSocket.
Work is connection-local and linear in actual framing/content. Input is
assembled once per complete message; advertised lengths do not preallocate
payloads. Outbound framing snapshots each submitted message and uses native
writable backpressure. Callers await send when producing a sustained stream.
There is no history scan, app loop, diagnostic payload store or automatic retry.
The authored test/websocket.test.mjs fixtures cover this boundary; source
inspection is distinct from executing them or verifying a browser deployment.
resolvePwaRetirementResponse()
async resolvePwaRetirementResponse({workspaceRoot=process.cwd(), appId}={})
Import from arcane-os. This Node API supplies the shared disabled-PWA worker
response to an application's existing server without starting or replacing it.
It reads the current standalone workspace configuration and root authored
descriptor, using the package descriptor only when the authored file is absent.
The optional appId must match the selected descriptor. It uses the existing
configuration contracts, performs no writes and rereads current configuration
on each call; there is no retained cache, timer, subscription or dispose handle.
It returns null for a non-standalone workspace, omitted or enabled PWA, an
omitted pwa.enabled field, or an existing root arcane-sw.js entry. The author's
explicit pwa.enabled:false choice plus an ENOENT root
worker produces {statusCode:200, headers, body}, with the existing JavaScript
content type, Cache-Control: no-cache, and the complete retirement script.
Configuration/JSON errors and other filesystem failures reject. The result
carries no prior worker Last-Modified validator.
The caller owns its exact GET/HEAD /arcane-sw.js route and applies the supplied
status, headers and body through its existing node-http-server public
serve() path. A null result leaves normal routing intact. There is no request
payload transformation, server listener, generated file, cache/storage cleanup,
client enumeration or reload. The worker skips waiting on installation and
unregisters its own registration on activation; existing-page controller timing
remains browser-owned. The custom-host PWA guide
shows the complete hook and preservation contract. The Node filesystem path is
portable across Windows, Linux and macOS; Android needs its normal Node host
adaptation, and browser retirement requires native service-worker support.
startDevServer()
Overview
Starts one owned browser development server with exact runtime/app route mappings and a caller-selected bind address.
Source callers may pass core, a handle returned by
createDevelopmentCore(). The server delegates the
Core HTTP routes and closes that owner during shutdown. The existing internal
localAI handle remains accepted; core takes precedence when explicitly supplied.
HTTP and HTTPS serving use published node-http-server 10.0.0. The SDK
selects source routes and supplies generated representations; the module owns
static-file conditional GET/HEAD handling and response delivery. The SDK
retains modification dates for its generated representations. Unchanged
resources can return 304 with no body while changed resources return their
complete current representation. PEM-path listeners use module deployment and
negotiate HTTP/2 or HTTP/1.1 on the same HTTPS port. Explicit raw tls options
retain native HTTPS transport with the same module response and static-file
operations.
Static files retain the module's complete built-in MIME map, including PDF,
Markdown, audio and video. Generated representations use the same published
node-http-server/mime-types map. Existing text charsets and the
application/octet-stream fallback for unknown extensions remain unchanged;
supported document and media types need no application override.
Signature, modes, and result
async startDevServer(options={})
Import it from arcane-os. Source mode accepts
{workspaceRoot=process.cwd(), appId, mode='source', host='127.0.0.1', port=0, httpPort=0, http=false, certPath, keyPath, tls, signal, onEvent} and serves one validated
workspace application plus its complete SDK or integrated runtime. Packaged mode uses
{mode:'packaged', releaseRoot, workspaceRoot, host, port, httpPort, http=false, certPath, keyPath, tls, signal, onEvent} and serves the complete selected release files.
External source mode accepts both the installed-package route layout and the
existing physical runtime layout. Installed-package mode serves the configured
SDK resources directly from node_modules at their logical browser URLs;
it does not create a workspace arcane/ directory or require arcane.lock.json.
For a standalone appsRoot:'.' source application with explicit
pwa.enabled:false and an absent root arcane-sw.js, the exact worker URL
returns a small retirement worker. Its native install requests skipWaiting();
activation unregisters only its own registration, without a fetch handler,
storage/cache changes, client claiming or page reload. The browser owns update
timing and an open page may retain the neutral controller until its lifetime
ends. An existing authored worker, omitted/enabled PWA, multi-app source routes
and packaged mode stay unchanged. See the complete
disabled-worker lifecycle.
host defaults to 127.0.0.1 and accepts an
explicit network address or hostname. Use 0.0.0.0 for all IPv4 interfaces or
:: for the platform's IPv6 wildcard listeners. port selects the HTTPS
application port, and httpPort selects the paired HTTP redirect port. Each
defaults to 0, which asks the operating system for an available port.
The SDK request hook returns 308 for HTTP with a Location pointing to the
actual HTTPS port while preserving the original request path and query. Both listeners
use the selected host.
Source servers and packaged browser previews default to HTTPS, including
localhost. The existing https option is accepted; https:false and
tls:false alone do not disable HTTPS. HTTPS startup reads .arcane/dev/server-cert.pem and
.arcane/dev/server-key.pem relative to workspaceRoot unless explicit
certPath and keyPath are supplied together; relative paths resolve from the
workspace. A direct tls object instead supplies Node HTTPS server options, including
cert and key, without reading certificate files. Keep private material
server-side. Missing PEM files and Node certificate/key parse errors reject
startup without falling back to HTTP. Node owns TLS option handling and the
handshake; browser trust and address matching are evaluated when a client
connects. The CLI's --public selects the wildcard bind;
the API's host option alone changes only the bind address.
Explicit http:true selects one HTTP content listener in source or packaged mode and skips
certificate loading. port selects that listener's port, including 0 for an
available port. Source mode keeps the same application, runtime and generated PWA routes.
Packaged mode serves the complete selected releaseRoot; pass the artifact's
web-root directory, not its enclosing native package directory. Its declared
application start path, query and fragment are preserved. A caller requiring a
stable origin must reuse its selected host and port; a bind conflict rejects
startup rather than silently choosing another port.
http must be boolean; http:true rejects https:true,
explicit certificate/key paths, a tls value other than undefined, null or
false, and a nonzero httpPort. Browser secure-context and installation
requirements remain browser-owned; see explicit HTTP development.
The promise settles after all selected listeners are ready and resolves to
{server, protocol, mode, workspaceRoot, appId, host, port, origin, cleanUrl, url, networkUrls, httpPort, httpOrigin, httpUrl, close, closed, lifecycle}. server is the raw Node
server for application content: Http2SecureServer for PEM-backed HTTPS,
https.Server for explicit raw tls options, or http.Server for explicit
HTTP mode. HTTP/2 uses Node's compatibility request/response APIs;
callers accessing the raw server must account for its native type.
protocol describes the URL scheme: 'https:' for either negotiated HTTPS
protocol or 'http:' with explicit HTTP mode.
url and cleanUrl are the same application URL. Wildcard listeners use
localhost in that local URL; host retains the actual bound address.
httpPort is the actual HTTP listener port, httpOrigin is its HTTP origin,
and httpUrl combines that origin with the application start path. These
fields identify the redirect endpoint in HTTPS mode; origin, url, cleanUrl,
and networkUrls identify application endpoints. In HTTP mode, httpPort,
httpOrigin, and httpUrl equal port, origin, and url; they identify the
single content listener, with no redirect listener.
networkUrls lists application URLs for applicable non-loopback interface
addresses discovered once at startup. These URLs are connection candidates,
not evidence of reachability from another device. The server adds no session
capability or authentication. In packaged mode, workspaceRoot and appId
are null.
PEM-path startup reads the selected pair. The server does not create certificates or modify trust stores. Each client must trust the issuing CA and open an address covered by the server certificate. Lifecycle events and CLI summaries exclude TLS options and private key contents. See development HTTPS setup.
Starting the server opens the selected listener or listeners and emits awaited,
backpressured server.starting and server.started events. server.started
includes the selected protocol, httpPort, httpOrigin, and httpUrl alongside the application endpoint.
Request failures emit server.request.failed; shutdown emits server.stopped after owned
requests and event delivery drain. Call await result.close() in a finally
block, or abort signal; close() is idempotent and returns the
same settlement represented by both closed and lifecycle. Closing the
operation closes every selected listener once. A listener error or an
event-callback failure closes the operation and rejects the lifecycle. Invalid
mode/host/port/httpPort, malformed workspace or release content, an occupied port,
or an already-aborted signal rejects startup.
Availability and normalization
Node control plane; browser data plane. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {startDevServer} from 'arcane-os';
async function inspectSourceServer(workspaceRoot, signal) {
const running = await startDevServer({
workspaceRoot,
appId: 'example-app',
mode: 'source',
host: '127.0.0.1',
port: 0,
signal
});
try {
// Hand running.url directly to the intended development browser.
console.log(`Serving on ${running.origin}`);
return {origin: running.origin, port: running.port};
} finally {
await running.close();
}
}
startSourceExampleServer()
Overview
Starts a generic server for examples that consume live source trees. The
caller explicitly maps URL prefixes to directories, so an example can serve
its own small wrapper, SDK src, browser-runtime, and runtime trees, and an
external model directory without copying those files or owning a static-server
implementation.
Signature, options, and result
async startSourceExampleServer(options={})
Import it from arcane-os. Options are
{mounts, startPath='/', host='127.0.0.1', port=0, tls, crossOriginIsolated=false, signal, onEvent}. mounts is a nonempty array of
{urlPath, root, index?, include?} records:
urlPathis an absolute URL path. Nested mounts are allowed and the longest matching URL path owns the request.rootis a filesystem path orfile:URL. It is resolved when the server starts, but the directory does not need to exist until a file is requested.indexoptionally names the relative file used for a mount or directory URL.includeoptionally lists exact relative files and directory prefixes ending in/. When omitted, every regular file under the mount is addressable.
startPath is returned in the public URL and receives a redirect from / when
it is not /. host and port are passed to the owned Node listener; an
explicit 0.0.0.0 or :: host allows LAN access. tls, when supplied, is the
ordinary options object passed to node:https.createServer. Set
crossOriginIsolated:true when a browser-WASM example needs
Cross-Origin-Opener-Policy: same-origin and
Cross-Origin-Embedder-Policy: require-corp; otherwise those headers are
absent. The helper adds no Content Security Policy.
GET and HEAD stream the complete selected regular file. A single HTTP Range is handled automatically, including open-ended and suffix ranges. Content length, content range, and range offsets exist only as required HTTP transport framing; they are not size limits, admission rules, progress values, or product policy. Missing mounts remain lazy and return 404 until their files exist. Unsupported methods return 405 and an invalid range returns 416.
The promise settles after the listener is ready and resolves to
{server, protocol, host, port, origin, url, close, closed}. server is the
raw Node HTTP or HTTPS server, close() is idempotent, and closed settles
when the listener closes. It rejects with an operational server failure after
the listener closes. An abort signal closes the listener. Optional onEvent
receives source-server.starting, source-server.started,
source-server.request.failed, and source-server.failed records; an event
listener failure is logged without replacing the request outcome.
Availability and normalization
Node control plane; browser data plane. Explicit URL mounts, complete file streaming, protocol-local HTTP ranges, and a closeable server result. Deep protocol: Node ESM.
Example
import {startSourceExampleServer} from 'arcane-os';
async function serveSourceExample(signal) {
const running = await startSourceExampleServer({
mounts: [
{
urlPath: '/examples/chat',
root: new URL('./', import.meta.url),
index: 'index.html',
include: ['index.html', 'app.js', 'assets/']
},
{
urlPath: '/src',
root: new URL('../../src/', import.meta.url)
},
{
urlPath: '/browser-runtime',
root: new URL('../../browser-runtime/', import.meta.url)
},
{
urlPath: '/runtime',
root: new URL('../../runtime/', import.meta.url)
},
{
urlPath: '/examples/chat/models',
root: process.env.ARCANE_EXAMPLE_MODEL_ROOT
|| new URL('./models/', import.meta.url)
}
],
startPath: '/examples/chat/',
host: '127.0.0.1',
port: 8444,
crossOriginIsolated: true,
signal
});
console.log(`Serving on ${running.url}`);
return running;
}
validateWorkspace()
Overview
Runs canonical workspace, runtime, descriptor, and selected-app validation with progress events.
Signature and result
async validateWorkspace({
workspaceRoot=process.cwd(),
appId,
allowMissingManagedImportMap=false,
signal,
onEvent
}={})
Import it from arcane-os. It resolves to a validation result with
valid, workspaceMode, workspaceRoot, appId, appRoot, the selected
configuration/application, lock data where the layout uses it, and completed
checks. External installed-v1 selection reads package metadata directly and
does not require a workspace arcane.lock.json or runtime projection. For an
external workspace the result additionally includes the installed package:
const result = {
sdkInstallation: {
dependencyName,
packageSource,
canonicalPackageRoot,
packageName: 'arcane-os',
packageVersion,
runtimeRoot,
browserRuntimeRoot
}
};
The dependency can be named arcane-os or use an npm alias for the selected
arcane-os version. The configured package source must match that declaration;
packageVersion reports the installed package's version. Duplicate
canonical/alias declarations reject.
allowMissingManagedImportMap is an internal packaging/development seam. An
ordinary caller should leave it false.
Availability and normalization
Node. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Node ESM.
Example
import {validateWorkspace} from 'arcane-os';
const validation = await validateWorkspace({
workspaceRoot: process.cwd(),
appId: 'hello-world'
});
console.log(validation.sdkInstallation?.dependencyName);
console.log(validation.sdkInstallation?.packageVersion);
Headless toolchain operations
buildApplication()
Overview
Builds one explicitly selected target through its adapter. A paired native builder packages the selected app and its explicit bundled-app closure, then passes those complete releases to the provider. Provider verification and host launch remain separate operations.
The selected target reaches each app's packager, so every app's own
nativeResources and separate native input directory apply consistently to
both copying and output-overlap calculations. The provider receives the actual
release roots, manifests and complete file readers. An explicit nativeBuilder
retains its existing identity and contract. See
portable Core packaging.
Signature and result
async buildApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {buildApplication} from 'arcane-os';
async function usebuildApplication(...arguments_) {
return buildApplication(...arguments_);
}
bundleApplication()
Overview
Creates one deterministic external application bundle from one authenticated packaged release.
The high-level operation reads the app's selected package directory. Its default archive is placed beside that directory; an explicit artifact path retains the existing output-path contract.
Signature and result
async bundleApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {bundleApplication} from 'arcane-os';
async function usebundleApplication(...arguments_) {
return bundleApplication(...arguments_);
}
checkApplication()
Overview
Runs the selected application or integrated shared validation boundary.
Signature and result
async checkApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {checkApplication} from 'arcane-os';
async function usecheckApplication(...arguments_) {
return checkApplication(...arguments_);
}
createApplication()
Overview
Creates one new external application workspace through the shared headless toolchain.
Signature and result
async createApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {createApplication} from 'arcane-os';
async function usecreateApplication(...arguments_) {
return createApplication(...arguments_);
}
createToolchain()
Overview
Returns a frozen convenience object that applies shared defaults to every headless application operation.
The object includes importMap(options), which merges defaults with explicit
call options and refreshes every directly navigable descriptor-selected browser
document for one selected app. The equivalent generic route is
execute('import-map', options).
For a standalone root app with pwa.enabled:false, ordinary refresh removes
marked SDK-generated PWA references from selected documents. An explicit
importMap({retireGeneratedPwa:true}) also retires the four standard root PWA
outputs and matching older manifest references after the application owner
confirms they are generated. See disabled-PWA retirement
for the required source-selection adjustment and preserved content.
It also includes upgrade(options), which performs the explicit installed-SDK
consumer upgrade described by upgradeApplication(), and
updateCheck(options), which invokes checkSdkUpdate() once. Constructing the
toolchain does not check, poll, schedule, download, install, regenerate, or
mutate anything.
Signature and result
createToolchain(defaults={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {createToolchain} from 'arcane-os';
const toolchain = createToolchain({
workspaceRoot: process.cwd(),
appId:'hello-world',
onEvent(event) {
console.info(event.type);
}
});
// Only this explicit call refreshes the managed map and selected HTML documents.
const result = await toolchain.importMap();
console.log(Object.keys(result.importMap.imports).length);
console.log(result.importMap.documentPaths, result.importMap.documentCount);
describeTargets()
Overview
Returns the normalized target catalog through the headless operation lifecycle.
Signature and result
async describeTargets(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {describeTargets} from 'arcane-os';
async function usedescribeTargets(...arguments_) {
return describeTargets(...arguments_);
}
developApplication()
Overview
Starts one owned browser development server for the selected application.
The selected descriptor's native.services composes application Core services
independently of local AI. Programmatic serviceModules:[{module,options}]
replaces that list; services adds constructed service definitions and context
supplies app-owned launch fields. The result adds core when composed and retains
localAI for selected native local AI. Page rendering and the listener do not
wait for service readiness. See source-development Core
for explicit /arcane-core.js loading, cancellation and current-state replay.
http, https, certPath, keyPath, and tls follow the
startDevServer() transport contract, alongside host, port, and
httpPort. By default, port selects HTTPS and httpPort selects the HTTP 308
redirect listener; each defaults to an available port. Explicit http:true
selects one source HTTP content listener at port, without certificate loading.
The operation refreshes the selected authored descriptor's arcane-package.json
projection and managed import maps under one development-refresh lock, then
releases that lock before opening the selected source listener or listeners.
It returns their application endpoints and shared shutdown
lifecycle. Package-only apps remain unchanged. The operation generates
no packaged output; enabled PWA manifests
are served directly from the selected source resources.
The source listener also supplies the disabled-worker retirement lifecycle for explicit disabled standalone PWA configuration when the root worker is absent. This does not grant filesystem retirement authority or change the refresh operation's preservation of authored files. Browser activation and unregistration proceed through the native lifecycle without clearing saved data or reloading an open page.
Signature and result
async developApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {developApplication} from 'arcane-os';
async function usedevelopApplication(...arguments_) {
return developApplication(...arguments_);
}
executeOperation()
Overview
Dispatches one named headless SDK operation with normalized acceptance, events, cancellation, and failure.
The exact command 'import-map' dispatches one app-scoped refresh across the
.html/.htm documents selected by
package.documents or automatic discovery, and returns
{workspaceRoot, workspaceMode, appId, importMap}. The importMap value reports the generated imports and complete
ordered documentPaths. This route mutates the map artifact and selected managed HTML
documents through sequential writes and has no supported dry-run or
all-file transaction. An error or cancellation can leave completed writes in
place; rerun the operation after resolving the cause.
For a standalone appsRoot:'.' app with pwa.enabled:false, ordinary refresh
removes active generated registration scripts and matching manifest relationships
marked data-arcane-manifest. Unmarked references and existing PWA files remain.
Set retireGeneratedPwa:true only after confirming generated ownership of the
matching root manifest references and all four standard outputs:
arcane.webmanifest, arcane-offline.json, arcane-sw.js and arcane-pwa.mjs.
Remove those generated outputs from required package.include entries first,
and confirm that unselected documents no longer need them. The operation writes
selected reference changes before deleting these files; its
import-map.root-files.completed event reports actual removed paths in
retiredPwa. Repeated retirement accepts already-absent output.
An omitted PWA record selects no retirement; an enabled record keeps normal generation. The option belongs only to this explicit import-map API route. Ordinary development refresh does not forward file-retirement authority, and there is no new CLI flag. Other files, unselected/inactive HTML, authored content and browser registrations, caches and saved data keep their existing ownership. See the complete source PWA contract.
The exact command 'upgrade' dispatches upgradeApplication(options). It is
external-workspace-only and runs that application's ordinary npm upgrade
command. It does not independently reconcile the installed SDK projection,
semantic Arcane lock, or managed import map; npm retains authority for
dependency selection and network behavior.
The exact command 'update-check' dispatches one checkSdkUpdate(options)
call. Dispatch never installs a recurring task, polls application state, or
causes another command to check for updates implicitly. There is no exported
importMapApplication() or generateImportMap() binding and no
arcane-os/import-map package subpath.
Signature and result
async executeOperation(command, options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {executeOperation} from 'arcane-os';
const result = await executeOperation('import-map', {
workspaceRoot:process.cwd(),
appId:'hello-world'
});
console.log(result.importMap.committed, Object.keys(result.importMap.imports).length);
console.log(result.importMap.documentPaths, result.importMap.documentCount);
packageApplication()
Overview
Runs the high-level package operation for one selected application. It reads
the installed SDK/runtime selection and packages the saved source and managed
import maps through packageApp(). Map generation remains the explicit
arcane import-map operation and the ordinary arcane dev startup refresh.
Root app files retain their paths at the output root, while explicitly nested
apps retain apps/<id>/ paths alongside the shared routes and any root launcher
described by packageApp().
The same low-level operation resolves the app's optional outputDirectory;
there is no separate high-level destination override. release.outputRoot
names the resulting complete release directory, with omitted configuration
retaining dist/<app-id>. Browser preview and bundle creation use that selected
root. This ordinary package operation retains browser selection; paired native
assembly through buildApplication() separately passes its actual target and
applies each app's native-resource output selection.
Packaging does not automatically run tests or checks. Verification occurs only
when explicitly requested or when required for the selected release output.
A failure leaves the prior distribution untouched. Success returns the selected
workspace and app identity plus release, containing the low-level package
result, manifest, and complete file inventory. ARCANE_APP_RELEASE.json records
that inventory and the distinct app-relative app.entry and package-relative
app.start; it remains package metadata rather than an application route.
Signature and result
async packageApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {packageApplication} from 'arcane-os';
const result = await packageApplication({
workspaceRoot: process.cwd(),
appId: 'hello-world'
});
console.log(result.release.manifest.app.start, result.release.files);
planApplication()
Overview
Creates one authenticated native build plan without executing the provider build.
Signature and result
async planApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {planApplication} from 'arcane-os';
async function useplanApplication(...arguments_) {
return planApplication(...arguments_);
}
repositoryApplication()
Overview
Dispatches one selected repository status, pull, or push operation through the headless lifecycle.
Signature and result
async repositoryApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {repositoryApplication} from 'arcane-os';
async function userepositoryApplication(...arguments_) {
return repositoryApplication(...arguments_);
}
runApplication()
Overview
Runs a browser app or performs the selected native build/launch lifecycle for one target. It does not run tests or checks automatically; selected release-output verification remains explicit to that release operation.
Browser runs resolve the app's current outputDirectory, defaulting to
dist/<app-id>, and preview that existing release without repackaging it.
Native artifact output remains separately selected by its target contract.
Signature and result
async runApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {runApplication} from 'arcane-os';
async function userunApplication(...arguments_) {
return runApplication(...arguments_);
}
testApplication()
Overview
Runs the selected application's exact test boundary or one integrated shared test.
For external and modern integrated apps, app-scope testing authenticates the
existing managed import-map artifact against the selected runtime and each
selected HTML document before launching isolated files. The child loader maps
only exact entries such as arcane/SpeechPlayback, preserves
arcane-os/testing, resolves supported URL-like compatibility keys, and rejects
an unmapped arcane/* or #arcane/* specifier. The compact map
locator is removed from the child environment before application test code is
imported.
Signature and result
async testApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {testApplication} from 'arcane-os';
async function usetestApplication(...arguments_) {
return testApplication(...arguments_);
}
upgradeApplication()
Overview
Runs the selected external installed-SDK application's ordinary npm upgrade
command without adding a separate lock, runtime, import-map, authentication, or
reconciliation workflow. npm retains authority for dependency selection and
network behavior.
Signature and result
async upgradeApplication(options={})
The mutable arcane-application-upgrade result includes workspaceRoot,
workspaceMode, appId, and the normal process result (command, args,
cwd, code, stdout, and stderr).
Availability and normalization
Node; external installed-SDK workspaces only. SDK-normalized inputs, errors, events, and documented process results.
Example
import {upgradeApplication} from 'arcane-os';
const upgraded=await upgradeApplication({
workspaceRoot:process.cwd(),
appId:'hello-world'
});
console.log(upgraded.command,upgraded.args,upgraded.code);
verifyApplication()
Overview
Runs the high-level verification operation for one selected browser release.
Signature and result
async verifyApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {verifyApplication} from 'arcane-os';
async function useverifyApplication(...arguments_) {
return verifyApplication(...arguments_);
}
verifyBundleApplication()
Overview
Runs the high-level external bundle verification operation.
Signature and result
async verifyBundleApplication(options={})
Import it from arcane-os or arcane-os/toolchain. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node; selected operation may produce browser or native output. SDK-normalized inputs, errors, events, and documented result. Deep protocol: Shared headless operation API + arcane-cli-events/1.
Example
import {verifyBundleApplication} from 'arcane-os';
async function useverifyBundleApplication(...arguments_) {
return verifyBundleApplication(...arguments_);
}
Events, processes, and testing
createReporter()
Overview
Creates the ordered CLI reporter that normalizes accepted, progress, terminal, JSON, and NDJSON event delivery.
Signature, state, and output
createReporter({ command, output='human', stdout=process.stdout, stderr=process.stderr, operationId=randomUUID(), clock=()=>new Date() }={})
Import it from arcane-os or arcane-os/events. This function returns
synchronously. output must be "human", "json", or "ndjson".
stdout and stderr are writable streams; operationId and clock can be
injected for deterministic tests.
The returned object is
{operationId, output, accept, emit, forward, complete, reject, accepted, terminal}. accepted and terminal are live getters. Call accept(data)
before emit(type, data, message) or forward(value, data). Acceptance happens
once; later accept() calls return null. complete(result) and
reject(error) are mutually terminal, and later progress or terminal calls
return null. Each emitted event contains arcane-cli-events/1, the operation
id, a strictly increasing sequence, an ISO timestamp, the command, type, status,
and JSON-safe data. Circular members and unsupported JSON values are omitted;
errors are reduced through errorRecord().
Human mode writes work events to stderr, readable results to stdout, and a
completion line to stderr. JSON mode writes work events to stderr and exactly
one final success/error envelope to stdout. NDJSON mode writes every event to
stdout. Reporter methods write synchronously to the supplied streams; they do
not provide backpressure promises, cancellation, or receipts. An unsupported
mode, emit() before acceptance, an invalid clock result, or a stream write
failure throws synchronously.
Availability and normalization
Node. SDK event/error/report normalization. Deep protocol: arcane-cli-events/1.
Example
import {createReporter} from 'arcane-os';
const reporter = createReporter({command: 'check', output: 'human'});
reporter.accept({appId: 'example-app'});
reporter.emit(
'workspace.validate.check',
{name: 'descriptor', ok: true},
'Validated the application descriptor.'
);
reporter.complete({ok: true});
default()
Overview
Default-export alias of the public test registration function.
Signature and result
default(name, optionsOrCallback, maybeCallback)
Import it from arcane-os/testing. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK event/error/report normalization. Deep protocol: Node ESM / owned process or test lifecycle.
Example
import test from 'arcane-os/testing';
test('adds two values', () => {
if (1 + 1 !== 2) throw new Error('Unexpected result.');
});
DEFAULTTESTTIMEOUT_MS
Overview
Default timeout applied by the public isolated test API.
Value and import
const DEFAULT_TEST_TIMEOUT_MS
Import it from arcane-os or arcane-os/testing. Treat arrays and records as immutable public values.
Availability and normalization
Node. Exact immutable SDK value. Deep protocol: Node ESM / owned process or test lifecycle.
Example
import {DEFAULT_TEST_TIMEOUT_MS} from 'arcane-os';
console.log(DEFAULT_TEST_TIMEOUT_MS);
registeredTestCount()
Overview
Returns the number of tests registered in the current isolated test realm.
Signature and result
registeredTestCount()
Import it from arcane-os or arcane-os/testing. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK event/error/report normalization. Deep protocol: Node ESM / owned process or test lifecycle.
Example
import {registeredTestCount} from 'arcane-os';
console.log(registeredTestCount());
createGitTextSnapshot()
Overview
Reads complete application-selected UTF-8 text from one fetched revision using a dedicated bare Git cache. It does not create or alter a working checkout.
Signature, lifecycle, and result
createGitTextSnapshot({cacheDirectory,remote,remoteBase,ref,selectPath,allowUnborn=false,gitIdentity,onEvent,run=runProcess}={})
Import from arcane-os. The application owns the cache location, remote, ref,
path predicate and service factory. The returned refresh({signal}={}) returns
{revision,files:[{path,content}]} in Git tree order. Concurrent calls share work;
unchanged fetched revisions reuse completed text retrieval. Caller cancellation
ends only that wait. close(), drain() and dispose() stop acceptance and
await accepted refresh/process cleanup. Errors remain observable instead of
returning stale or partial success. See Git text snapshots
for complete inputs, text semantics, errors, events and Core service composition.
Optional allowUnborn:true observes the complete remote advertisement on every
acquisition. Only successful empty output returns
{revision:null,files:[],unborn:true}; committed results add unborn:false and
retain the actual commit even for an empty tree. Any advertised HEAD, branch
or tag continues through ordinary selected-ref fetch; missing refs and actual
Git failures remain errors. Omitted/false preserves the prior result and commands.
See unborn remotes.
Optional remoteBase explicitly selects remote as a local filesystem locator.
Only its Git fetch argument is derived using path.resolve(remoteBase, remote),
once at construction, independently of the cache location and later changes to
the working directory. Relative bases, including '', use the construction-time
working directory. Original locator/options remain unchanged. Omission preserves
Git remote names, URLs, SCP-like addresses and remote-helper strings without
guessed parsing. Unrepresentable base text reports TypeError without
transformation; actual Git failures retain their existing error behavior.
See relative local repository locators.
Optional gitIdentity:{name?,email?,username?} captures a child-process-only
selection for init/fetch and subsequent Git commands, preserving shared refresh
cancellation and complete content. See Git identity configuration
for author precedence, scoped defaults and credential username semantics.
Example
import {createGitTextSnapshot} from 'arcane-os';
const dispatches = createGitTextSnapshot({
cacheDirectory: applicationCacheDirectory,
remote: applicationRepository,
ref: applicationRef,
selectPath: function selectDispatch(filename) {
return filename.startsWith('dispatches/') && filename.endsWith('.md');
}
});
const snapshot = await dispatches.refresh({signal});
await dispatches.close();
runProcess()
Overview
Runs one shell-free child command with complete stdout and stderr, ordered stream events, heartbeats, and explicitly selected process cancellation behavior.
Signature, parameters, and result
async runProcess(command, args=[], { cwd, env, signal, onEvent, onOutput, captureOutput=true, emitOutputEvents=true, outputEncoding='utf8', heartbeatMs=5000, terminationGraceMs=DEFAULT_TERMINATION_GRACE_MS, allowNonzero=false, input, cancellationMode='terminate-tree' }={})
Import it from arcane-os. command is executed directly with shell:false;
args must be a fixed array of strings, so shell expansion, pipelines, and
redirection never occur. cwd selects the child directory. env is shallowly
merged over process.env. In the default cancellationMode:'terminate-tree',
supplied input is written once and stdin is closed; otherwise stdin closes
immediately. With cancellationMode:'close-input', optional input is written
once and stdin remains open until cancellation or a callback/input failure
requests shutdown. On Microsoft NT, npm and npx are normalized to their Node
CLI entrypoints.
For the literal git command on Windows, the default runner reads Git for
Windows' registered InstallPath in the current-user and machine registry
views. When that installation's cmd/git.exe exists, its cmd directory is
appended only to this child's effective PATH. Existing entries and native
command lookup retain priority; duplicate Path/PATH spellings follow Node's
lexical selection. Other environment fields, explicit executable paths,
custom process adapters, other commands and other platforms keep their existing
behavior. No global environment or registry setting is changed, and no Git
download, installation or command retry occurs.
One successful location is retained in memory for this process while its
executable remains present. A removed executable triggers fresh discovery;
absent, failed and cancelled lookups are not retained. Concurrent cold callers
own independent discovery and cancellation. The standard Windows registry
helper uses the existing process owner; its lifecycle callbacks have
process.git.discovery.* event names, and its captured metadata is separate
from the requested command's output. Missing registration leaves ordinary
lookup unchanged. Discovery failure emits process.git.discovery.unavailable
with the complete error before ordinary lookup continues. Cancellation or an
event-callback failure stops the operation before Git starts. Normal Git
errors and missing-working-directory errors remain actual command failures.
An AsyncIterable input instead feeds stdin with awaited writes and closes it
when the producer finishes. Its return() must cooperate with cancellation of
an outstanding next(); the process owner drains both input and output work.
onOutput({stream,chunk}) receives complete ordered chunks and is awaited with
backpressure for each stream. UTF-8 decoding retains split characters. The
default capture and nonempty-line events remain unchanged; line events are not
a substitute for lossless chunk delivery.
captureOutput and emitOutputEvents accept booleans or per-stream selections,
for example {stdout:false} while stderr retains its default. A stream with
capture disabled returns null and requires an onOutput consumer.
outputEncoding defaults to 'utf8'; explicitly selecting null, globally or
per stream such as {stdout:null}, delivers native Buffer chunks unchanged.
A raw stream requires capture and line events explicitly disabled for that
stream plus an onOutput owner. It is never decoded or sent as text implicitly.
Complete failed chunks, original callback failures, process diagnostics and
exit results remain available through the normal error record after drain.
onEvent is awaited in order for process.starting, nonempty
process.stdout/process.stderr lines, coalesced process.heartbeat, and the
terminal process event. Stream delivery pauses the corresponding child stream
while the callback owns that chunk. heartbeatMs defaults to 5 seconds; the
timer applies a 1-second floor to ordinary numeric values.
terminationGraceMs defaults to 1,500 ms and must
be an integer from 100 through 30,000. allowNonzero:false rejects a nonzero
exit; true returns it as data.
The promise resolves to
{command, args, cwd, code, signal, stdout, stderr}. Here signal is the
child's terminating signal name or null, not the input AbortSignal. args
is copied, cwd defaults to the current process directory, and each captured
text stream preserves its complete content. A missing executable rejects with
ARCANE_PREREQUISITE_MISSING; invalid arguments, a disallowed nonzero exit,
and spawn/runtime failures use the normalized SDK error boundary, with the
nonzero result retained in error details.
Aborting signal emits cancellation-requested state. The default mode terminates
the owned process tree and escalates after the grace interval. close-input
instead closes only the child's stdin, with no forced termination or deadline;
the selected child must own EOF shutdown. This lets a native host finish
accepted service work before exiting. Both paths continue observing output and
drain event delivery before rejection with ARCANE_CANCELLED and exit code 130.
An abort after the child's close event does not cancel already completed work.
An onEvent failure requests shutdown through the same selected mode. The
close-input failure retains the child's complete result in details and
additional failures in errors, with the original primary error as cause
when wrapping is needed. A cancellation rejection can therefore contain a
successful child exit code 0; that is the child's drained result, distinct
from the cancelled caller operation. Cancellation cannot reverse external
effects already performed by the command.
Availability and normalization
Node. SDK event/error/report normalization. Deep protocol: Node ESM / owned process or test lifecycle.
Example
import {runProcess} from 'arcane-os';
const result = await runProcess(process.execPath, ['--version'], {
cwd: process.cwd(),
onEvent(event) {
if (event.type === 'process.stderr') console.error(event.message);
}
});
console.log(result.stdout.trim(), result.code);
runRegisteredTests()
Overview
Executes the current isolated realm's registered tests once and returns the normalized Vanilla Test report.
Signature, lifecycle, and result
async runRegisteredTests({signal, requireTests=true, onPhase}={})
Import it from arcane-os or arcane-os/testing. Register every top-level test
with test() before this call. One module realm can run its registry only once;
a second call rejects with ReferenceError. With requireTests:true, an empty
registry becomes one failed report outcome. Set it to false only when an empty
suite is intentional.
Tests run sequentially. A test callback receives
{signal, after(callback), test(name, options?, callback)} for cooperative
cancellation, FIFO cleanup, and owned nested tests. Each test uses its declared
timeout or DEFAULT_TEST_TIMEOUT_MS; test timeouts can abort the remainder of
the run, cleanup and report phases have their own bounded timeouts, and cleanup
is skipped after fatal timeout or cancellation because JavaScript promises
cannot be preempted safely. The awaited onPhase callback receives started and
completed records for test, cleanup, and report phases. A phase-callback failure
is authoritative and can reject the run.
The promise resolves to the frozen Vanilla Test snapshot
{passed, failed, total, failureCount, ok, report}. passed and failed are
frozen description arrays and report is the rendered text. Ordinary assertion
failures produce ok:false; invalid API use, cancellation, a fatal timeout, or
an authoritative phase/report failure rejects. Aborting signal propagates to
the currently owned test and stops later tests, but test callbacks must observe
their supplied signal to stop host work cooperatively.
Availability and normalization
Node. SDK event/error/report normalization. Deep protocol: Node ESM / owned process or test lifecycle.
Example
import {runRegisteredTests, test} from 'arcane-os/testing';
test('normalizes an application id', () => {
const value = 'example-app'.trim();
if (value !== 'example-app') throw new Error('Unexpected id.');
});
const report = await runRegisteredTests({
onPhase(phase) {
if (phase.status === 'started') console.log(phase.name);
}
});
if (!report.ok) process.exitCode = 1;
test()
Overview
Registers one public test, optional timeout, callback, nested cases, and FIFO cleanup in the isolated runner.
Signature and result
test(name, optionsOrCallback, maybeCallback)
Import it from arcane-os or arcane-os/testing. The signature above states whether settlement is synchronous or promise-based. The overview and owning group define result authority, side effects, callbacks, events, cancellation, and lifecycle.
Availability and normalization
Node. SDK event/error/report normalization. Deep protocol: Node ESM / owned process or test lifecycle.
Example
import {test} from 'arcane-os';
test('adds two values', () => {
if (1 + 1 !== 2) throw new Error('Unexpected result.');
});
Explicit SDK update checks
This is an on-demand Node.js control-plane and CLI maintainer surface. It never runs from renderer application code automatically. One call can make one ordinary HTTP or HTTPS GET to the selected npm registry and reads the complete response subject only to unavoidable HTTP framing; there is no polling, recurrence, interval, background agent, download, install, dependency mutation, runtime replacement, or self-update. The only timer is the timeout owned and cleared by that one request.
SDKUPDATEREGISTRY
Overview
Default npm registry root for an explicit SDK update check.
Value
const SDK_UPDATE_REGISTRY = 'https://registry.npmjs.org/'
The request builder appends the fixed
-/package/arcane-os/dist-tags endpoint only after validating the root.
Availability and normalization
Node; on-demand CLI or maintainer check only. Exact default HTTPS origin string. Importing it performs no request and starts no timer.
Example
import {SDK_UPDATE_REGISTRY, validateUpdateRegistry} from 'arcane-os';
const registry = validateUpdateRegistry(SDK_UPDATE_REGISTRY);
console.log(registry.origin);
SDKUPDATETIMEOUT_MS
Overview
Default timeout for the single registry request owned by an explicit update check.
Value
const SDK_UPDATE_TIMEOUT_MS = 2500
Availability and normalization
Node; on-demand CLI or maintainer check only. Exact default millisecond integer. Accepted per-call timeouts are positive safe integers.
Example
import {SDK_UPDATE_TIMEOUT_MS} from 'arcane-os';
console.log(`Update-check timeout: ${SDK_UPDATE_TIMEOUT_MS} ms`);
checkForSdkUpdate()
Overview
Performs exactly one complete registry read and reports whether the npm dist-tag selected for the installed SDK is newer. It only checks metadata; it does not download, install, mutate, or schedule anything.
Signature and parameters
async checkForSdkUpdate({
packageName=SDK_NAME,
currentVersion=SDK_VERSION,
registry=SDK_UPDATE_REGISTRY,
timeoutMs=SDK_UPDATE_TIMEOUT_MS,
fetchImpl=globalThis.fetch,
signal,
onEvent,
clock=()=>new Date()
}={})
packageName must be exactly arcane-os. currentVersion must be strict
semantic version text: prereleases select npm dev, while stable versions
select latest. registry must pass validateUpdateRegistry(); ordinary HTTP
and HTTPS npm registries, including caller-selected local or corporate paths,
remain functional. fetchImpl and clock are explicit injection points.
timeoutMs is a positive safe integer. signal provides caller
cancellation, and each supplied onEvent callback is awaited.
The request is one ordinary GET accepting JSON and follows the selected
runtime's normal registry behavior. The response must return HTTP 200 and JSON
media type, be valid UTF-8, and decode to a nonempty dist-tag object whose
string values are strict semantic versions.
Result, events, and errors
The promise resolves to a mutable object:
{
packageName,
currentVersion,
registryVersion,
tag, // 'dev' or 'latest'
status, // 'update-available', 'current', or 'ahead'
updateAvailable,
registry, // normalized origin
checkedAt // clock().toISOString()
}
After initial validation it emits awaited update.check.started. Success emits
update.check.completed; a non-cancellation request or response failure emits
update.check.failed with the normalized failure code.
Registry, timeout, HTTP, content, JSON, dist-tag, version, or clock
failures reject with ARCANE_UPDATE_CHECK_FAILED. Caller cancellation rejects
with ARCANE_CANCELLED; it is distinct from the per-request timeout. Event
callbacks are awaited, and a callback rejection can reject or replace the
operation's normal settlement; it is never ignored. The owned timeout is cleared
in finally.
Availability and normalization
Node; on-demand CLI or maintainer check only. Registry data is reduced to one mutable status result. No provider payload becomes installation authority, and applications never invoke this function automatically.
Example
import {checkForSdkUpdate} from 'arcane-os';
// Defined for an explicit maintainer action; this function is not scheduled.
async function checkInstalledSdkOnce(signal) {
const result = await checkForSdkUpdate({
signal,
onEvent(event) {
console.info(event.type, event.message);
}
});
console.log(result.status, result.registryVersion);
return result;
}
checkSdkUpdate()
Overview
High-level toolchain/CLI wrapper for exactly one checkForSdkUpdate() call.
Signature and result
async checkSdkUpdate(options={})
Import it from arcane-os or arcane-os/toolchain.
It forwards the options unchanged and preserves the direct result, events,
errors, cancellation, timeout, and security boundary. executeOperation()
routes the exact command 'update-check' here, and createToolchain() exposes
it as updateCheck(options). Neither route polls or schedules a later call.
Availability and normalization
Node; on-demand CLI or maintainer check only. Same normalized contract as
checkForSdkUpdate() with no additional request or mutation.
Example
import {checkSdkUpdate} from 'arcane-os';
async function runRequestedUpdateCheck(signal) {
const result = await checkSdkUpdate({signal});
return result.updateAvailable;
}
compareSdkVersions()
Overview
Synchronously compares two strict semantic SDK versions without network access.
Signature and result
compareSdkVersions(leftValue, rightValue)
Returns -1 when the left version has lower precedence, 0 when precedence is
equal, and 1 when it is higher. Major, minor, patch, then semantic prerelease
identifiers are compared. A stable version outranks a prerelease at the same
core version; build metadata does not affect precedence. Invalid input throws
the packager's semantic-version validation error synchronously.
Availability and normalization
Node; on-demand CLI or maintainer check only. Pure in-process comparison; no request, timer, event, mutation, or cancellation contract.
Example
import {compareSdkVersions} from 'arcane-os';
console.log(compareSdkVersions('0.1.0-dev.4', '0.1.0-dev.5')); // -1
console.log(compareSdkVersions('1.0.0+local', '1.0.0+registry')); // 0
updateTagForVersion()
Overview
Selects the one npm dist-tag appropriate for an installed SDK version.
Signature and result
updateTagForVersion(value)
Returns 'dev' when the strict semantic version contains any prerelease
identifier and 'latest' otherwise. Invalid input synchronously throws
ARCANE_UPDATE_CHECK_FAILED with the semantic-version error as its cause.
Availability and normalization
Node; on-demand CLI or maintainer check only. Pure dev/latest
normalization; no registry request or state change.
Example
import {updateTagForVersion} from 'arcane-os';
console.log(updateTagForVersion('0.1.0-dev.4')); // dev
console.log(updateTagForVersion('1.0.0')); // latest
validateUpdateRegistry()
Overview
Synchronously validates one ordinary HTTP or HTTPS registry URL.
Signature and result
validateUpdateRegistry(value)
The URL must use HTTP or HTTPS. Caller-selected credentials, ports, paths,
queries, and normal redirects remain under the selected registry and Fetch
runtime. The function returns the normalized URL object and performs no DNS
lookup or request.
Invalid syntax or an unsupported scheme throws synchronously with
ARCANE_UPDATE_CHECK_FAILED.
Availability and normalization
Node; on-demand CLI or maintainer check only. URL normalization only; no request, polling, or mutation.
Example
import {SDK_UPDATE_REGISTRY, validateUpdateRegistry} from 'arcane-os';
const registry = validateUpdateRegistry(SDK_UPDATE_REGISTRY);
console.log(registry.href); // https://registry.npmjs.org/
Central events, time travel, and DOM instrumentation
ARCANEEVENTSTACK_PROTOCOL
Overview
The exact discriminator for serialized Arcane event-stack documents and every record they contain. Use it to reject incompatible diagnostic files before review or playback.
Value and use
const ARCANE_EVENT_STACK_PROTOCOL = 'arcane-event-stack/1'
This is a data-format version, not the Core arcane/1 RPC protocol and not a network transport. parseEventStack() enforces it on the document and each retained record. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Node and browser/bundler. Exact host-neutral protocol string; it grants no capability or authority.
Example
import {ARCANE_EVENT_STACK_PROTOCOL} from 'arcane-os/event-manager';
if (document.protocol !== ARCANE_EVENT_STACK_PROTOCOL) {
throw new Error('Unsupported event stack.');
}
DEFAULTDOMEVENT_TYPES
Overview
The mutable default list of 44 capture-phase browser interaction names observed by DOM instrumentation. Pass a smaller eventTypes array when a debugger needs only a focused interaction class.
Value and use
const DEFAULT_DOM_EVENT_TYPES
The list is configuration, not an event source. Observation begins only after a controller starts, normally because time travel is enabled on a manager with attached DOM instrumentation. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Node and browser/bundler; meaningful to browser DOM instrumentation. The array contains the exact event-name strings; live host event objects are never stored in this value.
Example
import {DEFAULT_DOM_EVENT_TYPES} from 'arcane-os/event-manager';
console.log(DEFAULT_DOM_EVENT_TYPES.includes('click'));
DOMINTERACTIONEVENT
Overview
The event name used for complete diagnostics of captured clicks, keys, pointer actions, form activity, and the other configured DOM interactions. Its payload describes the target and path without retaining DOM nodes and preserves readable event details and target values.
Value and use
const DOM_INTERACTION_EVENT = 'arcane.dom.interaction'
Listen on the EventManager to update a debugger in real time. DOM instrumentation records complete readable interaction details and target values. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Browser DOM or a DOM-compatible test host; constant imports in Node. Target, path, flags, and enabled details are normalized diagnostics, not replayable browser event objects.
Example
import {DOM_INTERACTION_EVENT, arcaneEvents} from 'arcane-os/event-manager';
arcaneEvents.on(DOM_INTERACTION_EVENT, diagnostic => {
console.log(diagnostic.eventType, diagnostic.target?.selector);
});
DOMMUTATIONEVENT
Overview
The event name used for normalized attribute, character-data, and child-list mutation diagnostics. It lets review tools correlate observable DOM changes with the interaction that preceded them.
Value and use
const DOM_MUTATION_EVENT = 'arcane.dom.mutation'
Mutation capture uses MutationObserver and is enabled by default when DOM instrumentation starts. Complete markup, text, selectors, URLs, and attribute values are preserved. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Browser DOM or a DOM-compatible test host; constant imports in Node. The payload is complete normalized diagnostic data and cannot reconstruct or authorize changes to the DOM.
Example
import {DOM_MUTATION_EVENT, arcaneEvents} from 'arcane-os/event-manager';
arcaneEvents.on(DOM_MUTATION_EVENT, mutation => {
console.log(mutation.mutationType, mutation.target?.selector);
});
DOMOBSERVATIONSTARTED_EVENT
Overview
The lifecycle event emitted after the requested DOM listeners and mutation observer start successfully. The payload identifies the root and records the active capture options.
Value and use
const DOM_OBSERVATION_STARTED_EVENT = 'arcane.dom.observation.started'
A failed start cleans up partial listeners and does not emit this event. The event is recorded only when the owning EventManager currently has time travel enabled. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Browser DOM or a DOM-compatible test host; constant imports in Node. The payload is a normalized diagnostic of configuration, not proof of host capability outside the current controller.
Example
import {DOM_OBSERVATION_STARTED_EVENT, arcaneEvents} from 'arcane-os/event-manager';
arcaneEvents.once(DOM_OBSERVATION_STARTED_EVENT, state => {
console.log(state.eventTypes.length);
});
DOMOBSERVATIONSTOPPED_EVENT
Overview
The lifecycle event emitted after normal shutdown of active DOM observation. It supports debugger state and teardown assertions without exposing listener internals.
Value and use
const DOM_OBSERVATION_STOPPED_EVENT = 'arcane.dom.observation.stopped'
Calling stop() when already inactive is idempotent and emits nothing. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Browser DOM or a DOM-compatible test host; constant imports in Node. Its root payload is a normalized descriptor and contains no live DOM node.
Example
import {DOM_OBSERVATION_STOPPED_EVENT, arcaneEvents} from 'arcane-os/event-manager';
arcaneEvents.on(DOM_OBSERVATION_STOPPED_EVENT, ({root}) => {
console.log(root?.kind);
});
EventManager
Overview
A synchronous pub/sub manager with opt-in complete time-travel recording, strict event-stack import/export, cursor review, playback, and optional DOM instrumentation. Create an instance for an isolated subsystem or use arcaneEvents for the package singleton.
Syntax and result
new EventManager({
timeTravel=false,
dom=null,
clock=()=>new Date(),
now,
sessionId
}={})
Listeners receive the original live arguments synchronously. When recording is enabled, the manager separately stores complete mutable snapshots, parent/causation structure, timing, status, captured stack text, and error detail. History has no configured retention cap. See the central events guide for every getter, method, default, failure, and recovery path. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Node and browser/bundler; DOM capture requires a compatible DOM. Pub/sub is host-neutral. Recorded values are normalized snapshots; live payload identity and listener side effects remain application-defined.
Example
import {EventManager} from 'arcane-os/event-manager';
const events = new EventManager({timeTravel:true});
events.on('cart.updated', cart => console.log(cart.total));
events.emit('cart.updated', {total:42});
console.log(events.history.at(-1).status);
PLAYBACKCANCELLEDEVENT
Overview
The playback lifecycle event emitted when an AbortSignal aborts an active review. Its mutable summary reports the source session, number delivered, current cursor, completed:false, and a complete normalized error snapshot.
Value and use
const PLAYBACK_CANCELLED_EVENT = 'arcane.time-travel.playback.cancelled'
The playback promise rejects with the abort reason after emitting this event. Already delivered callbacks or event handlers are not rolled back. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Node and browser/bundler. The lifecycle summary is normalized; cancellation remains cooperative and local to playback.
Example
import {PLAYBACK_CANCELLED_EVENT, arcaneEvents} from 'arcane-os/event-manager';
arcaneEvents.on(PLAYBACK_CANCELLED_EVENT, result => {
console.log(result.delivered, result.completed);
});
PLAYBACKCOMPLETEDEVENT
Overview
The playback lifecycle event emitted after every selected record and onRecord callback completes. The same mutable summary shape is returned from playback().
Value and use
const PLAYBACK_COMPLETED_EVENT = 'arcane.time-travel.playback.completed'
Completion means the local review loop finished. It does not mean original external side effects were reproduced, acknowledged, or committed. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Node and browser/bundler. Session, delivered count, cursor, and completion state are normalized.
Example
import {PLAYBACK_COMPLETED_EVENT, arcaneEvents} from 'arcane-os/event-manager';
arcaneEvents.once(PLAYBACK_COMPLETED_EVENT, result => {
console.log(`Reviewed ${result.delivered} records`);
});
PLAYBACKFAILEDEVENT
Overview
The playback lifecycle event emitted when parsing, timing, event delivery, or the caller's onRecord callback fails for a non-cancellation reason. The playback promise then rejects with the original error.
Value and use
const PLAYBACK_FAILED_EVENT = 'arcane.time-travel.playback.failed'
The diagnostic error in the lifecycle payload is a complete normalized snapshot and may not preserve object identity. Records delivered before failure are not undone. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Node and browser/bundler. The failure summary is normalized; the thrown error remains the local failure value.
Example
import {PLAYBACK_FAILED_EVENT, arcaneEvents} from 'arcane-os/event-manager';
arcaneEvents.on(PLAYBACK_FAILED_EVENT, result => {
console.error(result.error);
});
PLAYBACKRECORDEVENT
Overview
The event emitted once per selected stack record in the default review playback mode. Debuggers can render the mutable normalized record without re-emitting the record's original application event.
Value and use
const PLAYBACK_RECORD_EVENT = 'arcane.time-travel.playback.record'
Use review for inspection. mode:'events' deliberately re-emits original types and payload snapshots and can trigger application side effects; mode:'none' invokes only onRecord. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Node and browser/bundler. Each delivered value is a validated mutable arcane-event-stack/1 record.
Example
import {PLAYBACK_RECORD_EVENT, arcaneEvents} from 'arcane-os/event-manager';
arcaneEvents.on(PLAYBACK_RECORD_EVENT, record => {
console.log(record.sequence, record.type, record.status);
});
PLAYBACKSTARTEDEVENT
Overview
The lifecycle event emitted before the first selected record is delivered. It reports the source session, selected count and range, playback speed, and delivery mode.
Value and use
const PLAYBACK_STARTED_EVENT = 'arcane.time-travel.playback.started'
The event is emitted even when the selected range contains no records; a successful empty review then completes with delivered:0. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Node and browser/bundler. The lifecycle payload is a normalized local playback summary.
Example
import {PLAYBACK_STARTED_EVENT, arcaneEvents} from 'arcane-os/event-manager';
arcaneEvents.on(PLAYBACK_STARTED_EVENT, run => {
console.log(run.mode, run.count);
});
TIMETRAVELSEEK_EVENT
Overview
The event emitted when seek() moves the review cursor. Its payload carries the current session, requested sequence, and the matching retained record—or null for sequence zero or an unretained sequence gap.
Value and use
const TIME_TRAVEL_SEEK_EVENT = 'arcane.time-travel.seek'
Seeking never dispatches the selected record's original type and never mutates history. It is a review cursor operation only. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Node and browser/bundler. The cursor payload is normalized and contains the mutable retained record when one exists.
Example
import {TIME_TRAVEL_SEEK_EVENT, arcaneEvents} from 'arcane-os/event-manager';
arcaneEvents.on(TIME_TRAVEL_SEEK_EVENT, ({sequence}) => {
console.log('Cursor:', sequence);
});
arcaneEvents
Overview
The synchronous semantic event authority used in the current JavaScript realm.
Module evaluation reads globalThis.arcaneEvents, reuses a value with the
current protocol and required callable API, or installs a new authority. Window,
frame, worker, Node realm, and process boundaries remain distinct and have no
automatic transport between them.
Value and use
globalThis.arcaneEvents === arcaneEvents
arcaneEvents.protocol === 'arcane-event-authority/1'
arcaneEvents[Symbol.for('arcane-os.arcane-events-authority')]
=== 'arcane-event-authority/1'
When this module installs the authority, the global is an own, non-enumerable,
writable, configurable data property. The created authority's brand and public
protocol properties are ordinary mutable properties. An existing value is
reused based on its protocol and required callable API; any other value is
replaced when the property can be defined. A failed definition throws
ARCANE_EVENT_AUTHORITY_INSTALL_FAILED.
Canonical subscription is
arcaneEvents.subscribe(type,handler,{once=false,signal}={}). It returns an
idempotent unsubscribe function with
unsubscribe.dispose === unsubscribe. An already-aborted signal installs
nothing; later abort removes the registration synchronously. handler receives
one mutable arcane-event-occurrence/1, and wildcard subscription is not
admitted.
The source factory signatures are:
arcaneEvents.createSource(owner,{source,eventTypes,onListenerError?})
createArcaneEventSource(owner,{source,eventTypes,onListenerError?})
The exported wrapper calls the authority method and returns the same mutable
handle. One owner may have one active source. The handle exposes
protocol, descriptor, source, instanceId, eventTypes, disposed,
subscribe, on, once, addEventListener, removeEventListener,
dispatch, dispatchEvent, dispose, and destroy.
onListenerError(error,errorOccurrence) receives the raw listener failure and
the canonical listener-error occurrence at the owner-local boundary;
errorOccurrence is null only when that secondary publication could not be
constructed.
source.dispatch(type,detail,{operationId=null,publicDetail, cancelable=false}={}) synchronously returns the mutable
{occurrence,accepted} publication. The occurrence contains mutable
protocol, occurrenceId, type, source, instanceId, operationId,
complete normalized detail, cancelable, live
defaultPrevented, and preventDefault(). Canonical listeners run before the
source's EventTarget-shaped listeners. When publicDetail is omitted, canonical
detail is the normalized source detail; record values merge with explicitly
supplied publicDetail, and other combinations are retained under
{compatibility,publicDetail}. Cancellation is synchronous and only
sets acceptance; the publisher decides whether to begin or continue domain work.
Listener promises are not awaited. The authority is not an async queue:
operation-owned promises and createEventQueue() own async ordering,
backpressure, cancellation, and failure. Listener exceptions are observational;
they publish one arcane.event.listener.error occurrence with code
ARCANE_EVENT_LISTENER_CALLBACK_FAILED, source identifiers, and a complete
normalized error snapshot, and do not throw from committed source dispatch.
ARCANE_EVENT_ERROR_CODES is a mutable object that maps every exported code key
to that identical string value. Thrown authority failures expose the matching
value as error.code; ARCANE_EVENT_LISTENER_CALLBACK_FAILED is carried by its
observational error occurrence, and
ARCANE_EVENT_DISPATCH_EVENT_INVALID identifies invalid Event-like input to a
source handle's dispatchEvent() adapter.
projectArcaneDOMEvent(target,occurrence,{type,bubbles=false,composed=false, cancelable=occurrence.cancelable}={}) is a one-way DOM projection.
Its mutable detail carries occurrenceId, arcaneSource, instanceId, and
operationId; it never republishes the DOM event. DOM cancellation propagates
back to a cancelable occurrence. isArcaneEventOccurrence(value) recognizes
only canonical occurrences and source event views created by this
realm's authority.
The first source.dispose()/destroy() publishes the final noncancelable
arcane.event.source.disposed occurrence, removes source-owned listeners, frees
the owner for a new source, and returns true; later or reentrant calls return
false.
Availability and normalization
Node and browser/bundler, once per JavaScript realm; DOM projection requires
CustomEvent and a target with dispatchEvent. Canonical public detail is a
complete mutable normalized snapshot. Array and plain-record source detail is
shallow-copied for the source event view; other host objects remain owner-local
by identity.
Example
import {arcaneEvents, createArcaneEventSource} from 'arcane-os/event-manager';
const owner = {};
const source = createArcaneEventSource(owner, {
source:'sdk.operation',
eventTypes:['sdk.operation.completed']
});
const unsubscribe = arcaneEvents.subscribe(
'sdk.operation.completed',
occurrence => console.log(occurrence.detail.operationId)
);
source.dispatch(
'sdk.operation.completed',
{operationId:'operation-1'},
{operationId:'operation-1', publicDetail:{operationId:'operation-1'}}
);
unsubscribe.dispose();
source.dispose();
ARCANEEVENTAUTHORITY_BRAND
Overview
Global registry symbol used as a protocol marker on an Arcane event authority created in a JavaScript realm.
Value and import
const ARCANE_EVENT_AUTHORITY_BRAND
Its exact value is Symbol.for('arcane-os.arcane-events-authority').
Availability and normalization
Node and browser/bundler. A created authority receives this ordinary enumerable, writable, configurable symbol property. It is a realm-local protocol marker, not transport or authenticity.
Example
import {ARCANE_EVENT_AUTHORITY_BRAND,arcaneEvents} from 'arcane-os/event-manager';
console.log(arcaneEvents[ARCANE_EVENT_AUTHORITY_BRAND]);
ARCANEEVENTAUTHORITY_KIND
Overview
Stable kind discriminator for the authority descriptor.
Value and import
const ARCANE_EVENT_AUTHORITY_KIND
Its exact value is arcane-event-authority.
Availability and normalization
Node and browser/bundler. Reading it creates no authority or listener.
Example
import {ARCANE_EVENT_AUTHORITY_KIND,arcaneEvents} from 'arcane-os/event-manager';
console.log(arcaneEvents.descriptor.kind===ARCANE_EVENT_AUTHORITY_KIND);
ARCANEEVENTAUTHORITY_PROTOCOL
Overview
Stable protocol discriminator for compatible per-realm event authorities.
Value and import
const ARCANE_EVENT_AUTHORITY_PROTOCOL
Its exact value is arcane-event-authority/1.
Availability and normalization
Node and browser/bundler. A global value with this protocol and all required authority methods is reused. Other values are replaced when the global property can be defined.
Example
import {ARCANE_EVENT_AUTHORITY_PROTOCOL,arcaneEvents} from 'arcane-os/event-manager';
console.log(arcaneEvents.protocol===ARCANE_EVENT_AUTHORITY_PROTOCOL);
ARCANEEVENTERROR_CODES
Overview
Mutable registry of event-authority failure-code names.
Value and import
const ARCANE_EVENT_ERROR_CODES
Every key maps to its identical string value; thrown authority failures expose
the matching value as error.code.
Availability and normalization
Node and browser/bundler. The registry is an exported code lookup, not a registration API. Each current key maps to its identical string value.
Example
import {ARCANE_EVENT_ERROR_CODES} from 'arcane-os/event-manager';
console.log(ARCANE_EVENT_ERROR_CODES.ARCANE_EVENT_SOURCE_DISPOSED);
ARCANEEVENTLISTENERERROREVENT
Overview
Canonical observational event emitted when an event listener throws.
Value and import
const ARCANE_EVENT_LISTENER_ERROR_EVENT
Its exact value is arcane.event.listener.error.
Availability and normalization
Node and browser/bundler. Mutable public detail carries the exact failure
code, source occurrence identifiers, and a complete normalized error snapshot.
Its shape is
{code:'ARCANE_EVENT_LISTENER_CALLBACK_FAILED',reason:'listener-threw', eventType,occurrenceId,source,instanceId,operationId,error}. Publication is
synchronous and nonrecursive.
Example
import {ARCANE_EVENT_LISTENER_ERROR_EVENT,arcaneEvents} from 'arcane-os/event-manager';
const unsubscribe=arcaneEvents.subscribe(ARCANE_EVENT_LISTENER_ERROR_EVENT,console.log);
ARCANEEVENTOCCURRENCE_PROTOCOL
Overview
Stable protocol discriminator for canonical occurrences.
Value and import
const ARCANE_EVENT_OCCURRENCE_PROTOCOL
Its exact value is arcane-event-occurrence/1.
Availability and normalization
Node and browser/bundler. Occurrences are mutable realm-owned identity values with complete normalized public detail and synchronous cancellation state.
Example
import {ARCANE_EVENT_OCCURRENCE_PROTOCOL} from 'arcane-os/event-manager';
console.log(publication.occurrence.protocol===ARCANE_EVENT_OCCURRENCE_PROTOCOL);
ARCANEEVENTSOURCEDISPOSEDEVENT
Overview
Final noncancelable occurrence published during a source's first disposal.
Value and import
const ARCANE_EVENT_SOURCE_DISPOSED_EVENT
Its exact value is arcane.event.source.disposed.
Availability and normalization
Node and browser/bundler. Canonical detail is the normalized merged value
{source,instanceId,reason:'source-disposed'}. Delivery precedes source-listener cleanup;
reentrant or later disposal publishes nothing and returns false.
Example
import {ARCANE_EVENT_SOURCE_DISPOSED_EVENT} from 'arcane-os/event-manager';
source.once(ARCANE_EVENT_SOURCE_DISPOSED_EVENT,console.log);
source.dispose();
ARCANEEVENTSOURCE_KIND
Overview
Stable kind discriminator for source descriptors.
Value and import
const ARCANE_EVENT_SOURCE_KIND
Its exact value is arcane-event-source.
Availability and normalization
Node and browser/bundler. Reading it does not register or dispose a source.
Example
import {ARCANE_EVENT_SOURCE_KIND} from 'arcane-os/event-manager';
console.log(source.descriptor.kind===ARCANE_EVENT_SOURCE_KIND);
ARCANEEVENTSOURCE_PROTOCOL
Overview
Stable protocol discriminator for source handles and descriptors.
Value and import
const ARCANE_EVENT_SOURCE_PROTOCOL
Its exact value is arcane-event-source/1.
Availability and normalization
Node and browser/bundler. One handle belongs to one active owner in one realm and declares every publishable type before use.
Example
import {ARCANE_EVENT_SOURCE_PROTOCOL} from 'arcane-os/event-manager';
console.log(source.protocol===ARCANE_EVENT_SOURCE_PROTOCOL);
createArcaneEventSource()
Overview
Registers one active declared semantic source for a non-null object or function owner on the installed per-realm authority.
Signature and result
createArcaneEventSource(owner, options)
options is the closed data record {source,eventTypes,onListenerError?}. The
result is one mutable arcane-event-source/1 handle with synchronous
subscription, publication, cancellation admission, EventTarget-shaped adapters,
and idempotent disposal. A second active source for the same owner fails with
ARCANE_EVENT_SOURCE_ALREADY_REGISTERED.
Availability and normalization
Node and browser/bundler, within the current JavaScript realm. The wrapper
reuses globalThis.arcaneEvents; it creates no second bus, queue, Worker, or
transport. Provider or host work remains owned by its own promise and signal.
Example
import {createArcaneEventSource} from 'arcane-os/event-manager';
const source=createArcaneEventSource({}, {
source:'sdk.example',
eventTypes:['sdk.example.completed']
});
source.dispose();
isArcaneEventOccurrence()
Overview
Recognizes canonical occurrences and source event views created by the current realm's authority.
Signature and result
isArcaneEventOccurrence(value)
Returns a boolean. Structurally similar or protocol-shaped foreign values return
false.
Availability and normalization
Node and browser/bundler, within the current JavaScript realm. Recognition is synchronous and identity-based, with no parsing, cloning, or transport.
Example
import {isArcaneEventOccurrence} from 'arcane-os/event-manager';
console.log(isArcaneEventOccurrence(publication.occurrence));
projectArcaneDOMEvent()
Overview
Projects one authority-created occurrence to one CustomEvent without
republishing the DOM event into the canonical authority.
Signature and result
projectArcaneDOMEvent(target, occurrence, options)
The result is the combined DOM/canonical acceptance boolean. Mutable projection
detail adds the occurrence, canonical source, source instance, and operation
identifiers while preserving a caller-owned source-detail source. A
pre-cancelled occurrence skips DOM dispatch; DOM cancellation propagates only
to a cancelable occurrence.
Availability and normalization
Browser DOM or a DOM-compatible host with CustomEvent and
dispatchEvent. Projection is synchronous, state-free, and one-way.
Example
import {projectArcaneDOMEvent} from 'arcane-os/event-manager';
projectArcaneDOMEvent(button,publication.occurrence,{bubbles:true});
createDOMInstrumentation()
Overview
Creates a mutable controller that projects DOM interactions and mutations into an EventManager. The returned controller owns start(), stop(), active, cleanupPending, observedRootCount, and the configured root.
Syntax and result
createDOMInstrumentation({
eventManager,
root=document,
eventTypes=DEFAULT_DOM_EVENT_TYPES,
MutationObserver,
captureMutations=true,
observeOpenShadowRoots=true
}={})
The factory validates configuration but does not start automatically. It records complete readable event details, target values, markup, text, selectors, URLs, and mutation attribute values. captureMutations and observeOpenShadowRoots are the two boolean capture controls and both default to true. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Browser DOM or a DOM-compatible test host. It normalizes diagnostics only; it does not serialize a complete DOM or synthesize browser interactions during review.
Example
import {createDOMInstrumentation, EventManager} from 'arcane-os/event-manager';
const events = new EventManager({timeTravel:true});
const observation = createDOMInstrumentation({eventManager:events, root:document});
observation.start();
// Later: observation.stop();
createEventManager()
Overview
Constructs an independent EventManager using the same options and validation as the class constructor. Prefer it when factory-based dependency injection reads more clearly than new EventManager().
Syntax and result
createEventManager(options)
The returned manager does not share listeners, history, session, cursor, or DOM controller with arcaneEvents or any other instance. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Node and browser/bundler; DOM capture requires a compatible DOM. Constructor validation and snapshot normalization are identical to EventManager.
Example
import {createEventManager} from 'arcane-os/event-manager';
const events = createEventManager({timeTravel:true, sessionId:'checkout-test'});
events.instrument('checkout.started', {cartId:'cart-1'}, {source:'test'});
describeDOMTarget()
Overview
Returns a mutable descriptor for a document, shadow root, text node, element, global object, or generic event target. It is useful for diagnostic UI and behavioral assertions without retaining the target object.
Syntax and result
describeDOMTarget(target, root)
Element descriptors include a best-effort selector, tag, id, role, name, type, and complete markup or text content. Text descriptors include complete text content; shadow-root descriptors may include their host descriptor. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Browser DOM or DOM-compatible objects; importable in Node. The result is a normalized diagnostic identity, not a stable locator or capability token.
Example
import {describeDOMTarget} from 'arcane-os/event-manager';
const descriptor = describeDOMTarget(document.querySelector('button'), document);
console.log(descriptor.selector, descriptor.role);
domSelector()
Overview
Builds a best-effort diagnostic selector from IDs, Arcane/test IDs, element names, and sibling positions. Open shadow-root boundaries are separated with >>>.
Syntax and result
domSelector(target, root)
The helper returns :document, :shadow-root, an element selector, a text node's parent selector, or null for an unsupported target. Generated selectors are for diagnostics and are not guaranteed unique after DOM changes. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Browser DOM or DOM-compatible objects; importable in Node. Selector text is normalized locally and grants no access to the described target.
Example
import {domSelector} from 'arcane-os/event-manager';
console.log(domSelector(document.activeElement, document));
parseEventStack()
Overview
Parses a JSON string or object and strictly validates an arcane-event-stack/1 document. It returns a mutable null-prototype normalized data object suitable for review or playback.
Syntax and result
parseEventStack(source)
Validation rejects unknown keys, accessors, sparse arrays, unsafe values, invalid timestamps/statuses/nesting, inconsistent sessions/protocols, and non-increasing sequences. It preserves the complete valid event history. Full operational guidance: central events, DOM instrumentation, and time-travel review.
Availability and normalization
Node and browser/bundler. The result is mutable normalized diagnostic data. Parsing never dispatches events, restores live objects, or confers host authority.
Example
import {parseEventStack} from 'arcane-os/event-manager';
const stack = parseEventStack(serialized);
console.log(stack.sessionId, stack.events.length);
Core client and native runtime
The focused Core entrypoints share the arcane/1 wire contract while retaining
separate owners for renderer RPC, native dispatch and stdio framing. Start with
the complete Core browser client and
native Core runtime guides for lifecycle and composition.
CORE_PROTOCOL
Overview
Protocol identifier shared by Core requests, responses, events and controls. The identifier describes the wire contract; it does not grant a method, transport, service or model capability.
Value and import
const CORE_PROTOCOL = 'arcane/1'
Import it from arcane-os/core/contracts.
Availability and normalization
Node and browser/bundler. The exported value is the exact protocol string used in every Core frame.
Example
import {CORE_PROTOCOL} from 'arcane-os/core/contracts';
const request = {
protocol: CORE_PROTOCOL,
type: 'request',
id: 'moon-cheese-1',
method: 'catalog.read',
parameters: {name: 'Lunar cheddar'}
};
COREREADYEVENTS
Overview
Names the two events the browser client retains as durable completions:
transport.ready and core.ready. Transport connection and dispatcher
readiness remain distinct from application-service, repository and model
readiness.
Value and import
const CORE_READY_EVENTS
Import it from arcane-os/core/contracts.
Availability and normalization
Node and browser/bundler. These names define the events accepted by
client.events.when() and reported by client.events.completed().
Example
import {CORE_READY_EVENTS} from 'arcane-os/core/contracts';
console.log(CORE_READY_EVENTS.includes('core.ready')); // true
COREFRAMECONTRACTS
Overview
Describes the public fields for request, response, event, single-request
cancellation, all-request cancellation and runtime.replay control frames.
These are wire descriptions, not application validation or method admission.
Value and import
const CORE_FRAME_CONTRACTS
Import it from arcane-os/core/contracts.
Availability and normalization
Node and browser/bundler. Each record names its frame type and required, success, failure or optional fields without starting a transport.
Example
import {CORE_FRAME_CONTRACTS} from 'arcane-os/core/contracts';
console.log(CORE_FRAME_CONTRACTS.response.failure); // ['error']
COREMETHODCONTRACTS
Overview
Describes existing Core method input and output shapes plus semantic distinctions that callers must preserve. The active host and its registered services remain the authority for actual method availability.
Value and import
const CORE_METHOD_CONTRACTS
Import it from arcane-os/core/contracts.
Availability and normalization
Node and browser/bundler. Reading the metadata starts no request and grants no host capability.
Example
import {CORE_METHOD_CONTRACTS} from 'arcane-os/core/contracts';
console.log(CORE_METHOD_CONTRACTS['system.ping'].meaning);
CoreError
Overview
Common Core error class for complete service, transport and host diagnostics. It retains supplied own fields, stack and cause while filling absent Arcane error metadata with ordinary defaults.
Constructor and result
new CoreError(value)
Import it from arcane-os/core/contracts. The instance exposes its supplied
fields plus normalized name, code, message, resolution, diagnosticId,
technicalMessage, hresult and causeName values.
Availability and normalization
Node and browser/bundler. Native bridge codes and messages remain available when supplied; normalized defaults fill only absent fields.
Example
import {CoreError} from 'arcane-os/core/contracts';
const error = new CoreError({
code: 'MOON_CHEESE_MISSING',
message: 'The emergency lunar cheddar is missing.',
diagnosticId: 'catalog-7'
});
console.log(error.code, error.diagnosticId);
serializeCoreError()
Overview
Projects an error into the plain diagnostic record used by Core responses and events. It retains own properties and the ordinary name, message, stack and cause fields, recursively including Error causes and AggregateError members.
Signature and result
serializeCoreError(error)
Import it from arcane-os/core/contracts. The result is a plain object suitable
for the selected transport's JSON encoding.
Availability and normalization
Node and browser/bundler. Missing error metadata receives explicit ordinary defaults; complete supplied diagnostic fields remain present.
Example
import {serializeCoreError} from 'arcane-os/core/contracts';
const record = serializeCoreError(new AggregateError([
new Error('The moon vault door jammed.'),
new Error('The backup raccoon lost the key.')
], 'Catalog startup failed.'));
console.log(record.errors.map(error => error.message));
createCoreClient()
Overview
Creates one correlated renderer RPC client. It owns pending requests, cancellation, timeouts, durable readiness events and one source in the shared SDK event authority. Native host execution and service policy remain outside the client.
Signature and result
createCoreClient({global=globalThis, transport=null, eventOwner=arcaneEvents, eventOwnerReady, autoConnect=true, replayRuntimeState=false, onError}={})
Import it from arcane-os/core/client. The result exposes invoke, receive,
connect, close, failTransport, cancelAll, events, eventsReady, runtime.current(),
uuid, protocol and Error. A supplied transport must provide callable
send(frame); an invalid transport stays disconnected and reports
ARCANE_TRANSPORT_INVALID. Optional subscribe(receive) may return its cleanup
function.
invoke(method, parameters, {signal, timeoutMs}) preserves complete supplied
parameters and resolves the correlated response result. A send failure rejects
its still-pending request; a failure arriving after response, cancellation or
timeout reaches onError. Deferred event-owner connection preserves the FIFO
order of queued frames and subscription actions, including reentrant delivery.
replayRuntimeState:true sends one observed runtime.replay control after the
receive listener and transport.ready are established, without delaying page
startup. The default is false; select replay only with a supporting host.
Repeated connection calls do not repeat that control, and send failures reach
onError. The host replays actual dispatcher and service state without
restarting services; transport, Core and service readiness remain distinct.
failTransport(error) ends the client after an actual terminal transport
failure. Pending RPCs and WebKit acknowledgements reject with the complete
CoreError, future invocations reject with that failure, and onError observes
it once. The client releases its owned listeners, callbacks and timers without
sending cancellation frames to the failed transport. The first terminal failure
returns true; an already closed client returns false. Ordinary close()
retains its separate cancellation behavior.
Availability and normalization
Browser and native WebView JavaScript hosts. Built-in transports select WebView2, WebKitGTK, Android WebView or an explicitly enabled development HTTP bridge. An ordinary browser remains disconnected. Full lifecycle guidance: Core browser client.
Example
import {createCoreClient} from 'arcane-os/core/client';
import {CORE_PROTOCOL} from 'arcane-os/core/contracts';
let outbound;
const client = createCoreClient({
transport: {
name: 'moon-wire',
send(frame) { outbound = frame; }
}
});
const operation = client.invoke('catalog.read', {name: 'Lunar cheddar'});
client.receive({
protocol: CORE_PROTOCOL,
type: 'response',
id: outbound.id,
ok: true,
result: {found: true, location: 'Vault 7'}
});
console.log(await operation);
client.close();
createCoreFacade()
Overview
Projects a Core client into the established application-facing Arcane namespace. The facade retains the existing method names, operation-specific parameters, timeouts, streaming correlations and cancellation while the selected host owns their implementations and availability.
Signature and result
createCoreFacade(client)
Import it from arcane-os/core/client. The result includes runtime, events,
Error and the existing ai, environment, mail, speech, localAI,
ollama, application, platform, storage and other host namespaces.
facade.speech.synthesize(request, {signal}) and
facade.speech.transcribe(request, {signal}) accept an optional AbortSignal
through the same correlated request lifetime. Each complete request and existing
180,000 ms timeout remain unchanged. A pre-aborted signal sends no speech
request; an in-flight abort emits that request's request.cancel, rejects with
ARCANE_REQUEST_ABORTED and leaves unrelated requests active. Late responses
cannot settle the cancelled request. Actual native synthesis or transcription
interruption belongs to the registered service and engine; this facade supplies
no engine. The native routes of AI.fetchTTS(payload, signal) and
AI.fetchSTT(audio, signal) forward their signals through these calls and
normalize cancellation to AbortError with ARCANE_AI_REQUEST_ABORTED.
facade.speech.openStream(request,options) returns
{streamId,ready,completion,current,push,forceEndpoint,finish,cancel}.
Ordered Float32 input retains the actual declared sample rate. Endpoint preserves
stream/speaker scope and waits preceding updates; finish drains terminally.
Do not await endpoint/finish/completion from their own update callback. Explicit
cancel joins its native cleanup control, unlike ordinary signal cancellation.
synthesizeStream(request,{signal,onAudio,onProgress,onRequest}) awaits each
complete ordered Uint8Array PCM contribution and its consumption acknowledgement,
returns terminal metadata, and joins native cancellation. It plays no audio.
Both streaming operations have no fixed timeout. Engine support/readiness remains
independent from facade availability. See streaming native speech.
facade.window.state({signal}?) reads the calling document's native window;
facade.window.setState({state}, {signal}?) selects normal, maximized or
fullscreen for that same window. The matching Windows host returns
{platform:'windows', supported:true, state}, with observed state also able
to be minimized. Fullscreen removes the frame and fills the selected monitor;
leaving it restores the preceding normal bounds and frame controls before any
requested maximization. Visible state transitions prevent activation/focus
assignment to the requesting window without changing TopMost, Core, origin or
profile. Optional native.window.state selects startup state after initial
sizing; omission preserves host behavior. Saved Settings remain application-owned.
Cancellation does not undo an already-applied change. Other hosts retain their
actual unavailable-method/transport errors; the facade provides no fallback.
See current-window state for complete
native errors, partial-state evidence, navigation and cleanup ownership.
facade.window.setTheme(presentation, {signal}?) forwards the complete
presentation to the current native window, independently of OS-user appearance.
Optional backgroundColor and textColor accept {red,green,blue,alpha} or
null for a platform-default reset; omitted fields remain unchanged. The
result is {platform,supported,applied,unsupported} with actual per-field
acceptance, rather than a measured-pixel or atomic-update claim. Cancellation
uses the existing request lifetime and does not undo settings already accepted.
Shared ThemeBootstrap forwards the app's computed semantic colors without
blocking rendering; applications using it need no duplicate listener. See the
current-window contract for channel
values, errors, navigation, disposal and current host support. The facade does
not add this operation to an older executable or an unsupported host.
Availability and normalization
Browser and native WebView JavaScript hosts with a Core client. Creating the facade starts no service and grants no method capability. Full method routing is documented in the Core browser client guide.
Example
import {createCoreClient, createCoreFacade} from 'arcane-os/core/client';
const client = createCoreClient({autoConnect: false});
const Arcane = createCoreFacade(client);
console.log(Arcane.protocol, Arcane.runtime.current());
client.close();
installCoreClient()
Overview
Installs one synchronous globalThis.Arcane facade and native
__arcaneReceive and __arcaneTransportFailed callbacks. Repeated installation
returns the same client for that global lifetime.
Signature and result
installCoreClient(global=globalThis, options={})
Import it from arcane-os/core/client. The returned client is the same contract
as createCoreClient(). Closing it releases subscriptions, native callbacks,
timers and pending renderer requests; it does not kill Core.
__arcaneTransportFailed(error) delegates actual terminal host failures to
client.failTransport(error). Closing or failing restores previous facade and
callback globals only while the installation still owns them, preserving later
replacements. getInstalledCoreClient() returns null after release, including
before an installed terminal failure reaches onError.
Availability and normalization
Browser and native WebView JavaScript hosts. Installation makes synchronous facade and current-state shapes available even while the selected transport is disconnected. Service readiness remains separately host-owned.
Example
import {installCoreClient} from 'arcane-os/core/client';
const client = installCoreClient();
try {
console.log(globalThis.Arcane.runtime.current());
} finally {
client.close();
}
getInstalledCoreClient()
Overview
Reads the existing live SDK-installed client without installing, connecting or replacing a facade. Applications use this accessor instead of private fields.
Signature and result
getInstalledCoreClient(global=globalThis)
Import it from arcane-os/core/client. It returns the exact client installed in
the selected global, including a classic document-created installation, or
null when no live SDK installation exists. A foreign Arcane facade does not
constitute an SDK installation. Close and terminal failure release the
installation before subsequent reads.
Availability and normalization
Browser and native WebView JavaScript hosts. This synchronous read changes
no globals and starts no service, transport or model. The returned client's
runtime.current() describes transport state; service readiness remains with
its authoritative owner. See Core browser client.
Example
import {getInstalledCoreClient} from 'arcane-os/core/client';
const client = getInstalledCoreClient();
console.log(client ? client.runtime.current() : 'No SDK client is installed.');
subscribeCoreClient()
Overview
Observes the selected global's SDK client installation without creating a transport or delaying rendering. Applications can subscribe before independently loaded development or native bootstrap code installs the client.
Signature and result
subscribeCoreClient(listener,{global=globalThis,emitCurrent=true,signal}={})
Import from arcane-os/core/client. Returns an idempotent unsubscribe function.
The listener receives {client,previousClient,reason,error} with the exact
client and error objects. Reasons are current, installed, closed and
transport-failed. Current state replays synchronously unless disabled; an
already-aborted signal registers nothing. Close or terminal failure releases
the prior installation before notification. A reentrant replacement is retained.
Availability and normalization
Browser and native WebView JavaScript hosts. Installation is distinct from
Core, service or model readiness. Read client.runtime.current() and subscribe
to that client's authoritative runtime/service events for those states. This
observer starts no service and uses the shared event owner, not polling. See
Core client and source-development Core.
Example
import {subscribeCoreClient} from 'arcane-os/core/client';
const unsubscribe = subscribeCoreClient(function installationChanged({client}) {
console.log(client ? client.runtime.current() : 'Core is not installed.');
});
// The application owner calls unsubscribe() when this observer is retired.
createCoreClassicSource()
Overview
Generates the native host's classic script from the installed canonical ESM client and contracts. It creates no copied client implementation or bundler.
Signature and result
async createCoreClassicSource({eventOwnerModuleURL,replayRuntimeState=false}={})
Import it from arcane-os/core/classic-source. Supply the actual served URL for
the selected SDK event-manager module. The promise resolves to the complete
classic-script source.
Optional replayRuntimeState:true forwards the current runtime-replay selection
to the installed client. Omission retains the existing no-replay behavior; use
true only when the composing host supports runtime.replay.
Availability and normalization
Node; generated source runs in browser and native WebView renderers. The facade and native receive callback install synchronously. Only the shared event owner import waits for document parsing when needed, while queued event frames, subscription actions and final responses retain FIFO order. See classic native-host injection.
Example
import {createCoreClassicSource} from 'arcane-os/core/classic-source';
const source = await createCoreClassicSource({
eventOwnerModuleURL: '/arcane/sdk/event-manager.mjs'
});
nativeHost.setDocumentCreatedScript(source);
createCodexAppServerSession()
Import from arcane-os/codex/app-server. Creates a synchronous session handle
without starting a process. connect() starts the caller-selected executable
and completes native JSONL initialization. The session owns explicit thread
creation/resumption, complete native requests, live turn callbacks, exact-turn
completion, interruption, real server-request replies and process retirement.
Application-owned prompts, approvals and display policy stay with the caller.
It neither attaches to desktop chats nor installs or authenticates Codex.
See the complete session options, methods, events, results, errors and recovery
contract.
openCodexAppServerSession()
Import from arcane-os/codex/app-server. Creates the same session, awaits
connect(), and returns it; failed opening disposes the owned process before
rejecting. Prefer createCodexAppServerSession() when the caller must retain
the handle during initialization. Neither factory creates or resumes a thread.
See connection ownership.
createMcpStdioServer()
Import from arcane-os/mcp/stdio. Creates one optional Node STDIO session for
application-owned tool and static-resource descriptors. start() attaches
caller-owned streams; handlers receive complete arguments and return explicit
MCP result containers. Requests run independently; protocol output writes are
ordered. Normal EOF and close() drain accepted work. Cancellation is
cooperative, and transport failures remain observable through closed.
See options, handlers, methods, errors and supported profile.
MCPPROTOCOLVERSION
Import from arcane-os/mcp/stdio. The supported initialization profile is
exactly '2025-11-25'. This does not claim later profiles or every optional
capability. See protocol support.
McpProtocolError
Import from arcane-os/mcp/stdio. new McpProtocolError(code,message,data)
represents an explicit JSON-RPC error with complete message and optional data.
Ordinary domain tool failures use an explicit CallToolResult with isError.
See error outcomes.
createDevelopmentCore()
Overview
Composes application-selected Core services and the SDK-owned development HTTP
transport independently of local AI. Import from arcane-os/core/development
or arcane-os; ordinary applications normally use developApplication() with
their descriptor's native.services.
Signature and result
createDevelopmentCore({appRoot=process.cwd(),application,version,services=[],serviceModules=[],context={},getReplayEvents,signal,onEvent}={})
returns {ready,handler,current,close} synchronously. Module default factories
receive unchanged (options,context). ready reports composed dispatcher
startup, not readiness of every service. current() returns complete
{state,error,core}; handler(request,response) owns /rpc, /events and both
bootstrap aliases; idempotent close() joins accepted service work and output.
Availability and example
Node on Windows, Linux and macOS. Browser callers use the public Core client. Android needs its host adapter. This adds no cross-process host discovery.
import {createDevelopmentCore, startDevServer} from 'arcane-os';
const core = createDevelopmentCore({
appRoot: process.cwd(),
serviceModules: [{module: 'bridge/moon-cheese.mjs', options: {shelf: 'Lunar cheddar'}}]
});
let server;
try {
server = await startDevServer({workspaceRoot: process.cwd(), core});
await server.closed;
} finally {
await core.close();
}
The complete guide defines document cancellation, service-lifetime drain, diagnostics, optional explicit service snapshots and non-blocking page bootstrap. App policy and explicit native process activation remain app-owned.
createCoreRuntime()
Overview
Creates the app-neutral native dispatcher. The composing host supplies its application identity, version and explicit services; product data, prompts, privileges and persistence remain with those owners.
Signature and result
createCoreRuntime({application, version, services=[]}={})
Import it from arcane-os/core/runtime. The runtime exposes current(),
subscribe(), onFrame(), emit(), registerService(), getService(), start(), handle()
and idempotent close().
runtime.handle(frame, {contextRequestId, contextClientRequestId}) accepts
optional nonempty transport metadata strings. Handler requestId remains
contextRequestId ?? frame.id; additive clientRequestId is
contextClientRequestId ?? contextRequestId ?? frame.id; coreRequestId always
exposes the actual internal frame.id. Direct handle(frame) exposes all three
equal. Stdio and both IPC paths supply the actual client identity separately,
preserving the owning shared-host adapter's established internal requestId.
Active requests, cancellation, response IDs and request-event envelopes retain
the internal ID. Parameters, results and event data stay unchanged; transports
own client-facing protocol correlation. See
the runtime contract.
await runtime.getService(name) and service context.getService(name) return
the actual registered service after its shared startup. They wait for that
dependency alone, may start it before runtime.start(), and add no renderer or
all-service barrier. Unknown services reject with CORE_SERVICE_UNAVAILABLE;
new lookups during shutdown reject with CORE_CLOSING. Startup failures retain
their original error. This is readiness, not a lifetime lease: retain acquired
native handles for their actual cleanup rather than looking them up during
disposal. See native service composition.
Services start independently. Request-lifetime work receives cooperative
cancellation; accepted lifetime:'service' work survives renderer cancellation.
Shutdown stops admission, waits accepted responses, then runs each service's
startup, drain and dispose in order while independent services close
concurrently.
The runtime.replay control publishes current dispatcher and service state
without restarting services. Its snapshot preserves complete service errors
and active request state; see runtime replay
for authoritative readiness and reentrant lifecycle ordering.
An unregistered method returns METHOD_NOT_ALLOWED with its exact method,
first dotted namespace, and reason:'core-namespace-unavailable' when that
namespace has neither a named service nor any registered method. Otherwise
the reason is core-method-unavailable; built-in system, app and version
namespaces count as present. This is a lookup result before handler or
permission decisions. Handler/startup errors and older unmarked errors do not
establish namespace absence. The dispatcher does not choose a replacement
service; optional browser adapters own their documented response to absence.
Availability and normalization
Node on Windows, Linux and macOS native hosts; Android requires its native host adaptation. Request parameters, results, correlations and serialized errors remain complete. The runtime uses the shared SDK event authority and never exits the host. Full contract: native Core runtime.
Example
import {createCoreRuntime} from 'arcane-os/core/runtime';
const runtime = createCoreRuntime({
application: {id: 'moon-catalog', name: 'Moon Cheese Catalog'},
version: '1.0.0',
services: [{
name: 'catalog',
methods: {
'catalog.read': parameters => ({found: true, name: parameters.name})
}
}]
});
runtime.start();
const response = await runtime.handle({
protocol: 'arcane/1',
type: 'request',
id: 'catalog-1',
method: 'catalog.read',
parameters: {name: 'Lunar cheddar'}
});
console.log(response.result);
await runtime.close();
encodeCoreFrame()
Overview
Encodes one Core frame as UTF-8 JSON preceded by the native transport's
Content-Length header. The length is transport framing only, never
application policy or capability admission.
Signature and result
encodeCoreFrame(frame)
Import it from arcane-os/core/stdio. The result is one Node Buffer ready for
the selected writable stream.
Availability and normalization
Node. JSON encoding preserves the supplied frame fields supported by JSON. The helper neither writes the buffer nor starts a runtime. See stdio transport.
Example
import {encodeCoreFrame} from 'arcane-os/core/stdio';
const encoded = encodeCoreFrame({
protocol: 'arcane/1',
type: 'control',
control: 'requests.cancelAll'
});
output.write(encoded);
createCoreFrameDecoder()
Overview
Creates the incremental decoder for fragmented or consecutive native Core frames.
Signature and result
createCoreFrameDecoder(onFrame)
Import it from arcane-os/core/stdio. The result exposes push(chunk) and
finish(). push() calls onFrame once for each complete parsed JSON value in
arrival order. finish() reports an incomplete final header or body instead of
dropping it.
Availability and normalization
Node. Malformed framing, UTF-8 and JSON remain observable at their owning parser. Full transport lifecycle: stdio transport.
Example
import {createCoreFrameDecoder, encodeCoreFrame} from 'arcane-os/core/stdio';
const frames = [];
const decoder = createCoreFrameDecoder(frame => frames.push(frame));
decoder.push(encodeCoreFrame({
protocol: 'arcane/1',
type: 'event',
event: 'moon.opened',
data: {vault: 7}
}));
decoder.finish();
console.log(frames[0].data.vault);
startCoreStdio()
Overview
Attaches an existing runtime to framed input and output, then starts that runtime. Requests dispatch concurrently while outgoing frames retain queued writable-callback order.
Signature and result
startCoreStdio({runtime, input=process.stdin, output=process.stdout, onError}={})
Import it from arcane-os/core/stdio. The result is
{runtime, closed, close}. EOF or input close starts graceful shutdown;
closed settles only after accepted runtime work and queued output settle.
Responses, request events, cancellation controls and current-state replay are
connection-scoped even when an additional IPC listener shares the runtime.
Stdio preserves original handler requestId values while routing fresh internal
IDs; uncorrelated service events remain shared. EOF retains its existing
runtime-wide shutdown ownership. Additional clients attach through
startCoreListener().
Availability and normalization
Node with readable input and writable output streams. Parser, input, output
and shutdown failures reach onError and reject closed. The transport pauses
and detaches input without ending caller-owned output or exiting the host. See
stdio transport.
Example
import {createCoreRuntime} from 'arcane-os/core/runtime';
import {startCoreStdio} from 'arcane-os/core/stdio';
const runtime = createCoreRuntime({
application: {id: 'moon-catalog'},
version: '1.0.0'
});
const transport = startCoreStdio({runtime});
await transport.closed;
createModelObservationService()
createModelObservationService({runtime,localAI=null,image=null,decisions=null}={})
Import from arcane-os/core/model-observation. Supply the existing Core runtime
and actual native service definitions, including their current() and methods.
Returns {name:'model-observation',current,dispose,methods}. Register it on that
runtime after ordinary host creation and before opening an additional listener.
Construction starts no service, model, worker or readiness wait.
The four methods are model.observation.current, model.observation.watch,
model.observation.renderer.attach and model.observation.renderer.publish.
current() returns {core,native:{localAI,image,decisions},renderers} from the
supplied owners. Absent model owners are null; absent attachments produce [].
The watch replays current state and remains pending until cancellation. Its
diagnostics:false default excludes live failure frames; explicit true
observes complete failed Core responses for the supplied owners' method keys.
It retains no failure history and invents no model-operation identities.
Renderer attachment and watch acknowledgements use actual clientRequestId;
attachments are keyed by the actual coreRequestId to distinguish clients with
equal local IDs. dispose() retires observation requests/subscriptions only.
Core still owns model services and shutdown. See
complete methods, events and evidence limits.
attachModelObservation()
attachModelObservation({client,aiRuntimeState=null,imageRuntime=null,decisionModel=null,modelController=null,signal,onError}={})
Import from arcane-os/ai/model-observation. Pass the existing Core client and
the application-owned instances already doing the work. Supported owner methods
are AIRuntimeState's getAIRuntimeState/subscribeAIRuntimeState, image runtime's
current/subscribe, decision model's status/subscribe, and ModelController's
status/on. It creates no replacement owner or transport.
Returns {ready,closed,current,close}. ready resolves with the Core-supplied
{attachmentRequestId,coreRequestId} acknowledgement. Subscriptions then publish
complete current owner snapshots, including a fresh read after acknowledgement.
current() returns the latest renderer snapshot, initially null. The existing
Core error serializer represents owner Error fields at the JSON boundary;
other fields remain unchanged.
Caller abort, page retirement, retirement of the exact installed client,
transport failure or close() retires only observation RPCs/subscriptions.
close() returns closed; it never closes the supplied client or unloads models.
Normal cancellation closes cleanly; cancellation before acknowledgement rejects
ready. Other errors reject public promises and reach onError, defaulting to
complete console diagnostics. A replacement client requires a new explicit
attachment. Keep attachment readiness independent of page rendering. See
renderer ownership and lifecycle.
subscribeModelObservation()
subscribeModelObservation({client,signal,onState,onDiagnostic,onError}={})
Import from arcane-os/ai/model-observation. Requires an existing client and
onState; returns {ready,closed,current,close}. ready resolves with the first
current-state snapshot and current() retains the latest snapshot, initially
null. Providing onDiagnostic explicitly selects live complete correlated Core
model failure frames; omission selects state only. These are developer
diagnostics, not ordinary user status or saved conversation content.
The observer uses the same observation-only cancellation/error lifecycle as
the attachment. Callback failures retire it and reach onError; callback
promises may await close() without becoming its completion barrier. It starts
no model, refresh, polling, endpoint discovery, host or reconnect. See
observation records and limits.
acquireCoreDocument()
acquireCoreDocument({url,client,signal,onProgress}={})
Import from arcane-os/document-acquisition. The asynchronous helper uses the
supplied or installed Core client to invoke documents.acquire with {url}.
The application must compose the native document service. Missing Core reports
DOCUMENT_ACQUISITION_CORE_UNAVAILABLE; a missing service retains the existing
unavailable-method error. Browser-only previews have no browser Fetch fallback.
Resolves with {requestedUrl,finalUrl,url,status,statusText,ok,headers,mediaType, body,complete,redirects}. The final body and every ordered redirect body are
complete Blob values. An HTTP error response retains its status and content;
ok:false is a result, not a generic acquisition error. Headers and entity
content reflect Fetch's public response, including ordinary content decoding.
signal cancels this request; there is no implicit timeout. onProgress receives
request-correlated documents.progress records with phases, document counts
and status fields, never body content. All accepted callback promises settle
before the helper settles. Callback failures cancel acquisition and remain
observable; concurrent operation and callback failures retain an AggregateError.
A late callback or subscription cleanup failure retains the completed response
in error.documentAcquisition with the original cause or aggregated failures.
Every settlement removes the subscription. Local abort rejects immediately and
does not wait for native error evidence. See
complete result, progress and error records.
createDocumentAcquisitionService()
createDocumentAcquisitionService({destinationPredicate,signal}={})
Import from arcane-os/core/document-acquisition. This synchronous factory
returns the Core service definition with documents.acquire, direct
acquire({url,signal,onProgress}) and idempotent asynchronous dispose().
Select it through the application's existing native service composition. The
ordinary service performs HTTP(S) GET acquisition without a predicate.
An application-selected destinationPredicate(destinationUrl, {requestedUrl,previousUrl,signal}) runs locally before every actual GET,
including the first destination and each redirect. Only true permits the
request; other returns produce DOCUMENT_DESTINATION_DECLINED, and a thrown
or rejected value remains the original cause. The predicate is never serialized.
Redirects retain every response body; no automatic retry or redirect-count cap
is imposed. The caller can cancel a repeating redirect chain.
Direct results and error evidence retain Uint8Array bodies. Acquisition errors
keep the original cause and documentAcquisition response/redirect records;
an interrupted body read retains available content marked complete:false.
Only Core JSON transport encodes bodies as base64; the browser restores Blobs.
The factory signal owns the service lifetime; each call signal owns only its
request and leaves sibling acquisitions active. dispose() aborts and joins all
active operations. Bodies are buffered completely; progress is not a body stream.
See native composition and lifecycle.
createPortableNativeProvider()
Overview
Creates the SDK-owned native builder for one portable Core payload. The caller
selects application service modules already present in the app release. The
provider does not load Arcane OS source, choose a model, compile an executable
or substitute for an unavailable platform host. An explicit native.localAI
selection prepares and bundles its selected official runtime distributions;
without that selection, no local-AI runtime is downloaded.
Signature and result
createPortableNativeProvider({services,packagedWeb=false,webKitDocumentLifecycle=false}={})
Import it from arcane-os/native/portable-provider. Each service selection is
{module, options}. Omitted services uses appDescriptor.native.services;
an explicit array, including [], overrides the descriptor selection.
The Mac composition selects packagedWeb:true for the SDK-owned serving service
and webKitDocumentLifecycle:true for the canonical client projection. Defaults
retain the existing portable and Windows behavior.
The returned arcane-native-builder/1 provider exposes
describe(), doctor(), prepare(), build(), verify() and run().
describe() and successful payload results report executable:false; run()
reports ARCANE_NATIVE_RUN_UNSUPPORTED.
build() copies the complete selected app and dependency releases, the
published SDK/runtime dependencies and the canonical Core entry/client into a
temporary assembly, then publishes it at <outputRoot>/<app-id>/. Later
successful builds replace only that app's generated output. Publication retains
the previous output until the completion callback and cancellation boundary
accept the replacement; failure restores it. Models and saved state belong in
their separate persistent directories. See stable output and recovery.
Service factories are imported only when a real native
host later launches the generated Core entry, never during packaging.
The generated runtime/arcane-core.mjs also accepts
--arcane-app-entry <app-relative-module> through the host's supported Node
executable; the portable provider supplies no executable. Include that module
and its complete source closure through package.nativeResources. The flag
imports it from the packaged app/ directory, preserves complete process.argv,
and runs its top-level work rather than invoking an export or making it
import.meta.main. The entry owns explicit launch-context reads, services,
signals and shutdown; ordinary Core startup is skipped only in this mode.
See app-owned runtime entry
and packaged MCP commands and lifetime.
Explicit native.launchContext.coreListener:{endpoint} also composes one passive
model observation service after startCoreHost() and before listener binding,
using that runtime and existing services exposing localai.status, image.status
and decisions.status. Missing owners remain null; renderer attachment stays
application-owned. Ordinary stdio and shared/headless branches gain no model
startup or readiness barrier. See native observation composition.
An optional appDescriptor.native.window record carries width, height,
resizable and state into manifest.window. Dimensions are positive integral
logical client units; resizable is an optional boolean, and state selects
normal, maximized or fullscreen. Omitted fields remain omitted. The portable
payload records the selection; the matching Windows host applies it, while
current other-platform hosts retain their existing window behavior. See
initial native window size and state.
Availability and normalization
Node; produces a portable payload rather than an executable host. Existing outputs remain untouched, cancellation removes only the incomplete new output, and verification reads the semantic manifest and listed files without executing a host. Full ownership and layout contract: portable Core packaging.
Example
import {createPortableNativeProvider} from 'arcane-os/native/portable-provider';
const provider = createPortableNativeProvider({
services: [{
module: 'native/moon-ledger.mjs',
options: {ledgerName: 'Cheese debts'}
}]
});
console.log(await provider.describe());
arcaneNativeBuilderProvider
Overview
Package-owned provider with no preconfigured application services. Each native provider subpath exports its own singleton and exposes that same object as its default binding. The ordinary singleton uses the app descriptor's service selection.
Value and import
const arcaneNativeBuilderProvider
Import it from arcane-os/native/portable-provider for a non-executable payload,
or arcane-os/native/windows-provider for the Windows x64 executable contract.
Availability and normalization
Node for assembly. The portable singleton retains the contract described by
createPortableNativeProvider(). The Windows singleton retains
createWindowsNativeProvider() and needs Windows x64/WebView2 for execution.
The two providers are distinct objects; named/default identity holds within
each selected subpath.
Example
import {arcaneNativeBuilderProvider} from 'arcane-os/native/portable-provider';
const description = await arcaneNativeBuilderProvider.describe();
console.log(description.targets, description.executable);
arcaneNativeBuilderProvider default export
Overview
Default package binding for the same object exposed as
arcaneNativeBuilderProvider.
Value and import
default as arcaneNativeBuilderProvider
Import it from arcane-os/native/portable-provider or
arcane-os/native/windows-provider, selecting that subpath's provider.
Availability and normalization
Node for assembly; execution depends on the selected provider. Within each subpath the default and named bindings have exact object identity and the same lifecycle; portable remains a non-executable payload.
Example
import portableProvider, {
arcaneNativeBuilderProvider
} from 'arcane-os/native/portable-provider';
console.log(portableProvider === arcaneNativeBuilderProvider); // true
createWindowsNativeProvider()
Overview
Creates the SDK-owned Windows x64 provider. It assembles the selected app's complete portable payload with the precompiled WebView2 launcher and Node SEA Core from the numeric release matching the installed SDK version.
Signature and result
createWindowsNativeProvider({services,hostDirectory}={})
Import it from arcane-os/native/windows-provider. services has the same
descriptor/explicit-array semantics as the portable provider. An optional
hostDirectory selects an already-built complete host tree; otherwise build()
downloads and extracts the matching arcane-native-windows-x64.tar.gz beneath
the selected output root. There is no compiler or OS checkout requirement for
application builds. The build machine needs its normal Node/npm toolchain and
tar; execution needs Windows x64, .NET Framework 4.6.2 or later and WebView2.
Successful builds publish the complete payload at <outputRoot>/<app-id>/,
replacing that app's prior generated artifact through the same
joined publication lifecycle.
Runtime caches, models, saved profiles and unrelated outputs remain separate.
The matching Windows host consumes appDescriptor.native.window through
manifest.window. Optional width and height select initial client dimensions
in 96-DPI logical units; the host scales them for its actual DPI and fits the
outer window within the current screen's usable area. Optional resizable:false
selects a fixed-size border and disables the maximize control. Optional state
selects normal, maximized or fullscreen; the host applies an explicit state
after its initial sizing pass and before the composing launcher's Load handler.
Initial sizing runs only for a Normal window. Omitted fields preserve existing
host choices, including the current state when state is omitted. Fullscreen
retains normal bounds and frame controls for restoration. No saved-bounds store
is added, and initial-fit logic is not reapplied during later user resizing.
See initial native window size and state
for the complete descriptor and unchanged other-platform behavior.
The packaged runtime/ArcaneCore.exe also accepts
--arcane-app-entry <app-relative-module> directly, without a script argument
or the GUI launcher. Include the entry and complete source closure through
package.nativeResources. It imports the selected packaged app/ module with
complete process.argv unchanged, running top-level work without invoking an
export or making it import.meta.main. The entry owns explicit launch-context
reads, services, signals and shutdown; this mode skips ordinary Core startup,
while omission retains it. See app-owned runtime entry
and packaged MCP commands and lifetime.
The returned arcane-native-builder/1 provider exposes describe, doctor,
prepare, build, verify and run. Build returns {app,target,manifest}
with the actual directory at target.rootDir. Verification reads the artifact;
it does not launch the window. Run launches the executable recorded in the
saved manifest.host.executable and observes complete diagnostics and exit.
Cancellation closes input and waits for host-owned drain,
including accepted service work, without a forced termination deadline. Missing
prerequisites, download/extraction failures and host failures remain observable
through the operation's error/event boundary.
Assembly names the launcher from appDescriptor.displayName plus .exe,
with a matching .exe.config file. Low-level compositions without a nonempty
string display name use the app ID. Windows-reserved filename characters and
control characters become underscores; reserved DOS device basenames receive
an underscore prefix. Supported Unicode, spaces and case remain, as do the
original descriptor and title. Icon embedding, file inventory, verification
and run use this same name. Existing artifacts retain the executable recorded
in their manifest; the reusable downloaded host retains Arcane.exe and
Arcane.exe.config, and runtime/ArcaneCore.exe remains unchanged.
During assembly, appDescriptor.native.icon selects the app's existing image.
PNG and ICO inputs produce a derived runtime/arcane-app.ico and update only
the copied application's executable icon. Source assets, the selected host
cache, other executable resources and the Core executable remain unchanged.
manifest.host.icon identifies the selected runtime icon, while
manifest.host.executableIcon records whether embedding succeeded.
The builder's onEvent receives native.icon.completed after successful
embedding or native.icon.unsupported when the selected format or executable
layout cannot provide it. Both carry target, appId, icon and executable;
the unsupported event also carries the original code and complete message.
Unsupported embedding preserves ordinary assembly and the original icon path.
Unreadable files or malformed supported image data retain their ordinary errors.
The matching host loads the window/taskbar icon independently of page and Core
startup. PNG/ICO embedding and runtime codec support are separate boundaries;
see application icon and window colors
for formats, per-window colors, errors and platform limits. npm publication
alone does not establish delivery or execution of the matching native archive.
Example
import {createWindowsNativeProvider} from 'arcane-os/native/windows-provider';
const nativeBuilder = createWindowsNativeProvider({
services: [{module: 'native/moon-ledger.mjs', options: {ledgerName: 'Cheese debts'}}]
});
Pass nativeBuilder to the existing native build-plan contract. For the ordinary
CLI route and the complete artifact/launch contract, see
Windows executable packaging.
createMacOSNativeProvider()
createMacOSNativeProvider({services,hostDirectory}={})
Import from arcane-os/native/macos-provider. The named
arcaneNativeBuilderProvider and default export are the same provider with
descriptor-owned services and the exact SDK release's selected host asset.
The six-method arcane-native-builder/1 contract supports macos-arm64 and
macos-x64, platform macos, format app. A selected hostDirectory allows
same-project collaboration on host output; otherwise assembly downloads the
matching numeric SDK release's arcane-native-macos-<architecture>.tar.gz.
Neither an available source implementation nor doctor() proves that the
asset is published or its Mac runtime has been executed.
Build preserves the complete portable payload inside the bundle's Resources
directory (target.rootDir) and returns its .app location as bundleRoot.
The accepted bundle is <outputRoot>/<app-id>.app/; a later successful build
replaces that bundle through the shared publication lifecycle,
preserving separate saved state and model directories.
The bundle supplies the SDK launcher and selected Node runtime. verify()
reads assembled files; run() directly launches the bundled executable only on
the matching Darwin architecture, observes diagnostics and waits for graceful
Core/listener drain on cancellation. See the complete
macOS composition and prerequisite contract.
createPackagedWebService()
createPackagedWebService({artifactRoot}, context={})
Import from arcane-os/core/packaged-web. Returns the Core service
{name:'packaged-web', start, drain}. Start reads the native manifest, serves
its complete web root with the existing explicit HTTP packaged server on
127.0.0.1, and emits core.web.ready with {origin,url,port} only after the
actual listener is ready and its first selected port is saved. The complete
manifest start URL is resolved against that origin.
State uses context.stateRoot or the native launcher's separate
--arcane-host-state-root argument. The saved packaged-web-origin.json keeps
the same port on subsequent launches; unreadable state or port conflicts remain
errors, with no silent new origin. Startup rejection belongs to the Core
core.service.state event; an unexpected post-start close/failure emits
core.web.failed with the complete serialized error. Drain owns listener close
and lifecycle completion. No application launch payload is rewritten, no model
is loaded, and the ordinary server's HTTPS default is unchanged.
createPreferencesService()
Overview
Supplies the five existing Arcane.preferences methods using an application-selected
JSON file. Construction performs no filesystem work. Preference names, defaults,
schemas and writable location remain application-owned.
Signature and result
createPreferencesService({file}={})
Import from arcane-os/core/preferences. The returned Core service exposes
preferences.list/get/set/setMany/delete, drain() and dispose(). Writes use
lifetime:'service', preserve complete JSON values and existing document metadata,
and acknowledge after the new content is flushed and the selected file replaced.
Operations selecting the same resolved filename share an ordered in-process queue.
Unreadable or malformed files report their errors without being replaced; a missing
file starts with empty entries. Unrepresentable JSON values fail before replacement.
import {createPreferencesService} from 'arcane-os/core/preferences';
const preferences = createPreferencesService({file: selectedPreferenceFile});
Register the service with the existing Core owner. Its drain/dispose stops new
acceptance, waits for accepted work and exposes failures; subsequent calls reject
with CORE_CLOSING. See method results, storage and service composition.
createPreferencesService default export
The default export from arcane-os/core/preferences is the same
createPreferencesService factory, with identical arguments, method results
and lifecycle:
import createPreferencesService from 'arcane-os/core/preferences';
createDiarization()
Overview
Retains one caller-selected Nemotron model in its first-party native helper and accepts independent mono-audio streams. Results contain generic timed speaker labels; they do not identify people or perform speech recognition.
Signature and result
createDiarization({executable,modelPath,runtime,onEvent}={})
Import from arcane-os/diarization. Supply absolute helper/model paths and the
selected runtime's library locations. The returned owner starts the helper and
exposes ready, completion, current(), replaying subscribe(),
openStream(), diarize() and close(). Readiness resolves only after model
loading. Each stream owns push, finish, cancel, completion and current;
pushes preserve mono float32 input, use backpressure and return the latest timed
segment snapshot. Caller callbacks may receive every probability frame.
import {createDiarization} from 'arcane-os/diarization';
const speakers = createDiarization({executable, modelPath, runtime});
const result = await speakers.diarize({audio: monoSamples, sampleRate: 16000});
await speakers.close();
Load, callback, process and cleanup failures remain observable. Cancellation suppresses later results for its stream and closes it after accepted native commands; the C ABI supplies no immediate interrupt. Close drains owned work and observes helper exit. See complete audio, callback and cancellation contracts.
buildDiarizationHelper()
async buildDiarizationHelper({runtime,outputRoot,signal,onEvent}={})
Import from arcane-os/diarization/build. Builds the first-party helper for the
current host using installed CMake/C++17 tools and the selected runtime's
cmakeDirectory. Returns {platform,architecture,root,executable,diagnostics}
after configure, compile and install, retaining complete command diagnostics.
Missing inputs or actual tool failures reject through the shared process owner;
no compiler, model or runtime is downloaded by this function.
import {buildDiarizationHelper} from 'arcane-os/diarization/build';
const helper = await buildDiarizationHelper({runtime, outputRoot: helperDirectory});
See runtime preparation, helper placement and platform support.
createDiarizationService()
createDiarizationService(options={},launch={})
Import from arcane-os/core/diarization. This synchronous native.services
factory accepts {executable,modelPath,runtime,onEvent} and the native launch
context. Relative executable/model paths use workspaceRoot, then appRoot,
then the current directory. It supplies diarization.status, diarization.load,
diarization.open, diarization.push, diarization.finish, diarization.cancel
and diarization.recording, state/update/probability events and drain/dispose hooks.
The first actual operation loads the model, independently of Core startup.
import {createDiarizationService} from 'arcane-os/core/diarization';
const service = createDiarizationService({executable, modelPath, runtime}, launch);
Session audio has service lifetime and explicit cancellation; a recording's request cancellation closes only that recording. Complete float32 samples use the documented Core transport framing. See inputs, results, events and lifetime.
createDiarizationService default export
The default binding from arcane-os/core/diarization is exactly the named
createDiarizationService factory, with the same selection and service lifecycle:
import createDiarizationService from 'arcane-os/core/diarization';
resolveNativeLaunchContext()
Overview
Resolves one application's native state, workspace and optional shared endpoint, plus a same-user shared model directory, through the same public owner used by its packaged executable and external MCP. This synchronous function performs no I/O, saved-state discovery, process start or migration.
Signature and result
resolveNativeLaunchContext({appId,context={}}={})
Import from arcane-os/core/host. The result is a new complete context with
omitted fields filled. stateRoot defaults on Windows to %LOCALAPPDATA%/Arcane/<appId>
(home AppData/Local fallback), macOS to
~/Library/Application Support/Arcane/<appId>, and portable Linux Node to
absolute $XDG_DATA_HOME/Arcane/<appId> or ~/.local/share/Arcane/<appId>.
Android and other adapted hosts provide their actual stateRoot and own native
IPC/process adaptation.
An omitted workspaceRoot becomes <absolute selected stateRoot>/Workspace.
An omitted modelsDirectory uses the operating-system user's shared Arcane
model directory: %LOCALAPPDATA%/Arcane/Models on Windows (home AppData/Local
fallback), ~/Library/Application Support/Arcane/Models on macOS, and absolute
$XDG_DATA_HOME/Arcane/Models or ~/.local/share/Arcane/Models on Linux. This
default remains shared when the application explicitly selects another
stateRoot; application state and workspace stay separate. Explicit
modelsDirectory values remain unchanged. Other adapted hosts may supply a
shared directory explicitly; their omitted value remains
<absolute selected stateRoot>/Models.
This resolver supplies a location to its consumers; it neither changes every
provider's store nor creates, moves or migrates model files. Services select
that directory as the shared model-assets working directory, while applications
may also discover their existing app-local originals. Model storage remains
separate from replaceable native build output. See persistent model locations.
Only a selected sharedHost object receives a default endpoint and log file:
Windows uses a named pipe containing the URL-encoded complete absolute state
path; Linux/macOS use <absolute selected stateRoot>/core.sock. The log is
<absolute selected stateRoot>/Core.log. Explicit fields, additional payloads
and explicit workspace values remain unchanged. Relative explicit paths retain
the caller's working-directory meaning. appId and the selected state path
must be nonempty strings; a selected sharedHost must be an object. Malformed
inputs report TypeError; native endpoint failures belong to the IPC operation.
native.launchContext.coreListener:{endpoint} instead attaches local IPC to
the existing window/stdio runtime. Its endpoint remains explicit and receives
no default. The generated entry rejects simultaneous coreListener and
sharedHost selections. Client disconnect affects that connection; window
shutdown still drains Core and closes the additional listener. See
startCoreListener() and
native launch locations.
import {resolveNativeLaunchContext} from 'arcane-os/core/host';
const context = resolveNativeLaunchContext({
appId: 'moon-cheese-post',
context: {sharedHost: {}}
});
// Use context.sharedHost.endpoint for the native UI and external MCP.
// An explicit context.workspaceRoot or context.stateRoot remains selected.
In a complete app descriptor, native.launchContext:{sharedHost:{}} selects
these defaults for ordinary packaged executable launch. Omitting sharedHost
keeps stdio-owned lifetime; omitting native.launchContext preserves the prior
generated-entry path. The selected shared entry creates its state directory
for socket/log use; application services own workspace I/O. MCP-first startup
prepares that returned state directory before the existing start option opens
its log. No caller needs to reconstruct platform paths. The separate
resolveArcaneDataPaths() repository-location contract remains unchanged.
See launch-time locations and
shared native/MCP hosting.
readCoreLaunchContext()
Overview
Combines complete packaged defaults, a separately supplied native host state
directory and the complete JSON object selected by --arcane-launch-config.
An explicit appId selects the native resolver; ordinary calls remain a
configuration reader without automatic location selection.
Signature and result
async readCoreLaunchContext({argv=process.argv.slice(2),defaults={},appId}={})
Import from arcane-os/core/host. Precedence is defaults, then
--arcane-host-state-root <directory>, then every complete top-level field from
the explicit launch JSON object. Nested fields replace rather than deep-merge.
The original file and its payload remain unchanged. Supplying appId applies
resolveNativeLaunchContext to that merged record; its defaults and input
contract then apply. Without appId, relative, null and other explicit state
values retain the prior reader semantics. With no arguments or defaults, the
ordinary call still resolves to {}.
Missing argument values, unreadable files, malformed JSON, non-object defaults
or launch records reject. Relative launch-file paths use the working directory.
The reader searches no other configuration, rewrites no content, migrates no
data and changes no environment. Application-owned fields such as
preferencesFile retain their complete values.
import {readCoreLaunchContext} from 'arcane-os/core/host';
const launchContext = await readCoreLaunchContext();
The generated entry supplies artifact-derived appRoot, then applies the whole
context and passes the same object as every service factory's second argument.
Authored service options remain the first argument. It supplies the descriptor's
native.launchContext as defaults and the app ID only when that optional
field is present. Matching Windows and macOS launchers apply the same packaged
defaults before explicit launch JSON and forward their actual state directory;
other composing hosts can use the same public seam. Compiled host availability
and native execution are separate from this JavaScript contract. See
launch-time locations.
resolveArcaneDataPaths()
Overview
Resolves the native per-user ArcaneData directory and its Repos child without
creating directories or changing application state.
Signature and result
resolveArcaneDataPaths({dataRoot}={})
Returns absolute {dataRoot,repositoriesRoot}. Defaults use Windows LocalAppData,
Linux XDG data home or ~/.local/share, and macOS user Application Support.
Android and other adapted hosts supply their persistent dataRoot. An explicit
root is used directly, with relative paths resolved from the process working
directory. See native repository locations.
import {resolveArcaneDataPaths} from 'arcane-os/core/repositories';
const {repositoriesRoot} = resolveArcaneDataPaths();
createRepositoryWorkspace()
Overview
Owns one native connected working checkout under ArcaneData/Repos/<name> or an
explicit existing path. The application owns the remote, branch and Core API.
Signature and result
createRepositoryWorkspace({name,directory,dataRoot,remote,remoteBase,branch,initialBranch,longPaths,cloneIdentity,gitIdentity,onEvent,run=runProcess}={})
Returns {directory,open,status,configuration,pull,push,write,close,drain,dispose}. Construction does
no I/O. Preparing operations accept {signal}; a missing or empty destination clones once,
while existing checkout files, branches, remotes and local changes remain intact.
Same-directory calls are ordered within the process. Shutdown drains accepted
work and preserves the checkout. No CLI cwd, launch state, preference, snapshot
cache or existing user-data location changes. See the complete inputs, results,
errors and lifecycle.
Optional initialBranch selects refs/heads/<initialBranch> only after a new
clone, successful complete empty remote advertisement, explicit local
initial-state observation and a successful empty local-ref listing. Any local
ref supplied by a Git template or hook remains unchanged. Existing destinations and committed/advertised
clones keep their branches; branch still means Git's existing-branch/tag clone
selection. New-clone open results with this option add complete ordered
preparation outputs; subsequent failures retain completed outputs and their
original cause. Omission adds no command or result field. See
first-publication composition
for the direct first commit/push without an implicit pull.
Optional factory remoteBase explicitly selects the initial-clone remote as
a local filesystem locator. Only its Git argument is derived through the host's
native path.resolve(remoteBase, remote), once at construction. Relative bases,
including '', use the construction-time working directory. The caller's
original locator remains unchanged; Git clone may save the derived argument as
its ordinary origin setting. Omission preserves Git remote names, URLs, SCP-like
addresses and remote-helper strings without guessed parsing. Unrepresentable
base text reports TypeError without transformation.
See relative local repository locators.
Optional longPaths captures a boolean for new Windows clones. Explicit true
or false supplies clone-local core.longpaths before the first checkout and
persists it only in the new repository. Omission preserves inherited/template
configuration. Existing repositories and non-Windows clone commands remain
unchanged; no global setting or data migration is performed. Git's ordinary
configuration precedence, hooks and single-clone lifecycle remain in effect.
See Windows long paths.
Optional cloneIdentity:{name?,email?} captures exact author strings and saves
only supplied fields in a newly created checkout through Git's clone --config
before its first checkout, on every supported platform. Empty strings are
explicit values; omitted or undefined fields preserve inherited and template
configuration. Existing repositories are never reconfigured. Unrepresentable
process arguments fail without changing the supplied text. This option changes
no global configuration, credentials, remote or branch, and does not identify
the authenticated account. Command-local gitIdentity remains independent.
See clone-local author selection.
Optional gitIdentity:{name?,email?,username?} captures explicit non-secret
settings for child Git operations without writing global/local configuration.
Selected author fields override inherited child author/committer fields;
omitted fields remain inherited. Username remains a credential hint, with
authentication owned by ordinary Git and its configured helper.
configuration({signal}) observes an existing working root without clone,
initialization or fetch. It returns {repositoryRoot,headRef,revision,unborn,origin,upstream}:
full symbolic HEAD (including unborn, null when detached), origin URL/pushURL
arrays and current branch remote/merge/URL/pushURL arrays. Unset, empty and
repeated configuration values remain distinct. revision:null,unborn:true
comes only from Git's explicit porcelain-v2 initial state; committed and
detached states retain their current revision with unborn:false. Missing
branch-state output reports ARCANE_REPOSITORY_HEAD_UNAVAILABLE. These are
ordinary configured values and local branch observations, not authentication
or endpoint proof, and are not atomic with later operations. Raw stdout is
decoded without replacement; unrepresentable text reports
ARCANE_GIT_CONFIGURATION_NOT_TEXT with full diagnostics.
pull({target,signal}), push({target,signal}) and
write({files:[{path,content}],message,target,signal}) accept optional
target:{remote,ref,remoteBase?}, captured as original strings at acceptance. The target
selects a fast-forward-only pull into the current branch or a non-force push
of current HEAD to the selected ref, without switching branches or changing
configuration. An operation's own remoteBase declares local-path intent and
captures the native absolute Git argument once at acceptance, before queueing.
It is independent of initial-clone remote/remoteBase/branch; omission of
target preserves ordinary configured behavior. Targeted pull/push results and
writer results/failure outcomes retain original remote, ref and any supplied
remoteBase, including relative or empty base text. See the complete configuration and
target contract.
write snapshots the exact selected
strings, writes those repository-relative files, commits only their literal
paths and performs an ordinary non-force push. It retains unrelated staged
paths and existing Git filters/hooks. Results and causal failures distinguish
confirmed local writes, commits, pushes and uncertain attempted side effects;
complete process output is retained. See the complete writer outcome
contract.
import {createRepositoryWorkspace} from 'arcane-os/core/repositories';
const repository = createRepositoryWorkspace({
name: 'moon-cheese-dispatches',
remote: applicationConnection.remote
});
await repository.open({signal});
await repository.close();
readGitIdentity()
Overview
Reads non-secret global, repository-local and effective Git configuration without changing files or querying credentials.
Signature and result
readGitIdentity({directory,signal,onEvent,run=runProcess}={})
Import from arcane-os/core/repositories. Returns a promise for
{global,local,effective}, each observed scope containing {name,email,githubUser}.
Fields preserve complete UTF-8 strings, including empty values, leading U+FEFF
and newlines; unset fields are null. Git values outside UTF-8 fail with
ARCANE_GIT_IDENTITY_NOT_TEXT instead of replacement characters.
With no directory, only global configuration is read and local/effective
are null. Existing repository directories, including bare caches, select the
context for all three observations. Configured includes and ordinary Git
precedence remain in effect. These are config observations, not authenticated
accounts or environment-resolved commit identities.
Independent scope queries run concurrently and join cleanup before settlement.
Raw stdout is parser-owned rather than emitted as text events; an injected
run must honor the existing raw-output process contract. Lifecycle and stderr
events retain their ordinary route. Errors preserve their original object,
code, cause and process diagnostics, with complete captured output added as
rawStdout (a Buffer). The raw-mode process result retains stdout:null.
If that property already exists or cannot be attached, a wrapper retains the
original as cause, its code/details/exit code and this observation's raw
output; original causal failures remain on the cause. An attachment exception
is retained as attachmentError. Existing property values remain untouched.
Decoding failures include their cause, complete process details and raw output.
Already-represented observer errors appear once; separate failures use
AggregateError. See the complete contract and
per-process selection example.
createCoreLocalAIProvider()
Overview
Creates a browser-safe llama.cpp LLM provider through an existing Core client. Construction selects no model and installs no runtime or transport.
Signature and result
createCoreLocalAIProvider({client,id='llama.cpp',prepareModel}={})
Import it from arcane-os/ai/core-local. The provider implements
arcane-ai-provider/2 and exposes catalog, status, inspect, load,
request, unload and dispose. Register it with the shared AI provider runtime,
select the exact provider/model with localOnly:true, and load that selection.
load() waits for the selected model's actual readiness; inference requests
require that load to have completed successfully. Requests preserve complete
payloads and parsed streaming chunks and cancel on observed readiness loss.
Missing Core reports unavailability; it does not choose a browser or cloud route.
Dispose/unregister at the caller's owning lifecycle boundary.
Omitted client follows late installation, replacement and retirement through
the shared Core installation subscription. An explicit client, including
null, remains fixed. Replacement revokes readiness and cancels owned work;
late results cannot restore it. inspect() distinguishes explicit load
capability from loaded readiness, while status() remains observational.
Disposal releases only an actually retained selection through its captured
client, so never-loaded and already-unloaded providers send no native unload.
The provider/2 runtime reconciles status at its operation boundaries; this
does not add an idle role-state subscription.
Optional prepareModel({selection,signal,progress}) runs at actual load and
returns {assetProjectionId,resourcePaths,executionTarget,release?}. Direct
load fields with those names override preparation when defined; an explicit
executionTarget:null requests the runtime default. Preparation release is
awaited after native load settles, including failure, cancellation and late
preparation results. The current successfully completed load owns readiness
and inference; a failed replacement cannot reuse an older model's ready state.
Native cleanup owns the last dispatched selection, while preparation alone
creates no native unload obligation. status().execution forwards native
execution diagnostics, including configured and observed targets separately.
import {createCoreLocalAIProvider} from 'arcane-os/ai/core-local';
import {getAIProviderRuntime} from 'arcane-os/ai-provider-runtime';
const provider = createCoreLocalAIProvider();
const unregister = getAIProviderRuntime().register(provider);
See the browser provider guide for model selection, streaming, cancellation and primary-model reload behavior.
createLocalAIService()
Overview
Composes application-selected llama.cpp, Ollama and ONNX engines as a native Core service. Runtime installation, process availability and model readiness remain separate states; prompts, models and application policy remain caller-owned.
Signature and result
createLocalAIService(configuration,{appRoot,runtimes=[],signal,onEvent,prepare,executionDevices,autoStart=true}={})
Import it from arcane-os/core/local-ai. configuration is the authored local-AI
record; appRoot resolves its relative model paths and runtimes supplies
resolved installed runtime records. It returns a Core service definition with
current() and independent selected-engine startup. Compose it through the
existing Core lifecycle. Shutdown cancels owned work and joins owned processes;
an already running external service remains under its external owner.
After await context.getService('local-ai'), service.getONNXRuntime() returns
that service's actual prepared ONNX owner. It creates no engine and rejects
unavailable or closing access. Reacquire on each explicit load after recovery;
retain the returned handle for cleanup. Core shutdown cancels request-lifetime
work, and independent services dispose concurrently. See
native service owners.
Optional prepare({signal,onEvent}) supplies resolved runtime records during
this service's startup. Only operations depending on that service wait for its
preparation; the development listener and independently composed image/model
asset services keep their own lifetimes. Pass only llama.cpp/Ollama/ONNX
requirements to this factory; createLocalImageService() owns selected image
requirements. The managed development and native entrypoints separate them.
autoStart:false leaves these selected engines unprepared and unstarted during
Core startup. Call client.invoke('localai.prepare', {}, {signal}) when the
application explicitly requests preparation. The operation invokes the
configured prepare owner, emits its complete events as localai.preparation,
starts configured engines and returns current state. Concurrent callers share
in-flight preparation; completed preparation is reused. Engine/model readiness
remains separate, so this result alone does not establish inference readiness.
The default autoStart:true preserves startup preparation. No model is selected
by this option.
The service provides localai.status, explicit localai.services.recover,
llama.status/models/load/unload/chat, onnx.status/load/run/unload, and the documented native Ollama methods.
localai.state reports runtime/model changes. llama.status and llama.models
observe current state without starting, restarting or waiting for an engine.
Explicit load retains startup and exact catalog-membership checks.
llama.chunk and ollama.chunk
carry original parsed chunks with streamId; terminal responses remain complete.
There is no background health polling or implicit model choice.
For managed llama.cpp loading, llama.load also accepts assetProjectionId,
resourcePaths:{model} and executionTarget. The existing model-assets owner
retains the exact projected GGUF through actual server exit. An omitted target
retains the same model's selection or configured default; null requests the
runtime default. {deviceId} uses this computer's execution-device catalog.
Windows NVIDIA selection resolves that physical device to its CUDA identity;
unsupported or unavailable targets report their actual failure. Runtime
execution reports requested, resolved and configured targets with
observedTarget:null; configuration does not establish physical execution.
An optional executionDevices catalog is borrowed by ONNX and llama.cpp; its
supplying owner retains disposal responsibility. Existing external listeners
retain their own model/device selection and reject managed reconfiguration.
import {createLocalAIService} from 'arcane-os/core/local-ai';
const service = createLocalAIService(application.native.localAI, {appRoot, runtimes});
See Core service configuration, results and failures and native bundling.
createONNXRuntime()
createONNXRuntime({modulePath,signal?,onEvent?}) from arcane-os/local-ai/onnx
owns retained native ONNX sessions in workers. It exposes load({id,model, sessionOptions?,executionPreference?,signal?}), run({id,feeds,fetches?,runOptions?,signal?}),
unload({id,signal?}), current(), replaying subscribe(listener) and close().
The direct model path is absolute. Complete typed tensor records use
{type,dims,data}; callers own the actual graph's inputs and preprocessing.
Models load only on explicit requests. A live session ID requires unloading
before replacement. Independent sessions run concurrently; same-session work
waits at that session's loading/execution boundary. Queued cancellation removes
that request; active cancellation retires the affected worker and suppresses
its response. Native code can delay termination; cleanup waits for actual exit.
current().sessions[].stopping revokes new-run availability at terminal
shutdown; exited records actual Worker exit. A recoverable run error leaves
the loaded session usable. Unload joins exit and output delivery even when a
termination request fails, preserving the complete cleanup error.
The generic load defaults to CPU. executionPreference:'gpu' tries advertised
CUDA, TensorRT, DirectML, CoreML and WebGPU session creation before CPU.
Explicit sessionOptions.executionProviders takes precedence unchanged.
The complete execution record reports discovery, provider attempts and
fallback; successful creation establishes configuration, not physical GPU
execution. Inference is never replayed on a different provider after failure.
See complete signatures, readiness, cancellation and usage.
createCoreONNXRuntime()
createCoreONNXRuntime({client}={}) from
arcane-os/ai/core-onnx accesses an available Core ONNX service. Its load,
run, and unload mirror the native session selection and accept signal and
timeoutMs (default 0). Relative model paths resolve at Core's appRoot.
The accessor owns complete tensor transport encoding/decoding, inspect(),
current(), replaying subscribe(listener) and close(). Closing cancels this
accessor's requests and subscriptions; unloading shared models is explicit.
Construction installs no runtime and opens no transport. Existing browser
ONNX/Wllama remain independent. Omitted client follows late installation and
reads each installed connection's current status; explicit clients, including
null, remain fixed. Retirement or replacement clears readiness and cancels
owned work, with late old-client results suppressed. Close also removes the
installation subscription. See Core and browser usage.
createImageRuntime()
createImageRuntime({libraryPath,bindingModulePath,variants=[],models=[],backend='auto',signal?,onEvent?})
from arcane-os/local-ai/image retains the native image owner for the selected
library. Prepare the installed record through ensureLocalAIRuntimes() and
supply complete model descriptors with actual native resource paths. The
factory installs no software and starts its worker when an operation needs it.
It returns load({model,context?,signal?}), generate({model,prompt,parameters?, signal?,onProgress?}), edit({model,image,prompt,strength,parameters?,signal?,onProgress?}),
unload({signal?}), current(),
subscribe(listener,{replay=true}) and asynchronous close(). A model ID uses
its supplied descriptor; a complete descriptor may be passed directly.
Generation returns all PNG results as images: [{data,mediaType,width,height}]
with native result metadata. Prompts and parameters remain complete.
edit() accepts the original complete PNG as image: {data: Uint8Array, mediaType} and copies the supplied view at acceptance. Its explicit finite
strength is from 0 through 1, takes precedence over model/parameter
defaults and is never clamped. It decodes in the existing worker and uses the
same selected context, queue, progress, cancellation and complete result
contract. SD1.4 and SDXL Base 1.0
advertise txt2img and whole-image img2img. See the
editing contract for supported
PNG input, native preprocessing, alpha and strength-zero semantics; the
original file remains unchanged.
Accessors for the same library share its worker and selected context. Competing
native operations are ordered at that owner; unrelated services remain
concurrent. State observation replays synchronously by default. Cancellation
joins the owning native operation; a model constructor may finish before its
new context can be released. Native accessor close() cancels its requests,
joins them and releases the shared selected context before its working files
can be retired. The final reference closes the worker. This differs from the
browser accessor's detach-only ownership below. See the
image lifecycle, backend and error contract.
createCoreImageRuntime()
createCoreImageRuntime({client,signal?,onEvent?})
from arcane-os/ai/core-image returns immediately with load, generate, edit,
unload, inspect, current, subscribe and close. It subscribes before
requesting an initial status snapshot so newer lifecycle events win. It opens
no connection and installs or selects no model.
Omitted client follows late Core installation, replacement and retirement;
an explicit client, including null, remains fixed. Each installed client is
observed before its status request. Retirement cancels owned work and removes
old readiness; late results cannot restore it. Close removes both service and
installation subscriptions without closing the shared client or model.
load({model,context?,assetProjectionId?,resourcePaths?,signal?}) and
generate({model,prompt,parameters?,assetProjectionId?,resourcePaths?,signal?, onProgress?}) use the selected Core service. Generation acknowledges with
transient Thinking synchronously and returns complete
images: [{blob,mediaType,width,height}] plus native result metadata.
unload({signal?}) explicitly releases the shared selected model;
inspect({signal?}) reads authoritative state without waiting for preparation.
All request methods use timeoutMs:0. current() includes transient requests,
status, busy and closed state; no prompt or image history is saved.
edit({model,image,prompt,strength,parameters?,assetProjectionId?,resourcePaths?, signal?,onProgress?}) accepts the original PNG Blob or File and returns the
same complete Blob result shape. It publishes Thinking before reading that
input, preserves its complete encoded content through Core, and performs no
browser drawing, re-encoding, resizing or saving. The request signal covers
input preparation and native cancellation; an in-flight Blob.arrayBuffer()
finishes before cancellation can be observed. No aborted result or late
progress reaches the caller. See full editing usage and format limits.
subscribe(listener,{replay=true,signal?}) returns an unsubscribe function.
close() cancels and joins only this accessor's requests and subscriptions,
leaving the shared Core client and selected model with their owners. Request
errors retain complete details; an unavailable Core reports
ARCANE_IMAGE_CORE_UNAVAILABLE. Aborted operations deliver no late result or
progress. See the complete browser example and events.
createLocalImageService()
createLocalImageService(configuration,{appRoot,runtimes=[],signal?,onEvent?,prepare?,modelAssets?})
from arcane-os/core/image returns a Core service with current(), replaying
subscribe(listener), native preparation, request methods and joined disposal.
configuration is the selected localAI record. Optional
prepare({appRoot,configuration,requirement,signal,onEvent}) returns one
installed image-runtime record. Startup retains this preparation in the
background; image.status and unrelated services remain responsive.
The service owns image.status/load/generate/edit/unload and
image.state/progress. Pass the same createModelAssetService() instance that
Core exposes when using assetProjectionId and resourcePaths. It retains
prepared model files through actual native completion, replacement, unload and
shutdown. PNG base64 is transport-only framing; the complete result is decoded
by the browser accessor. See parameters, results and ownership.
image.edit takes {model,image,prompt,strength,parameters?,streamId?, assetProjectionId?,resourcePaths?}. Only the Core JSON boundary encodes the
input as {data: completeBase64PNG,encoding:'base64',mediaType}. The service
acknowledges accepted work through image.progress, preserves the original
prompt and complete image, and retains existing model-assets ownership through
native completion. Its complete encoded PNG result has the same shape as
image.generate; editing semantics remain with the
selected model and native engine.
createLocalImageService default export
The default export from arcane-os/core/image is the same
createLocalImageService factory and lifecycle described above.
createNativeKokoroRuntime()
Overview and signature
The named export from arcane-os/local-ai/kokoro composes the selected Kokoro
FP32 graph with the host's existing native ONNX owner, model-resource owner
and prepared persistent phonemization/Opus helper. Construction starts no
native work and acquires no model or runtime.
createNativeKokoroRuntime({
onnx, modelAssets, runtime, prepare, modelId = 'kokoro',
model = KOKORO_MODEL, revision = KOKORO_REVISION, dtype = 'fp32',
paths, assetProjectionId, resourcePaths, sessionOptions,
executionPreference = 'gpu', executionTarget, signal, onEvent
} = {})
Supply the existing onnx runtime or a prepare callback that provides it.
runtime describes the matching native helper and data. paths supplies
complete prepared graph/tokenizer/voice resources; a completed
assetProjectionId instead retains projected resources through modelAssets.
The selected model/revision/FP32 contract is fixed by this frontend.
See native Kokoro for exact resource mappings, preparation,
runtime distribution and model ownership.
Members and results
current()returns complete model/lifecycle state, execution configuration, current request, queue, progress, error, default voice and supported voices.subscribe(listener,{replay=true,signal}={})returns an unsubscribe function and replays current state by default.load(options={})activates the selected resources, retaining omitted selections. Explicit projection/resource mapping or execution-target changes join prior native retirement before loading the new activation.synthesize(request,{signal,onProgress,requestId=null}={})requires a loaded activation.requestcontains the completeinputstring, optionalmodelmatchingmodelId,voice(defaultaf_heart), positive finitespeed(default1) andresponseFormat(wavby default,opusorogg). The result is{audioBase64,contentType,sampleRate,channels,model,voice,speed}; content type isaudio/wavoraudio/ogg; codecs=opus, with mono 24kHz PCM synthesis. The full input is processed in ordered model segments.unload()retires the activation and joins owned native work.close()permanently closes the engine and releases its state subscriptions.
Queued requests retain order. Cancelling a queued request removes only that request. Active cancellation waits for actual helper/session retirement; surviving requests resume with the same accepted provider configuration. The ONNX owner may need a running native call to return before its worker exits. Readiness is lost while that retirement/reload occurs. Errors retain the actual engine and cleanup failures; unsupported explicit voices or formats are never substituted. No audio is played by this engine.
Example
import {createNativeKokoroRuntime} from 'arcane-os/local-ai/kokoro';
// The host supplies its existing ONNX owner and already prepared resources.
async function narrateMoonGoat({onnx, runtime, paths}) {
const voice = createNativeKokoroRuntime({
onnx, runtime, paths, executionPreference: 'cpu'
});
try {
await voice.load();
return await voice.synthesize({
input: 'Captain Goat has landed. Guard the moon cheese!',
voice: 'af_heart', responseFormat: 'wav'
});
} finally {
await voice.close();
}
}
Changing voice to bf_emma selects British English. responseFormat: 'opus'
selects Ogg Opus encoding. GPU/physical-device selection uses the existing
ONNX execution contract; an accepted
provider configuration is separate from observed hardware execution.
The SDK publishes a Windows x64 helper archive. Other platforms need a matching
custom helper distribution and supported native ONNX host. Native helper
production and platform execution evidence remain separate.
createNativeKokoroRuntime default export
The default export from arcane-os/local-ai/kokoro is the same
createNativeKokoroRuntime factory with identical inputs, results and lifetime.
KOKORO_MODEL
Named string export from arcane-os/local-ai/kokoro, with value
onnx-community/Kokoro-82M-v1.0-ONNX. It identifies this frontend's model family
for matching graph, tokenizer and voice resource selection.
KOKORO_REVISION
Named string export from arcane-os/local-ai/kokoro, with value
1939ad2a8e416c0acfeecc08a694d14ef25f2231. Resource preparation uses this
upstream revision with KOKORO_MODEL.
KOKOROSAMPLERATE
Named number export from arcane-os/local-ai/kokoro, with value 24000.
It describes the engine's mono PCM synthesis rate in samples per second.
KOKORO_VOICES
Named array export from arcane-os/local-ai/kokoro containing all 28 supported
US/GB voice identifiers. The engine uses af_heart when the caller omits
voice; an explicit unsupported selection reports an error. Use this complete
array to populate a native Kokoro voice selector.
createNemotronRuntime()
Overview and syntax
Creates one retained native recognizer and optional diarizer without opening a microphone, loading a model or starting inference at construction.
createNemotronRuntime({
runtime, prepare, modelId = 'nemotron-3.5-asr-streaming-0.6b',
modelPath, diarizationModelPath, modelAssets, assetProjectionId,
resourcePaths, gpu, onEvent
} = {})
Supply a prepared runtime or lazy prepare({signal,onEvent}) descriptor
with helperExecutable and selected native library paths. Select gpu
explicitly (native ordinal, or -1 for CPU). Model paths may come from the
descriptor; omit the diarization path when speaker labels are not requested.
Preparation, models and device selection remain caller-owned.
Alternatively supply the existing modelAssets service and a completed
assetProjectionId, with resourcePaths:{model,diarization?} naming exact
projection members. load() retains that projection before yielding and keeps
it through actual helper cleanup; the caller can release preparation ownership
after loading begins. Explicit load accepts these selection fields, and an
active selection must be unloaded before replacement. Direct paths remain
supported. See shared catalog preparation.
Returned members and lifetime
The engine exposes current/subscribe/load/unload/transcribe/openStream/close.
Current state and replaying subscriptions report actual loaded readiness,
native version, requested device, active speaker scope, error and reset state.
load initializes the selection; unload and close join owned cleanup.
openStream({sampleRate=16000,languageCode,model,onUpdate,signal}) resolves an
owned push/forceEndpoint/finish/cancel/completion/current handle plus
sampleRate and speakerScope. Feed mono Float32Array or
{encoding:'f32le',data:BASE64} at the actual declared rate. The native sample
rate contract accepts integer 8000–96000 or 0 for model rate. No encoded-media
decoder is supplied. Updates preserve every alternative, text, word, timestamp,
numeric speaker and final/provisional status.
forceEndpoint drains an utterance while retaining stream and speaker scope;
finish terminally drains accepted input. Partial snapshots replace; finals
remain separate recognition segments, never inferred conversational completion.
transcribe({audio,sampleRate,model?,languageCode?},options) uses this same
stream and returns complete {text,words,results,speakerScope}.
Cancellation joins native and callback cleanup. Terminating genuinely
noninterruptible helper work exposes resetRequired and requires explicit
reload; no engine restarts silently. Callbacks must return before joining their
own stream/engine lifecycle, otherwise NEMOTRON_CALLBACK_WAIT is reported.
Unsupported input reports NEMOTRON_AUDIO_FORMAT_UNSUPPORTED; native, callback
and cleanup failures remain observable.
Availability and example
Node on Windows, Linux and macOS with the first-party helper and matching upstream NeMo ASR runtime/models; Android requires host adaptation. Selected Windows helper compilation is recorded in the engine guide; that is separate from inference, microphone or other-platform execution.
import {createNemotronRuntime} from 'arcane-os/local-ai/nemotron';
function prepareDragonInterpreter(runtime, modelPath, gpu) {
return createNemotronRuntime({runtime, modelPath, gpu});
}
// The native owner explicitly loads, supplies PCM and joins close.
See native Nemotron for complete options, snapshots, callback rules and cancellation/reset outcomes.
createNemotronRuntime default export
The default export from arcane-os/local-ai/nemotron is the same
createNemotronRuntime function, with identical inputs, results and lifetime.
NEMO_SPEECH_MODELS
Import this catalog from arcane-os/local-ai/nemotron. stt describes the
selected Nemotron ASR and diarization GGUF companions; tts describes Magpie,
NanoCodec and the matching ten tokenizer/configuration members. Each selection
contains modelId, providerId, name, ordinary members, resourcePaths
and optional archives. The upstream selections come from NVIDIA's
NeMo-Speech.cpp 0.2.0 catalog. Importing the catalog performs no I/O and installs
no runtime or model. See the exact companion contract.
prepareNemotronModels()
prepareNemotronModels({modelAssets,workingDirectory,directories,id,signal,onProgress,refresh=false}={})
Import from arcane-os/local-ai/nemotron. Explicitly prepares the catalog's
complete ASR and diarization selection through the existing model-assets
service. Optional directories are searched first when refresh is false;
the first complete matching catalog record is opened without downloading.
Otherwise the shared prepare owner acquires the complete selection beneath
workingDirectory/model-assets/. refresh:true requests a separate acquisition.
The promise resolves to {assetProjectionId,directory,members,resourcePaths,release}.
An omitted id is generated. Ordered asynchronous onProgress receives full
file-based semantic progress; existing selections report reuse then ready.
Native acquisition additionally reports its shared resume, ownership-wait,
activity and terminal states described under createModelAssetService().
Completed members and saved partial transfers remain available for retry;
HTTP continuation depends on the source response. Direct installed-directory
reuse keeps its existing phase/file-count callback shape.
Call the idempotent asynchronous release() to relinquish preparation ownership
after the engine has retained it. Complete acquisitions and borrowed originals
remain stored. Cancellation and callback failures join cleanup and preserve
actual failures. The wrapper selects no device, installs no native runtime and
starts no microphone or inference. See native model acquisition.
prepareMagpieModels()
prepareMagpieModels({modelAssets,workingDirectory,directories,id,signal,onProgress,refresh=false}={})
Import from arcane-os/local-ai/nemotron. It has the same preparation,
discovery, progress, cancellation and release contract as prepareNemotronModels,
using the catalog's complete Magpie/NanoCodec/tokenizer selection. Its returned
resourcePaths contains model, codec and tokenizerConfig. The shared TAR
reader extracts the ten selected tokenizer members from the catalog's selected
upstream archive ranges; offsets stay transport-local. Pass the completed
projection to the existing Magpie engine. Voice, language and device selection
remain caller-owned; preparation performs no synthesis.
buildNemotronHelper()
Overview and syntax
buildNemotronHelper({runtime,outputRoot,signal,onEvent}={}) configures, builds
and installs only the first-party Nemotron helper. runtime.cmakeDirectory
selects an installed NeMo CMake package with its matching public ASR headers and
libraries; outputRoot is the caller-owned output directory.
Result, availability and example
Returns {platform,architecture,root,helperExecutable,executable,diagnostics};
executable aliases helperExecutable, and diagnostics retains complete
configure/compile/install results. Requires Node, CMake 3.26+, a C++17 compiler
and matching platform runtime. It downloads no dependency or model and performs
no inference. Cancellation and process failures remain observable.
import {buildNemotronHelper} from 'arcane-os/local-ai/nemotron/build';
async function buildSelectedRecognizer(runtime, outputRoot, signal, onEvent) {
return buildNemotronHelper({runtime, outputRoot, signal, onEvent});
}
See preparation and selection.
buildNemotronHelper default export
The default export from arcane-os/local-ai/nemotron/build is the same
buildNemotronHelper function.
createMagpieRuntime()
Overview and syntax
Creates one retained native Magpie/NanoCodec synthesis owner. Construction downloads, loads and plays nothing.
createMagpieRuntime({
runtime, prepare, paths, modelAssets, assetProjectionId, resourcePaths,
modelId = 'magpie', voice = 'Aria', languageCode = 'en-US',
executionTarget, signal, onEvent
} = {})
Supply a prepared executable/library descriptor or prepare({signal}).
Select matching Magpie, NanoCodec and tokenizer paths, or an existing
model-assets projection and resourcePaths. Explicit executionTarget
selects CPU or CUDA with the host's visible device/UUID; no provider or device
fallback is inferred. The tokenizer's own speaker map determines voice IDs.
Returned members and lifetime
The engine exposes current/subscribe/load/unload/synthesize/synthesizeStream/stop/close.
State includes independent loaded readiness, active/queued requests, voice and
language defaults, model-owned voices and streaming/format capability.
load retains selected models; unload and close join owned work/assets.
Both synthesis methods accept exact {input,model?,voice?,languageCode?,speed?};
language is separate control information, and native speed must be 1.
synthesize(request,{signal,requestId,onProgress}) returns complete base64
WAV (default) or PCM audio, MIME/format and speech metadata. Select
responseFormat:'pcm' explicitly when needed.
synthesizeStream(request,{signal,requestId,onProgress,onAudio}) requires an
awaited ordered onAudio({pcm,format,sampleRate,channels,requestId}) callback.
PCM is a Node Buffer of signed 16-bit little-endian samples; terminal metadata
has complete:true without retaining the complete audio again. Playback
belongs to the caller.
Requests retain FIFO ownership. stop({requestId}) stops only that queued or
active utterance and joins native/callback cleanup; cancellation rejects
synthesis. In-flight native interruption is observed at a PCM callback boundary.
A callback can abort its caller-owned signal and return; self-joining lifecycle
calls reject MAGPIE_CALLBACK_WAIT. Complete native and cleanup errors remain
observable. An interrupted request never returns fabricated complete audio.
Availability and example
Node on Windows, Linux and macOS with a matching helper, upstream NeMo TTS runtime and selected model assets; Android needs host adaptation. The engine guide separates selected Windows compilation from unverified inference, playback and other-platform execution.
import {createMagpieRuntime} from 'arcane-os/local-ai/magpie';
function prepareDragonAnnouncer(runtime, paths, executionTarget) {
return createMagpieRuntime({runtime, paths, executionTarget});
}
// The native owner loads explicitly; synthesis returns audio, not playback.
See native Magpie for complete selection, language, voices, callback constraints and request lifetime.
createMagpieRuntime default export
The default export from arcane-os/local-ai/magpie is the same
createMagpieRuntime function, with identical inputs, results and lifetime.
buildMagpieHelper()
Overview and syntax
buildMagpieHelper({runtime,outputRoot,signal,onEvent}={}) configures, builds
and installs the first-party Magpie helper against the caller's installed
runtime.cmakeDirectory, public NeMo TTS headers and matching libraries.
Result, availability and example
Returns {platform,architecture,root,helperExecutable,diagnostics}, preserving
complete configure/compile/install results. Requires Node, CMake 3.26+, C++17,
platform threads and matching NeMo libraries. outputRoot belongs to the
caller. It downloads no dependency, model or voice and performs no inference.
Cancellation and process failures remain observable.
import {buildMagpieHelper} from 'arcane-os/local-ai/magpie/build';
async function buildSelectedAnnouncer(runtime, outputRoot, signal, onEvent) {
return buildMagpieHelper({runtime, outputRoot, signal, onEvent});
}
See helper build prerequisites.
buildMagpieHelper default export
The default export from arcane-os/local-ai/magpie/build is the same
buildMagpieHelper function.
createWhisperRuntime()
Overview
Creates one retained native Whisper engine from a prepared runtime or a lazy
preparation function. Construction starts no helper, model load or inference.
Import the named factory from arcane-os/local-ai/whisper.
Syntax and inputs
createWhisperRuntime({runtime, prepare, modelId, temporaryDirectory, onEvent}={})
Supply runtime or prepare({signal,onEvent}), and an application-owned
temporaryDirectory. modelId selects a model from the prepared runtime;
omitting it uses the runtime's selected model. onEvent receives complete
native preparation/process diagnostics. The runtime describes matching helper,
Whisper backend libraries, decoder and model files; see the complete
native Whisper preparation contract.
Returned members and lifetime
| Member | Contract |
|---|---|
current() |
Returns providerId, modelId, state, loaded, busy, requestId, requestedBackend, observedBackend, backendEvidence, requestedEncoder, observedEncoder, encoderEvidence and error. State reports actual helper/model readiness; encoder and decoder initialization evidence remain separate. |
subscribe(listener,{replay=true,signal}={}) |
Observes the current snapshot immediately by default, then each state change; returns the unsubscribe closure. |
load({modelId,signal}={}) |
Prepares the selected runtime if necessary and retains its initialized helper/model. Same-model loading is shared; replacement remains explicit. |
transcribe(request,{signal,onProgress,requestId}={}) |
Accepts the complete {audioBase64,mimeType?,model?,language?,translate?} recording for the loaded model and returns {text,language,duration,segments}. audioBase64 transports the original media; the decoder recognizes its actual format. Progress is ordered; control metadata stays outside the request. |
unload() |
Cancels owned loading/transcription, joins decoder/helper work and releases the retained model before resolving its state snapshot. |
close() |
Performs joined unload and disposes state observation. Repeated calls share the closing result. |
The decoder consumes the complete submitted media into native 16 kHz mono PCM
without changing the caller's recording. The result preserves the engine's
complete text and segment order. Temporary operation files remain until decoder
and inference settle. The engine accepts one active recording; overlapping
requests report WHISPER_BUSY, and unavailable/closing/model failures retain
their explicit diagnostics. Caller cancellation retains its supplied reason.
With backend: 'auto', an eligible accelerated native failure may drain that
helper and retry the same complete recording and selected model once on the
prepared CPU backend. Its snapshot is recovering, unloaded and busy during
recovery. Cancellation, malformed input, observer/protocol failure and explicit
backend selection do not cause that retry. requestId is the actual optional
transport correlation, never a generated replacement or payload field; it
remains through terminal error settlement and clears or changes on the next
request/load/unload/close. The shared speech adapter preserves
only that continuing owned request, while new requests require actual readiness.
Availability and example
Node on Windows, Linux and macOS with matching native resources; Android needs the corresponding host/process adaptation. Prepared files establish resource availability, not execution on every platform. This uses an already prepared runtime and the application's own temporary directory:
import {createWhisperRuntime} from 'arcane-os/local-ai/whisper';
import {createSpeechService} from 'arcane-os/core/speech';
const stt = createWhisperRuntime({runtime, modelId: 'whisper-small', temporaryDirectory});
const speech = createSpeechService({stt});
// Register speech with the existing Core owner; it owns start/drain/dispose.
createWhisperRuntime default export
The default binding from arcane-os/local-ai/whisper is identical to the named
createWhisperRuntime() factory and has the same inputs,
members, readiness, cancellation and native-resource requirements.
buildWhisperHelper()
buildWhisperHelper({runtime,outputRoot,cmake='cmake',generator,cmakeArgs=[],env, signal,onEvent}={}) from arcane-os/local-ai/whisper/build builds the first-party
persistent helper using the installed native toolchain. runtime.directory
selects the prepared libraries and runtime.sourceDirectory selects their
matching headers; outputRoot owns build/install output. Optional CMake
arguments, generator and environment remain caller-selected.
The operation runs configure, Release build and install in order. It returns
{platform,architecture,root,executable,runtimeDirectory,diagnostics}, with
complete configure, compile and install process results. Cancellation and
process errors use the existing owned process lifetime. It installs neither a
toolchain nor a model and performs no inference. Windows helper installation
includes the selected compiler's redistributable runtime closure. Use a
toolchain and prepared runtime matching the target platform/architecture; a
source package alone is not a compiled helper. See the helper build procedure.
buildWhisperOpenVinoRuntime()
buildWhisperOpenVinoRuntime({sourceDirectory,openvinoDirectory,cudaDirectory, outputRoot,cmake='cmake',generator,cmakeArgs=[],env,signal,onEvent}={}) from
arcane-os/local-ai/whisper/openvino-build produces the optional native Intel
NPU encoder runtime on Windows x64. This producer uses an already installed
compatible CMake/MSVC environment, Whisper 1.9.4 source and OpenVINO 2026.3.1
development tree. Required sourceDirectory, openvinoDirectory and
outputRoot name those inputs and the producer-owned output. It installs no
driver, toolchain or model and performs no inference.
The producer copies Whisper source into outputRoot/source, applies its
encoder-failure propagation and stderr diagnostic corrections there, and runs
CMake configure/build into outputRoot/build. The original source stays
unchanged. It assembles the runtime under outputRoot/runtime, retaining
OpenVINO/NPU, CPU, TBB, import libraries and packaging notices. Optional
cudaDirectory names the matching upstream b5130 CUDA library directory;
its selected precompiled backend libraries add CUDA alongside CPU. Omission
produces the NPU-plus-CPU tree. cmake, generator, cmakeArgs and env
configure the existing build environment.
The result is {version,openvinoVersion,platform,architecture,encoder,backend, backends,root,directory,libraryDirectory,sourceDirectory,diagnostics}.
directory equals root; the returned sourceDirectory is the copied source.
diagnostics retains complete configure and compile process results.
signal and onEvent use the existing process cancellation and diagnostic
contract. Missing required strings produce a TypeError; an unsupported
producer host or unmatched source correction reports an error. Filesystem,
process, cancellation and observer failures remain observable, with partial
producer output left for its owner.
Build the matching first-party helper separately with buildWhisperHelper,
then retain its complete installed bin alongside this runtime. The
complete producer example
covers that composition. Applications normally select the precompiled asset
through encoder: 'openvino-npu'; they do not run this producer at startup.
createSpeechService()
Overview and usage
createSpeechService({stt,tts,signal,autoLoad=true}={}) from arcane-os/core/speech composes
independently selected STT and TTS engines as one Core service. Supply either
role or both. Construction downloads, installs and loads nothing; the host
owns engine creation, model/device selection and supported formats.
import {createCoreRuntime} from 'arcane-os/core/runtime';
import {createSpeechService} from 'arcane-os/core/speech';
// transcriptionEngine is the host's already constructed, selected engine.
const speech = createSpeechService({stt: transcriptionEngine});
const core = createCoreRuntime({services: [speech]});
core.start();
Each supplied engine exposes current(), replaying subscribe(listener),
load({signal}), close() and its role's
transcribe(request,{signal,onProgress}) or
synthesize(request,{signal,onProgress}). The service forwards complete
requests and results unchanged. Format decoding, model processing and encoding
remain with that engine. This factory supplies no speech engine or automatic
browser/native provider selection.
Optional engine openStream({...options,signal,onUpdate}) supplies continuous
recognition; optional synthesizeStream(request,{signal,onProgress,onAudio,requestId})
supplies awaited ordered PCM output. Each role reports supportsStreaming
independently from loaded readiness. The Core streaming methods are
speech.open, push, endpoint, finish, cancel, synthesizeStream,
audioConsumed and cancelSynthesis (each under speech.). Request-scoped
speech.opened, speech.transcription and speech.audio events retain stream
ownership; TTS acknowledgements apply backpressure while control traffic continues.
Endpoint drains an utterance without closing its stream; finish closes terminally.
ASR finals are recognition segments, not conversational decisions. Cancellation
joins the selected engine's native work. See the complete streaming contract.
Members, results and events
The returned object has name: 'speech', current, subscribe, close,
start, methods, drain and dispose:
start(context)subscribes and starts both configured engine loads independently, returning immediately. Core and status remain responsive during loading; one role's failure leaves the other usable. WithautoLoad:false, subscriptions and role capabilities remain available while startup requests no engine load. Explicitspeech.loadactivates the selected role. The default preserves automatic startup loading.current()andmethods['speech.status']()return the same snapshot:ready,transcriptionAvailable,synthesisAvailable,status,sttEngine,ttsEngine,roles.stt,roles.ttsandclosed.readyrequires both roles; each independent availability flag requires its model loaded inreadyorrunningstate while the service accepts work.statusiscreated,ok,closingorclosed; per-role state carries model loading, progress and complete errors. An omitted role is unavailable.subscribe(listener,{replay=true,signal}={})replays current state by default and returns an unsubscribe function. Its signal owns only that subscription; a closed service can replay its final snapshot.methods['speech.transcribe'](request,context)andmethods['speech.synthesize'](request,context)are registered as the matching Core RPC methods. The context suppliessignal,requestIdandemit. The service publishes synchronous acceptedThinkingbefore waiting for its role's load, then forwards the engine's complete progress and result.methods['speech.load'](request,context)andmethods['speech.unload'](request,context)route explicit activation to the explicitrole: 'stt' | 'tts'and forward the remaining activation fields and result through that role's configured engine. A startup load remains owned independently of callers waiting for it. The browser facade exposesArcane.speech.load(request,options)andunload(request,options)withsignal,onRequestand no elapsed-time cutoff. See activation routing for selection and errors.close()and itsdrain()alias stop acceptance, abort the service lifetime, close both engines concurrently and await startup and request work. Repeated calls share one promise.dispose()also releases event subscriptions.
speech.state carries the complete snapshot. speech.progress carries
{requestId,role,status:'Thinking',progress} with initial
progress:{phase:'accepted'}. The service's subscription replays state; Core's
generic runtime replay does not replay this custom event. Browser consumers
subscribe before requesting Arcane.speech.status() and preserve any newer
state event received while that request is pending.
Cancellation, errors and availability
The optional factory signal owns the service lifetime. A request signal is combined with that lifetime and reaches its selected engine. Cancelling one request waiting for a shared load settles that request without cancelling the other requests or role. No later cancelled progress or result is delivered. Actual queued/running native interruption belongs to the engine; it must settle before Core reaches service shutdown, because Core first cancels and awaits active requests.
Invalid engine interfaces or listeners throw TypeError. Missing roles reject
their operation with SPEECH_ENGINE_UNAVAILABLE; work after shutdown begins
rejects with CORE_CLOSING. Engine errors remain observable, and engine cleanup
failures reject shutdown with AggregateError. Asynchronous listener failures
reach developer diagnostics. Engine platform support remains its own contract;
this Node composition layer adds no engine dependency. The shared AI adapter
follows the selected model and engine in per-role snapshots, including Nemotron
and Magpie. Only its older aggregate-only fallback retains fixed
whisper.cpp/whisper-small and kokoro-onnx/kokoro expectations.
Unavailable streaming operations reject SPEECH_OPERATION_UNAVAILABLE without
fallback. See the complete engine and lifetime contract.
createSpeechService default export
The default export from arcane-os/core/speech is the same
createSpeechService factory, with identical inputs, results and lifecycle.
prepareCoreModelAssets()
prepareCoreModelAssets({client=getInstalledCoreClient(),workingDirectory,members,signal?,onProgress?})
from arcane-os/ai/core-model-assets projects ordered complete
members: [{path,file}] through an available Core connection. Each file is a
Blob or File. It returns {id,directory,members:[{path,nativePath}],release}
after all members finish writing and close. Independent members transfer
concurrently; each member's writes remain ordered.
The caller releases preparation ownership with asynchronous idempotent
release(). Native engines acquire their own retain handle before loading,
and files remain until their actual native use ends. Cancellation and failure
join transfers and uncancelled cleanup, preserving complete original errors.
The helper downloads no model, changes no DBOPFS original and selects no
engine. See complete preparation and cleanup usage.
createModelAssetService()
createModelAssetService({appRoot=process.cwd()}={}) from
arcane-os/core/model-assets returns the Core service for
modelAssets.open/write/complete/release/status,
modelAssets.discover/openExisting/prepare/cancelPrepare, and modelAssets.state.
Relative working directories resolve from appRoot; explicit absolute
directories remain caller-selected. Each projection has its own child
directory and complete member files.
current() returns {closing,projections}. retain(id) accepts a completed
projection and returns {id,directory,members,release} for a native owner.
Native prepare({id,workingDirectory,members=[],archives=[],signal,onProgress,refresh=false})
accepts ordered {path,url} members and optional uncompressed TAR selections,
returning their complete ready projection. An archive declares
{url,format:'tar',ranges?,members:[{path,member}]}. Optional inclusive
{start,end,stopBefore?} ranges use HTTP partial responses; the parser handles
ordinary and PAX member paths and preserves each selected file completely.
All declared companions must finish before readiness. Range framing stays
transport-local.
Complete native acquisitions persist beneath workingDirectory/model-assets/
through unload, disposal and restart; ordinary calls reuse the exact complete
ordered source selection without a network freshness check. Explicit
refresh:true acquires a separate complete set without replacing active files.
Independent members transfer concurrently. Interrupted or cancelled acquisitions
retain completed members and closed partial files for retry. A retry reuses the
same recorded attempt and downloads only missing members. Ordinary-file HTTP
continuation uses its retained strong ETag or Last-Modified validator with
Range and If-Range; a matching 206 response appends. A full 200, 416,
missing validator or prior encoded response restarts only that member and
reports restart. One prior partial remains until its replacement completes.
TAR selections replay the required segment framing while preserving already
completed companions. HTTP framing remains internal to the transfer, not
model identity or user-facing progress.
Matching same-process preparations share acquisition with independent callbacks
and cancellation; cancelling one interested caller leaves the others running.
The last interested cancellation joins I/O while retaining resumable data.
Matching selections in separate processes coordinate their recorded transfer
owner, report waiting, then reuse or resume after that owner releases or exits.
Unrelated acquisitions remain concurrent. Member completion follows stream/file
closure and promotion; whole-acquisition readiness follows all selected members.
Startup downloads nothing, and retry remains an explicit preparation request.
Native acquisition progress is
{phase,state,message,completed,total,unit:'files',memberIndex?,path?,reason?,recovery?,error?,activity?}.
Phases are open, download, reuse, resume, restart, complete, ready,
waiting, heartbeat, stalled, interrupted, cancelled and failed.
States are waiting, downloading, stalled, interrupted, cancelled,
failed and ready. A five-second heartbeat keeps active work observable;
stalled means no source activity arrived for fifteen seconds, not a diagnosed
outage. Waiting may include the other owner's observed activity. Plain
message and recovery belong in ordinary status; complete error details
remain diagnostic data. Progress uses phases and completed-file counts, not
invented percentages. Terminal acquisition state does not imply that a
cancelled subscriber receives callbacks after its cancellation boundary.
discover({directories,catalog=[],recursive=true,signal}) reads only explicit
installed directories and returns {directories,models}. Directory observations
contain {directory,exists,error?}. Each model record has
{directory,entryPath,members:[{path,nativePath,available}],missingMembers,complete,source,catalogId?}.
The source is directory, catalog or acquisition. Split GGUF filename sets
are one numerically ordered selection, including missing expected shards and
the first shard as entry. This grouping also applies to completed acquisitions;
all declared companions remain present. Ordinary readable symlinked files and
directories are followed, with real-path cycle detection.
Catalog entries {id,members,archives?,entryPath?} declare exact companion sets.
Acquisition-backed matching honors supplied source URLs and archive member
names; path-only catalogs and ordinary directory discovery make no origin or
runtime-readiness claim. No files are downloaded, loaded or moved by discovery.
openExisting({id,directory,members:[{path}],signal}) opens a complete borrowed
projection using those existing files. Missing members reject with
MODEL_ASSET_MEMBERS_MISSING and the complete missing-member list. Release
never deletes or copies borrowed originals. The three new operations also have
matching Core RPC methods. Request-scoped modelAssets.progress carries
{id,progress} with full file-based semantic progress; cancelPrepare aborts
and joins actual acquisition cleanup. The browser helpers below preserve the
request correlation and cancellation joins.
release(id) relinquishes live preparation ownership. Native retains continue
through actual engine release; completed native acquisitions remain stored.
Browser open/write/complete projections retain their temporary lifetime and
are removed only after all native uses end. See
native preparation.
dispose() releases preparation ownership and joins file writes, closes and
all native retain lifetimes before cleanup. The native owner releases its
handle only after its actual context/worker use ends. Original stored model
files remain with their application owner. See
working-file service and wire operations.
discoverCoreModelAssets()
discoverCoreModelAssets({client=getInstalledCoreClient(),directories,catalog,recursive,signal}={})
Import from arcane-os/ai/core-model-assets. Resolves the native discover
result described above through the installed Core connection. Directories and
catalog selections remain application-owned. Complete shard and companion
availability is filesystem evidence, not a selected or loaded model. See
discovery records.
openExistingCoreModelAssets()
openExistingCoreModelAssets({client=getInstalledCoreClient(),directory,members,signal}={})
Import from arcane-os/ai/core-model-assets. Opens selected complete existing
files through Core and returns {id,directory,members,release}. The helper
generates its projection ID; release() is asynchronous and idempotent.
Native engines retain their own use; borrowed original files remain intact.
Cancellation joins uncancelled cleanup before rejecting.
downloadCoreModelAssets()
downloadCoreModelAssets({client=getInstalledCoreClient(),workingDirectory,members,archives,refresh=false,signal,onProgress}={})
Import from arcane-os/ai/core-model-assets. Explicitly invokes native
acquisition for complete ordinary and optional TAR-selected members and returns
{id,directory,members,release}. It generates the ID, observes only that request's
complete progress, and awaits asynchronous callbacks in order. Cancellation or
a callback failure joins native cancelPrepare cleanup and local callback
delivery before settlement; actual cleanup failures remain observable.
When Core rejects preparation, the helper first delivers already queued
terminal progress before its internal cleanup cancellation and rejection.
Explicit caller cancellation retains its no-late-callback boundary.
Release relinquishes preparation ownership while completed downloads remain
stored. Interrupted/cancelled native transfers retain completed members and
saved partials for an explicit retry; the shared owner's HTTP continuation and
member-restart rules apply. Progress forwards its full ownership-wait,
heartbeat/stall and terminal records without inventing completion. No model,
runtime or device is selected implicitly. See
download and progress usage.
createModelAssetService default export
The default export from arcane-os/core/model-assets is the same
createModelAssetService factory and lifecycle described above.
createLocalAIService default export
The default binding from arcane-os/core/local-ai is exactly the named
createLocalAIService factory above, with the same arguments, return value and
lifecycle:
import createLocalAIService from 'arcane-os/core/local-ai';
ensureLocalAIRuntimes()
Overview
Reuses matching managed runtimes or installs complete selected llama.cpp/Ollama/ONNX/image distributions, NeMo libraries or native Kokoro helper/data trees in an explicitly supplied directory.
Signature and result
async ensureLocalAIRuntimes({runtimes=[],directory,platform=process.platform,architecture=process.arch,signal,onEvent}={})
Import it from arcane-os/local-ai. Runtime requirements accept IDs or
{id,version?,url?} records. The result is an array of absolute
{id,version,platform,architecture,root} records, with executable for servers,
modulePath for ONNX, image libraryPath/bindingModulePath/variants/models,
or NeMo library directories. The SDK-selected Windows x64 ONNX 1.30.0
distribution also returns nativeDistributionRevision: '1.30.0-directml-reshape-1'.
With no explicit url, an omitted ONNX version or explicit 1.30.0 selects
the corrected native archive from the installed SDK's numeric release.
Other ONNX versions, platforms/architectures and explicit URLs retain their
upstream package path. Reuse requires the selected revision; older installation
trees remain intact while a fresh installation is prepared. See
ONNX runtime preparation.
Image requirements also accept backend and
models; their pinned default runtime, CPU/Metal selection and separate model
preparation are described in local image generation.
kokoro-native returns helperExecutable, espeakDataDirectory and
libraryDirectory. Windows x64 defaults to the helper archive from the
installed SDK's numeric release; an explicit url or helperRoot selects a
complete custom distribution. The data directory is the parent of
espeak-ng-data. Helper preparation loads no Kokoro graph and keeps the
existing ONNX/model-resource owners separate. See native speech.
Matching concurrent
installs share their work. Downloads retain runtime libraries and surface
network/archive failures; cancellation and operation events remain observable.
Installation changes no global PATH or system service and loads no model.
Supported assets belong to the selected distribution; see
platform and archive requirements.
import {ensureLocalAIRuntimes} from 'arcane-os/local-ai';
// Call explicitly when the app needs its selected official runtime installed.
async function prepareMoonCheeseRuntime(){
return ensureLocalAIRuntimes({
runtimes: ['llama.cpp'], directory: '.arcane/local-ai/runtimes'
});
}
bundleLocalAIRuntimes()
Overview
Prepares selected runtimes through the same installer and copies their complete trees into one fresh native staging destination.
Signature and result
async bundleLocalAIRuntimes({runtimes=[],directory,outputRoot,platform=process.platform,architecture=process.arch,signal,onEvent}={})
Import it from arcane-os/local-ai. directory owns the reusable installation;
outputRoot owns the fresh artifact. The promise resolves to {runtimes,files}:
runtime paths are artifact-relative under runtime/local-ai/<id>, and files
contains the complete emitted inventory. Existing runtime destinations are
preserved and reported as a conflict. Copying settles all started work and
reports failures/cancellation without executing app services or models.
The corrected Windows x64 ONNX selection retains its
nativeDistributionRevision and complete native libraries. Its modulePath
is relocated with the other runtime paths; bundling introduces no separate
runtime selection. See ONNX runtime preparation.
Kokoro bundling retains the complete helper/data tree and relocates
helperExecutable, espeakDataDirectory and libraryDirectory. Its selected
ONNX runtime and model resources retain their existing independent ownership.
Image records relocate the complete library, binding and variant paths. Model URL descriptors retain their original acquisition metadata for preparation after launch. Runtime-contained native model paths become artifact-relative; external working paths report their portability incompatibility rather than embedding this machine's path. Use the application-owned native-resource or post-launch model-assets workflow for those files.
import {bundleLocalAIRuntimes} from 'arcane-os/local-ai';
// Call explicitly with a fresh output directory for this native assembly.
async function bundleMoonCheeseRuntime(outputRoot){
return bundleLocalAIRuntimes({
runtimes: ['llama.cpp'], directory: '.arcane/local-ai/runtimes', outputRoot
});
}
The ordinary provider invokes this owner only for an explicit native local-AI selection. See selected local-AI runtimes.
startCoreListener()
Overview and signature
Attaches a local IPC listener to an existing Core runtime, without creating, starting or taking ownership of that runtime or its services.
startCoreListener({runtime,endpoint,onError}={})
Import from arcane-os/core/host. Resolves {endpoint,closed,close} after the
selected endpoint binds. close() is idempotent, cancels the listener's
request-lifetime work, flushes queued output and closes its connections. It
does not call runtime.close() or wait for accepted service-lifetime work;
that work remains tracked by the existing runtime. Runtime shutdown rejects
new listener requests, retains the endpoint through service drain/disposal,
and closes the listener automatically. Observe both owners' closed promises.
Bind errors reject startup without closing the supplied runtime. Transport
errors reach onError, with complete console diagnostics by default; terminal
listener errors reject closed. Attaching to a draining/closed runtime reports
CORE_CLOSING.
Node supports named pipes on Windows and Unix-domain sockets on Linux/macOS;
Android requires its host adaptation. Supply a nonempty endpoint and an existing
parent directory where required. Connect with connectSharedCoreHost({endpoint})
and omit start. Its current-runtime replay does not replay requests. The
borrowed listener implements no core.host.shutdown operation; use client
close() for disconnection and the existing runtime's owner for host shutdown.
Each connection owns response/event correlation and request cancellation.
Handler requestId and clientRequestId preserve the client ID; coreRequestId is the distinct
internal dispatch ID. Parameters, results and event data, including
data.requestId, remain unchanged. Runtime-state snapshots retain internal
active IDs; no service event is invented or retained for later replay.
import {startCoreListener} from 'arcane-os/core/host';
const listener = await startCoreListener({runtime: host.runtime, endpoint: selectedEndpoint});
try {
await host.closed;
} finally {
await listener.close();
}
host is the application's existing stdio host. Generated native entries
select this attachment with native.launchContext.coreListener:{endpoint},
preserving their actual runtime, service set, profile, origin and state root.
That generated opt-in registers the passive observation service from existing
native model owners before binding; direct startCoreListener() itself never
registers services. Renderer owners are attached separately by the application.
Omit sharedHost; the two options describe alternative lifetimes. Full
contract: existing-runtime listener.
startSharedCoreHost()
Overview
Owns one application's Core runtime at an explicitly selected local endpoint. It claims the endpoint before constructing services, so UI and MCP processes can share the same service state without constructing duplicate owners.
Signature and result
startSharedCoreHost({endpoint,application,version,configure,getReplayEvents,signal,onError}={})
Resolves {runtime,endpoint,closed,close}. configure(runtime,{signal})
registers services through the existing runtime; services start independently.
Optional synchronous getReplayEvents() supplies current {event,data}
snapshots, never historical replies. close() joins composition, accepted
service work, service cleanup and queued frames before releasing the endpoint.
Request-lifetime work is cancelled; accepted service-lifetime work remains
service-owned. The supplied signal begins the same shutdown. closed rejects
on shutdown failure; onError observes transport/background failures, with
complete console diagnostics by default.
The owning adapter preserves its existing internal handler requestId, equal
to coreRequestId, and its matching data.requestId compatibility mapping.
Additive clientRequestId exposes the original client ID independently; other
parameters, results and event data remain unchanged.
Availability and example
Node supports app-selected named pipes on Windows and Unix-domain sockets on
Linux/macOS; Android needs its host adaptation. Parent directories must exist.
An occupied endpoint returns native EADDRINUSE with
coreHostPhase:'listen', without calling configure. Native failures remain
observable; the SDK does not delete an existing endpoint to take ownership.
import {startSharedCoreHost} from 'arcane-os/core/host';
const host = await startSharedCoreHost(
{
endpoint: selectedEndpoint,
application: {id: 'moon-cheese-ledger'},
configure(runtime) {
runtime.registerService(ledgerService);
}
}
);
// The application owner later calls await host.close().
selectedEndpoint and ledgerService belong to the application. See
shared Core hosting for correlation, replay and cleanup.
connectSharedCoreHost()
Overview and signature
Connects to the selected application host, optionally starting an explicit headless entry when that endpoint is absent.
connectSharedCoreHost({endpoint,start,signal,onError}={})
Resolves {client,endpoint,closed,close,shutdown}. client is the existing Core
client with current-runtime replay. Optional start is
{command,args=[],cwd,env,logFile}; its entry calls runSharedCoreHost().
Only ENOENT or ECONNREFUSED selects startup. Arguments/environment are
captured at acceptance, diagnostics append completely to the selected log,
and requests are never automatically repeated. Other connection/start errors
propagate; closed rejects on transport failure. Node/platform availability
matches startSharedCoreHost().
close() disconnects this client and cancels only its request-lifetime work;
it preserves the host and accepted service work. Cancelling startup wait does
not kill a host another client may use. No startup timeout is imposed; supply
signal when needed. shutdown(invokeOptions) explicitly invokes
core.host.shutdown, drains all shared services and returns {state:'closed'}
before disconnecting. It affects every client; cancellation after acceptance
does not reverse it. A drain failure returns the full Core error.
The same connector can attach to startCoreListener() with start omitted.
There, close() still disconnects only this client, and shutdown() has no
listener-owned operation: absent an application method of that name, the
ordinary dispatcher returns METHOD_NOT_ALLOWED. The existing window/runtime
owner remains responsible for shutdown.
import {connectSharedCoreHost} from 'arcane-os/core/host';
const connection = await connectSharedCoreHost(
{endpoint: selectedEndpoint}
);
try {
const catalog = await connection.client.invoke(
'catalog.read',
{}
);
console.log(catalog);
} finally {
await connection.close();
}
connectAppControl()
connectAppControl({endpoint,signal,onError}={})
Connects once to the explicit running native window and resolves
{endpoint,closed,status,inspect,capture,act,key,resize,close}. The Windows host selects its
own listener through native.launchContext.appControl.endpoint and preserves the
existing Core child, origin, profile and application lifetime. The client uses
portable Node local IPC; other native host adapters do not yet implement these
document operations. No application is launched, no desktop window is activated,
and no automatic reconnect or action retry occurs.
status(options) reports current app/window/document readiness, including
observed window state Normal, Maximized, Minimized or Fullscreen.
inspect(parameters={},options) returns complete selected DOM HTML/text
and live control state. Inspection and actions accept optional shadowPath, an
ordered array of unique CSS host selectors through open shadow roots; their
selector resolves inside the final root. Omission retains top-level light DOM.
Closed roots remain unavailable. Inspection also returns top-level viewport
CSS-pixel width/height and devicePixelRatio, documentHasFocus, and focusPath
through the active open-shadow branch. These focus records have null selectors
and remain separate from the selected root's activeElement; frames and closed
roots end the path. capture(parameters={},options) returns a full base64 PNG
of the rendered viewport. act(parameters,options) requires a returned
documentGeneration, one CSS selector, and click, fill, select or scroll
fields.
key(parameters,options) requires the observed documentGeneration and
key:'Tab', 'Enter', 'Space' or 'Escape'; shiftKey:true is supported only
for Tab.
It sends a fixed ordered press/release pair to the selected WebView's current
focus, without selecting an element or activating the desktop window. Accepted
pairs share one keyboard owner. Once a press is attempted, its matching release
is attempted on the same WebView even after cancellation, navigation or failure;
a failed or ambiguous press is never replayed. Results retain previous/actual
document views and complete attempted/completed phase records. Generation checks
bracket native input rather than atomically binding it to a document, so focus
or navigation can change between phases.
resize(parameters,options) accepts positive integral native client width
and height supported by WinForms, plus optional documentGeneration. It changes
only ClientSize while the actual window is Normal; maximized, minimized or
fullscreen windows fail before size mutation. Results retain immediate
previous/actual native dimensions, requested dimensions, attempted/completed flags and a later
observed CSS viewport. Platform constraints can change actual dimensions;
native and CSS observations are not an atomic snapshot. Restore explicitly with
the same operation's previous.width and previous.height, not CSS dimensions
or a historical status snapshot. Cancellation does not restore the window.
Options preserve the Core client signal/timeout contract. Cancellation before
dispatch prevents execution; dispatched work and owned key release remain
observed through completion. Actual errors retain complete partial results;
responses completed after cancellation or disconnection remain in host
diagnostics. close() cancels this connection's requests and returns closed,
without closing the app. Document changes and actual errors remain observable.
Dispatch completion does not establish application handler completion or a
successful business action; inspect the resulting built application to establish
that outcome. Assembly requires a matching published Windows host asset.
The CLI provides app-control key and app-control resize, each forwarding the
complete parsed --request object. Full parameter/result, error, cancellation,
CLI and platform contracts are in native application control.
runSharedCoreHost()
Accepts the same options as startSharedCoreHost(options) and adds the headless
startup handshake. The winning launcher returns the host handle. A losing
launcher connects to the existing owner, confirms dispatcher response and
returns null without constructing its own services. Startup success or the
complete error reaches an existing parent Node IPC channel; the helper never
calls process.exit(). Host lifetime, errors and platform requirements retain
the contracts above.
import {runSharedCoreHost} from 'arcane-os/core/host';
const host = await runSharedCoreHost(applicationHostOptions);
await host?.closed;
The application supplies applicationHostOptions, including its endpoint and
service factory. This is the entry selected by the start option of
connectSharedCoreHost().
startSharedCoreBridge()
Connects one framed stdio client to the shared host, preserving complete
requests, responses and events through the existing arcane/1 transport.
startSharedCoreBridge({endpoint,start,input=process.stdin,output=process.stdout,signal,onError}={})
Resolves {endpoint,closed,close}. start and connection errors follow
connectSharedCoreHost(). EOF, close() or cancellation disconnects this
client only. Terminal stream errors settle pending writes and reject closed;
service shutdown is separate. Node readable/writable streams and the selected
local IPC endpoint are required. This is Core framing, not external MCP framing.
import {startSharedCoreBridge} from 'arcane-os/core/host';
const bridge = await startSharedCoreBridge(
{endpoint: selectedEndpoint}
);
await bridge.closed;
Generated native entries select this bridge only through explicit launch
context sharedHost:{endpoint,logFile}. Omitting it preserves ordinary
stdio-owned Core lifetime. See native shared-host launch.
startCoreHost()
For an external client of the actual window-owned runtime, attach
startCoreListener() to host.runtime. For an explicitly
independent headless lifetime, use the shared host functions.
Ordinary startCoreHost() retains its existing stdio-owned lifetime.
Overview
Composes explicitly supplied application services with the shared Core runtime and stdio transport. It is a lifecycle helper for a host-owned Node process, not an executable host or another dispatcher implementation.
Signature and result
startCoreHost({application, version, services=[], input, output, onError, signal}={})
Import it from arcane-os/core/host. The result is the existing stdio owner
{runtime, closed, close}. An optional abort signal invokes that same
idempotent close() and its graceful drain.
Dispatcher readiness does not wait for service or model readiness. Renderer
cancellation reaches request-lifetime work, while accepted
lifetime:'service' work survives and settles before service drain, disposal
and final output completion.
Availability and normalization
Node with readable input and writable output streams. Errors remain
observable through onError and closed. The helper never kills or exits the
process and does not end caller-owned output. See
portable Core packaging
and the native Core runtime.
Example
import {startCoreHost} from 'arcane-os/core/host';
const host = startCoreHost({
application: {id: 'moon-catalog', name: 'Moon Cheese Catalog'},
version: '1.0.0',
services: [{
name: 'catalog',
methods: {
'catalog.read': parameters => ({found: true, name: parameters.name})
}
}]
});
await host.closed;
BROWSERWASMRUNTIME_AUTHORITY
Overview
Mutable metadata for the browser-only runtime behind
arcane-os/ai/browser-wasm. It records protocol
arcane-ai-browser-wasm/2, @wllama/wllama 3.6.0, the packaged JavaScript
and WebAssembly asset locations, MIT license identifiers for Wllama and
llama.cpp, and the disabled compatibility-runtime/remote-model-helper policy.
Its execution policy declares webgpuRequired:false,
defaultGpuLayers:99999, cpuGpuLayers:0, and cpuFallback:false. The default
requests full GPU offload; gpuLayers:0 explicitly selects CPU. A failed GPU
load never silently switches to CPU. The metadata contains no model weights
or default model catalog and does not establish that a model has loaded.
Value and import
const BROWSER_WASM_RUNTIME_AUTHORITY
The value is available from arcane-os/ai/browser-wasm only. Importing and
inspecting it does not initialize Wllama, request storage, or download a model.
Availability and normalization
Browser metadata. This is component metadata, not a provider, model, browser-permission grant, or proof that WebAssembly, OPFS, a secure context, or WebGPU is available.
Example
import {BROWSER_WASM_RUNTIME_AUTHORITY} from 'arcane-os/ai/browser-wasm';
console.log(BROWSER_WASM_RUNTIME_AUTHORITY.protocol);
console.log(BROWSER_WASM_RUNTIME_AUTHORITY.package.version);
Complete lifecycle, model authority, cache, cancellation, and tool behavior: Browser-WASM local AI.
completeValueText()
Overview
Returns complete caller content as text. Strings are returned unchanged; supported non-string values become readable JSON text without clipping, with explicit representations for cycles, special primitives, maps, sets, dates, regular expressions, typed views, buffers, functions, symbols, and accessors.
Signature and result
completeValueText(value)
Import it from arcane-os/ai/browser-wasm. The function reads no provider,
model, cache, or browser capability.
Availability and normalization
Browser or compatible JavaScript module host. Complete strings remain exact; other supported values normalize to complete readable JSON text.
Example
import {completeValueText} from 'arcane-os/ai/browser-wasm';
console.log(completeValueText({content:'Complete response'}));
createArcaneAI()
Overview
Creates the application-facing AI API module around a compatible provider or
controller. The default on-demand policy loads before first use; manual
requires an explicit successful load() before requests. When both llm and
provider are supplied, llm takes precedence.
Signature and result
createArcaneAI({ llm=null, provider=null, loadPolicy='on-demand', security }={})
At least one llm or provider is required. The mutable API object contains
llm, runtime, createChatSession, status, load, unload, probe,
fetchRequest, streamRequest, and dispose. status() returns
{llm: status}; lifecycle methods return the flat LLM status.
fetchRequest() returns the completion. streamRequest() consumes streaming,
delivers every choice's ordinary content/reasoning values in provider order,
and returns ordinary terminal text for one choice, a structural-call array for
selected tool output, or complete JSON text for a multi-choice completion.
onDataChunk receives provider chunks with private structural fields removed;
onDataResult preserves the complete terminal record independently of that
application-facing projection. Supply toolText:{name,field} with
onToolText(text,call,displayId) to receive one selected root string argument
as it arrives. call contains {id,name,field,index,choiceIndex} with the real
normalized call ID, call position, and response-choice index. The SDK decodes
JSON string escapes, preserves whitespace and order, and starts delivery once
the matching tool name and call ID are known. displayId is the same request
display ID as onChunk. This separate callback does not add ordinary prose,
execute tools, or persist history. Complete-only providers emit the selected
text only on actual completion; repeated terminal snapshots do not replay
emitted text. Callback failures reach the request owner and cancellation
prevents later delivery. Omitting toolText preserves the existing behavior.
See the tool-text example. Use
ai.llm.stream() for the async iterator; structural fragments remain private
until the complete terminal result validates.
When llm is an existing ModelController, it retains the load policy chosen
when that controller was created. createArcaneAI() does not reapply its
loadPolicy argument in that case. Provider input creates a new controller and
applies the supplied loadPolicy.
createChatSession(options) asynchronously imports the private managed
#arcane/persistent-ai-chat-session specifier, resolves a
Promise<PersistentAIChatSession>, and binds its AI API to this exact
controller. Applications continue to use this public controller method rather
than importing that private specifier. options must be a plain object and cannot contain
ai or chat. The resulting session preserves coherent complete live context while
letting each user/assistant/tool turn choose matching durable ChatEntity/DBOPFS
persistence. A persist:false turn participates in one request and response,
then retains neither side in subsequent model context, the transcript, durable
history, memory, or DBOPFS. There is no storage or provider fallback.
The session's stream() uses this controller's streaming transport when
available and otherwise completes the same atomic turn through its configured
non-stream request; lack of optional streaming is not a protocol error.
Per-turn request options merge over the session defaults while messages and
the caller signal remain session-owned. A visibility-only consumer can submit
one atomic result batch for every pending tool-call ID with
request:{toolChoice:'none'} so the continuation cannot open another tool loop,
without calling Wllama directly. A terminal-only structural call is valid. Each
call observed during streaming is published only after its choice, ordered
position, exact ID, type, name, argument string, and extension fields match the
terminal response; omission or divergence rejects with
AI_CHAT_STREAM_TOOL_CALL_MISMATCH before persistence or commit.
Availability and normalization
Browser. It normalizes lifecycle, statechange and progress observation,
lazy/manual use, cancellation, completions, and structural tool-call
visibility. It neither selects a provider fallback nor executes an application
tool. Persistent sessions additionally require ChatEntity/DBOPFS in the
managed browser runtime.
ai.llm.addEventListener(type,listener,options) and
removeEventListener(type,listener,options) are EventTarget compatibility
views over globalThis.arcaneEvents; null/non-listener callbacks and event names
other than statechange or progress are compatibility no-ops.
ai.llm.on(type,listener) installs through that same view and returns
one idempotent removal closure whose .dispose property is that same closure.
The controller exposes no public dispatchEvent() and
therefore does not let consumers forge lifecycle occurrences. Compatibility
listeners receive the mutable full status snapshot as event.detail with the controller
as this, target, and currentTarget. Canonical statechange and progress
occurrences use source ai-model-controller; every load or unload owns one
non-null operation ID shared by its state and progress occurrences. Public
progress retains the exact selected modelId, phase, state, and nested
file-progress field names. Browser-WASM download progress preserves
completed, total, and unit:'files', with complete per-file members
reporting stored shards. A member's total remains null until its complete
response is stored, unless the HTTP range plan already establishes its shard
total. activeTransfers, transferLimit, and transferMode describe the
active download work. Closed shards, active-worker changes, and completion
boundaries publish semantic progress; the existing heartbeat repeats the latest
record. These fields describe files and shards, without byte-based display
requirements or estimated transfer rates.
Accessor-bearing provider status
and malformed progress reject with ARCANE_AI_PROVIDER_STATUS_INVALID and
ARCANE_AI_PROVIDER_PROGRESS_INVALID. After disposal, lifecycle operations fail with
ARCANE_AI_DISPOSED.
Example
const ai = createArcaneAI({provider, loadPolicy:'manual'});
async function openLocalReviewAfterUserChoice() {
const stop = ai.llm.on('progress', event => renderProgress(event.detail));
try {
await ai.load({offline:true});
} finally {
stop();
}
return ai.createChatSession({
chatFileName:'local-review.jsonl',
loadExisting:true
});
}
createToolTextObserver()
Overview
Creates the shared tool-text observer used by SDK provider integrations before
private structural fields are removed. Application callers normally use
streamRequest({toolText,onToolText}) instead.
Signature and result
createToolTextObserver(selection, onText, {signal}={})
selection is {name,field}: the exact tool name and one root string argument.
undefined, null, or false selection returns null. An active selection
requires nonblank string name and field values and an onText function;
invalid configuration throws TypeError.
The result is an async observeToolText(chunk) function. It accepts raw
OpenAI-compatible choices[].delta.tool_calls fragments and complete
choices[].message.tool_calls or message.tool_calls snapshots. onText is
awaited with each newly decoded fragment and
{id,name,field,index,choiceIndex}. It preserves decoded string content and
whitespace, waits for the matching name and real normalized ID, and reports
malformed selected argument text with ARCANE_AI_TOOL_TEXT_INVALID.
Availability and normalization
Compatible JavaScript module host. One observer owns one request's call
state. Consume each raw delta once, before any structural filtering; pass the
same observer through the provider integration instead of creating another
parser. Complete snapshots may be observed again without replaying emitted
text. A complete-only response emits only when received. signal stops later
observation after cancellation; callback errors propagate to the caller. The
observer does not modify the supplied chunk, invoke tools, persist history, or
start inference.
Example
import {createToolTextObserver} from 'arcane-os/ai/tool-text-stream';
function createProviderTextObserver(onText, signal) {
return createToolTextObserver(
{name:'prepare_conversation_closing_report', field:'final_message'},
onText,
{signal}
);
}
The provider owner passes actual raw chunks to the returned observer and awaits it before continuing its existing filtered stream delivery.
createBrowserModelSource()
Overview
Validates a caller-owned ordered model-file descriptor and creates the
cancellable HTTPS source accepted by the browser-WASM store/provider. The
canonical descriptor is {id,files:[{name?,url,bytes?},...]}. The nonempty file
array has unique normalized names and URLs. A positive safe-integer bytes
value supplies observational progress and HTTP Range planning only; missing or
unusable metadata is treated as unavailable and never blocks the download. It
is never a content-validation, admission, identity, or cache-reuse rule.
Signature and result
createBrowserModelSource(descriptor, { fetchImpl=null }={})
Every URL must be absolute HTTPS with no credentials or fragment. Use a
caller-selected version-pinned URL when reproducibility matters. The mutable
source exposes kind, the canonical descriptor fields, descriptor, and
open(memberIndex=0,{signal}); an omitted index selects the first member. The result is
{body,requestedUrl,finalUrl,contentLength,cancel}; contentLength is the
positive observed HTTP response length or null. Every direct open()
performs the configured fetch and preserves the complete response body subject
only to unavoidable HTTP framing.
Availability and normalization
Browser Fetch with CORS and a readable response body. Downloads omit
credentials/referrer, disable HTTP caching, follow redirects, require a final
HTTPS URL, and honor AbortSignal. Declared and observed byte measures feed
only progress and transfer planning. The DBOPFS store does not use them to
limit, hash, digest, identify, admit, validate, or decide cache reuse for model
content.
Example
const source = createBrowserModelSource({
id:'reviewed-model',
files:[{
name:'model-q4-00001-of-00002.gguf',
url:'https://models.example/releases/4f7c/model-q4-00001-of-00002.gguf'
},{
name:'model-q4-00002-of-00002.gguf',
url:'https://models.example/releases/4f7c/model-q4-00002-of-00002.gguf'
}]
});
getBrowserDeviceClass()
Overview
Returns mobile or desktop to select application-owned settings. Phones and
tablets use mobile when browser client hints, platform, user-agent information,
or the iPadOS Mac-platform/touch combination identifies them. Missing or
unrecognized identity uses desktop.
Signature and result
getBrowserDeviceClass(navigatorObject = globalThis.navigator)
The optional navigator-like object supplies userAgentData, userAgent,
platform, and maxTouchPoints. The synchronous string result reports a
settings class, not hardware capability or readiness.
Availability and normalization
Import from arcane-os/browser-device in Node or a browser. The dependency-free
entrypoint reads only the supplied or global browser identity and does not load
an AI runtime. No model, GPU, storage, network, or listener operation runs.
Missing or unrecognized identity returns desktop; browser identity masking
can affect classification. Existing provider defaults remain unchanged unless
the caller selects and supplies its own profile.
Example
import {getBrowserDeviceClass} from 'arcane-os/browser-device';
const deviceClass = getBrowserDeviceClass();
console.log(deviceClass); // mobile or desktop
PWASTATEEVENT
Overview
The event name arcane.pwa.state identifies PWA registration, native worker
lifecycle and page-local update availability published through the existing Arcane event owner.
Example
import {PWA_STATE_EVENT} from 'arcane-os/pwa';
console.log(PWA_STATE_EVENT);
See the PWA state contract for complete payload fields and current-state subscriptions. Importing the constant does not register a worker.
registerPwa()
Overview
registerPwa({workerUrl = './arcane-sw.js', scope} = {}) starts native browser
registration and returns a synchronous owner with ready, state, subscribe,
update and dispose. It does not block page rendering or load models.
Unsupported environments receive an explicit unsupported state.
The generated page bootstrap also starts the SDK's background resource check.
It stores one lastChecked timestamp per app/cache in DBOPFS, advancing it only
after the full resource check succeeds, and revalidates on page load after
120 seconds in development or 15 minutes in packaged delivery. Complete
responses remain cached without SDK expiration; 304 retains the response
and a successful replacement updates it. A complete successful refresh latches
state.updateAvailable when parseable old/new Last-Modified dates differ or
a successfully checked resource was absent from the prior durable inventory.
Initial population, eviction repair, 304, and unknown/equal modification
dates do not announce updates. Partial-change evidence survives worker restart
until complete success; existing scoped window clients receive the completed
signal. The state replays to subscribers and remains true for this page owner.
The registration owner's update() only requests a native worker update check;
it does not reload the page. See the PWA guide.
Example
import {registerPwa} from 'arcane-os/pwa';
const pwa = registerPwa();
pwa.ready.catch(function reportRegistrationError(error) {
console.error(error);
});
The PWA guide defines inputs, native registration results, error state,
current-state replay, disposal, offline resource ownership and update behavior.
The generated bootstrap registers automatically; a manual caller owns a separate
entry point and must observe its ready rejection.
PWAINSTALLSTATE_EVENT
Overview
The exact event name arcane.pwa.install.state identifies native installation
availability, choice and shared update-prompt state through the existing Arcane event owner. It is
separate from service-worker registration state. Importing it starts no
observation or installation.
Example
import {PWA_INSTALL_STATE_EVENT} from 'arcane-os/pwa';
console.log(PWA_INSTALL_STATE_EVENT);
See the installation state contract for the complete payload and current-state subscription behavior.
getPwaInstall()
Overview
getPwaInstall() returns one synchronous page owner exposing state, ready,
subscribe, prompt, dismiss, update, dismissUpdate and dispose. It captures the browser's
beforeinstallprompt event and observes appinstalled and app display-mode
changes. A missing event leaves installation availability unknown and the owner
waiting; it does not prove browser incompatibility.
State contains status, available, installed, dismissed, updateAvailable,
updateDismissed, outcome,
error and storageError. The owner restores pwa/installed.json through the
app-scoped DBOPFS singleton and saves {installed: true} after appinstalled
or an installed-app launch. Remembered installation suppresses both floating
and inline installation controls on later visits. Acceptance alone and ordinary fullscreen
do not record installation.
ready resolves to the state once the initial read settles. Native events are
captured immediately, while install availability waits for that read. Rendering
and worker registration remain independent. Storage failures are logged and
published in storageError; they do not reject ready or reverse an observed
installation. Confirmed-install writes remain owned after disposal.
Subscriptions replay current state by default. prompt() must be called
directly within the install click to preserve native user activation. It
consumes the event once and returns the browser choice, resolves to null when
unavailable, or rejects with the actual error. dismiss() remembers the
session's floating-suggestion dismissal without consuming a retained event.
The generated bootstrap starts this owner before worker registration, so it
observes the current page scope's arcane.pwa.state update signal while the
component loads. A late-created prompt also reads current state from live
registration owners. updateAvailable remains true for the page owner;
updateDismissed is a separate page-local choice. An explicit update() calls
ordinary location.reload() synchronously and returns true, or false when
unavailable/disposed; native errors propagate. It preserves native unload
handling and application draft ownership without promising transient-state
survival. dismissUpdate() returns the current state and writes no durable
record. Installed/running state or installation dismissal does not suppress
the update suggestion. A fresh page does not replay an old completed update.
Example
import {getPwaInstall} from 'arcane-os/pwa';
const install = getPwaInstall();
const button = document.querySelector('#install');
install.subscribe(function updateInstallButton(state) {
button.hidden = !state.available;
});
button.addEventListener('click', function requestInstallation() {
install.prompt().catch(function reportInstallFailure(error) {
console.error(error);
});
});
The PWA guide defines every status, event lifetime, session dismissal, errors and disposal. Disposing this shared owner removes its page-level observation; components normally unsubscribe only their own listener. Installation state does not establish offline readiness or completed Android WebAPK creation.
mountPwaInstallPrompt()
Overview
mountPwaInstallPrompt({appName = ''} = {}) starts the shared install observer
before asynchronously mounting one initially hidden pwa-install.html
component. Repeated calls return the same mounting promise. It resolves to the
ready html-import host, or null without a document or when the owner is
disposed before mounting. Component-load failure rejects; removal or disposal
during loading rejects with AbortError. A rejected mount permits another
explicit attempt. The first call
supplies the initial app name.
The generated PWA bootstrap calls this automatically with the manifest name. Component mounting and worker registration run independently, and application rendering must not await them. The floating component offers Install and a manual close control, or Update available with an explicit Update action after a completed changed refresh. Update dismissal is separate from installation dismissal. An application can also place the same component inline.
Example
import {mountPwaInstallPrompt} from 'arcane-os/pwa';
mountPwaInstallPrompt({appName: 'Example Library'}).catch(
function reportInstallComponentFailure(error) {
console.error(error);
}
);
See the mounting contract and component reference. The browser owns native installation eligibility and URL-bar promotion.
createNativeDecisionModel()
Overview
Runs explicitly selected Laya FP32/FP16 or Julia FP32 option scoring through an existing native ONNX owner, with tokenization in a Node Worker. It creates no second inference engine and starts no model download at construction.
Signature and result
createNativeDecisionModel({onnx,modelAssets,workingDirectory,paths,assetProjectionId,resourcePaths,family='laya',model='onnx-community/laya-typed-decisions-ONNX',revision='main',dtype='fp32',sessionOptions,executionPreference='gpu',executionTarget,signal}={})
Import from arcane-os/local-ai/decisions. Supply the existing onnx owner and
either modelAssets plus workingDirectory, or native paths for the model,
tokenizer and tokenizer configuration, or a ready assetProjectionId with
resourcePaths for those three roles. Supported selections are Laya fp32,
Laya fp16 and Julia fp32; constructor defaults remain Laya FP32. The
handle exposes load, evaluate, classify, current, status, subscribe,
unload and terminal dispose; classify aliases evaluate and status
aliases current.
load({family,model,revision,dtype,assetProjectionId,resourcePaths,executionTarget,signal})
selects each activation. Omitted or undefined fields retain their prior
selection. A changed model field, source, mapping or device replaces the
activation after actual cleanup; equal complete selections coalesce. Supply
all matching model fields and files when changing family: metadata does not
infer a repository or rewrite a supplied projection. Top-level model metadata
continues to describe the retiring activation while pendingActivation records
its successor. See model selection
for exact upstream graph/companion layouts and retained projection ownership.
evaluate(rows,{signal,runOptions}) preserves each complete state, question,
options and optional type separately. It returns {decisions,outputs} with
original rows, typed values, raw logits, unrounded probabilities and every
named tensor output. It requires a loading or loaded activation. Cancellation
retires the shared activation and joins its actual ONNX/tokenizer lifetime;
working files remain retained until both Workers exit. Ordinary invalid rows
leave a healthy session and sibling evaluations intact.
Availability and normalization
Node on Windows, Linux and macOS with the selected ONNX Runtime; Android needs host adaptation. GPU preference attempts actual advertised providers before CPU fallback; accepted configuration does not prove GPU node execution. Model selection, unchanged payloads, scoring interpretation and persistence remain application-owned. Complete lifecycle, errors and paths are documented in native typed decisions.
Example
import {createNativeDecisionModel} from 'arcane-os/local-ai/decisions';
function createMoonChefDecisions({onnx, paths}) {
return createNativeDecisionModel({onnx, paths});
}
The caller explicitly loads the returned model before evaluation and unloads or disposes it at its owning boundary; defining this function downloads nothing.
createNativeDecisionService()
Overview
Composes the same native decision model into an existing Core runtime without a renderer. The factory starts no inference, tokenizer or model preparation.
Signature and result
createNativeDecisionService(configuration={}, {appRoot=process.cwd()}={})
Import from arcane-os/core/decisions. Configuration selects the model options
above and an optional service name (default decisions); relative supplied
paths resolve from appRoot. Explicit load obtains the registered local-AI
and, when needed, model-assets owners through context.getService, then
reacquires getONNXRuntime() after any recovery. Native members are load,
evaluate, classify, current, subscribe, unload, dispose and Core
start(context).
RPC exposes decisions.status, decisions.load, decisions.evaluate and
decisions.unload. Load accepts optional family, model, revision, dtype,
assetProjectionId, resourcePaths and executionTarget, with the same
per-activation selection and omission behavior as direct native load; the Core
request signal owns cancellation. The service persists across model changes.
Evaluation accepts {rows,runOptions?} and returns complete
{decisions,outputs} using the existing tensor codec at the JSON boundary.
decisions.state and replaying subscribe(listener,{emitCurrent:true,signal})
report lifecycle. Unload is accepted service-lifetime cleanup; host shutdown
still cancels request-lifetime load/evaluation.
Availability and normalization
Node Core with an existing local-AI ONNX service and selected model files. Registration does not wait for all services or open another host. Original inputs, complete outputs, failures and cleanup semantics match the native model. See composition and example.
Example
import {createNativeDecisionService} from 'arcane-os/core/decisions';
const decisions = createNativeDecisionService({
model: 'onnx-community/laya-typed-decisions-ONNX',
dtype: 'fp32',
workingDirectory: '.models/laya'
});
// Add decisions to the application's existing Core services; load explicitly.
createNativeDecisionService default export
The default export from arcane-os/core/decisions is exactly the named
createNativeDecisionService factory, with the same arguments and lifecycle.
createBrowserDecisionModel()
Overview
Creates an explicitly loaded browser model for Laya typed decisions or
Julia-1. Laya defaults to FP16 and Julia to FP32; callers may select dtype
explicitly. The shared Worker owns Transformers.js loading, full-input
encoding, batched inference, complete results, cancellation and resource lifetime.
Applications own model selection, questions, option meanings and decision policy.
Existing chat and speech providers are unchanged.
Signature and result
createBrowserDecisionModel({family,model,revision,device,dtype,runtime,store}={})
import {createBrowserDecisionModel} from 'arcane-os/ai/browser-decisions';
const decisions = createBrowserDecisionModel(
{
family: 'laya',
model: 'onnx-community/laya-typed-decisions-ONNX',
device: 'webgpu'
}
);
Construction starts no model download. The returned client exposes
load({signal}), evaluate(rows, {signal}), status(),
subscribe(listener, {emitCurrent: true, signal}), unload() and dispose().
Each row contains its complete state, question, string options, and
optional type (choice, score, or noul). evaluate() returns
{decisions, outputs} with all graph outputs and raw, unrounded probabilities.
See the complete browser decision contract for
precision, tokenization, output meanings, lifecycle and model limitations.
Availability and normalization
Browser module Workers plus the selected Transformers.js backend are required
on explicit use. Import and construction do not activate a model. The optional
nonempty dtype string defaults to fp16 for Laya and fp32 for Julia. An
explicit value is forwarded unchanged to the upstream loader; unsupported
selections report its failure without precision fallback. For Laya FP32, pass
dtype: 'fp32'.
Cancellation terminates that client's Worker and rejects its in-flight work.
No decisions are inserted into chat history or durable storage.
For explicitly selected extension-local execution, supply runtime: {local: true} after packageApp({workspaceRoot, appId, browserDecisions: true}) for
installed-package routes, or after opting into the existing physical runtime
materializer. The SDK directly
imports its deployment-local decisions-runtime/transformers.min.js and
matched asyncify module/WASM. Explicit runtime.moduleUrl and
runtime.wasmPaths: {mjs, wasm} may select other compatible files in that same
deployment; a directory string is also accepted for wasmPaths. This mode
disables executable Blob preparation and upstream WASM cache/proxy creation,
selects one WASM thread, and preserves the caller's model, precision and
inference backend. With store, only the exact selected executable URLs bypass
it; model, tokenizer, configuration and external-data resources retain that
store. Local mode is opt-in; default browser behavior remains unchanged.
Optional store is an existing SDK DBOPFS model or speech store exposing
fetchResource(input, options). It remains outside cloned Worker configuration.
Without runtime.local, explicit activation first stores the complete selected runtime.moduleUrl
entry and materializes it as a JavaScript object URL without rewriting source.
The configured original URL remains the resource selection for later loads.
The selected loader also routes its actual model/configuration/tokenizer
resources through that owner and disables competing model caches in this mode.
Each activation revokes its runtime object URL after terminating its Worker on
cancellation, failure, unload or disposal. Resource progress counts closed
shards; cancellation joins runtime-entry and resource cleanup before outstanding
load()/evaluate() calls settle. Runtime-entry HTTP failures report
ARCANE_DECISION_RUNTIME_DOWNLOAD_FAILED with the complete stored response in
error.response for developer diagnostics.
unload() and dispose() acknowledge their state transition synchronously.
The default runtime entry is self-contained. Custom stored entries must work
from an object URL: entry materialization changes import.meta.url and does not
rewrite relative imports or original-location support-file references. Native
absolute ESM dependencies and custom factory imports outside upstream preloads
remain browser-owned. Omitting store preserves direct native module loading
and ordinary upstream model loading. See shared model resources.
Example
runButton.addEventListener(
'click',
async function askTeaRobot() {
const result = await decisions.evaluate(
[
{
state: 'The dragon is asleep. The tea robot has a very loud kettle.',
question: 'Should the robot boil tea now?',
options: ['Wait quietly', 'Boil the kettle']
}
]
);
output.textContent = result.decisions[0].value;
}
);
createBrowserWasmLlmProvider()
Overview
Creates the packaged Wllama provider from genuine source and store objects
created by this module. Structural lookalikes are rejected. It serializes
requests and exposes provider states unloaded, loading, ready,
unloading, and error.
Signature and result
createBrowserWasmLlmProvider({ sources, store, loadDefaults={}, security, logger=console }={})
sources is a nonempty array of unique SDK-created sources. Its first entry is
the default model. The mutable provider
exposes protocol, id, default model, catalog, capabilities, status,
load, unload, chat, stream, streamChat, use, probe, and dispose.
Direct load() selects a catalog model and returns {model,status}; the
public AI API module's ai.load() returns the flat controller status. Load settings include
offline mode, AbortSignal, progress, threads, and context/batch/micro-batch
tokens. loadDefaults:{gpuLayers:0} or load({gpuLayers:0}) explicitly selects
CPU. Omission requests full GPU offload (gpuLayers:99999); GPU failures never
silently switch to CPU.
Chat supports OpenAI-like message/generation fields, tools, tool choice,
parallel tool-call preference, and JSON/JSON-Schema structured output.
stream() returns a mutable async iterator with result and cancel(reason).
Direct chat and stream ingress validate complete history, require one nonblank
matching tool result for every pending ID, and validate every terminal choice.
Ordinary stream iteration preserves complete content/reasoning projections from
every choice in provider order while withholding structural deltas; the exact
validated terminal calls and every completion choice remain on result.
Every function declaration requires
parameters.properties.message:{type:'string',minLength:1} and includes
message in required. Returned calls preserve exact IDs, names, and
JSON-string arguments containing that nonempty user-facing message. The SDK
never invokes a handler or executes a tool; a matching executed, declined,
cancelled, or not-executed role:'tool' result is required before another user
turn.
Availability and normalization
Browser secure context with WebAssembly and OPFS/DBOPFS. The default GPU route
also requires WebGPU; explicit gpuLayers:0 CPU loading skips GPU requirements
and adapter work. A load succeeds after Wllama confirms the complete model is
loaded and its context was created. There is no automatic CPU fallback.
Cross-origin isolation and coarse hardware fields remain observations rather
than hard gates. Ordinary status reports complete catalog compatibility and
lifecycle state. capabilities() reports executionDevice:'cpu'|'webgpu' and
webgpuRequired for the active load plan. GPU adapter selection is instrumented as
arcane.ai.browser-wasm.webgpu.adapter.selected.
Cancellation normalizes to ARCANE_AI_REQUEST_ABORTED; load or availability failures
surface stable ARCANE_AI_* codes such as ARCANE_AI_WEBGPU_REQUIRED,
ARCANE_AI_MODEL_FULL_OFFLOAD_UNPROVEN, and
ARCANE_AI_MODEL_GPU_MEMORY_INSUFFICIENT on the GPU route, or
ARCANE_AI_MODEL_CPU_MEMORY_INSUFFICIENT on the CPU route. Concurrent runtime inference can fail
ARCANE_AI_RUNTIME_BUSY; inspection and status can report
ARCANE_AI_PROVIDER_UNAVAILABLE or fallback ARCANE_AI_RUNTIME_FAILED without
misrepresenting those observations as a successful load.
Example
const provider = createBrowserWasmLlmProvider({
sources:[source],
store,
loadDefaults:{threads:1, contextTokens:4096}
});
console.log(provider.status().state); // unloaded
createDbopfsModelStore()
Overview
Adapts an existing DBOPFS instance into a complete multi-model, ordered multi-file cache without renaming its public methods. Every new full response or Range transfer is committed in ordered parts. An interrupted set is not a cache hit, but its completed members remain available to the next install so only missing work is fetched.
Signature and result
createDbopfsModelStore({ dbopfs, tableName='arcane_ai_browser_models', estimateStorage=null, downloadConcurrency=4 }={})
downloadConcurrency must be a positive safe integer and defaults to four.
It bounds exactly one transfer axis: ordered multi-file GGUF sources use that
many concurrent member workers, with at most one Range worker inside each
member, while a single-member source can use the whole bound for HTTP Range
workers
when the probe returns a usable total from exposed Content-Range or optional
descriptor bytes. The mutable
result contains kind, tableName, downloadConcurrency, the original
adapter, and ready, install, ensure, remove, and fetchResource. ensure() returns
files and cache:'cached'|'installed'. It preserves the complete model content.
offline:true never downloads and rejects a miss with
ARCANE_AI_MODEL_OFFLINE_MISS.
When supplied, onProgress receives ordered file progress and members
records with each file's name, committed completed parts, total, and
unit:'shards'. Streaming totals remain null until the response finishes;
previously complete files identify state:'cached'. activeTransfers is the
current transfer-worker count, transferLimit is selected concurrency, and
transferMode is probing, files, ranges, or single. Closed-part and
lifecycle changes publish promptly, with an existing 250 ms heartbeat. No
byte progress, transfer rate, or estimated completion time is produced.
fetchResource(input,{signal,onProgress,...requestOptions}) returns
{file,status,statusText,headers,url,redirected} for a complete stored Fetch
response. SDK browser model loaders use this shared owner for configuration,
tokenizer, graph, external-data, and other fetched resources. Successful
complete GET resources may be reused; supported HTTP ranges resume closed
parts after interruption. Request framing stays at the transport boundary.
Availability and normalization
Browser with a ready DBOPFS instance and OPFS. Cache metadata is not a
transferable capability or license proof. Provider unload/dispose keeps all
cached files; store.remove(source) explicitly deletes that source's files and
resumable Range parts. For any source member, a followed redirect that
turns the first bytes=0-0 probe into 200 triggers one direct probe of the
final URL. Confirmed support cancels the original body and starts the Range
pool; refusal keeps the original response as the ordinary single-fetch path,
without requiring a readable Content-Length. A missing Content-Range can
use optional descriptor bytes for Range planning; without either total, the
store uses one full fetch streamed into ordered persistent parts. A confirmed source member is divided into
deterministic OPFS Range parts of roughly 4 MB each, up to 4,096 parts. A
monolithic source may use at most
downloadConcurrency Range workers; split sources keep one Range worker per
active member. Exact completed parts resume after interruption and are exposed
in order as one logical Blob. A later non-206, contradictory exposed Range
response, or incorrectly framed body fails rather than assembling partial
content. On failure or cancellation, peers settle while completed shards and
Range parts remain available for retry; an unfinished active part restarts after
refresh. Existing whole-file caches remain readable without migration. A persisted Range part whose length does not match its requested HTTP
frame is discarded and fetched again. A complete whole member supersedes its
redundant current Range fragments. Cleanup failure is warned without
hiding the usable model. Wllama requires every selected model Blob or File to
be non-empty.
Example
const store = createDbopfsModelStore({dbopfs});
async function openCachedModel() {
await store.ready();
const cached = await store.ensure(source,{offline:true});
console.log(cached ? 'cached' : 'cache miss');
}
adaptV1LlmProvider()
Overview
Projects one compatible v1 browser-WASM provider into the provider-neutral
LLM role consumed by arcane-os/ai-provider-runtime. The
runtime checks protocol arcane-ai-adapter/1, required identity/methods, and local-only
capability; it does not establish ownership for an arbitrary compatible
object. The adapter does not
change the wrapped provider, download a model, create a fallback, or execute a
tool.
Signature and result
adaptV1LlmProvider(provider)
The mutable result is
{protocol:'arcane-ai-provider/2',role:'llm',id,localOnly:true,catalog,inspect, status,load,request,unload,dispose}. inspect() returns an
arcane-ai-model-authority/1 record only for an exact catalog selection.
request() accepts only the chat and stream operations, preserves
structural tool calls, and never invokes application handlers. Both operations
validate declaration/history ingress and terminal structural messages. The
stream wrapper privately drains the provider whether the consumer iterates or
awaits result first, buffers complete content/reasoning projections from every
choice in FIFO order, and validates its complete terminal result. Terminal-only
tool calls are valid; observed calls must preserve the same choice, order,
identity, argument string, and extension fields at terminal settlement. An
early consumer return starts observed provider cancellation immediately without
making iterator return wait for provider cleanup. The terminal result retains
provider settlement; any later cancellation or iterator-return failure is
reported completely to the developer console.
Re-adapting the same provider returns the same adapter object.
Availability and normalization
Browser; the wrapped provider retains its own secure-context, WebAssembly, OPFS/DBOPFS, selected CPU or WebGPU route, model, and lifecycle requirements. The adapter normalizes provider/2 selection and lifecycle without adding Node, native, cloud, network, or CPU fallback behavior.
Example
import {adaptV1LlmProvider} from 'arcane-os/ai/browser-wasm';
import {getAIProviderRuntime} from 'arcane-os/ai-provider-runtime';
const runtime = getAIProviderRuntime();
const releaseProvider = runtime.register(adaptV1LlmProvider(provider));
// Configure an exact llm route before load/use.
releaseProvider();
Browser speech providers
arcane-os/ai/browser-speech exports the package members below.
It ships provider, authority, artifact-store, and Worker mechanisms but no
Whisper/Kokoro model weights, adapter runtime artifacts, voices, download URLs,
default catalog, CDN loader, native bridge, or cloud fallback. The providers
implement arcane-ai-provider/2; the managed arcane/AIProviderRuntime and
arcane/AIRuntimeState projection modules can normalize their independent
role lifecycle and observation, but are not exports of this package subpath.
BROWSERSPEECHARTIFACTGRAPHPROTOCOL
Overview
Stable protocol identifier for an SDK-created browser speech materialization
graph. The current authenticated discriminator identifies one complete
caller-owned runtime, model, and voice routing record but grants no provider,
model, runtime, voice, network, or license authority.
Value and import
const BROWSER_SPEECH_ARTIFACT_GRAPH_PROTOCOL
Its exact value is arcane-ai-browser-speech-artifact-graph/1, and it is
exported only by arcane-os/ai/browser-speech.
Availability and normalization
Browser metadata; the ESM binding is importable in Node. Reading the constant starts no fetch, cache, Worker, provider, or event operation. Actual artifact preparation and provider use require the selected browser storage and Worker capabilities.
Example
import {
BROWSER_SPEECH_ARTIFACT_GRAPH_PROTOCOL
} from 'arcane-os/ai/browser-speech';
console.log(BROWSER_SPEECH_ARTIFACT_GRAPH_PROTOCOL);
BROWSERSPEECHARTIFACT_PROTOCOL
Overview
Stable protocol identifier for the optional SDK-created browser speech artifact store. It identifies the store contract, not a model authority or capability grant.
Value and import
const BROWSER_SPEECH_ARTIFACT_PROTOCOL
Its exact value is arcane-ai-browser-speech-artifacts/1, and it is exported
only by arcane-os/ai/browser-speech.
Availability and normalization
Browser metadata. Importing or reading the constant starts no Worker and downloads no model or runtime artifact. Store use additionally requires DBOPFS/OPFS, Web Locks, and the browser APIs described below.
Example
import {
BROWSER_SPEECH_ARTIFACT_PROTOCOL
} from 'arcane-os/ai/browser-speech';
console.log(BROWSER_SPEECH_ARTIFACT_PROTOCOL);
createBrowserSpeechArtifactGraph()
Overview
Normalizes one complete caller-owned browser speech materialization graph. The caller declares runtime, model, and voice sources together with their paths, media types, routing aliases, and model/runtime identity, sample rate, and TTS default voice where applicable. The SDK selects none of those values.
Signature and result
createBrowserSpeechArtifactGraph({ kind='browser-speech-authenticated-artifact-graph', security, providerId=null, role, model, runtime, files }={})
role is exactly stt or tts; its model and runtime adapter fields must match
that role. Files are normalized into one functional path/source inventory, the
runtime entry and selected ONNX MJS/WASM pair must exist, and TTS voice records
must identify their selected files. Legal metadata is optional and inert; it is
never required or interpreted for runtime materialization.
The result is one mutable arcane-ai-browser-speech-artifact-graph/1 record
containing {protocol,kind,providerId,role,model,runtime,files,security?}. The
current kind and runtime.moduleGraph value is
browser-speech-authenticated-artifact-graph.
Availability and normalization
Browser metadata; the ESM subpath is importable in Node. Construction is synchronous and starts no fetch, cache, Worker, provider, or event operation. The store and provider accept SDK-created graph records so they can retain the associated materialization metadata. Preparing and executing a graph requires the selected DBOPFS, Web Locks, Fetch, object URL, and Worker capabilities.
Example
import {
createBrowserSpeechArtifactGraph
} from 'arcane-os/ai/browser-speech';
const graph = createBrowserSpeechArtifactGraph(callerOwnedGraphDescriptor);
console.log(graph.protocol, graph.kind);
createBrowserSpeechAuthority()
Overview
Validates and returns one mutable caller-owned Whisper STT or Kokoro TTS model/runtime selection. The application owns every model, runtime, revision, URL, voice, and business-policy choice; the SDK supplies no artifact selection.
Signature and result
createBrowserSpeechAuthority({ providerId, role, model, runtime, security }={})
role is exactly stt or tts. model supplies
{id,repository,revision,files} and, for TTS, defaultVoice. runtime
supplies {adapter,version,revision,entry,wasmPaths?,files}; the adapter is
exactly transformers-whisper for STT or kokoro-js for TTS. File records use
unique relative path, a caller-selected url, and optional mediaType.
The runtime entry names one JavaScript module in the selected runtime.
The result is a mutable arcane-ai-model-authority/1 record containing the
provider/model/role identity, normalized runtime and model file declarations,
and optional default voice. Construction validates the descriptor structure.
Availability and normalization
Browser descriptor construction; actual use requires the selected provider Web APIs. Credential-bearing URLs, duplicate identities, mismatched adapters, and malformed runtime descriptors reject.
Example
import {createBrowserSpeechAuthority} from 'arcane-os/ai/browser-speech';
const authority = createBrowserSpeechAuthority({
providerId:'review-whisper',
role:'stt',
model:{
id:'review-whisper-model',
repository:'caller-models',
revision:'model-r1',
files:[{
path:'model.onnx',
url:'https://models.example/model-r1/model.onnx'
}]
},
runtime:{
adapter:'transformers-whisper',
version:'1.0.0',
revision:'runtime-r1',
entry:'adapter.mjs',
files:[{
path:'adapter.mjs',
url:'https://runtime.example/runtime-r1/adapter.mjs',
mediaType:'text/javascript'
}]
}
});
removeBrowserSpeechModelCache()
removeBrowserSpeechModelCache({ repository, cacheStorage=globalThis.caches, signal }={})
Removes cached Hugging Face resources for the exact selected repository, across
all revisions, from the current origin's existing transformers-cache.
Returns {repository,removed}, including each complete URL actually deleted.
An absent model or cache returns an empty list. The caller must stop using the
retired model first; this operation does not unload providers or start inference.
Other models, runtime resources, voice caches, declared DBOPFS artifacts, and
preferences are preserved. Use store.remove(authority) separately for declared
DBOPFS artifacts. Missing storage and cache failures surface
ARCANE_AI_STORAGE_UNAVAILABLE and ARCANE_AI_STORAGE_DELETE_FAILED.
Cancellation stops subsequent deletions with AbortError; error.removed
retains the complete list of deletions already completed.
createDbopfsSpeechArtifactStore()
Overview
Adapts an existing DBOPFS instance into a complete caller-selected speech runtime/model store. It serializes each selected model with an exclusive Web Lock, preserves complete peer files and closed parts after failure, stores ordinary mutable selection metadata before content, and treats a changed file inventory or source mapping as a cache miss that is downloaded again.
Signature and result
createDbopfsSpeechArtifactStore({ dbopfs, tableName='arcane_ai_browser_speech', fetchImpl=null, objectUrlFactory=null }={})
The mutable result is {protocol,tableName,prepare,remove,fetchResource}.
prepare(authority,{signal,onProgress,offline=false,security}) uses a complete
compatible cache or downloads every declared file, preserves complete content
and materializes object URLs, then returns
{cache,runtime,model,release}. Call release() when the Worker no longer
needs those URLs. offline:true never fetches and rejects a miss with
ARCANE_AI_ARTIFACT_OFFLINE_MISS. remove(authority) deletes that exact
authority's files and selection metadata. Optional onProgress receives
preparation and download records with phase, stage, message, and the
current file when available. File operations report actual completed and
total inventory counts with unit:'files', and resource carries the current
closed-part progress with unit:'shards'; module preparation uses
total:null. Cancellation stops progress along with the owning operation.
New files stream into ordered DBOPFS parts with no required response length.
Existing complete whole files stay readable without migration.
fetchResource(input,{signal,onProgress,...requestOptions}) returns
{file,status,statusText,headers,url,redirected} and gives the dedicated
speech Worker the same complete resource storage owner for runtime fetches.
Native ESM imports and unmapped classic Worker internals retain their platform
loader; they are not claimed as intercepted HTTP fetches.
Availability and normalization
Browser with a ready DBOPFS instance, OPFS, Web Locks, Fetch or an injected
fetch function, File/Blob, and object URLs. An unavailable authority lock
fails as ARCANE_AI_STORAGE_BUSY; download, malformed cache, graph, and storage
failures remain observable ARCANE_AI_* errors.
Example
import {
createDbopfsSpeechArtifactStore
} from 'arcane-os/ai/browser-speech';
const speechStore = createDbopfsSpeechArtifactStore({dbopfs});
async function inspectCachedSpeechAfterUserChoice() {
// Offline mode uses the complete previously selected cache.
const prepared = await speechStore.prepare(authority, {offline:true});
try {
console.log(prepared.cache, prepared.runtime.entry);
} finally {
prepared.release();
}
}
createBrowserWhisperProvider()
Overview
Creates a local-only Whisper speech-to-text provider for the provider-neutral AI runtime. It owns one independent STT load/use/unload/dispose lifecycle and never selects a cloud, native, or LLM fallback.
Signature and result
createBrowserWhisperProvider(options={})
The recognized options are
{id='arcane-browser-whisper',localOnly=true,graph,model,runtime,appSecurity, security,store,offline=false,execution={device:'auto',maxConcurrentRequests:1}}.
execution.device is auto, webnn-npu, webgpu, or wasm; its capacity is
exactly 1. graph is mutually exclusive with model and runtime. The mutable
result is
{protocol:'arcane-ai-provider/2',role:'stt',id,localOnly:true, maxConcurrentRequests:1,catalog,inspect,status,load,request,unload,dispose}.
The only request operation is
transcribe; its payload is {audio:Float32Array,sampleRate:16000}. The
Worker-transferred result is a structured {text} record; the client does not
re-freeze the cloned record.
status() returns
{role,providerId,modelId,state,lifecycleStatus,lifecycleReason,activeOperation, loaded,busy,generation,errorCode,cache,warnings,execution} and includes
security only for an explicit secure intent.
execution reports requestedDevice, selectedDevice,
maxConcurrentRequests, and activeRequestCount; selectedDevice is null
before load and after unload. The high-level projection is
ai.providerRuntime.status('stt', {execution:true}).execution.
Automatic loading tries webnn-npu when navigator.ml.createContext is
exposed, then webgpu when navigator.gpu is exposed, then CPU through wasm.
A failed candidate is cleaned up before a fresh Worker tries the next backend
with the same prepared model and dtype. Explicit selections do not fall back.
selectedDevice names the backend requested by the successful upstream session
load; it does not prove that every operation ran on a physical accelerator.
WebNN may execute unsupported operations through WASM, and exact model,
browser, driver, and hardware compatibility remains upstream.
States are unloaded, loading, ready, unloading, error, and
disposed. Compatible concurrent loads coalesce; concurrent requests fail as
ARCANE_AI_PROVIDER_BUSY. Cancellation after the Worker request begins
terminates that Worker slot, returns the provider to unloaded, and rejects as
ARCANE_AI_REQUEST_ABORTED. Cancellation while shared Blob/File audio is still
being decoded occurs before Worker use; it rejects with the same code while the
loaded Worker remains intact and the provider stays ready.
The provider also accepts the shared AI speech payload
{audio:Blob|File,mimeType,model}. It requires an exact model match, validates
the MIME essence against Blob.type, decodes through browser audio APIs, and
copies authoritative 16 kHz mono Float32Array PCM into the same native
provider operation. Missing decode support fails
ARCANE_AI_AUDIO_DECODE_UNAVAILABLE; invalid or failed decoding fails
ARCANE_AI_INVALID_REQUEST or ARCANE_AI_AUDIO_DECODE_FAILED. Unknown fields
and accessors are rejected before Worker use.
Availability and normalization
Browser with Workers, object URLs, and a caller-selected
transformers-whisper runtime/model plus the required DBOPFS store and Web
Locks. The subpath is
importable in Node, but no Node storage, Worker, audio-decoder, or speech
execution adapter is published. No Core speech call, model/runtime download
authority, or automatic provider fallback is added. Provider objects are not event targets; register them with
the managed AI provider runtime when normalized AIRuntimeState observation is
needed.
Example
import {createBrowserWhisperProvider} from 'arcane-os/ai/browser-speech';
const whisper = createBrowserWhisperProvider({model, runtime, store:speechStore});
async function transcribeAfterUserChoice(audioBlob) {
await whisper.load({
role:'stt',
selection:{
providerId:whisper.id,
modelId:whisper.catalog()[0].id,
localOnly:true
}
});
const transcript = await whisper.request({
role:'stt',
operation:'transcribe',
payload:{
audio:audioBlob,
mimeType:audioBlob.type,
model:whisper.catalog()[0].id
}
});
console.log(transcript.text);
}
createBrowserSpeechRecognitionProvider()
Overview
Creates an explicitly selected provider/2 STT adapter for the browser's native
SpeechRecognition or webkitSpeechRecognition service. It declares
localOnly:false because recognition may use a remote browser service. It does
not change Whisper, TTS, typing, stored preferences, or any default selection.
Signature and result
createBrowserSpeechRecognitionProvider({id,model,language}={})
The application supplies its provider id and model:{id}; optional language
is passed to native recognition without changing transcript text. The provider
implements the required catalog, inspect, status, load, request,
unload, and dispose methods plus createCapture(options). There is no SDK
model download or storage. Construction/catalog do not require native support;
inspect/load report actual browser availability without opening a microphone.
File transcription requests are unsupported for this provider.
createCapture({language,continuous,onSegment,onInterim,onState,onError})
returns a single-use {start,stop,cancel,destroy,done} handle. Start must be
called directly from a user gesture and returns a promise for startup success.
Final callbacks carry exact {text,sequence} values once per final result;
interim {text} stays transient. Stop preserves pending native final results
through end; cancellation aborts recognition and suppresses late text.
done resolves true for normal native end and false for cancellation or
failure. Unload/dispose cancel owned capture.
The shared runtime's createTranscriptionCapture() additionally owns STT busy
state and lifecycle replacement. See the
complete native capture contract.
Availability and normalization
Conditional browser/native-WebView support on Windows, Linux, macOS and Android, determined by the actual browser API and permission/service outcome, not by operating-system name. Missing API, denied microphone permission and service errors remain honest STT failures without disabling TTS or typing. No Core, Whisper, or cloud-provider fallback is inferred.
Example
import {createBrowserSpeechRecognitionProvider} from 'arcane-os/ai/browser-speech';
async function selectNativeRecognition(ai, signal) {
const provider = createBrowserSpeechRecognitionProvider(
{id: 'WEB_SPEECH', model: {id: 'WEB_SPEECH'}}
);
return ai.configureSpeechProvider('stt', provider, {modelId: 'WEB_SPEECH', signal});
}
createBrowserSpeechSynthesisProvider()
Overview
Creates a provider/2 TTS adapter for native speechSynthesis. Construction,
voice discovery and preparation are silent. Applications choose when to play
and retain ownership of voice preferences. Browser voices may use remote
services, so the provider declares localOnly:false.
Signature and result
createBrowserSpeechSynthesisProvider({id,model,language}={})
Supply id and model:{id,name?,defaultVoice?}; optional language is a
browser language tag. The provider exposes ordinary catalog, inspect,
status, load, request, unload and dispose methods, plus:
catalog()returns the selected model withspeech:{playback:'native'}and actualvoicesrecords{id,name,lang,default,localService}. Voiceidis the browser's exactvoiceURI.subscribeCatalog(callback)immediately delivers the current catalog and observesvoiceschanged; its returned function removes that subscription.setDefaultVoice(voiceURI|null)synchronously changes the default for future preparations and returns the selected value. An empty string selectsnull. Repeating a value is silent; changing it publishes the catalog. Explicit choices and prepared, queued or active speech keep their captured voice.prepare({input,model?,voice?,language?,speed?},{signal?})returns a{kind:'native-speech',input,voice,language,speed,play}descriptor. Preparation preserves complete text and starts no speech.play({signal,onState})returns an owned handle withfinished,released,pause(),resume()andstop(), plus observable state and errors.
AI.prepareTTSPlayback(payload,signal) returns this native descriptor or real
Blob audio from a speech request. Streaming TTS and SpeechPlayback consume
those prepared results. Audio-file methods fetchTTS and durable prepareTTS
require real audio and report ARCANE_AI_TTS_AUDIO_EXPORT_UNAVAILABLE for native output.
Unload and disposal cancel owned playback and wait for native release.
Availability, errors and example
The actual browser must provide synthesis, utterance and voice-event APIs.
No SDK model, Worker, Core or DBOPFS is required. Missing native synthesis
reports ARCANE_AI_SPEECH_SYNTHESIS_UNAVAILABLE; an unavailable selected voice
reports ARCANE_AI_SPEECH_VOICE_UNAVAILABLE. Activation and playback remain
subject to browser behavior. A resolved playback operation describes its
observed native lifecycle, not proof that a person heard it.
import {createBrowserSpeechSynthesisProvider} from 'arcane-os/ai/browser-speech';
// Call from the application's speech-selection action. This stays silent.
async function selectNativeVoice(ai) {
const provider = createBrowserSpeechSynthesisProvider({
id: 'browser-voice',
model: {id: 'browser-voice'}
});
await ai.configureSpeechProvider('tts', provider, {modelId: 'browser-voice'});
return provider;
}
See native speech and voice selection for live catalogs, explicit playback, cancellation and language handling.
createTwinCloudTTSProvider()
Overview
Creates a localOnly:false TWiN Cloud provider/2 TTS adapter for the caller-selected
model. It submits independent synthesis jobs, polls their completion, and returns
each complete downloaded audio Blob. The shared AI
queue owns punctuation segmentation, bounded concurrent requests, and playback
in input order; this is not provider-native live audio streaming.
Signature and result
createTwinCloudTTSProvider({id,model,getApiKey,maxConcurrentRequests=4,followUpQueue:{maxConcurrentRequests=4,intervalMs=250}={},fetch=globalThis.fetch}={})
id is the application-owned provider identifier. model contains the selected
id and defaultVoice; the supported multilingual-v2 selection is
fal-ai/elevenlabs/tts/multilingual-v2. getApiKey() returns the
application's current DigitalOcean inference key or a promise for it. The credential is never
included in catalog or status. maxConcurrentRequests remains the positive
whole-synthesis-job capacity used by the shared AI runtime. It is independent
from followUpQueue.maxConcurrentRequests, which controls follow-up HTTP
operations. followUpQueue.intervalMs controls the spacing between those
dispatch starts. Optional fetch supplies the standard Fetch interface.
Availability and normalization
The adapter needs Fetch, Blob, and AbortController; it needs no Worker or
DBOPFS. Browser access depends on endpoint CORS support. Construction makes
no network request. Its provider-local js-queue is created only when this
factory is called; importing the entrypoint does not create a queue or load a
model. Local Kokoro and Whisper retain their independent paths. Inspection and
activation await the application's key reader without making an SDK network
request. Activation checks
local credential presence, not remote validity. Status reports remote
execution and current activity. Requests preserve complete text, selected
voice, and speed; multilingual-v2 speed outside 0.7 through 1.2 rejects
instead of clamping. Returned media is fetched without the inference key.
Cancelling a credential wait leaves the application's shared refresh alone
and prevents a late result from starting this cancelled operation.
The whole-job queue holds each slot through credential readiness, submission, remote completion and the complete audio response. Excess jobs wait in FIFO order; cancellation removes waiting work before submission. A separate queue owns initial POST attempts and eligible retries. Follow-up status/result GETs and audio downloads retain independent configurable capacity and cadence, defaulting to four requests and 250 ms between starts. Slots remain held through complete response-body consumption.
Readable HTTP 429 responses set a provider-wide cooldown observed by submissions
and follow-ups. One readable rate-limit retry is allowed per submission or
status read, respecting its applicable minimum delay and longer Retry-After.
An accepted job's failed status Fetch may retry once after a network failure.
Ambiguous POST network, JSON or error-body failures are surfaced without
replaying a potentially accepted paid job. A failed job leaves sibling jobs
intact. See the cloud speech queue contract
for full scheduling, retry and cancellation behavior.
Each provider/2 tts/synthesize request returns one complete audio Blob.
Request cancellation, unload, and disposal stop local polling/downloads and
discard late results; they cannot promise cancellation of an already submitted
remote job. HTTP, provider, and media failures remain observable. The adapter
does not select a fallback or silently resubmit a paid synthesis POST.
Example
import {createTwinCloudTTSProvider} from 'arcane-os/ai/browser-speech';
async function configureCloudVoice(ai, getApiKey) {
const provider = createTwinCloudTTSProvider({
id: 'selected-cloud-voice',
model: {id: 'fal-ai/elevenlabs/tts/multilingual-v2', defaultVoice: 'Rachel'},
getApiKey,
followUpQueue: {maxConcurrentRequests: 4, intervalMs: 250}
});
await ai.configureSpeechProvider('tts', provider);
return provider;
}
Call activation and synthesis from the application's explicit speech action. For streaming text, cancellation, and independent STT configuration, see TWiN Cloud speech.
createDigitalOceanFalTTSProvider()
Overview
Compatibility export of createTwinCloudTTSProvider, using the same function
and implementation. The canonical public name is TWiN Cloud; the underlying
DigitalOcean FAL endpoint and job protocol remain unchanged.
Signature and result
createDigitalOceanFalTTSProvider({id,model,getApiKey,maxConcurrentRequests=4,followUpQueue:{maxConcurrentRequests=4,intervalMs=250}={},fetch=globalThis.fetch}={})
Accepts the same options and returns the same provider as
createTwinCloudTTSProvider().
Availability and normalization
The alias shares the canonical factory's Browser and Node requirements, whole-job and submission queues, queued follow-ups, cancellation and result contract. Existing caller imports, stored provider IDs, and credentials remain valid; renaming a caller's import requires no saved-data migration.
Example
import {
createTwinCloudTTSProvider,
createDigitalOceanFalTTSProvider
} from 'arcane-os/ai/browser-speech';
console.log(createDigitalOceanFalTTSProvider === createTwinCloudTTSProvider);
createBrowserKokoroProvider()
Overview
Creates a local-only Kokoro text-to-speech provider for the provider-neutral AI runtime. It owns one independent, bounded Worker/session pool and never selects a cloud, native, or LLM fallback.
An ordinary model.voices array supplies optional display metadata for the
application's voice selector. catalog() retains each complete record without
loading or fetching a model. This metadata neither restricts synthesis voice
values nor proves playback availability. Artifact-graph voice paths remain a
separate asset-routing contract.
Signature and result
createBrowserKokoroProvider(options={})
The recognized options are
{id='arcane-browser-kokoro',localOnly=true,graph,model,runtime,appSecurity, security,store,offline=false,execution={device:'auto',maxConcurrentRequests:4}}.
execution.device is auto, webnn-npu, webgpu, or wasm; its capacity is
an integer from 1 through 4. graph is mutually exclusive with model and runtime. The
mutable result is
{protocol:'arcane-ai-provider/2',role:'tts',id,localOnly:true, maxConcurrentRequests,catalog,inspect,status,load,request,unload,dispose}. The
only request operation is
synthesize; its payload is {text,voice?,speed=1}. Omitted voice uses the
caller-supplied model.defaultVoice; speed is any finite number greater than
zero. The Worker-transferred result is a structured
{audio:Float32Array,sampleRate:24000,voice} record; the client does not
re-freeze the cloned record.
The shared AI request form is
{model,input,responseFormat,voice?,speed?}. It requires the exact model,
accepts only responseFormat:'wav', maps the complete input to provider-native text, and
returns mutable {audio:Uint8Array,contentType:'audio/wav'} containing 24 kHz
mono 16-bit PCM. Unsupported formats fail
ARCANE_AI_UNSUPPORTED_RESPONSE_FORMAT; malformed adapter audio fails
ARCANE_AI_INVALID_PROVIDER_RESULT. Unknown fields and accessors reject as malformed.
The Kokoro adapter retains upstream text normalization and phonemization, then
tokenizes without truncation and sends every content token through the selected
engine. Short inputs use one inference; longer inputs use ordered segments
within that engine's capacity and return all generated audio in order. Each
segment retains the engine's required outer padding, voice-style selection and
speed. The segments share the slot's existing loaded model and disposal owner;
they do not create another model or provider-pool slot. Cancellation is checked
between inference segments and before returning audio; already-running upstream
inference may finish. This engine transport is distinct from the SDK's optional
textFormat:'plain' input treatment. See complete synthesis input
for the selected tokenizer/model contract and upstream revision behavior.
Automatic execution tries a complete WebNN NPU pool when
navigator.ml.createContext is exposed, then WebGPU when navigator.gpu is
exposed, then CPU through WASM. A failed candidate is cleaned up before a fresh
pool tries the next backend. Explicit device selections do not fall back. Every
slot loads the same caller-selected model and dtype in a distinct Worker so the
selected adapter's per-isolate inference serialization does not serialize the
pool. Direct provider status().execution reports requestedDevice,
selectedDevice, maxConcurrentRequests, and activeRequestCount.
selectedDevice is null before load and after unload. For a provider created
by AI.configureBrowserSpeech(), use
ai.providerRuntime.status('tts', {execution:true}).execution. Requested
auto with selected wasm means automatic fallback occurred. Inspection
errors propagate; the default runtime status() remains a sticky lifecycle
read. selectedDevice names the backend requested by the successful upstream
session load. These fields do not prove that every operation ran on a physical
NPU or GPU, or that accelerator kernels overlap. WebNN may execute unsupported
operations through WASM; exact model, browser, driver, and hardware
compatibility remains upstream.
Capacity 4 means up to four segments synthesize at once. Segment 5 and later wait in the SDK's provider-neutral FIFO queue; they are not dropped. Synthesis may finish out of order, but high-level playback waits for earlier segments and plays exact input order. Each slot owns a Worker/model session, so raising capacity trades memory for latency. Direct provider callers supply their own admission/playback orchestration; use high-level AI speech to obtain the SDK queue and ordered playback together.
Lifecycle/status, coalesced load, capacity-busy, unload, Worker-failure, and
disposal behavior otherwise matches the Whisper provider. Cancellation after
Kokoro Worker use suppresses only that request and sends its targeted cancel
control; already-running upstream engine work may finish. Unload terminates all
pool Workers and cancels all active ownership. Stable failures include
ARCANE_AI_INVALID_REQUEST, ARCANE_AI_NOT_READY,
ARCANE_AI_PROVIDER_DISPOSED, ARCANE_AI_OPERATION_SUPERSEDED,
ARCANE_AI_WORKER_CRASHED, ARCANE_AI_WORKER_MESSAGE_ERROR, and
ARCANE_AI_ADAPTER_PROTOCOL_MISMATCH.
Availability and normalization
Browser with Workers, object URLs, and a caller-selected kokoro-js
runtime/model/voice selection plus the required DBOPFS store and Web Locks.
The subpath is
importable in Node, but no Node storage, Worker, or speech execution adapter is
published. No Core speech call, model/runtime/voice authority, or automatic provider fallback is
added. Provider objects are not event targets; managed AIProviderRuntime and
AIRuntimeState projections own normalized cross-role observation.
Example
import {createBrowserKokoroProvider} from 'arcane-os/ai/browser-speech';
// applicationProviderOptions is your application-owned model/runtime/store
// configuration. The browser speech quick start shows the high-level setup.
const {model, runtime, store: speechStore} = applicationProviderOptions;
const kokoro = createBrowserKokoroProvider({
model,
runtime,
store:speechStore,
execution:{device:'auto',maxConcurrentRequests:4}
});
async function synthesizeAfterUserChoice() {
await kokoro.load({
role:'tts',
selection:{
providerId:kokoro.id,
modelId:kokoro.catalog()[0].id,
localOnly:true
}
});
const speech = await kokoro.request({
role:'tts',
operation:'synthesize',
payload:{
model:kokoro.catalog()[0].id,
input:'Hello from Arcane.',
responseFormat:'wav',
speed:1
}
});
console.log(speech.audio, speech.contentType);
}
Portable Mail
The arcane-os/mail subpath is the dependency-free portable Mail boundary.
Node credentials, Resend commands, and the loopback gateway remain toolchain
and CLI responsibilities rather than browser-package exports.
MAILOUTBOXIDEMPOTENCYWINDOWMS
Overview
Duration for same-key retry before ambiguous delivery requires reconciliation.
Value and import
const MAIL_OUTBOX_IDEMPOTENCY_WINDOW_MS
Availability and normalization
Node and browser metadata. The immutable value is 86400000 milliseconds.
Example
import {MAIL_OUTBOX_IDEMPOTENCY_WINDOW_MS} from 'arcane-os/mail';
MAILOUTBOXPROTOCOL
Overview
Stable protocol identifier written to durable Mail outbox records.
Value and import
const MAIL_OUTBOX_PROTOCOL
Availability and normalization
Node and browser metadata. The immutable value is arcane-mail-outbox/1.
Example
import {MAIL_OUTBOX_PROTOCOL} from 'arcane-os/mail';
MAILOUTBOXSTATES
Overview
Mutable ordered vocabulary for durable Mail outbox lifecycle states.
Value and import
const MAIL_OUTBOX_STATES
Availability and normalization
Node and browser metadata. States are queued, sending, retrywait, accepted, failed, and reconciliationrequired.
Example
import {MAIL_OUTBOX_STATES} from 'arcane-os/mail';
MAILOUTBOXTABLE
Overview
Default DBOPFS-compatible table name for durable Mail outbox records.
Value and import
const MAIL_OUTBOX_TABLE
Availability and normalization
Node and browser metadata. The immutable value is mail_outbox.
Example
import {MAIL_OUTBOX_TABLE} from 'arcane-os/mail';
Overview
Owns the application Mail singleton, durable lifecycle, report normalization, and explicit transport selection.
Signature and result
new Mail(config=globalThis.arcane?.config?.mail||{}, options={})
Availability and normalization
Node with injected host adapters, or browser/native WebView with durable storage and Web Locks. Reports persist before delivery and results remain complete mutable records.
Example
import {Mail} from 'arcane-os/mail';
const mail = new Mail({}, options);
MailOutbox
Overview
Owns durable FIFO delivery, retry classification, and invalid-record maintenance.
Signature and result
new MailOutbox(options={})
Availability and normalization
Node or browser with injected DBOPFS-compatible storage and a Web
Locks-compatible lock manager. Records and summaries remain complete mutable
values. An accepted result requires a valid requestId; providerId and
acceptanceAuthority are optional transport metadata, and an acceptance
authority is valid only on an accepted result.
Example
import {MailOutbox} from 'arcane-os/mail';
const outbox = new MailOutbox(options);
MailTransportError
Overview
Normalized Mail transport failure with stable retry and uncertainty metadata.
Signature and result
new MailTransportError(message, options={})
Availability and normalization
Node and browser. It exposes code, retryable, retryAfterMs, statusCode, uncertain, and the complete remote detail subject only to HTTP framing.
Example
import {MailTransportError} from 'arcane-os/mail';
createMailOutbox()
Overview
Creates a MailOutbox from caller-owned storage, locking, delivery, and lifecycle adapters.
Signature and result
createMailOutbox(options)
Availability and normalization
Node or browser with the required injected adapters. The result is the same validated contract as direct MailOutbox construction.
Example
import {createMailOutbox} from 'arcane-os/mail';
const outbox = createMailOutbox(options);
Mail default export
Overview
Default package binding for the same Mail class exposed by the named export.
Signature and result
default as Mail
Availability and normalization
Node with injected host adapters, or browser/native WebView with durable
storage and Web Locks. Binding identity equals the named Mail export.
Example
import Mail from 'arcane-os/mail';
normalizeMailEndpoint()
Overview
Resolves and validates one credential-free HTTPS or loopback-HTTP endpoint.
Signature and result
normalizeMailEndpoint(endpoint, base=globalThis.location?.href)
Availability and normalization
Node and browser with URL support. Relative endpoints require a base; credentials, queries, fragments, and insecure non-loopback transport reject.
Example
import {normalizeMailEndpoint} from 'arcane-os/mail';
const endpoint = normalizeMailEndpoint('/v1/mail', location.href);
resolveMailConfig()
Overview
Resolves application identity, key, endpoint, and timeout without delivery.
Signature and result
resolveMailConfig(config=globalThis.arcane?.config?.mail||{}, options={})
Availability and normalization
Node with explicit configuration, or browser/native WebView with optional document and location defaults. The returned configuration is a mutable plain record.
Example
import {resolveMailConfig} from 'arcane-os/mail';
const config = resolveMailConfig();
sendMailReport()
Overview
Sends one complete Mail report with an idempotency key through HTTP.
Signature and result
sendMailReport({ appKey, appName, endpoint, fetchImpl=globalThis.fetch, report, reportKey, requestTimeout=null, serializedReport, signal })
Availability and normalization
Node and browser with Fetch and AbortController, or an explicit fetch
implementation. The complete response is preserved subject only to unavoidable
HTTP framing and normalized as acceptance or a MailTransportError.
Example
import {sendMailReport} from 'arcane-os/mail';
const result = await sendMailReport(options);
serializeMailReport()
Overview
Serializes one JSON-object Mail report for exact body comparison.
Signature and result
serializeMailReport(report)
Availability and normalization
Node and browser. Returns compact JSON and rejects non-object or non-serializable reports.
Example
import {serializeMailReport} from 'arcane-os/mail';
const body = serializeMailReport(report);
Shared logging
arcaneLogging
Overview
Shared console owner for Arcane runtime and application diagnostics. Available
in SDK 0.5.14, it reads the existing user.developer preference on every
diagnostic emission after the shared user is ready. Enable developer mode in
the application's profile settings. There is no separate verbosity setting.
See speech developer diagnostics
for API calls, generation queue state, and playback events.
Signature and result
const arcaneLogging
arcaneLogging.enabled
arcaneLogging.log(...args)
arcaneLogging.info(...args)
arcaneLogging.debug(...args)
arcaneLogging.warn(...args)
arcaneLogging.error(...args)
arcaneLogging.trace(...args)
enabled is a boolean getter for the current shared preference, not another
setting. log, info, and debug forward to console.info when enabled, so
diagnostics appear at the console's normal Info level. warn, error, and
failure trace calls forward to their corresponding console methods in either
mode. Each method returns undefined; a console failure does not change the
operation being observed.
Availability and normalization
Node and browser. Imports reuse the same realm-local owner through
Symbol.for('arcane.logging'), also exposed as globalThis.arcaneLogging.
Arguments pass to the host console unchanged, including complete object
references. The logger does not serialize content, retain diagnostic history,
write storage, or send network requests. Diagnostics remain disabled while
the shared user is not ready. The logger does not select a language or change
speech generation and playback behavior.
Example
import {arcaneLogging} from 'arcane-os/logging';
arcaneLogging.info('AI request', request);
arcaneLogging.info('AI response', parsedResponse);
readArcaneDeveloperMode()
Overview
Reads the same developer-mode preference used by arcaneLogging, preserving
the unloaded-user state without creating or changing a setting.
Signature and result
readArcaneDeveloperMode(target=globalThis)
target supplies the shared user. The result is null until
target.user.ready === true, then true only when
target.user.developer === true; other loaded preference values return
false. If preference access throws, the reader returns false.
Availability and normalization
Node and browser. Reads the supplied target synchronously. It performs no subscription, write, or logging, and does not cache the preference.
Example
import {readArcaneDeveloperMode} from 'arcane-os/logging';
const developerMode=readArcaneDeveloperMode();
fetchRequest()
Overview
Makes one complete TWiN Cloud request with explicit caller-owned credentials
and model selection. This named function is independent of the browser
AI instance method with the same name.
Signature and result
async fetchRequest(options={})
Import the named function from arcane-os/ai/twin-cloud. Supply twinKey,
model, and complete messages. The function requires the explicit model;
it reads no browser preference or default-model selection. Optional
structuredOutput:true or 'json' sends response_format:{type:'json_object'}.
A supplied JSON Schema sends response_format:{type:'json_schema', json_schema:{name:'structured_response',strict:true,schema:...}}. Omission
leaves structured output off. Optional tools, toolChoice,
parallelToolCalls, reasoningEffort, and temperature map to their existing TWiN wire
fields. Tool fields are sent when tools is nonempty; a nonempty
reasoningEffort is forwarded without selecting a default. No default output
cap, tool execution, or provider-response envelope validation is added.
temperature is forwarded unchanged when supplied, including 0. Omission or
undefined leaves it out of the request, preserving the provider's default.
The SDK adds no clamp or saved preference, and retries retain the same value.
The return value is the entire parsed provider JSON, not only one choice or
message. Optional callbacks are onRequest(request,id,metadata) before
dispatch and onResponse(response,id,false) before successful return;
id defaults to Date.now() and may be supplied by the caller. Request metadata
is {operation:'fetch',transport:'http',destination:'https://inference.do-ai.run/v1/chat/completions'}.
Both callbacks are awaited, and callback
failures propagate. Credentials are supplied to transport rather than added to
the message or response callback payload.
Availability and normalization
Node and Browser; Cloud transport. Uses standard Fetch and cancellation,
without DOM, browser profiles, user singletons, or storage initialization.
Import starts no request. Rejected Fetch and all HTTP 429/529 share three
retries. Quota recovery honors Retry-After, otherwise waits 3000, 6000,
or 12000 milliseconds by retry number. Active same-endpoint/credential calls
share quota cooldown and paced dispatch. Complete error bodies remain unchanged
on exhaustion; other HTTP failures are not retried. A missing key throws
AI_PROVIDER_NOT_CONFIGURED; a missing model throws TypeError. signal
cancellation during transport, body reading, retry waiting,
or callback settlement prevents successful return and uses
ARCANE_AI_REQUEST_ABORTED. No request history, DBOPFS write, or recurring
model context is retained. The caller owns persistence and key configuration.
See TWiN Cloud for a complete Node JSON-schema example and
the unchanged browser AI interface.
Example
import serverConfig from './server-config.json' with {type: 'json'};
import {fetchRequest} from 'arcane-os/ai/twin-cloud';
const response = await fetchRequest({
twinKey: serverConfig.twinKey,
model: 'openai-gpt-oss-20b',
messages: [{role: 'user', content: 'Describe a moon-powered toaster.'}]
});
console.log(response);
server-config.json is an application-owned, ignored configuration file;
never commit its key or print it in diagnostics. The SDK does not read it.
fetchSystemOneRequest()
Overview
Sends one native TWiN System One request with caller-owned credentials, model, state, and questions. Question definitions, scales, model selection, and answer interpretation remain application responsibilities.
Signature and result
async fetchSystemOneRequest({twinKey,model,state,questions,signal=null,id=Date.now(),onRequest,onResponse,onRetry=null}={})
Import the named function from arcane-os/ai/twin-cloud. It posts
{model,state,questions} to https://inference.do-ai.run/v1/systemone and
returns the entire parsed provider JSON. It adds no chat messages, tools,
scoring rules, or output limit. Payload content is preserved within ordinary
JSON transport encoding; serialization occurs before the diagnostic callback.
onRequest(request,id,metadata) receives the complete payload before dispatch,
with {operation:'systemone',transport:'http',destination:'https://inference.do-ai.run/v1/systemone'}
as metadata. onResponse(response,id,false) receives the entire parsed result
before return. Both callbacks are awaited and failures propagate. The key is
used only for transport authentication, outside the diagnostic payloads.
Availability and normalization
Node and Browser; Cloud transport. Uses the existing fetchJSONResponse
owner for complete errors, retries, onRetry, and signal cancellation, with
no browser singleton, profile, storage, or retained history. A missing key uses
AI_PROVIDER_NOT_CONFIGURED; a missing explicit model throws TypeError.
Cancellation prevents successful return and uses ARCANE_AI_REQUEST_ABORTED,
including checks after callback settlement. Import starts no request.
Example
import {fetchSystemOneRequest} from 'arcane-os/ai/twin-cloud';
const response = await fetchSystemOneRequest({
twinKey: applicationRuntime.twinKey,
model: 'typesafe-jev-1.13.0',
state: applicationState,
questions: applicationQuestions
});
The runtime configuration, state, and questions in this example belong to the application. The JEV identifier is an explicit caller choice, not a default. See TWiN Cloud for the complete transport and callback contract.
generateImages()
Overview
Generates images through TWiN Cloud with a caller-selected model and complete prompt. Returns every image as a Blob in provider order. The application owns display, filenames, storage, credentials and model choice.
Signature and result
async generateImages({model,prompt,parameters={},twinKey,getApiKey,signal=null,id=Date.now(),onRequest,onResponse,onProgress}={})
Supported models are fal-ai/flux/schnell through async invocation and
stable-diffusion-3.5-large through image generation. prompt is a string;
parameters carries the selected provider's additional fields. Supply the
prompt through its named argument, and the model through model. An explicit
twinKey takes precedence over getApiKey(); the latter may return a promise.
The result is {images:[{blob,mediaType,width?,height?},...]}. Media metadata is
retained when the provider supplies it. onRequest(request,id,metadata) and
onResponse(result,id,false) receive complete diagnostic records;
onProgress({stage,model,id,requestId?}) reports credentials, requesting,
queued, generating, downloading and complete stages as applicable. Keep these
diagnostics outside durable conversation history.
The operation submits once. Async jobs are polled using their returned request
ID; a readable Retry-After controls the wait. Ambiguous submission failures
are surfaced without automatic resubmission. Cancellation covers credentials,
observers, requests, response bodies and media downloads; it cannot promise
that an accepted remote job was cancelled. Media downloads omit the inference
credential. The SDK writes no image or conversation records.
Availability, errors and example
Node or browser with Fetch, Blob and AbortController; browser requests also
depend on endpoint CORS. Missing credentials report AI_PROVIDER_NOT_CONFIGURED,
unsupported models ARCANE_AI_IMAGE_MODEL_UNSUPPORTED, malformed returned
media ARCANE_AI_INVALID_PROVIDER_RESULT, and cancellation
ARCANE_AI_REQUEST_ABORTED. HTTP/provider failures preserve their returned
detail. Call only from the application's explicit generation action:
import {generateImages} from 'arcane-os/ai/twin-cloud';
async function drawLunarGarden(twinKey, signal) {
return generateImages({
twinKey,
model: 'fal-ai/flux/schnell',
prompt: 'A moon gardener watering a single enormous radish.',
signal
});
}
See image generation and MarkdownMedia for application-owned image storage and document references.
fetchHTTPResponse()
Overview
Shared low-level HTTP owner used by browser AI and the focused TWiN API.
Ordinary TWiN callers use fetchRequest() instead.
Signature and result
async fetchHTTPResponse(url,options,{onRetry=null}={})
Returns the successful Fetch Response without consuming its body. Both URL
and Fetch options are caller-supplied; this helper adds no key, model, or
request envelope. Non-success responses are read completely as JSON when the
content type contains application/json, otherwise as text. Rejected Fetch
and all 429/529 share three retries with complete terminal errors.
429 honors Retry-After or exponential delay and coordinates a transient
same-endpoint/credential cooldown. See shared request behavior.
Availability and normalization
Node and Browser. Exported from arcane-os/ai/twin-cloud for shared SDK
integration. options.signal cancels Fetch and recovery/pacing waits and is checked
after response/error-body reads. Cancellation uses
ARCANE_AI_REQUEST_ABORTED. Retry warnings use the existing shared logger;
onRetry observes complete waiting/requesting records outside the payload.
Example
import {fetchHTTPResponse} from 'arcane-os/ai/twin-cloud';
// The integration supplies its selected endpoint and complete Fetch options.
const response = await fetchHTTPResponse(endpoint, requestOptions);
fetchJSONResponse()
Overview
Shared complete JSON-body reader built on fetchHTTPResponse().
Signature and result
async fetchJSONResponse(url,options,{onRetry=null}={})
Returns the full parsed JSON value. A successful response whose content type
does not contain application/json throws TypeError; JSON parser failures
propagate. The helper does not select choices or validate a provider envelope.
Availability and normalization
Node and Browser. Exported from arcane-os/ai/twin-cloud for shared SDK
integration; it retains the HTTP owner's retry/cancellation behavior and checks
cancellation again after parsing. Ordinary callers use fetchRequest().
Example
import {fetchJSONResponse} from 'arcane-os/ai/twin-cloud';
// The integration supplies its selected endpoint and complete Fetch options.
const completion = await fetchJSONResponse(endpoint, requestOptions);
structuredOutputFormat()
Overview
Normalizes the existing AI structured-output option without rewriting a schema.
Signature and result
structuredOutputFormat(value=false)
False, null, and undefined return null. True and 'json' return 'json'.
A plain object with Object.prototype or a null prototype is returned
unchanged. Other values throw AI_STRUCTURED_OUTPUT_INVALID.
Availability and normalization
Node and Browser. Synchronous helper exported from
arcane-os/ai/twin-cloud; performs no network or storage operation.
Example
import {structuredOutputFormat} from 'arcane-os/ai/twin-cloud';
const format = structuredOutputFormat({
type: 'object',
properties: {text: {type: 'string'}}
});
openAIResponseFormat()
Overview
Maps a normalized structured-output choice to chat-completion wire fields.
Signature and result
openAIResponseFormat(format)
'json' becomes {type:'json_object'}; a supplied schema becomes
{type:'json_schema',json_schema:{name:'structured_response',strict:true,schema:format}}.
A disabled format returns null. Use structuredOutputFormat() first to
normalize the public option; this mapper does not validate schema contents.
Availability and normalization
Node and Browser. Synchronous helper exported from
arcane-os/ai/twin-cloud, shared with browser AI and performing no I/O.
Example
import {structuredOutputFormat, openAIResponseFormat} from 'arcane-os/ai/twin-cloud';
const responseFormat = openAIResponseFormat(structuredOutputFormat(true));
// {type: 'json_object'}
isAIRequestAbort()
Overview
Recognizes the existing AI request cancellation forms.
Signature and result
isAIRequestAbort(error,signal)
Returns a boolean: true when the signal is aborted, the error name is
AbortError, or its code is ARCANE_REQUEST_ABORTED,
ARCANE_AI_REQUEST_ABORTED, or AI_REQUEST_ABORTED.
Availability and normalization
Node and Browser. Synchronous helper exported from
arcane-os/ai/twin-cloud; it neither changes nor aborts the supplied operation.
Example
import {isAIRequestAbort} from 'arcane-os/ai/twin-cloud';
const controller = new AbortController();
controller.abort();
const cancelled = isAIRequestAbort(undefined, controller.signal);
normalizeAIRequestAbort()
Overview
Keeps cancellation under the shared AI error code while preserving its cause.
Signature and result
normalizeAIRequestAbort(error)
An existing ARCANE_AI_REQUEST_ABORTED error is returned unchanged. Otherwise
the result is an Error named AbortError, with code
ARCANE_AI_REQUEST_ABORTED, message The AI request was cancelled., and the
supplied value as its cause. The helper returns the error; it does not throw it.
Availability and normalization
Node and Browser. Synchronous helper exported from
arcane-os/ai/twin-cloud; creates no request, storage, or user state.
Example
import {normalizeAIRequestAbort} from 'arcane-os/ai/twin-cloud';
const cancelled = normalizeAIRequestAbort(new DOMException('Cancelled', 'AbortError'));
Data export subpaths
The package also exposes eight JSON Schemas (including arcane-os/schemas/event-stack.json) and its package manifest. These are data contracts, not callable JavaScript members. See schema contracts and the files under schemas/.
arcane-os/schemas/arcane-app.json describes schema-2 package.nativeResources;
arcane-os/schemas/arcane-package.json describes the projected schema-1
nativeResources. Both use the existing literal application-relative path
contract. See native-only application resources.