Skip to content
Masterplanner25Public

About

standalone aindy-sdk repo

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

aindy-sdk

Universal interface SDK for the A.I.N.D.Y. runtime API.

aindy-sdk is the local+cloud bridge: the same client code works against a locally-installed runtime (where the operator owns the infrastructure) and a cloud-hosted runtime (where the provider owns the infrastructure). Switching deployment context requires only a base_url change — no application code changes.

Part of the Masterplan Infinite Weave ecosystem by Shawn Knight. Runtime infrastructure: https://github.com/Masterplanner25/aindy-runtime

Install

pip install aindy-sdk

Requirements

  • Python 3.11+
  • No external dependencies (stdlib only) for the API client
  • Watcher subpackage optional dependencies: psutil (fallback window detection), pyobjc-framework-AppKit + pyobjc-framework-Quartz (macOS window titles), xdotool system package (Linux window detection)

Getting started

1. Start the runtime

Install and start aindy-runtime (full instructions):

git clone https://github.com/Masterplanner25/aindy-runtime.git
cd aindy-runtime
cp AINDY/.env.example AINDY/.env   # set SECRET_KEY and OPENAI_API_KEY at minimum
docker compose up -d

Wait until the server is ready:

curl http://localhost:8000/ready    # → {"status": "ok", ...}

2. Register and log in

# Register. Returns 202 with no token: registration does not log you in.
# Passwords must be at least 8 characters.
curl -s -X POST http://localhost:8000/auth/register \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "password": "yourpassword", "username": "you"}' \
  | python -m json.tool

# Log in — copy the access_token from the response
curl -s -X POST http://localhost:8000/auth/login \
  -H "Content-Type: application/json" \
  -d '{"email": "[email protected]", "password": "yourpassword"}' \
  | python -m json.tool

Promote your account to admin, which POST /platform/keys requires:

# Using the CLI (no server restart needed). In a compose deployment it runs inside the container:
docker compose exec api aindy-runtime auth promote-admin [email protected]

# Or via env var (requires server restart)
# Add [email protected] to AINDY/.env, then docker compose restart api

3. Create a Platform API key

Platform API keys start with aindy_ and are shown only once — save the key field.

JWT="<your-access_token>"

curl -s -X POST http://localhost:8000/platform/keys \
  -H "Authorization: Bearer $JWT" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "my-app",
    "scopes": ["memory.read", "memory.write", "flow.execute", "event.emit"]
  }' \
  | python -m json.tool

The scopes this SDK's calls use:

Scope Grants access to
memory.read Read and search memory nodes (client.memory.read/search/list/tree/trace)
memory.write Write memory nodes (client.memory.write). It also grants read, but not delete
flow.execute Run registered flows and Nodus scripts (client.flow.run, client.nodus)
event.emit Emit events to the event bus (client.events.emit)
execution.read Read execution unit status (client.execution.get)
platform.admin Full platform admin, which passes every scope check

The runtime's README has the complete set. An unknown scope is a 422. Grant a key only what it needs.

4. First call

from aindy_sdk import AINDYClient

client = AINDYClient(
    base_url="http://localhost:8000",
    api_key="aindy_your_platform_key",
)

result = client.memory.read("/memory/you/notes/**", limit=5)
print(result["data"]["nodes"])

Run the full example:

AINDY_API_KEY=aindy_... python examples/quickstart.py

Usage

from aindy_sdk import AINDYClient

# Local runtime (operator owns infrastructure)
client = AINDYClient(
    base_url="http://localhost:8000",
    api_key="aindy_your_platform_key",
)

# Cloud-hosted — same code, different base_url
# client = AINDYClient(base_url="https://runtime.aindy.ai", api_key="...")

# Read memory
result = client.memory.read("/memory/shawn/entities/**", limit=5)
nodes = result["data"]["nodes"]

# Run a flow
analysis = client.flow.run("analyze_entities", {"data": nodes})

# Write memory
client.memory.write(
    "/memory/shawn/insights/outcome",
    analysis["data"].get("summary", ""),
    tags=["sdk-demo"],
)

# Emit an event
client.events.emit("analysis.completed", {"node_count": len(nodes)})

API reference

All capabilities are accessed through namespaces on AINDYClient:

Namespace Description
client.memory Read, write, and search memory nodes by MAS path or vector similarity
client.flow Run a registered flow and get its result
client.events Emit events to the runtime event bus
client.nodus Compile and execute Nodus scripts
client.syscalls List and inspect the syscall registry
client.execution Introspect in-flight or completed execution units
client.sandbox Query sandbox assurance posture

Every method returns a syscall envelope:

{
    "status":      "success",        # "success" or "error"
    "data":        { ... },          # payload — varies by call
    "trace_id":    "abc123...",      # for log correlation
    "duration_ms": 12,               # server-side execution time in ms
    "error":       None,             # error description when status == "error"
}

Memory (client.memory)

# Read nodes at a MAS path (glob patterns supported)
result = client.memory.read("/memory/shawn/entities/**", limit=10)
nodes = result["data"]["nodes"]

# Write a node
result = client.memory.write(
    "/memory/shawn/insights/daily-summary",
    "Worked on SDK documentation today.",
    tags=["insight", "daily"],
    node_type="insight",
)
node_id = result["data"]["node"]["id"]

# Semantic similarity search
result = client.memory.search("recent project decisions", limit=5)

Flow (client.flow)

# Run a registered flow and get its result (synchronous)
result = client.flow.run("analyze_entities", {"data": nodes})
output = result["data"]

Events (client.events)

# Emit an event (can trigger waiting flows)
result = client.events.emit(
    "user.action.completed",
    {"user_id": "u-123", "action": "document_saved"},
)

Nodus (client.nodus)

# Execute a Nodus script
result = client.nodus.run_script(
    script="""
let greeting = "Hello from Nodus"
set_state("message", greeting)
emit("script.hello", {text: greeting})
""",
    input={},
)
print(result["nodus_status"])      # "complete" | "wait" | "error"
print(result["output_state"])      # dict of set_state() calls
print(result["events_emitted"])    # count of emit() calls

Execution (client.execution)

run = client.execution.get("run-abc123")
status = run["data"]["status"]          # "running" | "success" | "failed" | "waiting"
syscall_count = run["data"]["syscall_count"]
wall_time_ms = run["data"]["wall_time_ms"]  # accumulated wall-clock time (includes I/O wait)

Syscalls (client.syscalls)

registry = client.syscalls.list(version="v1")
print(registry["total_count"])
for action, spec in registry["syscalls"]["v1"].items():
    deprecated = " [DEPRECATED]" if spec.get("deprecated") else ""
    print(f"sys.v1.{action}{deprecated}")

Error handling

The SDK maps HTTP status codes to typed exceptions so you can handle failure cases explicitly rather than inspecting status codes:

from aindy_sdk import AINDYClient
from aindy_sdk.exceptions import (
    AuthenticationError,    # 401 — key missing, invalid, or expired
    PermissionDeniedError,  # 403 — key scope doesn't include this capability
    NotFoundError,          # 404 — resource doesn't exist
    ValidationError,        # 422 — bad request shape or schema violation
    ResourceLimitError,     # 429 — syscall count or wall_time_ms exceeded
    ServerError,            # 5xx — unexpected runtime error
    NetworkError,           # connection refused, timeout, or DNS failure
    AINDYError,             # base class — catches all of the above
)

client = AINDYClient(base_url="http://localhost:8000", api_key="aindy_...")

try:
    result = client.memory.read("/memory/shawn/entities/**", limit=5)
except AuthenticationError:
    print("Invalid API key — check AINDY_API_KEY")
except PermissionDeniedError as exc:
    print(f"Key scope missing: {exc.message}")
    # exc.response contains the full server error payload
except ValidationError as exc:
    print(f"Bad request: {exc.message}")
except NetworkError as exc:
    print(f"Server unreachable: {exc.cause}")
except AINDYError as exc:
    print(f"Runtime error [{exc.status_code}]: {exc.message}")

All typed errors carry:

  • .message — human-readable description
  • .status_code — HTTP status code (None for NetworkError)
  • .response — raw server JSON dict

Watcher

The SDK ships the A.I.N.D.Y. Watcher client process. The watcher runs on your machine, observes the active OS window, classifies your activity, and emits structured signals to the runtime for flow triggering and session tracking.

First mint your own watcher key. Any signed-in user can, and it needs runtime 2.31.4 or later. The key is shown once, works only on the watcher's routes, and acts only for you:

curl -s -X POST http://localhost:8000/watcher/keys \
  -H "Authorization: Bearer <your-jwt>" \
  -H "Content-Type: application/json" \
  -d '{"name": "my-laptop"}' \
  | python -m json.tool
# List your keys: GET /watcher/keys. Revoke one: DELETE /watcher/keys/{id}
# Start the watcher (requires AINDY_WATCHER_KEY and AINDY_WATCHER_API_URL)
aindy-watcher

# Dry run — logs signals, no HTTP requests
aindy-watcher --dry-run

# Custom poll interval and verbose logging
aindy-watcher --poll-interval 10 --log-level DEBUG

# Without the script on PATH (1.2.0+), or on 1.1.0 and earlier: python -m aindy_sdk.watcher.watcher
python -m aindy_sdk.watcher

When a session ends (1.2.0+). The session_ended signal says why in metadata.end_reason:

  • input_idle: no keyboard or mouse input for AINDY_WATCHER_IDLE_TIMEOUT seconds. The session ends at the last input, so the idle stretch counts as neither duration nor focus. This works on Windows and macOS, and on Linux under X11 with xprintidle installed; elsewhere the watcher logs that it is unavailable at startup.
  • idle: a lock screen, the logon screen, a screensaver, or no window in front.
  • stopped: the watcher was stopped (Ctrl+C or SIGTERM). Closing its console window kills it without a stop, so no signal is sent.

metadata.focused_seconds is the time spent working between samples, and focus_score is that over duration_seconds. Before 1.2.0 both were inflated (see the changelog).

Your own app lists (1.2.0+). Each of these is a comma-separated list of app (process) names, matched case-insensitively as a substring. A name you add is checked before every built-in list, so AINDY_WATCHER_WORK_APPS=spotify makes Spotify work. -name removes a built-in entry.

AINDY_WATCHER_WORK_APPS="blender, davinci, spotify"
AINDY_WATCHER_DISTRACTION_APPS="-music"
AINDY_WATCHER_DISTRACTION_TITLES="the onion, -reddit"   # window-title text, in a browser
AINDY_WATCHER_BROWSER_APPS="librewolf"

Environment variables:

Variable Default Description
AINDY_WATCHER_API_URL http://localhost:8000 Runtime base URL
AINDY_WATCHER_KEY (required on your machine) Your own key from POST /watcher/keys (X-Platform-Key header). Needs runtime 2.31.4 or later
AINDY_API_KEY (services only) The deployment's shared key (X-API-Key header), used when AINDY_WATCHER_KEY is unset. It can act for any user, so don't install it on a user's machine
AINDY_WATCHER_DRY_RUN false Log signals only, no HTTP POST
AINDY_WATCHER_POLL_INTERVAL 5 Seconds between window samples
AINDY_WATCHER_FLUSH_INTERVAL 10 Seconds between signal batch flushes
AINDY_WATCHER_BATCH_SIZE 20 Signals per POST batch
AINDY_WATCHER_CONFIRMATION_DELAY 30 Seconds of focus before session_started fires
AINDY_WATCHER_DISTRACTION_TIMEOUT 60 Seconds of off-task time before distraction state
AINDY_WATCHER_RECOVERY_DELAY 30 Seconds of focus to recover from distraction
AINDY_WATCHER_HEARTBEAT_INTERVAL 300 Seconds between heartbeat signals
AINDY_WATCHER_IDLE_TIMEOUT 300 Seconds without keyboard or mouse input before the session ends. 0 turns it off. 1.2.0+
AINDY_WATCHER_WORK_APPS, _DISTRACTION_APPS, _COMMUNICATION_APPS, _IDLE_APPS, _BROWSER_APPS (built-in lists) Comma-separated app names; -name removes a built-in. 1.2.0+
AINDY_WATCHER_DISTRACTION_TITLES (built-in list) Browser window-title text that marks a distraction; -text removes a built-in. 1.2.0+
AINDY_WATCHER_LOG_LEVEL INFO DEBUG | INFO | WARNING | ERROR

This repo's examples/watcher_demo.py is a dry-run demonstration. It is not in the installed package; aindy-watcher --dry-run does the same.


Status

Beta. Every payload the SDK sends is checked in CI against the runtime's own schemas (tests/test_wire_contract.py, which installs the latest aindy-runtime). The watcher's own key needs runtime 2.31.4 or later.

Security issues: see SECURITY.md.

About

standalone aindy-sdk repo

Resources

Security policy

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages