Skip to content

Latest commit

 

History

History
860 lines (716 loc) · 42.9 KB

File metadata and controls

860 lines (716 loc) · 42.9 KB

API Reference

PortOS exposes a REST API on port 5555 and WebSocket events via Socket.IO.

Base URL

http://localhost:5555/api

When a TLS cert is provisioned (npm run setup:cert), :5555 serves HTTPS instead and a loopback-only HTTP mirror runs on http://127.0.0.1:5553 for local scripts. See PORTS.md.

This document covers the most commonly used endpoints plus a route-domain index. The in-app API Explorer at /api-reference/catalog is the exhaustive, generated reference:

For the bridge between these HTTP/event inventories and model-facing tools, see API and MCP Unified Tool Contract. It records the shipped semantic registry, MCP context/action schemas, authority matrix, and the current-vs-proposed boundary.

  • GET /api/api-docs/catalog.json — searchable metadata for every mounted HTTP operation.
  • GET /api/api-docs/internal/openapi.json — OpenAPI 3.0.3 for the complete internal HTTP surface.
  • GET /api/api-docs/openapi.json — OpenAPI 3.0.3 for only the external APIs currently exposed in Settings.
  • GET /api/api-docs/events.json — searchable Socket.IO event inventory.
  • GET /api/api-docs/asyncapi.json — AsyncAPI 3 for the Socket.IO transport.
  • GET /api/api-docs/tools.min.json — the minimized semantic tool resource: only the operations annotated x-portos-tool, flattened to provider-neutral tool records with an HTTP binding. Sized for an agent to read whole, unlike the full internal document.

Generated entries are explicitly marked generated until a runtime-backed payload contract exists; detailed entries are marked modeled. Regenerate the checked-in route and event manifests with npm run generate:api-docs. Drift tests fail when source declarations and committed manifests diverge.

When adding an HTTP route, keep its request Zod schema in a reusable server library and register the detailed documentation in server/lib/apiOperationContracts.js; the route and OpenAPI should consume the same schema object. Add an x-portos-tool annotation to that contract entry to also publish the operation as an agent-callable tool in tools.min.json, and declare the codes its error responses really throw in x-portos-error-codes — the HTTP status alone does not identify the code, since errorHandler prefers an explicit err.code over the status map. Socket payload schemas follow the same pattern in server/lib/socketEventContracts.js. The generators guarantee inventory coverage, while these small registries make richer contracts incremental without maintaining a second handwritten list of paths or events.

Building a native companion client? See COMPANION_APP_API.md — the stable, pre-auth-discoverable contract (discovery/identity, HTTP Basic auth, instance management, palette actions, daily-log, POST progress, and the iCloud-sync precedent) that the PortDeck app consumes.

Security Model

PortOS is designed for personal/developer use on trusted networks. It implements the following security measures:

  • Network isolation: By default, access should be restricted to trusted networks (e.g., Tailscale VPN, localhost)
  • Command allowlist: Shell command execution is restricted to an approved allowlist (see server/lib/commandSecurity.js)
  • Input validation: All API inputs are validated using Zod schemas
  • Opt-in authentication: Off by default (trusting private network/Tailscale), PortOS supports opt-in instance password authentication (enforced by server/services/authGate.js) gating /api/*, /data/*, and /sdapi/* via session cookies, Bearer tokens, or HTTP Basic credentials

Important: Do not expose PortOS APIs directly to untrusted networks. For production deployments, consider:

  • Binding to 127.0.0.1 instead of 0.0.0.0
  • Enabling instance password authentication in Settings → Security
  • Running behind an authenticated reverse proxy
  • Using Tailscale or similar VPN for remote access

REST Endpoints

System

Method Endpoint Description
GET /system/capabilities Host-local platform, architecture, Apple Silicon, memory, CPU, and cached CUDA capability snapshot used to filter model/provider selections. Probe failures remain unknown; this payload is intentionally not included in federation health records.

Federated peer-probe contract

PortOS peers running independently upgraded installs use the following existing endpoints during the periodic reachability probe in server/services/instances.js. They are a frozen compatibility contract: keep their paths, request semantics, and listed response fields compatible. Additive response fields are allowed. A breaking change needs a new, explicitly versioned endpoint and a staged migration of the probe; schemaVersions.js gates synchronized records, not these request/response contracts.

All three requests use the configured peer HTTP Basic credential when the remote instance enables its optional password gate. They are not a general cross-install data channel: probe results are stored only as the local peer's health, app, and sync snapshots. Do not add personal records, peer lists, credentials, local paths, or build identity to these responses.

Method Endpoint Stable request and response contract
GET /system/health/details Returns an object containing instanceId and version (each may be null) for peer identity and compatibility display. The health summary remains an object so an older prober can retain it as its last-known health snapshot.
GET /apps Returns either the legacy app array or { apps: [...] }. Each app entry used by peers retains id, name, icon, overallStatus, uiPort, apiPort, and type; fields may be absent or null when unknown.
GET /instances/sync-status?forPeer=<instance-id> forPeer is optional and remains lenient: an unknown or legacy identifier, blank value, or omitted value must degrade to the unscoped status response rather than fail the probe. A recognized peer receives its cursorForYou alongside the normal sync status.

The separate /federation/media/v1 surface is already versioned and has its own wire contract in FEDERATED_MEDIA_PROVIDERS.md.

Apps

Method Endpoint Description
GET /apps List all registered apps
POST /apps Register a new app
GET /apps/:id Get app details
PUT /apps/:id Update app
DELETE /apps/:id Unregister app
POST /apps/:id/start Start app via PM2
POST /apps/:id/stop Stop app via PM2
POST /apps/:id/restart Restart app via PM2
GET /apps/:id/status Get PM2 status
GET /apps/:id/logs Get recent logs
POST /apps/:id/refresh-config Re-parse ecosystem config

Processes & Logs

Method Endpoint Description
GET /logs/processes List all PM2 processes
GET /logs/:name Get logs for process
GET /ports/scan Scan for active ports

AI Providers

Method Endpoint Description
GET /providers List all AI providers. Also returns runnerAllowedCommands — the CoS Agent Runner's exec allowlist, read-only, so the editor can warn that a custom command won't spawn via /spawn / /spawn-tui.
POST /providers Add new provider
PUT /providers/:id Update provider
DELETE /providers/:id Delete provider
POST /providers/:id/test Test provider connectivity
PUT /providers/active Set active provider
GET /providers/runtimes Per-runtime install status (claude, codex, opencode, grok, kimi, agy, cursor-agent): is the binary runnable here, and can PortOS install it? Booleans and labels only — never resolved filesystem paths. 60s TTL cache. Ollama / LM Studio are absent on purpose — Models → LLMs owns their install.
POST /providers/runtimes/install?runtime=<id> Install one runtime from the installer's fixed table, streaming installer output as SSE. Rejects any id not in the table.
GET /providers/readiness Requirements checklist per provider backed by a LOCAL daemon (llama.cpp / Ollama / LM Studio / MTPLX), keyed by provider id: is the daemon installed, is it answering at the endpoint THIS provider points at, and is it serving the provider's default model. Each entry also carries setup — what the one-click fix below can do about the unmet checks (null when nothing is auto-fixable here). Providers with no local dependency are absent from the map. Complements /providers/runtimes (which answers "can PortOS run this CLI?"). Booleans, labels, and the provider's own endpoint only — never a resolved binary path. Skips disabled providers; 15s endpoint-probe cache (one probe per distinct endpoint), 60s binary-PATH cache, both dropped by the llama-server start/stop/install routes.
POST /providers/readiness/setup?provider=<id> Install and/or start the LOCAL DAEMON that provider points at (llama.cpp / Ollama / LM Studio / MTPLX), streaming progress as SSE — the "do it for me" half of /providers/readiness, so an unmet requirement is fixed from the card instead of from a vendor setup doc. The request names a PROVIDER only: the runtime kind and endpoint are re-derived server-side from the stored record, so no query value reaches a spawn argument (an optional runtime= is cross-checked and 409s on a mismatch). Every command comes from a fixed per-runtime table. Never downloads model weights, never starts llama-server (it needs a checkpoint you choose), and never runs MTPLX's privileged fan-control helper. Single-flight.
POST /providers/readiness/serve-model?provider=<id> Relaunch the local daemon so it answers under the model id THIS provider sends — the other half of the readiness model mismatch. llama-server serves one model per process under the --alias on its launch line, so the fix keeps the loaded weights and changes only the name; the whole launch line is carried forward and the previous one restored if the relaunch is rejected or never answers. The model id is re-derived server-side from the stored record. 400s for a runtime that has no such label (Ollama / LM Studio / MTPLX name a model after its weights), 409s when PortOS did not start the daemon.
GET /providers/opencode/installation Legacy alias, kept so a stale client bundle still renders: { installed, npmAvailable } for the opencode runtime. New code uses /providers/runtimes.
POST /providers/opencode/install Legacy alias for /providers/runtimes/install?runtime=opencode.

AI Runs

Method Endpoint Description
GET /runs List run history
POST /runs Execute new AI run
GET /runs/:id Get run details
GET /runs/:id/output Get run output
POST /runs/:id/stop Stop active run
DELETE /runs/:id Delete run

AI Agents

Method Endpoint Description
GET /agents List running AI agent processes
GET /agents/:pid Get agent process details
DELETE /agents/:pid Kill agent process

Agent Tools (MCP)

Method Endpoint Description
GET /agent-context/manifest Inspect the local context profile, scopes, semantic-action grants, schemas, exclusions, and limits; available while MCP is disabled
POST /agent-context/mcp Loopback-only, opt-in MCP Streamable HTTP endpoint for bounded context plus explicitly granted semantic PortOS tools

Context tools remain read-only. Semantic reads and writes are independent, default-off grants; MCP advertises only granted actions and never accepts a raw route, URL, shell command, or SQL query. See Agent Tools (MCP) for setup, transport headers, privacy profiles, grants, and tool schemas.

Command Execution

Method Endpoint Description
POST /commands/execute Execute shell command
POST /commands/:id/stop Stop running command
GET /commands/allowed List allowed commands
GET /commands/processes List PM2 processes

History

Method Endpoint Description
GET /history List action history
GET /history/stats Get history statistics
DELETE /history Clear history

Detection & Import

Method Endpoint Description
POST /detect/port Detect process on port
POST /detect/repo Validate repo path
POST /detect/pm2 Detect PM2 processes for a repo
POST /detect/ai AI-powered app detection

Scaffold (App Templates)

Method Endpoint Description
GET /scaffold/directories List candidate parent directories
GET /scaffold/templates List available templates
POST /scaffold/templates/create Create app from template
POST /scaffold Scaffold a new app

Prompts

Method Endpoint Description
GET /prompts List all prompt stages
GET /prompts/:stage Get stage template
PUT /prompts/:stage Update stage/template
POST /prompts/:stage/preview Preview compiled prompt
GET /prompts/variables List all variables
PUT /prompts/variables/:key Update variable
POST /prompts/variables Create variable
DELETE /prompts/variables/:key Delete variable

Chief of Staff

Method Endpoint Description
GET /cos Get CoS status
POST /cos/start Start daemon
POST /cos/stop Stop daemon
GET /cos/config Get configuration
GET /cos/tools Provider-neutral semantic tool catalog; `scope=agent
POST /cos/tools/call Execute one schema-validated semantic tool with server-derived authority and idempotency
GET /cos/tools/calls/:requestId Read a retained normalized tool result
PUT /cos/config Update configuration
GET /cos/tasks Get all tasks
POST /cos/evaluate Force task evaluation
GET /cos/health Get health status
POST /cos/health/check Run health check
GET /cos/agents List active agents
POST /cos/agents/:id/terminate Terminate agent
GET /cos/reports List reports

CoS Task Learning

Method Endpoint Description
GET /cos/learning Get learning insights and recommendations
GET /cos/learning/durations Get task duration estimates by type
POST /cos/learning/backfill Backfill learning data from history

CoS Jobs (Autonomous Jobs)

Method Endpoint Description
GET /cos/jobs List all jobs
GET /cos/jobs/due List jobs due to run
GET /cos/jobs/intervals Get available interval options
GET /cos/jobs/allowed-commands Get allowed commands for shell jobs
GET /cos/jobs/gates Get job gate status
GET /cos/jobs/:id Get a specific job
POST /cos/jobs Create a new job
PUT /cos/jobs/:id Update a job
DELETE /cos/jobs/:id Delete a job
POST /cos/jobs/:id/toggle Toggle job on/off
POST /cos/jobs/:id/trigger Run a job immediately
POST /cos/jobs/:id/gate-check Evaluate a job's gates

CoS Task Schedule & Timeline

Method Endpoint Description
GET /cos/schedule Get full task schedule status
GET /cos/upcoming Get upcoming scheduled tasks preview
GET /cos/schedule/interval-types Get available interval types and descriptions
GET /cos/schedule/due List all tasks due to run
GET /cos/schedule/due/:appId List tasks due for specific app
GET /cos/schedule/task/:taskType Get interval and schedule settings for a task type
PUT /cos/schedule/task/:taskType Update schedule settings for a task type
POST /cos/schedule/trigger Trigger an on-demand task run
GET /cos/schedule/on-demand List pending on-demand task requests
DELETE /cos/schedule/on-demand/:requestId Clear a pending on-demand request
POST /cos/schedule/reset Reset execution history for a task type
GET /cos/schedule/templates List all template tasks
POST /cos/schedule/templates Add a template task
DELETE /cos/schedule/templates/:templateId Delete a template task

(GET /cos/scripts still exists but now lists generated scripts only; scheduling lives in /cos/jobs and /cos/schedule.)

CoS Weekly Digest

Method Endpoint Description
GET /cos/digest Get current week's digest
GET /cos/digest/list List all available weekly digests
GET /cos/digest/progress Get current week's live progress
GET /cos/digest/text Get text summary for notifications
GET /cos/digest/:weekId Get digest for specific week
POST /cos/digest/generate Force generate digest for a week
GET /cos/digest/compare Compare two weeks

Memory System

Method Endpoint Description
GET /memory List memories with filters
GET /memory/:id Get single memory
POST /memory Create memory
PUT /memory/:id Update memory
DELETE /memory/:id Delete (soft) memory
POST /memory/search Semantic search
GET /memory/categories List categories
GET /memory/tags List tags
GET /memory/timeline Timeline view data
GET /memory/graph Graph visualization data
GET /memory/stats Memory statistics
POST /memory/link Link two memories
POST /memory/consolidate Merge similar memories
POST /memory/decay Apply importance decay
DELETE /memory/expired Clear expired memories
GET /memory/embeddings/status LM Studio connection status

PM2 Standardization

Method Endpoint Description
POST /standardize/analyze Analyze app for standardization
POST /standardize/apply Apply standardization changes
GET /standardize/template Get PM2 template reference
POST /standardize/backup Create git backup

Usage Metrics

Method Endpoint Description
GET /usage Get usage statistics
GET /usage/daily Get daily activity
GET /usage/hourly Get hourly activity

Eidoverse Worlds

The PortOS-owned Eidoverse adapter is private and install-local. It stores its identity and projection recipe under data/eidoverse/, joins the separately installed Eidoverse runtime through its WebSocket protocol, and does not federate world records.

Method Endpoint Description
GET /eidoverse/world/status Private world identity, CoS presence, projection recipe, setup, and storage boundary
PUT /eidoverse/world/config Persist the world identity and deterministic resource projection recipe
POST /eidoverse/world/presence Establish the install's persistent CoS agent presence
POST /eidoverse/world/project Project current PortOS resources into the world using the saved recipe
POST /eidoverse/world/augment Apply bounded, allowlisted world construction/role operations
POST /eidoverse/world/say Send a bounded message as the PortOS CoS presence

Legacy OpenWorld / CyberCity

The old UI routes redirect to Eidoverse; these APIs remain available as backward-compatible historical snapshot/introspection endpoints.

Method Endpoint Description
GET /city/snapshots Recorded city-state series, oldest-first (since, limit query params)
POST /city/snapshots/capture Capture a city snapshot frame on demand
GET /city/snapshots/config Effective snapshot capture config + next run time
GET /city/introspection DB tables (rows/size/pgvector) + data/ domain sizes for the Data Harbor district. Cached server-side; db: null means the database is unreachable (distinct from reachable-but-empty)

Brain (Second Brain)

Method Endpoint Description
POST /brain/capture Capture and classify thought (a text that is only a URL is filed straight to /brain/links — no classifier call — and returns the link alongside the inbox entry)
GET /brain/inbox List inbox log with filters
POST /brain/review/resolve Resolve needs_review item
POST /brain/fix Correct misclassified item
GET /brain/people List people
POST /brain/people Create person
GET /brain/people/:id Get person
PUT /brain/people/:id Update person
DELETE /brain/people/:id Delete person
GET /brain/projects List projects
POST /brain/projects Create project
GET /brain/projects/:id Get project
PUT /brain/projects/:id Update project
DELETE /brain/projects/:id Delete project
GET /brain/ideas List ideas
POST /brain/ideas Create idea
GET /brain/ideas/:id Get idea
PUT /brain/ideas/:id Update idea
DELETE /brain/ideas/:id Delete idea
GET/PUT /brain/ideas/idealoom/settings Get or update local IdeaLoom integration settings (disabled by default)
GET/POST /brain/ideas/idealoom/lists List or create machine-local IdeaLoom lists
GET/PUT/DELETE /brain/ideas/idealoom/lists/:id Read, update, or delete a machine-local IdeaLoom list
POST /brain/ideas/idealoom/import Explicitly import valid IdeaLoom Markdown from the configured Obsidian vault
POST /brain/ideas/idealoom/sync Explicitly export all lists, or one list (listId), to the configured Obsidian vault. recreateMissing: true is the only way to rewrite a note deleted in the vault — automatic sync never sets it
GET /brain/admin List admin tasks
POST /brain/admin Create admin task
GET /brain/admin/:id Get admin task
PUT /brain/admin/:id Update admin task
DELETE /brain/admin/:id Delete admin task
GET /brain/digest/latest Get latest daily digest
GET /brain/review/latest Get latest weekly review
POST /brain/digest/run Trigger daily digest
POST /brain/review/run Trigger weekly review
GET /brain/settings Get Brain settings
PUT /brain/settings Update Brain settings
GET /brain/summary Get brain statistics summary
GET /brain/reconcile/manifest Per-record parity manifest ({ id, updatedAt, deleted } per entity type) a peer audits against — ids and clocks only, no record bodies
GET /brain/reconcile/parity Last stored parity report per peer (local read, no peer I/O)
POST /brain/reconcile/parity Run the record-level parity audit — body { peerId? }, omitted sweeps every federating peer

Brain Links

Method Endpoint Description
GET /brain/links List saved links
GET /brain/links/:id Get link details
POST /brain/links Save a new link
PUT /brain/links/:id Update link
DELETE /brain/links/:id Delete link
POST /brain/links/:id/clone Clone GitHub repo
POST /brain/links/:id/pull Pull updates for cloned repo
POST /brain/links/:id/open-folder Open cloned repo in file manager

File Uploads

Method Endpoint Description
GET /uploads List all uploaded files
POST /uploads Upload file (base64)
GET /uploads/:filename Download/serve file
DELETE /uploads/:filename Delete file
DELETE /uploads?confirm=true Delete all files

Task Attachments

Method Endpoint Description
GET /attachments List all attachments
POST /attachments Upload task attachment
GET /attachments/:filename Download attachment
DELETE /attachments/:filename Delete attachment

Digital Twin

Method Endpoint Description
GET /digital-twin/documents List all documents
GET /digital-twin/documents/:id Get document content
POST /digital-twin/documents Create document
PUT /digital-twin/documents/:id Update document
DELETE /digital-twin/documents/:id Delete document
GET /digital-twin/categories List document categories
GET /digital-twin/export Export twin in various formats
POST /digital-twin/tests/run Run behavioral tests
GET /digital-twin/tests/results Get test results
GET /digital-twin/enrichment/categories List enrichment categories
POST /digital-twin/enrichment/generate Generate content from answers
GET /digital-twin/traits Get extracted personality traits
POST /digital-twin/traits/analyze Analyze traits from documents
GET /digital-twin/confidence Get confidence scores
POST /digital-twin/confidence/calculate Calculate confidence
GET /digital-twin/gaps Get enrichment recommendations
GET /digital-twin/completeness Get completeness validation
POST /digital-twin/contradictions Detect contradictions
POST /digital-twin/import/spotify/browser/open Open Spotify privacy page in the managed browser
POST /digital-twin/import/spotify/browser/import Request/read the Spotify browser export and analyze it
POST /digital-twin/import/analyze Analyze external data import
POST /digital-twin/import/save Save analyzed import as document

Agent Personalities

Method Endpoint Description
GET /agents/personalities List all agent personalities
GET /agents/personalities/:id Get personality details
POST /agents/personalities Create personality
PUT /agents/personalities/:id Update personality
DELETE /agents/personalities/:id Delete personality
POST /agents/personalities/generate AI-generate personality
POST /agents/personalities/:id/toggle Toggle personality active state

Platform Accounts

Method Endpoint Description
GET /agents/accounts List linked platform accounts
GET /agents/accounts/:id Get account details
POST /agents/accounts Link new account
DELETE /agents/accounts/:id Unlink account
POST /agents/accounts/:id/test Test account connection
POST /agents/accounts/:id/claim Claim account for an agent

Automation Schedules

Method Endpoint Description
GET /agents/schedules List all schedules
GET /agents/schedules/stats Get schedule statistics
GET /agents/schedules/:id Get schedule details
POST /agents/schedules Create schedule
PUT /agents/schedules/:id Update schedule
DELETE /agents/schedules/:id Delete schedule
POST /agents/schedules/:id/toggle Toggle schedule on/off
POST /agents/schedules/:id/run Run schedule immediately

Agent Activity

Method Endpoint Description
GET /agents/activity List activity logs
GET /agents/activity/timeline Get activity timeline
GET /agents/activity/agent/:agentId Get agent's activity
GET /agents/activity/agent/:agentId/stats Get agent statistics
POST /agents/activity/cleanup Clean up old activity logs
GET /agents/activity/run-events Read the append-only CoS run lifecycle ledger (filters: runId, agentId, taskId, kind, since, limit)
GET /agents/activity/run-events/stats Ledger generation sizes and the count + age retention bounds
GET /agents/activity/run-events/projections Current run status derived by replaying the ledger
GET /agents/activity/run-events/run/:id One run's projection plus the events behind it
GET /agents/activity/run-events/reconcile Where the ledger and the durable run records disagree (filters: runId, limit) — read-only
POST /agents/activity/run-events/reconcile Close the run records the ledger proves are finished; reports what it closed

Notifications

Method Endpoint Description
GET /notifications List notifications
GET /notifications/count Get unread count
GET /notifications/counts Get counts by type
POST /notifications/:id/read Mark as read
POST /notifications/read-all Mark all as read
DELETE /notifications/:id Delete notification
DELETE /notifications Clear all notifications

Media (Audio/Video Capture)

Method Endpoint Description
GET /media/devices List available media devices
GET /media/status Get capture status
POST /media/start Start capture
POST /media/stop Stop capture
GET /media/video Get video stream
GET /media/audio Get audio stream

Browser Management

Method Endpoint Description
GET /browser Get browser status
GET /browser/config Get browser configuration
PUT /browser/config Update browser configuration
POST /browser/launch Launch browser instance
POST /browser/stop Stop browser instance
POST /browser/restart Restart browser instance
POST /browser/navigate Navigate browser to URL
GET /browser/health Get browser health status
GET /browser/process Get browser process info
GET /browser/pages Get open browser pages
GET /browser/version Get browser version info
GET /browser/logs Get browser logs

Meatspace Genome

Method Endpoint Description
GET /meatspace/genome Get genome summary
POST /meatspace/genome/upload Upload 23andMe genome file
POST /meatspace/genome/scan Scan curated SNP markers
POST /meatspace/genome/search Search SNP by rsid
GET /meatspace/genome/markers Get scanned markers
GET /meatspace/genome/markers/:rsid Get single marker details
PUT /meatspace/genome/markers/:rsid/notes Update marker notes
POST /meatspace/genome/markers/:rsid/save Save marker to genome.json
DELETE /meatspace/genome/markers/:rsid Remove saved marker
GET /meatspace/genome/categories Get marker categories
GET /meatspace/genome/clinvar/:rsid Lookup ClinVar data for rsid
GET /meatspace/genome/epigenetic Get epigenetic interventions
POST /meatspace/genome/epigenetic Add epigenetic intervention
PUT /meatspace/genome/epigenetic/:id Update intervention
DELETE /meatspace/genome/epigenetic/:id Delete intervention
POST /meatspace/genome/epigenetic/:id/log Log intervention entry

Moltworld Agent Tools

Method Endpoint Description
POST /agents/tools/moltworld/join Join/move agent in world
POST /agents/tools/moltworld/explore Get nearby entities
POST /agents/tools/moltworld/build Place/remove blocks
POST /agents/tools/moltworld/think Display thinking bubble
POST /agents/tools/moltworld/say Send chat message
GET /agents/tools/moltworld/status Get world status

Route Domain Index

Every mounted API prefix (see server/index.js for the authoritative list). Domains documented in detail above are omitted. Each prefix corresponds to a router in server/routes/.

Prefix Domain
/api/auth Optional password gate
/api/alerts System alerts
/api/avatar Avatar rendering/config
/api/system System health metrics
/api/system/capabilities Local hardware capabilities for model/provider selection
/api/system-resources System storage report and AI-assisted cleanup triage
/api/remote-desktop, /remote-desktop PortDeck remote desktop session broker and viewer
/api/capabilities Feature capability flags
/api/agent-context Opt-in, loopback-only MCP context plus separately granted semantic PortOS actions
/api/workspace-contexts Workspace context management
/api/apps/:appId/reference-repos Per-app reference repos
/api/network-exposure Network exposure checks
/api/history User/system action history log
/api/commands Allowlisted command execution
/api/git Git operations for managed apps
/api/screenshots Screenshot capture
/api/search Global search
/api/rapid-reader Rapid reader library and Accelerando source cache
/api/palette ⌘K command palette manifest + actions
/api/dashboard/layouts Dashboard widget layouts
/api/dashboard/daily-actions Dashboard daily action tracking
/api/media/collections, /api/media/annotations, /api/media/sketches Media library collections/annotations/sketches
/api/client-errors Client-side error reporting
/api/backup Backup snapshots + restore
/api/legacy-export Legacy data export
/api/database Postgres introspection
/api/image-clean Image metadata cleaning
/api/eidoverse/world Private Eidoverse identity, projection, presence, augmentation, and chat adapter
/api/openworld, /api/city Legacy OpenWorld/CyberCity snapshots and introspection
/api/cos/gsd CoS GSD workflow
/api/feature-agents Feature agent runs
/api/feeds RSS/content feeds
/api/catalog Creative ingredients catalog
/api/tribe Tribe relationship graph
/api/notes Notes
/api/calendar Calendar integration
/api/messages Messages (email) integration
/api/digital-twin/social-accounts, /api/digital-twin/identity, /api/digital-twin/autobiography Digital-twin sub-domains
/api/meatspace MeatSpace (health, POST, genome)
/api/lmstudio, /api/local-llm Local LLM backends and the local runtime servers PortOS can start/stop (Ollama, LM Studio, llama-server, MTPLX — the last two as PM2 processes; POST /api/local-llm/save-startup is pm2 save), plus MTPLX's checkpoint catalog — GET /api/local-llm/mtplx/models/search, POST .../models/pull (byte progress on the mtplx:download socket event), POST .../models/remove
/api/code-review Code review runs
/api/voice, /api/voice/public Voice assistant
/api/api-docs Generated HTTP/event catalogs, OpenAPI 3.0.3 documents, AsyncAPI 3 document, and the minimized semantic tool resource
/api/data Data manager/sync
/api/datadog, /api/jira, /api/github, /api/telegram External integrations
/api/health Apple Health metrics, ingest, and XML import
/api/insights Cross-domain insights
/api/instances, /api/sync, /api/peer-sync, /api/sharing Federation / peer sync (see COMPANION_APP_API.md)
/api/federation/media/v1 Authenticated queued peer audio provider (see FEDERATED_MEDIA_PROVIDERS.md)
/api/mortalloom MortalLoom (iCloud-JSON sync precedent)
/api/review Review queue
/api/settings App settings
/api/update Self-update flow
/api/loops Loops
/api/character Character management
/api/tools Agent tool registry
/api/image-gen, /api/video-gen, /api/image-video/models Image/video generation
/api/devtools/video-download Video download
/api/video-timeline Video timeline editor
/api/media-jobs Async media job queue
/api/creative-director Creative Director projects
/api/fableloom FableLoom interactive story generation
/api/music-video Music video projects
/api/mood-boards Mood boards
/api/writers-room Writers Room
/api/universe-builder Universe Builder
/api/authors, /api/artists, /api/albums, /api/tracks, /api/music Music/creator catalogs
/api/pipeline Series/comic pipeline
/api/conflict-journal Sync conflict journal
/api/importer Story importer
/api/story-builder Story Builder
/api/loras, /api/lora-datasets, /api/lora-training LoRA management/training
/sdapi/v1 AUTOMATIC1111-compatible image generation surface (gated by settings.imageGen.expose.a1111)
/api/openclaw OpenClaw operator chat
/api/rounds Rounds (music + Morse training)
/api/ask Ask (LLM Q&A)
/api/quota-burn Quota-burn plan, catalog, and runs
/api/timeline Human-activity timeline (day + events)
/api/games Game projects
/api/sprites Sprite catalog / export
/api/threejs-models Procedural Three.js models
/api/image-to-3d Image-to-3D conversion
/api/privacy PII vault / trusted-org / broker opt-out
/api/shell Browser PTY shells
/api/ports Port scan / allocation
/api/logs PM2 process logs
/api/detect App-repo detection
/api/scaffold App scaffolding
/api/usage Provider usage / quota
/api/daily-driver Daily-driver snapshot
/api/attachments Task / CoS file attachments
/api/autofix Autofixer metrics
/api/uploads Generic uploads
/api/agents Agent process management (personalities, accounts, schedules, activity, tools)
/api/agents/tools/moltworld, /api/agents/tools/moltworld/ws MoltWorld agent tools and WebSocket
/api/cos Chief of Staff
/api/memory Memory CRUD / search
/api/brain, /api/brain/import Brain (second brain) and document import
/api/media Media library
/api/imessage, /api/contacts, /api/signal, /api/spotify, /api/youtube Personal-data ingest
/api/notifications Notification stream
/api/standardize App PM2 standardizer
/api/stacker-news, /api/x Social integrations
/api/model-personality LLM personality tests
/api/browser Managed Chromium
/api/creative-commission Creative commissions
/api/midi-runtime MIDI runtime

WebSocket Events

Connect to Socket.IO at http://localhost:5555.

The complete generated event list is visible in API Explorer → Event API and available at GET /api/api-docs/asyncapi.json as AsyncAPI 3. The examples below highlight common flows rather than serving as the exhaustive inventory.

Log Streaming

// Subscribe to process logs
socket.emit('logs:subscribe', { processName: 'portos-server', lines: 100 });

// Receive log lines
socket.on('logs:line', ({ processName, line }) => {
  console.log(`[${processName}] ${line}`);
});

// Unsubscribe
socket.emit('logs:unsubscribe', { processName: 'portos-server' });

Error Notifications

Server errors are broadcast to all connected sockets — no subscription handshake is needed.

// Receive error events
socket.on('error:occurred', (error) => {
  console.error('Server error:', error.message, error.code);
});

Chief of Staff Events

// Join the CoS room to receive agent lifecycle events
socket.emit('cos:subscribe');

socket.on('cos:agent:spawned', (agent) => {
  console.log('Agent spawned:', agent.id, agent.task);
});

socket.on('cos:agent:updated', (agent) => {
  console.log('Agent updated:', agent.id, agent.status);
});

socket.on('cos:agent:completed', (agent) => {
  console.log('Agent completed:', agent.id, agent.success);
});

socket.on('cos:agent:output', ({ agentId, lines }) => {
  console.log('Agent output:', agentId, lines);
});

Memory Events

socket.on('memory:created', (memory) => {
  console.log('Memory created:', memory.id);
});

socket.on('memory:updated', (memory) => {
  console.log('Memory updated:', memory.id);
});

socket.on('memory:deleted', ({ id }) => {
  console.log('Memory deleted:', id);
});

App Detection (Streaming)

// Start streaming detection
socket.emit('detect:start', { path: '/path/to/repo' });

// Receive discovery steps
socket.on('detect:step', (step) => {
  console.log('Discovered:', step.field, step.value);
});

// Detection complete
socket.on('detect:complete', (appData) => {
  console.log('Detection complete:', appData);
});

Shell Terminal

Security: The shell WebSocket API provides full terminal access as the PortOS process user. It relies on PortOS's network-level access control (see Security Model) — do not expose the PortOS server to untrusted networks.

// Start a shell session — the server assigns the id and replies with shell:started
socket.emit('shell:start', {});
socket.on('shell:started', ({ sessionId }) => console.log('session', sessionId));

// Send input to shell. Submit with `\r` (the byte Enter sends), never `\n` — cmd.exe
// under Windows ConPTY ignores LF and the line is typed but never executed.
socket.emit('shell:input', { sessionId, data: 'ls -la\r' });

// Receive shell output
socket.on('shell:output', ({ sessionId, data }) => {
  console.log(data); // Terminal output
});

// Change directory — send the PATH, not a command. The server renders the `cd` for
// the shell this session runs (`cd /d "…"` on cmd.exe, Set-Location on PowerShell).
socket.emit('shell:cd', { sessionId, path: '/path/to/app' });

// Resize terminal
socket.emit('shell:resize', { sessionId, cols: 120, rows: 40 });

// Stop shell session
socket.emit('shell:stop', { sessionId });

Provider Status

// Provider availability changed
socket.on('provider:status:changed', ({ providerId, status, reason }) => {
  console.log(`Provider ${providerId}: ${status}`, reason);
});

Request Examples

Register an App

curl -X POST http://localhost:5555/api/apps \
  -H "Content-Type: application/json" \
  -d '{
    "name": "My App",
    "repoPath": "/path/to/repo",
    "uiPort": 3000,
    "apiPort": 3001,
    "pm2ProcessNames": ["myapp-server", "myapp-client"]
  }'

Execute AI Run

curl -X POST http://localhost:5555/api/runs \
  -H "Content-Type: application/json" \
  -d '{
    "prompt": "List all files in the current directory",
    "workspacePath": "/path/to/workspace"
  }'

Get PM2 Process Logs

curl http://localhost:5555/api/logs/portos-server?lines=50

Error Responses

All errors return JSON with consistent structure:

{
  "error": "Error message",
  "code": "ERROR_CODE",
  "timestamp": 1704067200000,
  "context": {}
}

Common error codes:

  • NOT_FOUND - Resource not found
  • VALIDATION_ERROR - Invalid request data
  • COMMAND_NOT_ALLOWED - Shell command not in allowlist
  • INTERNAL_ERROR - Server error