Cogniscript Language Guide

Cogniscript is a custom, compiled, stack-based programming language designed specifically for the Maitento AI Operating System. This comprehensive guide covers everything you need to know to write, understand, and debug Cogniscript programs.

Table of Contents

  1. What is Cogniscript?
  2. Language Syntax
  3. Statements and Expressions
  4. Built-in Functions
  5. Maitento Syscalls
  6. File References (@prompt/@json)
  7. VM Architecture Overview
  8. Complete Code Examples

What is Cogniscript?

Cogniscript is a purpose-built programming language that enables automation and scripting within the Maitento ecosystem. It provides a C-like syntax that is familiar to most developers while being specifically designed for AI-driven workflows.

Key Characteristics

  • Statically Typed: All variables must be declared with explicit types
  • Compiled: Source code is compiled to bytecode for efficient execution
  • Stack-Based: Uses a stack-based virtual machine for execution
  • Sandboxed: Executes in a secure, isolated environment
  • Async-Capable: Supports asynchronous operations through syscalls

Compilation Pipeline

Cogniscript source code goes through a multi-stage compilation process:

Source Code (.cog)
      |
      v
+------------------+
| 1. Tokenization  |  Breaks source into tokens
+------------------+
      |
      v
+------------------+
| 2. Parsing       |  Builds Abstract Syntax Tree (AST)
+------------------+
      |
      v
+------------------+
| 3. Assembly Gen  |  Generates assembly code
+------------------+
      |
      v
+------------------+
| 4. Assembly Parse|  Creates executable bytecode
+------------------+
      |
      v
+------------------+
| 5. Execution     |  VM executes the bytecode
+------------------+

Key Components

ComponentDescription
CogniscriptCompilerTokenizes and parses source into AST
CogniscriptAssemblerCreates executable operations from assembly
CogniscriptVirtualMachineExecutes compiled operations
CogniscriptCoreCore data structures and operations
CogniscriptStandardLibrary80+ built-in functions
CogniscriptMaitentoLibrary109 Maitento-specific syscalls

Language Syntax

Data Types

Cogniscript supports eight built-in data types:

TypeKeywordDescriptionExample
IntegerintWhole numbers (32-bit signed)int count = 42;
DecimaldecimalFloating-point numbersdecimal price = 19.99;
StringstringText valuesstring name = "Alice";
BooleanboolTrue/False valuesbool active = true;
GUIDguidGlobally unique identifiersguid id = {550e8400-e29b-41d4-a716-446655440000};
DatedateDateTime valuesdate now = DateGetUtc();
JSON ObjectjsonObjectKey-value JSON objectsjsonObject obj = JsonObjectCreate();
JSON ArrayjsonArrayOrdered JSON arraysjsonArray arr = JsonArrayCreate();
VoidvoidNo return value (functions only)void main() { }

Variable Declarations

Variables are declared with an explicit type, identifier, and initial value:

// Syntax: <type> <identifier> = <expression>;

// Primitive types
int counter = 0;
decimal price = 19.99;
string name = "Product";
bool inStock = true;
guid productId = {550e8400-e29b-41d4-a716-446655440000};

// With expressions
int sum = a + b;
string fullName = firstName + " " + lastName;
bool isValid = count > 0 && count < 100;

Rules:

  • All variables must be initialized at declaration
  • Variable names must start with a letter
  • Variable names can contain letters and digits only
  • Duplicate variable declarations in the same scope cause errors

Operators

Operator Precedence (lowest to highest)

PrecedenceCategoryOperatorsAssociativity
1 (lowest)Assignment= += -= *= /= %=Right-to-left
2Logical OR||Left-to-right
3Logical AND&&Left-to-right
4Equality== !=Left-to-right
5Relational< > <= >=Left-to-right
6Additive+ -Left-to-right
7Multiplicative* / %Left-to-right
8Unary! - ++ -- (prefix)Right-to-left
9 (highest)Postfix++ -- (postfix) ()Left-to-right

Arithmetic Operators

int a = 10;
int b = 3;

int sum = a + b;           // 13 (or string concatenation)
int diff = a - b;          // 7
int product = a * b;       // 30
int quotient = a / b;      // 3
int remainder = a % b;     // 1

String Concatenation

The + operator intelligently handles strings:

// String concatenation
string result = "Hello" + " " + "World";  // "Hello World"
string message = "Count: " + IntToString(count);

// Smart behavior: if both operands parse as numbers, performs addition
// Otherwise: performs string concatenation

Comparison Operators

bool eq = a == b;    // Equal to
bool ne = a != b;    // Not equal to
bool lt = a < b;     // Less than
bool gt = a > b;     // Greater than
bool le = a <= b;    // Less than or equal
bool ge = a >= b;    // Greater than or equal

Logical Operators

bool andResult = a && b;   // Logical AND
bool orResult = a || b;    // Logical OR
bool notResult = !a;       // Logical NOT

Compound Assignment Operators

counter += 1;    // counter = counter + 1
counter -= 5;    // counter = counter - 5
counter *= 2;    // counter = counter * 2
counter /= 4;    // counter = counter / 4
counter %= 3;    // counter = counter % 3

Increment/Decrement Operators

int x = 5;
int y = x++;   // y = 5, x = 6 (post-increment)
int z = ++x;   // z = 7, x = 7 (pre-increment)
x--;           // x = 6 (post-decrement)
--x;           // x = 5 (pre-decrement)

Comments

Cogniscript supports single-line comments only:

// This is a comment
int x = 5; // Inline comment

// Multiple lines require
// multiple comment markers

String Literals and Escape Sequences

string simple = "Hello, World!";
string empty = "";

// Escape sequences
string newline = "Line 1\nLine 2";     // Newline
string tabbed = "Col1\tCol2";          // Tab
string quoted = "She said \"Hi!\"";    // Double quote
string path = "C:\\Users\\Name";       // Backslash
string crlf = "Line 1\r\nLine 2";      // Windows line ending
EscapeCharacter
\nNewline
\rCarriage return
\tTab
\\Backslash
\"Double quote

Statements and Expressions

Function Definitions

Functions are declared with a return type, name, parameters, and body:

// Function with no parameters
int getDefaultValue() {
    return(42);
}

// Function with parameters
int add(int a, int b) {
    return(a + b);
}

// Function with no return value
void logMessage(string message) {
    PrintLine(message);
}

// Function with multiple parameters
decimal calculateTotal(decimal price, int quantity, decimal taxRate) {
    decimal subtotal = price * quantity;
    decimal tax = subtotal * taxRate;
    return(subtotal + tax);
}

Important: The return, exit, and throw keywords use function-call syntax with parentheses:

return(value);   // Return with value
return();        // Return without value (void functions)
exit(0);         // Exit program
throw("Error");  // Throw exception

Control Flow

If/Else Statements

if (condition) {
    // true block
}

if (condition) {
    // true block
} else {
    // else block
}

if (score >= 90) {
    return("A");
} else if (score >= 80) {
    return("B");
} else if (score >= 70) {
    return("C");
} else {
    return("F");
}

While Loops

int i = 0;
while (i < 10) {
    PrintLine(IntToString(i));
    i++;
}

// Infinite loop with break
while (true) {
    if (done) {
        break;
    }
}

For Loops

// Standard for loop
for (int i = 0; i < 10; i++) {
    PrintLine(IntToString(i));
}

// Counting down
for (int i = 10; i > 0; i--) {
    PrintLine(IntToString(i));
}

// Increment by 2
for (int i = 0; i <= 20; i += 2) {
    PrintLine(IntToString(i));
}

// Nested loops
for (int row = 0; row < 3; row++) {
    for (int col = 0; col < 3; col++) {
        Print("(" + IntToString(row) + "," + IntToString(col) + ") ");
    }
    PrintLine("");
}

Break and Continue

// Break exits the loop
for (int i = 0; i < 100; i++) {
    if (i == 10) {
        break;  // Exit loop when i reaches 10
    }
}

// Continue skips to next iteration
for (int i = 0; i < 10; i++) {
    if (i % 2 == 0) {
        continue;  // Skip even numbers
    }
    PrintLine(IntToString(i));  // Prints 1, 3, 5, 7, 9
}

Error Handling

Try/Catch

try {
    // Code that might throw an exception
    riskyOperation();
} catch {
    // Handle the error
    string error = GetLastError();
    PrintLine("Error: " + error);
}

Throw

void validateAge(int age) {
    if (age < 0) {
        throw("Age cannot be negative");
    }
    if (age > 150) {
        throw("Age exceeds maximum allowed value");
    }
}

Exception Propagation

Exceptions propagate up the call stack until caught:

void level3() {
    throw("Error in level 3");
}

void level2() {
    level3();  // Exception propagates up
}

void level1() {
    try {
        level2();
    } catch {
        PrintLine("Caught: " + GetLastError());
    }
}

The main Function

Every Cogniscript program must have a main function as its entry point:

void main() {
    PrintLine("Hello, World!");
}

// Or with parameters
void main(int count, string message) {
    for (int i = 0; i < count; i++) {
        PrintLine(message);
    }
}

Built-in Functions

Cogniscript includes 80+ built-in functions organized by category.

String Functions

FunctionDescriptionExample
StringLength(value)Returns string lengthStringLength("hello") = 5
StringConcatenate(a, b)Concatenates two stringsStringConcatenate("Hello, ", "World!")
StringReplace(text, search, replace)Replaces all occurrencesStringReplace("hello", "l", "L")
StringToUpper(value)Converts to uppercaseStringToUpper("hello") = “HELLO”
StringToLower(value)Converts to lowercaseStringToLower("HELLO") = “hello”
StringTrim(value)Removes leading/trailing whitespaceStringTrim(" hi ") = “hi”
StringIsEmpty(value)Checks if null/empty/whitespaceStringIsEmpty("") = true
StringContains(value, search, ignoreCase)Checks for substringStringContains("Hello", "ell", false)
StringStartsWith(value, prefix, ignoreCase)Checks prefixStringStartsWith("Hello", "He", false)
StringEndsWith(value, suffix, ignoreCase)Checks suffixStringEndsWith("Hello", "lo", false)
StringIndexOf(value, search, startIndex, ignoreCase)Finds first occurrenceStringIndexOf("Hello", "l", 0, false)
StringLastIndexOf(value, search, ignoreCase)Finds last occurrenceStringLastIndexOf("Hello", "l", false)
StringSubstring(value, startIndex, length)Extracts substringStringSubstring("Hello", 0, 4) = “Hell”
StringSplit(value, separator, removeEmpty)Splits into arrayStringSplit("a,b,c", ",", false)
StringJoin(array, separator)Joins array into stringStringJoin(arr, ", ")
StringPadLeft(value, totalWidth, paddingChar)Left-pads stringStringPadLeft("42", 5, "0") = “00042”
StringPadRight(value, totalWidth, paddingChar)Right-pads stringStringPadRight("Hi", 5, ".") = “Hi…”

Math Functions

FunctionDescriptionExample
MathAbs(value)Absolute valueMathAbs(-5.5) = 5.5
MathRound(value, decimals)Rounds to decimal placesMathRound(3.14159, 2) = 3.14
MathFloor(value)Rounds downMathFloor(3.7) = 3
MathCeiling(value)Rounds upMathCeiling(3.2) = 4
MathTruncate(value)Removes fractional partMathTruncate(3.9) = 3
MathMin(a, b)Returns smaller valueMathMin(5, 3) = 3
MathMax(a, b)Returns larger valueMathMax(5, 3) = 5
MathPow(base, exponent)Raises to powerMathPow(2, 3) = 8
MathSqrt(value)Square rootMathSqrt(16) = 4
MathRandom(min, max)Random numberMathRandom(1, 10)

Date/Time Functions

FunctionDescriptionExample
DateGetUtc()Current UTC date/timeDateGetUtc()
DateDiff(left, right)Difference in millisecondsDateDiff(date1, date2)
DateAddDays(date, days)Adds daysDateAddDays(today, 1)
DateAddHours(date, hours)Adds hoursDateAddHours(now, 2)
DateGetYear(date)Extracts yearDateGetYear(someDate)
DateGetMonth(date)Extracts month (1-12)DateGetMonth(someDate)
DateGetDay(date)Extracts day (1-31)DateGetDay(someDate)

JSON Object Functions

FunctionDescriptionExample
JsonObjectCreate()Creates empty objectJsonObjectCreate() = ”{}“
JsonObjectGet(obj, key)Gets value by keyJsonObjectGet(person, "name")
JsonObjectSetString(obj, key, value)Sets string valueJsonObjectSetString(obj, "name", "John")
JsonObjectSetBool(obj, key, value)Sets boolean valueJsonObjectSetBool(obj, "active", true)
JsonObjectSetInt(obj, key, value)Sets integer valueJsonObjectSetInt(obj, "age", 30)
JsonPathQuery(value, path)JSONPath queryJsonPathQuery(data, "$.users[*].name")
JsonAtaTransform(value, transform)JSONata transformationJsonAtaTransform(data, "price * quantity")
JsonIsParseable(value)Validates JSONJsonIsParseable('{"name":"John"}')

JSON Array Functions

FunctionDescriptionExample
JsonArrayCreate()Creates empty arrayJsonArrayCreate() = ”[]“
JsonArrayCount(array)Returns element countJsonArrayCount(myArray)
JsonArrayAdd(array, value)Adds elementJsonArrayAdd(arr, '"item"')
JsonArrayInsert(array, index, value)Inserts at indexJsonArrayInsert(arr, 1, '"item"')
JsonArrayGetAtIndex(array, index)Gets elementJsonArrayGetAtIndex(arr, 0)
JsonArraySetAtIndex(array, index, value)Sets elementJsonArraySetAtIndex(arr, 0, '"new"')
JsonArrayRemoveAtIndex(array, index)Removes elementJsonArrayRemoveAtIndex(arr, 0)

Type Conversion Functions

FunctionDescriptionExample
StringToInt(value)String to integerStringToInt("42") = 42
StringToDecimal(value)String to decimalStringToDecimal("3.14") = 3.14
StringToBool(value)String to booleanStringToBool("true") = true
StringToDateTime(value, format)String to dateStringToDateTime("2024-01-15", null)
StringToJsonObject(value)String to JSON objectStringToJsonObject('{"name":"John"}')
StringToJsonArray(value)String to JSON arrayStringToJsonArray('[1,2,3]')
IntToString(value)Integer to stringIntToString(42) = “42”
DecimalToString(value, format)Decimal to stringDecimalToString(3.14, "F2")
BoolToString(value)Boolean to stringBoolToString(true) = “true”
DateTimeToString(value, format)Date to stringDateTimeToString(date, "yyyy-MM-dd")
JsonObjectToString(value, pretty)JSON object to stringJsonObjectToString(obj, true)
JsonArrayToString(value, pretty)JSON array to stringJsonArrayToString(arr, false)

Type Checking Functions

FunctionDescriptionExample
TypeIsNull(value)Checks if nullTypeIsNull(someValue)
TypeIsInteger(value)Checks if valid integerTypeIsInteger("42") = true
TypeIsDecimal(value)Checks if valid decimalTypeIsDecimal("3.14") = true
TypeIsJson(value)Checks if valid JSONTypeIsJson('{"a":1}') = true
TypeIsJsonObject(value)Checks if JSON objectTypeIsJsonObject('{"a":1}') = true
TypeIsJsonArray(value)Checks if JSON arrayTypeIsJsonArray('[1,2]') = true

Output Functions

FunctionDescriptionExample
Print(text)Writes to consolePrint("Hello, ")
PrintLine(text)Writes line to consolePrintLine("Hello!")
Trace(text)Writes to trace outputTrace("Debug info")
TraceLine(text)Writes line to traceTraceLine("Debug info")

Miscellaneous Functions

FunctionDescriptionExample
Sleep(milliseconds)Pauses executionSleep(1000)
GetLastError()Gets last error messageGetLastError()
RegexIsMatch(input, pattern)Tests regex patternRegexIsMatch("test@email.com", "^[\\w.-]+@")
HashMd5(text)Computes MD5 hashHashMd5("Hello")

Maitento Syscalls

The CogniscriptMaitentoLibrary provides 109 syscalls across 18 categories, enabling Cogniscript programs to interact with the Maitento AI OS.

Syscall Categories Summary

CategoryCountDescription
Agents4AI agent management
Apps14Application lifecycle
Capsules18Container management
Interactions8Conversation handling
Virtual File Systems27File operations
Secrets5Secure credential storage
Namespaces4Resource organization
Code Generation4AI-powered code generation
Automated Actions15Scheduled task automation
Email1Email sending
Files3File management
Image Generation1AI image creation
Web Hooks4Event notifications
Connectors3External integrations
External Operations3Custom operations
Partitions3Data partitioning
Processes1Process control
AI Models1Model listing

Agents (4 syscalls)

SyscallDescriptionParametersReturns
AgentCreateCreate a new agentname*, aiModelId*, systemPrompt*, summary*, namespaceNameAgent JSON
AgentGetGet agent by namename* (supports “name@namespace”)Agent JSON
AgentListList all agentsnamespaceNameAgent[] JSON
AgentUpdateUpdate existing agentname*, newName, aiModelId, systemPrompt, summaryAgent JSON

Apps (14 syscalls)

SyscallDescriptionParametersReturns
AppListList all appsnamespaceNameApp[] JSON
AppGetGet app by namename*App JSON
AppStartStart app processname*, inputs (JsonObject)ProcessId
AppProcessGetGet process detailsprocessId*AppProcess JSON
AppStateGetInputGet input valuename*String or null
AppStateSetInputSet input valuename*, value*void
AppStateSetOutputStringSet string outputname*, valuevoid
AppStateSetOutputIntegerSet integer outputname*, valuevoid
AppStateSetOutputBoolSet boolean outputname*, valuevoid
AppStateSetOutputDecimalSet decimal outputname*, valuevoid
AppStateSetOutputGuidSet GUID outputname*, valuevoid
AppStateSetOutputDateSet date outputname*, valuevoid
AppStateSetOutputJsonObjectSet JSON object outputname*, valuevoid
AppStateSetOutputJsonArraySet JSON array outputname*, valuevoid

Capsules (18 syscalls)

SyscallDescriptionParametersReturns
CapsuleGetGet capsule processprocessId*CapsuleProcess JSON
CapsuleStartStart capsulename*, namespaceName*, vfsMounts, secretMounts, commandsProcessId
CapsuleTerminateTerminate capsuleprocessId*CommandId
CapsuleExecExecute commandprocessId*, command*, arguments, runAsUser, maximumDurationMs, asyncCommandId
CapsuleMountVfsMount VFSprocessId*, vfsId*, vfsNamespaceId*, mountName*CommandId
CapsuleUnmountVfsUnmount VFSprocessId*, mountName*CommandId
CapsuleMountSecretMount secretprocessId*, secretName*, mountName*CommandId
CapsuleUnmountSecretUnmount secretprocessId*, mountName*CommandId
CapsuleAddUserAdd userprocessId*, username*, sudoAsUsersCommandId
CapsuleRemoveUserRemove userprocessId*, username*CommandId
CapsuleInstallPackageInstall packageprocessId*, packageName*CommandId
CapsuleRemovePackageRemove packageprocessId*, packageName*CommandId
CapsuleDefinitionListList definitionsnamespaceNameCapsuleDefinition[] JSON
CapsuleDefinitionGetGet definitionname*, namespaceName*CapsuleDefinition JSON
CapsuleCommandGetGet commandprocessId*, commandId*Command JSON
CapsuleCommandAwaitWait for commandprocessId*, commandId*Command JSON
CapsuleWaitUntilStartedWait until runningprocessId*CapsuleProcess JSON
CapsuleWaitUntilFinishedWait until finishedprocessId*CapsuleProcess JSON

Interactions (8 syscalls)

SyscallDescriptionParametersReturns
InteractionStartStart interactionname*, inputs* (JsonObject)ProcessId
InteractionGetGet interactionname*Interaction JSON
InteractionListList interactionsnamespaceNameInteraction[] JSON
InteractionProcessGetGet processprocessId*InteractionProcess JSON
InteractionAddMessageAdd messageprocessId*, message*, authorName, authorIdvoid
InteractionAwaitWait for completionid*InteractionProcess JSON
InteractionVoteYesVote yesprocessId*, authorName, authorIdvoid
InteractionVoteNoVote noprocessId*, reason*, authorName, authorIdvoid

Virtual File Systems (27 syscalls)

Basic Operations

SyscallDescriptionParametersReturns
VfsCreateCreate VFSname*, namespaceName*VFS JSON
VfsDestroyDelete VFSname*, namespaceName*void
VfsGetGet VFS detailsname*, namespaceName*VFS JSON
VfsListAllList all VFSnamespaceNameVFS[] JSON

File Operations

SyscallDescriptionParametersReturns
VfsReadTextRead filevfsName*, namespaceName*, path*String
VfsWriteTextWrite filevfsName*, namespaceName*, path*, content*File JSON
VfsAppendTextAppend to filevfsName*, namespaceName*, path*, content*File JSON
VfsReadLinesRead as linesvfsName*, namespaceName*, path*String[] JSON
VfsWriteLinesWrite linesvfsName*, namespaceName*, path*, lines*File JSON
VfsAppendLinesAppend linesvfsName*, namespaceName*, path*, lines*File JSON
VfsDeleteFileDelete filevfsName*, namespaceName*, path*void

Directory Operations

SyscallDescriptionParametersReturns
VfsListDirectoryList directoryvfsName*, namespaceName*, path*Entry[] JSON
VfsMkdirCreate directoryvfsName*, namespaceName*, path*Directory JSON
VfsDeleteDirectoryDelete directoryvfsName*, namespaceName*, path*, recursivevoid
VfsExistsFileCheck file existsvfsName*, namespaceName*, path*Boolean
VfsExistsDirectoryCheck dir existsvfsName*, namespaceName*, path*Boolean

Advanced Operations

SyscallDescriptionParametersReturns
VfsCopyCopy file/dirvfsName*, namespaceName*, sourcePath*, destinationPath*Result JSON
VfsMoveMove/renamevfsName*, namespaceName*, sourcePath*, destinationPath*Result JSON
VfsFindFind filesvfsName*, namespaceName*, path, pattern, grep, …Results JSON
VfsEditEdit filevfsName*, namespaceName*, path*, operations*Result JSON
VfsTreeGet tree structurevfsName*, namespaceName*, path, maxDepth, …Tree JSON
VfsBatchReadRead multiple filesvfsName*, namespaceName*, paths*, maxLinesPerFileResult JSON
VfsBatchEditEdit multiple filesvfsName*, namespaceName*, edits*, atomicResult JSON

Secrets (5 syscalls)

SyscallDescriptionParametersReturns
SecretCreateCreate secretname*, value*Secret JSON
SecretGetGet secret valuename*String
SecretListList all secrets-Secret[] JSON
SecretUpdateUpdate secretname*, newName, newValueSecret JSON
SecretDeleteDelete secretname*void

Namespaces (4 syscalls)

SyscallDescriptionParametersReturns
NamespaceListList namespaces-Namespace[] JSON
NamespaceCreateCreate namespacename*Namespace JSON
NamespaceGetGet namespacename*Namespace JSON
NamespaceUpdateRename namespacename*, newName*Namespace JSON

Code Generation (4 syscalls)

SyscallDescriptionParametersReturns
CodeGenerationStartStart code gengitUrl*, gitSshKey, gitHttpCredentials, branchSource*, branchWork*, codeGuidelines*, steps*, fileIds*, generateDiffOnCompletion*, claudeAuthentication, engineProcessId
CodeGenerationGetGet processprocessId*Process JSON
CodeGenerationListList processes-Process[] JSON
CodeGenerationAwaitWait for completionid*Process JSON

Automated Actions (15 syscalls)

Core Operations

SyscallDescriptionParametersReturns
ActionCreateCreate actionnamespaceName*, name*, description, actionsJson*Action JSON
ActionGetGet actionnameOrId*Action JSON
ActionListList actionsnamespaceNameAction[] JSON
ActionUpdateUpdate actionactionId*, name*, description, actionsJson*Action JSON
ActionDeleteDelete actionactionId*void
ActionTriggerTrigger actionactionId*ExecutionId
ActionHistoryGet historyactionId*, limitHistory[] JSON

Schedule Management

SyscallDescriptionParametersReturns
ActionScheduleAddAdd cron scheduleactionId*, scheduleName, minute, hour, dayOfMonth, month, dayOfWeek, second, enabledAction JSON
ActionScheduleEnableEnable scheduleactionId*, scheduleId*Action JSON
ActionScheduleDisableDisable scheduleactionId*, scheduleId*Action JSON
ActionScheduleRemoveRemove scheduleactionId*, scheduleId*Action JSON

Message Trigger Management

SyscallDescriptionParametersReturns
ActionMsgTriggerAddAdd message triggeractionId*, triggerName, triggerType*, eventFilter, enabledAction JSON
ActionMsgTriggerEnableEnable triggeractionId*, triggerId*Action JSON
ActionMsgTriggerDisableDisable triggeractionId*, triggerId*Action JSON
ActionMsgTriggerRemoveRemove triggeractionId*, triggerId*Action JSON

Other Syscalls

CategorySyscallDescription
EmailSendEmail(recipient*, subject*, body*, isHtml*)Send email
FilesFileGetText(fileId*)Get file text
FilesFileSearch(partitionId*, query*)Search with embeddings
FilesFileDelete(fileId*)Delete file
ImageImageGenerate(model*, prompt*, partitionId*, aspectRatio*)Generate image
WebHooksWebHookCreate, WebHookList, WebHookUpdate, WebHookDeleteWebhook management
ConnectorsConnectorList, ConnectorGet, ConnectorDeleteConnector management
ExtOpsExtOpList, ExtOpGet, ExtOpDeleteExternal operation management
PartitionsPartitionList, PartitionCreate, PartitionDeletePartition management
ProcessesProcessKill(processId*, processType*)Kill process
AI ModelsAiModelList()List available AI models

File References (@prompt/@json)

Cogniscript supports inline file references using @prompt("filename") and @json("filename") syntax. This preprocessor feature allows embedding external file content directly into Cogniscript code.

Syntax

// Reference a prompt file (from prompts/ directory)
string systemPrompt = @prompt("my-prompt");

// Reference a JSON file (from json/ directory)
string schema = @json("output-schema");

How It Works

The FileReferencePreProcessor processes these references during compilation:

  1. Detection: Scans for pattern @prompt("filename") or @json("filename")
  2. Validation: Verifies the referenced file exists in the project directories
  3. Code Generation: Creates synthetic functions that return file contents as strings
  4. Replacement: Replaces references with generated function calls

File Resolution

ReferenceSource DirectoryFile Extension
@prompt("name")prompts/.md
@json("name")json/.json

Example Transformation

Input Cogniscript:

string prompt = @prompt("developer-system");
string schema = @json("response-format");

Generated Synthetic Code:

// Auto-generated by FileReferencePreProcessor
string PromptdevelopersystemaBC123() {
    return("You are an expert developer...");
}
string Jsonresponseformat9DE456() {
    return("{\"type\":\"object\"...}");
}

Transformed Cogniscript:

string prompt = PromptdevelopersystemaBC123();
string schema = Jsonresponseformat9DE456();

Use Cases

  • AI System Prompts: Store complex prompts in separate .md files
  • JSON Schemas: Reference structured schemas for validation
  • Configuration: Load configuration data at compile time
  • Templates: Embed template content in your code

VM Architecture Overview

The Cogniscript Virtual Machine is a stack-based bytecode interpreter that executes compiled Cogniscript programs in a secure, sandboxed environment.

Core Architecture

+------------------------------------------+
|           VirtualMachine                 |
|------------------------------------------|
|  - ExecutionContext                      |
|  - Operation Executors (25 types)        |
|  - Cancellation Support                  |
+------------------------------------------+
           |
           v
+------------------------------------------+
|         ExecutionContext                 |
|------------------------------------------|
|  - AssembledApp (bytecode)               |
|  - StackFrames[]                         |
|  - SysCallContext                        |
|  - SysCallProviders[]                    |
|  - ExitValue                             |
|  - LastErrorValue                        |
+------------------------------------------+
           |
           v
+------------------------------------------+
|           StackFrame                     |
|------------------------------------------|
|  - VariableScopes[]                      |
|  - ErrorHandlers[]                       |
|  - Arguments (dictionary)                |
|  - LocationBeforePush                    |
|  - LastReturnValue                       |
|  - LastSysCallValue                      |
+------------------------------------------+

Key Features

  • Stack-Based Architecture: Function calls create new stack frames for isolation
  • String-Based Values: All variables store values as strings internally
  • MessagePack Serialization: Efficient bytecode storage and loading
  • Dependency Injection: Extensible operation executors
  • Cancellation Support: Graceful termination via CancellationToken

Instruction Set (25 Opcodes)

OpcodeValueSymbolDescription
StackCreate1STK+Create new stack frame
StackDestroy2STK-Destroy current stack frame
Exit3EXITTerminate execution
VariableSet4VARSet variable to literal
VariableIncrement5VAR++Increment numeric variable
VariableDecrement6VAR--Decrement numeric variable
SysCall7SYSInvoke system call
Jump8JMPUnconditional jump
VariableScopeCreate9SCP+Create variable scope
VariableScopeDestroy10SCP-Destroy variable scope
JumpIf11JMPIFConditional jump
Return12RETReturn from function
Throw13THRThrow error
ErrorHandlerCreate14ERR+Register error handler
ErrorHandlerDestroy15ERR-Unregister error handler
VariableSetFromLastReturnValue16VARRETSet from return value
VariableSetFromLastErrorValue17VARERRSet from error
VariableSetFromLastSysCallValue18VARSYSSet from syscall
NoOp19NOOPNo operation
VariableMath20MATHArithmetic operation
VariableCopy21VARCCopy variable
Compare22CMPCompare values
LogicalNot23NOTLogical negation
VariableSetFromArgument24VARARGSet from argument
PushArgumentToStack25PUSHARGPush function argument

Stack Limits

ResourceMaximum
Stack Frames1000
Variable Scopes per Frame1000
Error Handlers per Frame100

Memory Model

All values are stored as strings internally. Type conversions happen on demand:

TypeC# TypeStorage Format
StringstringRaw string
IntegerintParseable integer
DecimaldecimalParseable decimal
Booleanbool”True” or “False”
GuidGuidStandard GUID format
DateTimeDateTimeParseable date/time
JsonObjectJsonObjectValid JSON object
JsonArrayJsonArrayValid JSON array

Error Handling Flow

When an exception occurs:

  1. Search current stack frame for error handler
  2. If found: jump to handler, set LastErrorValue
  3. If not found: destroy frame, search parent frame
  4. If no handler in any frame: program terminates with error

Complete Code Examples

Example 1: Hello World

void main() {
    PrintLine("Hello, World!");
}

Example 2: Factorial Calculator

// Calculate factorial using recursion
int factorial(int n) {
    if (n <= 1) {
        return(1);
    }
    return(n * factorial(n - 1));
}

void main() {
    PrintLine("=== Factorial Calculator ===");

    for (int i = 0; i <= 10; i++) {
        int result = factorial(i);
        PrintLine(IntToString(i) + "! = " + IntToString(result));
    }
}

Example 3: Prime Number Finder

// Find all prime numbers up to n
jsonArray findPrimes(int n) {
    jsonArray primes = JsonArrayCreate();

    for (int num = 2; num <= n; num++) {
        bool isPrime = true;

        for (int i = 2; i * i <= num; i++) {
            if (num % i == 0) {
                isPrime = false;
                break;
            }
        }

        if (isPrime) {
            primes = JsonArrayAdd(primes, IntToString(num));
        }
    }

    return(primes);
}

void main() {
    jsonArray primes = findPrimes(50);
    int count = JsonArrayCount(primes);

    PrintLine("Found " + IntToString(count) + " primes:");

    for (int i = 0; i < count; i++) {
        string prime = JsonArrayGetAtIndex(primes, i);
        Print(prime + " ");
    }
    PrintLine("");
}

Example 4: Error Handling

void validateAge(int age) {
    if (age < 0) {
        throw("Age cannot be negative");
    }
    if (age > 150) {
        throw("Age exceeds maximum allowed value");
    }
}

void main() {
    int ages[3] = {25, -5, 200};

    for (int i = 0; i < 3; i++) {
        int age = ages[i];
        try {
            validateAge(age);
            PrintLine("Age " + IntToString(age) + " is valid");
        } catch {
            PrintLine("Error: " + GetLastError());
        }
    }
}

Example 5: Working with JSON

void main() {
    // Create a person object
    jsonObject person = JsonObjectCreate();
    person = JsonObjectSetString(person, "name", "Alice");
    person = JsonObjectSetInt(person, "age", 30);
    person = JsonObjectSetBool(person, "active", true);

    PrintLine("Person: " + JsonObjectToString(person, true));

    // Create an array of skills
    jsonArray skills = JsonArrayCreate();
    skills = JsonArrayAdd(skills, '"Cogniscript"');
    skills = JsonArrayAdd(skills, '"AI"');
    skills = JsonArrayAdd(skills, '"Automation"');

    PrintLine("Skills: " + JsonArrayToString(skills, false));

    // Iterate over skills
    int count = JsonArrayCount(skills);
    for (int i = 0; i < count; i++) {
        string skill = JsonArrayGetAtIndex(skills, i);
        PrintLine("  - " + skill);
    }
}

Example 6: Maitento Integration

void main() {
    // Get current agent
    string agentJson = AgentGet("my-assistant");
    PrintLine("Agent: " + agentJson);

    // Create a VFS file
    VfsWriteText("data", "default", "/logs/output.txt", "Processing started...");

    // Start an app process
    jsonObject inputs = JsonObjectCreate();
    inputs = JsonObjectSetString(inputs, "task", "analyze");

    string processId = AppStart("data-processor", inputs);
    PrintLine("Started process: " + processId);

    // Wait for completion
    string process = AppProcessGet(processId);
    PrintLine("Process status: " + process);
}

Example 7: Using File References

void main() {
    // Load system prompt from prompts/assistant.md
    string systemPrompt = @prompt("assistant");

    // Load response schema from json/response-format.json
    string responseSchema = @json("response-format");

    PrintLine("System prompt loaded: " + IntToString(StringLength(systemPrompt)) + " chars");
    PrintLine("Schema: " + responseSchema);

    // Use the loaded content
    jsonObject config = JsonObjectCreate();
    config = JsonObjectSetString(config, "prompt", systemPrompt);
    config = JsonObjectSetString(config, "schema", responseSchema);

    PrintLine("Configuration ready!");
}

Example 8: Grade Calculator with Functions

string getGrade(int score) {
    if (score >= 90) {
        return("A");
    } else if (score >= 80) {
        return("B");
    } else if (score >= 70) {
        return("C");
    } else if (score >= 60) {
        return("D");
    } else {
        return("F");
    }
}

decimal calculateAverage(jsonArray scores) {
    int count = JsonArrayCount(scores);
    if (count == 0) {
        return(0);
    }

    decimal total = 0;
    for (int i = 0; i < count; i++) {
        string scoreStr = JsonArrayGetAtIndex(scores, i);
        total += StringToDecimal(scoreStr);
    }

    return(total / count);
}

void main() {
    jsonArray scores = JsonArrayCreate();
    scores = JsonArrayAdd(scores, "85");
    scores = JsonArrayAdd(scores, "92");
    scores = JsonArrayAdd(scores, "78");
    scores = JsonArrayAdd(scores, "88");
    scores = JsonArrayAdd(scores, "95");

    decimal avg = calculateAverage(scores);
    string grade = getGrade(MathRound(avg, 0));

    PrintLine("Scores analyzed:");
    int count = JsonArrayCount(scores);
    for (int i = 0; i < count; i++) {
        string score = JsonArrayGetAtIndex(scores, i);
        PrintLine("  Test " + IntToString(i + 1) + ": " + score + " (" + getGrade(StringToInt(score)) + ")");
    }

    PrintLine("");
    PrintLine("Average: " + DecimalToString(avg, "F1"));
    PrintLine("Final Grade: " + grade);
}

Quick Reference Card

Keywords

if, else, for, while, break, continue, try, catch
return, exit, throw
true, false
int, decimal, string, bool, guid, date, jsonObject, jsonArray, void

Operators

Arithmetic:    + - * / %
Assignment:    = += -= *= /= %=
Comparison:    == != < > <= >=
Logical:       && || !
Increment:     ++ --

Common Functions

// Output
Print(text);
PrintLine(text);

// String
StringLength(s);
StringConcatenate(a, b);
StringReplace(s, find, replace);
StringSubstring(s, start, length);
StringSplit(s, separator, removeEmpty);

// Math
MathAbs(n);
MathRound(n, decimals);
MathMin(a, b);
MathMax(a, b);

// Conversion
IntToString(n);
StringToInt(s);
DecimalToString(n, format);
StringToDecimal(s);

// JSON
JsonObjectCreate();
JsonObjectGet(obj, key);
JsonObjectSetString(obj, key, value);
JsonArrayCreate();
JsonArrayAdd(arr, value);
JsonArrayGetAtIndex(arr, index);
JsonArrayCount(arr);

// Date
DateGetUtc();
DateAddDays(date, days);

Control Flow Templates

// If/Else
if (condition) {
    // true
} else {
    // false
}

// For Loop
for (int i = 0; i < n; i++) {
    // body
}

// While Loop
while (condition) {
    // body
}

// Try/Catch
try {
    // risky code
} catch {
    string error = GetLastError();
}

This guide covers the complete Cogniscript language. For additional examples and advanced usage patterns, refer to the Maitento application templates and sample projects.