Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

API Specification

1. Purpose

The PsyDian API layer is part of the host-side AI Bridge rather than the bare-metal kernel.

The kernel does not directly expose a conventional HTTP API in the MVP. Instead, communication is separated into two boundaries:

PsyDian Kernel
      ↓
Serial / Diagnostic Protocol
      ↓
Host-side AI Bridge
      ↓
HTTPS / REST API
      ↓
External AI Service

This separation keeps network communication outside the privileged kernel.


2. API Scope

The API specification covers the interface used by the host-side AI Bridge to communicate with the configured external AI service.

The kernel-to-AI-Bridge communication protocol is specified separately because it is a local diagnostic/communication channel rather than a conventional HTTP REST API.

The API layer is responsible for:

  • Sending AI assistance requests.
  • Sending structured diagnostic context.
  • Receiving AI responses.
  • Handling authentication with the selected provider.
  • Handling validation failures.
  • Handling timeouts and dependency failures.
  • Preventing provider-specific details from leaking into the kernel.

3. Base Configuration

The external AI API configuration shall be supplied to the AI Bridge through environment/configuration rather than hard-coded source code.

Conceptually:

AI_PROVIDER
AI_BASE_URL
AI_MODEL
AI_API_KEY
AI_TIMEOUT
API_VERSION

Sensitive values such as API keys must not be stored in:

  • Kernel source code.
  • Git history.
  • Bootable kernel images.
  • Public logs.

The exact variable names will depend on the selected AI provider.


4. AI Bridge Internal API

The AI Bridge should expose a small internal interface between its protocol/diagnostic layer and its provider-specific AI client.

Conceptually:

Diagnostic Processor
        ↓
AI Client Interface
        ↓
Provider Adapter
        ↓
External AI API

Possible operations:

send_request()
validate_request()
parse_response()
validate_response()

The exact implementation may use Rust functions, traits, modules, or another appropriate abstraction.


5. Diagnostic Request API

5.1 Purpose

Used when PsyDian sends diagnostic information for AI-assisted analysis.

Conceptual operation:

POST /chat/completions

The actual endpoint shall be determined by the selected AI provider.

5.2 Request Concept

The AI Bridge shall construct the provider-specific request from validated PsyDian context.

Conceptual internal request:

{
  "requestType": "diagnostic_analysis",
  "diagnostic": {
    "severity": "error",
    "subsystem": "memory",
    "message": "Heap allocation failed"
  },
  "userQuery": "Why did this happen and how should I investigate it?"
}

This is an internal logical model. The provider-specific HTTP request may use a different schema.


6. AI Prompt Context

The AI Bridge should construct a controlled context containing only information relevant to the requested analysis.

Possible context:

{
  "system": {
    "name": "PsyDian",
    "architecture": "x86_64"
  },
  "diagnostic": {
    "severity": "error",
    "subsystem": "memory",
    "message": "Heap allocation failed"
  },
  "userQuery": "Explain this error"
}

The bridge should not blindly forward arbitrary kernel data.


7. AI Response API

7.1 Purpose

Receives the response generated by the configured AI provider.

The provider-specific response may contain:

  • Generated explanation.
  • Suggested troubleshooting steps.
  • Optional command suggestions.
  • Metadata.
  • Usage information.

The AI Bridge shall convert provider-specific data into a provider-independent internal response.

Conceptual internal response:

{
  "type": "ai_response",
  "version": 1,
  "summary": "The kernel encountered a heap allocation failure.",
  "suggestions": [
    "Inspect allocator state",
    "Check available heap memory"
  ],
  "commands": [],
  "requiresConfirmation": false,
  "limitations": []
}

8. Kernel ↔ AI Bridge Protocol

The local communication boundary is intentionally separate from the external REST API.

8.1 Message Types

The MVP may support:

AI_REQUEST
DIAGNOSTIC
AI_RESPONSE
ERROR
STATUS

8.2 Generic Message Envelope

{
  "type": "diagnostic",
  "version": 1,
  "id": "diag-001",
  "payload": {}
}

8.3 Diagnostic Message Example

{
  "type": "diagnostic",
  "version": 1,
  "id": "diag-001",
  "payload": {
    "severity": "error",
    "subsystem": "memory",
    "message": "Heap allocation failed"
  }
}

8.4 AI Response Message Example

{
  "type": "ai_response",
  "version": 1,
  "id": "resp-001",
  "payload": {
    "summary": "The heap allocation request could not be satisfied.",
    "suggestions": [
      "Inspect allocator state"
    ],
    "commands": [],
    "requiresConfirmation": false
  }
}

8.5 Framing and Encoding (Implemented, Kernel Side)

The kernel side of the protocol is implemented in kernel/src/protocol/.

Transport. Messages travel over the first serial port (COM1, 38400 baud, 8N1). In QEMU this is the -serial device, so the AI Bridge can attach to it through stdio, a PTY, or a socket.

Framing. The same serial line also carries ordinary console text (boot logs, shell prompt and output). A protocol message is therefore sent as a frame:

@PSY <JSON envelope>\n
  • A frame starts at the marker @PSY (including the space) and ends at the next line feed.
  • Everything on the serial line that is not part of a frame is human-readable console output and must be ignored by the bridge.
  • The envelope is a single line of UTF-8 JSON. Strings are escaped, so a frame never contains a raw line break.
  • An encoded message is at most 2048 bytes. The kernel drops a larger message instead of sending truncated JSON.
  • The bridge should look for the marker anywhere in a line, not only at its start, because a frame may be written while the cursor is at the shell prompt.

Messages the kernel sends.

Diagnostic record (sent whenever a diagnostic is reported, and again on diag send):

{"type":"diagnostic","version":1,"id":"diag-002","payload":{"severity":"error","subsystem":"memory","code":"MEM-003","uptime_ms":2070,"message":"Heap allocation failed","context":{"size":"67108864","align":"8","heap_size":"1048576","heap_used":"0"}}}
Payload fieldMeaning
severityinfo, warn, error or panic
subsystemboot, kernel, memory, interrupt, input, serial, shell, diagnostic or ai
codeStable error code (see Observability, section 11)
uptime_msMilliseconds since boot when the record was created
messageHuman-readable description
contextObject of string keys and string values; may be empty

AI request (sent by the ai <question> shell command):

{"type":"ai_request","version":1,"id":"req-001","payload":{"query":"why did the heap allocation fail?","diagnostic_id":"diag-002"}}

diagnostic_id names the most recent diagnostic record, or is null when none exists.

Status (sent once when the shell is ready for input):

{"type":"status","version":1,"id":"stat-001","payload":{"state":"ready","kernel":"0.1.0","uptime_ms":20}}

Messages the kernel receives (implemented, kernel/src/protocol/inbound.rs). The bridge writes frames to the kernel’s serial input with the same marker:

@PSY <JSON envelope>\n
  • A frame is recognised only when the marker starts a line, so text a user types is never mistaken for a frame. The bridge should therefore send a line break before the marker when it is unsure where the line stands.
  • A frame ends at \n or \r (a following \n is ignored). Frame bytes never reach the shell as keystrokes.
  • Frames sent to the kernel must be printable ASCII (0x20-0x7e) and at most 2048 bytes; use JSON \uXXXX escapes for anything else. A frame with other bytes, or a longer one, is discarded.
  • The interrupt handler only stores the raw line (up to 2 waiting frames). Parsing and validation run later, when ai waits for its answer.

AI response. The envelope id is the id of the request being answered (req-NNN):

{"type":"ai_response","version":1,"id":"req-001","payload":{"summary":"The heap allocator could not find a free block of the requested size.","suggestions":["Run meminfo to see heap usage"],"commands":["meminfo"],"requiresConfirmation":false}}
Payload fieldRule
summaryRequired, non-empty string, at most 480 characters
suggestionsOptional array of at most 4 strings, each at most 160 characters
commandsOptional array of at most 3 strings, each at most 80 characters. Shown numbered, each with its risk level. Nothing runs unless the user types run <number> (section 15)
requiresConfirmationOptional boolean, default false. When true, every suggested command asks for a y/N confirmation before it runs, even a safe one

Unknown payload fields (for example limitations) are ignored. Values that are too long are rejected, never truncated.

Bridge error. id may be the request id; otherwise the payload may name it in request_id. An error without a request id is applied to the request currently waiting:

{"type":"error","version":1,"id":"err-001","payload":{"code":"AI_TIMEOUT","message":"The AI service request timed out.","request_id":"req-001"}}

code is required (at most 32 characters, see section 9); message is optional (at most 200 characters).

Bridge status. A status frame such as {"type":"status","version":1,"id":"stat-001","payload":{"state":"bridge_ready"}} tells the kernel a bridge is attached. The bridge should send one when it connects.

Validation and failure handling. A frame is accepted only if it is valid JSON (nesting depth at most 8), version is 1, type is ai_response, error or status, and every field follows the rules above. A rejected frame is counted and logged as COMM-002. If it named a request id, the waiting ai command fails immediately with “invalid response” (AI-003) instead of waiting for the timeout.

ai waits 30 seconds for the answer once any bridge has been heard from since boot, or 3 seconds if none has, so the shell never hangs without a bridge. Ctrl+C cancels the wait. Replies to older, abandoned requests are discarded. Text from the bridge is printed with control characters replaced by spaces and non-ASCII characters replaced by ?, so a reply cannot move the cursor or send terminal escape sequences.

OutcomeShell resultLog code
Valid ai_responseSummary, suggestions and numbered suggested commands are printed; nothing runs-
error frameThe bridge’s code and message are printed; command failsAI-001
Invalid reply for this request“invalid response”; command failsAI-003
No reply, bridge seen before“did not answer in time”; command failsAI-002
No reply, no bridge ever seen“no response from the AI Bridge”; command fails-
Ctrl+C“AI request cancelled.”; command fails-

In every case the shell keeps running.


9. Standard Errors

The AI Bridge shall use stable internal error categories so failures can be handled consistently.

Conceptual format:

{
  "error": {
    "code": "AI_TIMEOUT",
    "message": "The AI service request timed out.",
    "requestId": "req-001"
  }
}

Possible error codes:

INVALID_MESSAGE
INVALID_REQUEST
INVALID_RESPONSE
COMMUNICATION_FAILURE
AI_TIMEOUT
AI_SERVICE_UNAVAILABLE
AI_AUTHENTICATION_FAILED
AI_RATE_LIMITED
UNSUPPORTED_OPERATION
VALIDATION_FAILED

User-facing messages should remain understandable and should not expose API credentials, internal stack traces, or unnecessary implementation details.


10. HTTP Status Handling

When communicating with an external REST API, the AI Bridge shall handle provider responses according to their documented status codes.

General handling:

StatusMeaningAI Bridge Behavior
200-299Successful responseParse and validate response
400Invalid requestReport request/validation failure
401Authentication failureReport configuration/authentication error
403ForbiddenReport authorization failure
404Endpoint/resource unavailableReport configuration/provider error
408Request timeoutHandle as timeout
409ConflictHandle according to provider response
429Rate limitedReport or retry using bounded backoff where appropriate
500Provider server errorControlled retry/failure
502/503/504Dependency/service unavailableControlled retry/failure

Provider-specific behavior shall follow the selected API’s documentation.


11. Timeout and Retry Policy

The AI Bridge shall use bounded request timeouts.

Conceptual flow:

AI Request
    ↓
Start Timeout
    ↓
Provider Request
    ├── Success → Validate Response
    ├── Timeout → Controlled Error
    └── Transient Failure → Bounded Retry

Retry behavior should be limited to transient failures and should not create unbounded request loops.

Examples of candidates for bounded retry:

429
502
503
504
network timeout

Authentication and malformed-request errors generally should not be blindly retried.


12. Authentication

The AI Bridge shall authenticate with the selected external AI provider using the provider’s supported authentication mechanism.

Typical architecture:

Environment / Secret Store
          ↓
      AI Bridge
          ↓
 Authentication Header
          ↓
   External AI API

API credentials must:

  • Remain outside source code.
  • Not be sent to the kernel.
  • Not be printed in logs.
  • Not be committed to Git.

13. Request Validation

Before an AI request is sent, the bridge shall validate:

  • Message type.
  • Protocol version.
  • Required fields.
  • Input length.
  • Diagnostic structure.
  • Supported request type.
  • Context size.

Malformed requests shall be rejected.


14. Response Validation

AI responses shall be treated as untrusted external data.

The bridge shall validate:

  • Response structure.
  • Required fields.
  • Data types.
  • Allowed response categories.
  • Suggested command format.
  • Confirmation metadata.
  • Length limits.
  • Provider response status.

Conceptually:

External AI
    ↓
Raw Response
    ↓
Parse
    ↓
Schema Validation
    ↓
Safety Validation
    ↓
Internal AI Response

Malformed responses shall not be treated as valid execution instructions.


15. AI-Suggested Command Handling

If the AI returns a suggested command:

AI Provider
    ↓
AI Bridge
    ↓
Suggested Command
    ↓
PsyDian
    ↓
Shell Parser
    ↓
Command Validation
    ↓
Risk Classification
    ↓
User Confirmation
    ↓
Execution

The API layer must never grant the AI direct command-execution authority.

15.1 How the Kernel Implements It

The kernel stores the commands of the latest valid ai_response (at most 3). They run only when the user types run <number>; run on its own lists them again. A new ai request discards the old list, so an old answer can never be run in reply to a new question.

run <number> applies these checks in order:

  1. Parser. The suggestion is parsed exactly like a typed line. Anything the parser rejects (unterminated quote, ;, invalid name) is blocked.
  2. Registry. The command must exist (exact, case-sensitive name).
  3. Arguments. The argument count must match the command’s usage.
  4. Recursion. A suggestion may not be run itself.
  5. Risk policy. Every command has a fixed risk level (Security design, section 5.2):
RiskCommandsSuggested by the AI
Safehelp, clear, info, meminfo, uptime, echo, history, logs, diag, runRuns at once (asks first if requiresConfirmation is true)
Sensitiveai (sends text to the host)Asks for y/N confirmation
PrivilegedshutdownAsks for y/N confirmation
Destructivepanic-test, fault-testBlocked. The user can still type it, and it then asks for confirmation as usual

A command that passes runs through Shell::execute, the same path a typed line takes. Only an explicit y or yes counts as confirmation.

EventLog code
Suggested command runAI-010 (INFO)
Suggested command blocked by a checkAI-011 (WARN)
Suggested command declined at the confirmationAI-012 (INFO), then CMD-004

Example session:

psydian> ai why did the heap fail?
[AI] Answer to req-002:
  A program asked the kernel heap for 64 MiB, but the whole heap is only 1024 KiB ...
  Suggested commands (nothing runs until you type 'run <number>'):
    1. meminfo                  [safe]
    2. shutdown                 [privileged]
    3. panic-test               [blocked: it is destructive; type it yourself if you really mean it]
psydian> run 1
[AI] Running suggested command: meminfo
Physical memory
  ...
psydian> run 2
[AI] Suggested command: shutdown (risk: privileged, changes the state of the system)
[WARN] This command was suggested by the AI assistant, not typed by you.
Proceed? [y/N] n
Cancelled.
psydian> run 3
[AI] Not running 'panic-test': it is destructive; type it yourself if you really mean it.
[ERROR] The suggested command was blocked.

16. Security Requirements

The API layer shall follow these rules:

  • Never expose the API key to PsyDian.
  • Never embed external API credentials in the kernel.
  • Validate all external responses.
  • Limit the information sent to the external service.
  • Use HTTPS for external communication.
  • Do not trust document/system text as API instructions.
  • Do not allow external responses to bypass local validation.
  • Do not log complete requests when they contain sensitive data.
  • Do not allow external API failures to terminate normal shell operation.

17. Rate Limiting and Resource Control

The AI Bridge should prevent uncontrolled request generation.

Controls may include:

  • Maximum request size.
  • Maximum response size.
  • Request timeout.
  • Bounded retry count.
  • Provider rate-limit handling.
  • Optional local request throttling.

This prevents an accidental loop in the shell or diagnostic subsystem from generating unlimited external API requests.


18. Logging and Request IDs

Each AI request should have a request identifier.

Conceptual flow:

User Request
    ↓
req-001
    ↓
AI Bridge
    ↓
External API
    ↓
Response
    ↓
req-001

The request ID should make it possible to correlate:

  • Kernel/bridge request.
  • AI provider request processing.
  • Validation result.
  • Error.
  • Final response.

Sensitive request contents should not be logged unnecessarily.


19. Health and Status

The AI Bridge should expose internal status information for diagnostics where useful.

Conceptual statuses:

READY
PROCESSING
DEGRADED
AI_UNAVAILABLE
CONFIGURATION_ERROR

A conceptual health check could be:

GET /health

for a future local AI Bridge HTTP control interface, but this is optional and not required for the initial MVP.

The core communication path does not depend on the bridge exposing an HTTP server.


20. API Versioning

The external provider API version should be configurable rather than hard-coded into the kernel.

The PsyDian internal protocol should include its own version field:

{
  "type": "diagnostic",
  "version": 1,
  "id": "diag-001",
  "payload": {}
}

This allows future protocol changes without requiring the entire system to be redesigned.


21. API Abstraction

The AI Bridge should provide a provider-independent interface.

Conceptually:

              AIProvider
                  │
        ┌─────────┼─────────┐
        ↓         ↓         ↓
    Provider A Provider B Local Model

Possible interface operations:

generate(request)
validate_response(response)
provider_name()
model_name()

This allows a provider to be replaced without changing the kernel communication protocol.


22. Complete API Data Flow

User
  ↓
PsyDian Shell
  ↓
Kernel
  ↓
Diagnostic / AI Request
  ↓
Serial / Local Protocol
  ↓
AI Bridge
  ↓
Protocol Validation
  ↓
Context Builder
  ↓
AI Provider Adapter
  ↓
HTTPS / REST API
  ↓
External AI Service
  ↓
Provider Response
  ↓
Response Parser
  ↓
Response Validation
  ↓
AI Bridge
  ↓
Serial / Local Protocol
  ↓
PsyDian Shell
  ↓
User

23. API Requirements Summary

IDRequirementPriority
API-001AI Bridge shall construct validated AI requests.Must
API-002AI Bridge shall use HTTPS for external AI communication.Must
API-003AI credentials shall remain outside kernel source code.Must
API-004AI Bridge shall validate external responses.Must
API-005AI Bridge shall handle timeout and transient failures.Must
API-006AI-generated commands shall not bypass shell validation.Must
API-007Requests shall have traceable identifiers.Should
API-008Internal protocol messages shall contain a version field.Must
API-009Provider-specific functionality shall be isolated behind an abstraction.Should
API-010Core shell operation shall continue when the external AI API is unavailable.Must
API-011Request and response size limits shall be enforced.Should
API-012The bridge shall avoid logging sensitive request content.Must
API-013The bridge shall support controlled retry behavior for transient failures.Should
API-014The bridge shall expose useful internal status information where required.Could
API-015The API design shall permit future provider replacement.Should

24. MVP API Boundary

For the 8-week MVP, the required API boundary is intentionally small:

PsyDian
   ↓
Diagnostic / AI Request
   ↓
AI Bridge
   ↓
One configured external AI provider
   ↓
Validated AI Response
   ↓
PsyDian

Advanced features such as multiple simultaneous providers, API gateways, distributed request queues, streaming response infrastructure, and enterprise API management are future scope.


25. Important Design Rule

The external AI API is an assistance dependency, not the operating-system execution layer.

Therefore:

AI API Available
      ↓
AI assistance works

AI API Unavailable
      ↓
AI assistance unavailable
      ↓
Core PsyDian shell/kernel remains operational

This separation is a fundamental requirement of the PsyDian architecture.