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
- What is Cogniscript?
- Language Syntax
- Statements and Expressions
- Built-in Functions
- Maitento Syscalls
- File References (@prompt/@json)
- VM Architecture Overview
- 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
| Component | Description |
|---|
| CogniscriptCompiler | Tokenizes and parses source into AST |
| CogniscriptAssembler | Creates executable operations from assembly |
| CogniscriptVirtualMachine | Executes compiled operations |
| CogniscriptCore | Core data structures and operations |
| CogniscriptStandardLibrary | 80+ built-in functions |
| CogniscriptMaitentoLibrary | 109 Maitento-specific syscalls |
Language Syntax
Data Types
Cogniscript supports eight built-in data types:
| Type | Keyword | Description | Example |
|---|
| Integer | int | Whole numbers (32-bit signed) | int count = 42; |
| Decimal | decimal | Floating-point numbers | decimal price = 19.99; |
| String | string | Text values | string name = "Alice"; |
| Boolean | bool | True/False values | bool active = true; |
| GUID | guid | Globally unique identifiers | guid id = {550e8400-e29b-41d4-a716-446655440000}; |
| Date | date | DateTime values | date now = DateGetUtc(); |
| JSON Object | jsonObject | Key-value JSON objects | jsonObject obj = JsonObjectCreate(); |
| JSON Array | jsonArray | Ordered JSON arrays | jsonArray arr = JsonArrayCreate(); |
| Void | void | No 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)
| Precedence | Category | Operators | Associativity |
|---|
| 1 (lowest) | Assignment | = += -= *= /= %= | Right-to-left |
| 2 | Logical OR | || | Left-to-right |
| 3 | Logical AND | && | Left-to-right |
| 4 | Equality | == != | Left-to-right |
| 5 | Relational | < > <= >= | Left-to-right |
| 6 | Additive | + - | Left-to-right |
| 7 | Multiplicative | * / % | Left-to-right |
| 8 | Unary | ! - ++ -- (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)
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
| Escape | Character |
|---|
\n | Newline |
\r | Carriage return |
\t | Tab |
\\ | 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
| Function | Description | Example |
|---|
StringLength(value) | Returns string length | StringLength("hello") = 5 |
StringConcatenate(a, b) | Concatenates two strings | StringConcatenate("Hello, ", "World!") |
StringReplace(text, search, replace) | Replaces all occurrences | StringReplace("hello", "l", "L") |
StringToUpper(value) | Converts to uppercase | StringToUpper("hello") = “HELLO” |
StringToLower(value) | Converts to lowercase | StringToLower("HELLO") = “hello” |
StringTrim(value) | Removes leading/trailing whitespace | StringTrim(" hi ") = “hi” |
StringIsEmpty(value) | Checks if null/empty/whitespace | StringIsEmpty("") = true |
StringContains(value, search, ignoreCase) | Checks for substring | StringContains("Hello", "ell", false) |
StringStartsWith(value, prefix, ignoreCase) | Checks prefix | StringStartsWith("Hello", "He", false) |
StringEndsWith(value, suffix, ignoreCase) | Checks suffix | StringEndsWith("Hello", "lo", false) |
StringIndexOf(value, search, startIndex, ignoreCase) | Finds first occurrence | StringIndexOf("Hello", "l", 0, false) |
StringLastIndexOf(value, search, ignoreCase) | Finds last occurrence | StringLastIndexOf("Hello", "l", false) |
StringSubstring(value, startIndex, length) | Extracts substring | StringSubstring("Hello", 0, 4) = “Hell” |
StringSplit(value, separator, removeEmpty) | Splits into array | StringSplit("a,b,c", ",", false) |
StringJoin(array, separator) | Joins array into string | StringJoin(arr, ", ") |
StringPadLeft(value, totalWidth, paddingChar) | Left-pads string | StringPadLeft("42", 5, "0") = “00042” |
StringPadRight(value, totalWidth, paddingChar) | Right-pads string | StringPadRight("Hi", 5, ".") = “Hi…” |
Math Functions
| Function | Description | Example |
|---|
MathAbs(value) | Absolute value | MathAbs(-5.5) = 5.5 |
MathRound(value, decimals) | Rounds to decimal places | MathRound(3.14159, 2) = 3.14 |
MathFloor(value) | Rounds down | MathFloor(3.7) = 3 |
MathCeiling(value) | Rounds up | MathCeiling(3.2) = 4 |
MathTruncate(value) | Removes fractional part | MathTruncate(3.9) = 3 |
MathMin(a, b) | Returns smaller value | MathMin(5, 3) = 3 |
MathMax(a, b) | Returns larger value | MathMax(5, 3) = 5 |
MathPow(base, exponent) | Raises to power | MathPow(2, 3) = 8 |
MathSqrt(value) | Square root | MathSqrt(16) = 4 |
MathRandom(min, max) | Random number | MathRandom(1, 10) |
Date/Time Functions
| Function | Description | Example |
|---|
DateGetUtc() | Current UTC date/time | DateGetUtc() |
DateDiff(left, right) | Difference in milliseconds | DateDiff(date1, date2) |
DateAddDays(date, days) | Adds days | DateAddDays(today, 1) |
DateAddHours(date, hours) | Adds hours | DateAddHours(now, 2) |
DateGetYear(date) | Extracts year | DateGetYear(someDate) |
DateGetMonth(date) | Extracts month (1-12) | DateGetMonth(someDate) |
DateGetDay(date) | Extracts day (1-31) | DateGetDay(someDate) |
JSON Object Functions
| Function | Description | Example |
|---|
JsonObjectCreate() | Creates empty object | JsonObjectCreate() = ”{}“ |
JsonObjectGet(obj, key) | Gets value by key | JsonObjectGet(person, "name") |
JsonObjectSetString(obj, key, value) | Sets string value | JsonObjectSetString(obj, "name", "John") |
JsonObjectSetBool(obj, key, value) | Sets boolean value | JsonObjectSetBool(obj, "active", true) |
JsonObjectSetInt(obj, key, value) | Sets integer value | JsonObjectSetInt(obj, "age", 30) |
JsonPathQuery(value, path) | JSONPath query | JsonPathQuery(data, "$.users[*].name") |
JsonAtaTransform(value, transform) | JSONata transformation | JsonAtaTransform(data, "price * quantity") |
JsonIsParseable(value) | Validates JSON | JsonIsParseable('{"name":"John"}') |
JSON Array Functions
| Function | Description | Example |
|---|
JsonArrayCreate() | Creates empty array | JsonArrayCreate() = ”[]“ |
JsonArrayCount(array) | Returns element count | JsonArrayCount(myArray) |
JsonArrayAdd(array, value) | Adds element | JsonArrayAdd(arr, '"item"') |
JsonArrayInsert(array, index, value) | Inserts at index | JsonArrayInsert(arr, 1, '"item"') |
JsonArrayGetAtIndex(array, index) | Gets element | JsonArrayGetAtIndex(arr, 0) |
JsonArraySetAtIndex(array, index, value) | Sets element | JsonArraySetAtIndex(arr, 0, '"new"') |
JsonArrayRemoveAtIndex(array, index) | Removes element | JsonArrayRemoveAtIndex(arr, 0) |
Type Conversion Functions
| Function | Description | Example |
|---|
StringToInt(value) | String to integer | StringToInt("42") = 42 |
StringToDecimal(value) | String to decimal | StringToDecimal("3.14") = 3.14 |
StringToBool(value) | String to boolean | StringToBool("true") = true |
StringToDateTime(value, format) | String to date | StringToDateTime("2024-01-15", null) |
StringToJsonObject(value) | String to JSON object | StringToJsonObject('{"name":"John"}') |
StringToJsonArray(value) | String to JSON array | StringToJsonArray('[1,2,3]') |
IntToString(value) | Integer to string | IntToString(42) = “42” |
DecimalToString(value, format) | Decimal to string | DecimalToString(3.14, "F2") |
BoolToString(value) | Boolean to string | BoolToString(true) = “true” |
DateTimeToString(value, format) | Date to string | DateTimeToString(date, "yyyy-MM-dd") |
JsonObjectToString(value, pretty) | JSON object to string | JsonObjectToString(obj, true) |
JsonArrayToString(value, pretty) | JSON array to string | JsonArrayToString(arr, false) |
Type Checking Functions
| Function | Description | Example |
|---|
TypeIsNull(value) | Checks if null | TypeIsNull(someValue) |
TypeIsInteger(value) | Checks if valid integer | TypeIsInteger("42") = true |
TypeIsDecimal(value) | Checks if valid decimal | TypeIsDecimal("3.14") = true |
TypeIsJson(value) | Checks if valid JSON | TypeIsJson('{"a":1}') = true |
TypeIsJsonObject(value) | Checks if JSON object | TypeIsJsonObject('{"a":1}') = true |
TypeIsJsonArray(value) | Checks if JSON array | TypeIsJsonArray('[1,2]') = true |
Output Functions
| Function | Description | Example |
|---|
Print(text) | Writes to console | Print("Hello, ") |
PrintLine(text) | Writes line to console | PrintLine("Hello!") |
Trace(text) | Writes to trace output | Trace("Debug info") |
TraceLine(text) | Writes line to trace | TraceLine("Debug info") |
Miscellaneous Functions
| Function | Description | Example |
|---|
Sleep(milliseconds) | Pauses execution | Sleep(1000) |
GetLastError() | Gets last error message | GetLastError() |
RegexIsMatch(input, pattern) | Tests regex pattern | RegexIsMatch("test@email.com", "^[\\w.-]+@") |
HashMd5(text) | Computes MD5 hash | HashMd5("Hello") |
Maitento Syscalls
The CogniscriptMaitentoLibrary provides 109 syscalls across 18 categories, enabling Cogniscript programs to interact with the Maitento AI OS.
Syscall Categories Summary
| Category | Count | Description |
|---|
| Agents | 4 | AI agent management |
| Apps | 14 | Application lifecycle |
| Capsules | 18 | Container management |
| Interactions | 8 | Conversation handling |
| Virtual File Systems | 27 | File operations |
| Secrets | 5 | Secure credential storage |
| Namespaces | 4 | Resource organization |
| Code Generation | 4 | AI-powered code generation |
| Automated Actions | 15 | Scheduled task automation |
| Email | 1 | Email sending |
| Files | 3 | File management |
| Image Generation | 1 | AI image creation |
| Web Hooks | 4 | Event notifications |
| Connectors | 3 | External integrations |
| External Operations | 3 | Custom operations |
| Partitions | 3 | Data partitioning |
| Processes | 1 | Process control |
| AI Models | 1 | Model listing |
Agents (4 syscalls)
| Syscall | Description | Parameters | Returns |
|---|
AgentCreate | Create a new agent | name*, aiModelId*, systemPrompt*, summary*, namespaceName | Agent JSON |
AgentGet | Get agent by name | name* (supports “name@namespace”) | Agent JSON |
AgentList | List all agents | namespaceName | Agent[] JSON |
AgentUpdate | Update existing agent | name*, newName, aiModelId, systemPrompt, summary | Agent JSON |
Apps (14 syscalls)
| Syscall | Description | Parameters | Returns |
|---|
AppList | List all apps | namespaceName | App[] JSON |
AppGet | Get app by name | name* | App JSON |
AppStart | Start app process | name*, inputs (JsonObject) | ProcessId |
AppProcessGet | Get process details | processId* | AppProcess JSON |
AppStateGetInput | Get input value | name* | String or null |
AppStateSetInput | Set input value | name*, value* | void |
AppStateSetOutputString | Set string output | name*, value | void |
AppStateSetOutputInteger | Set integer output | name*, value | void |
AppStateSetOutputBool | Set boolean output | name*, value | void |
AppStateSetOutputDecimal | Set decimal output | name*, value | void |
AppStateSetOutputGuid | Set GUID output | name*, value | void |
AppStateSetOutputDate | Set date output | name*, value | void |
AppStateSetOutputJsonObject | Set JSON object output | name*, value | void |
AppStateSetOutputJsonArray | Set JSON array output | name*, value | void |
Capsules (18 syscalls)
| Syscall | Description | Parameters | Returns |
|---|
CapsuleGet | Get capsule process | processId* | CapsuleProcess JSON |
CapsuleStart | Start capsule | name*, namespaceName*, vfsMounts, secretMounts, commands | ProcessId |
CapsuleTerminate | Terminate capsule | processId* | CommandId |
CapsuleExec | Execute command | processId*, command*, arguments, runAsUser, maximumDurationMs, async | CommandId |
CapsuleMountVfs | Mount VFS | processId*, vfsId*, vfsNamespaceId*, mountName* | CommandId |
CapsuleUnmountVfs | Unmount VFS | processId*, mountName* | CommandId |
CapsuleMountSecret | Mount secret | processId*, secretName*, mountName* | CommandId |
CapsuleUnmountSecret | Unmount secret | processId*, mountName* | CommandId |
CapsuleAddUser | Add user | processId*, username*, sudoAsUsers | CommandId |
CapsuleRemoveUser | Remove user | processId*, username* | CommandId |
CapsuleInstallPackage | Install package | processId*, packageName* | CommandId |
CapsuleRemovePackage | Remove package | processId*, packageName* | CommandId |
CapsuleDefinitionList | List definitions | namespaceName | CapsuleDefinition[] JSON |
CapsuleDefinitionGet | Get definition | name*, namespaceName* | CapsuleDefinition JSON |
CapsuleCommandGet | Get command | processId*, commandId* | Command JSON |
CapsuleCommandAwait | Wait for command | processId*, commandId* | Command JSON |
CapsuleWaitUntilStarted | Wait until running | processId* | CapsuleProcess JSON |
CapsuleWaitUntilFinished | Wait until finished | processId* | CapsuleProcess JSON |
Interactions (8 syscalls)
| Syscall | Description | Parameters | Returns |
|---|
InteractionStart | Start interaction | name*, inputs* (JsonObject) | ProcessId |
InteractionGet | Get interaction | name* | Interaction JSON |
InteractionList | List interactions | namespaceName | Interaction[] JSON |
InteractionProcessGet | Get process | processId* | InteractionProcess JSON |
InteractionAddMessage | Add message | processId*, message*, authorName, authorId | void |
InteractionAwait | Wait for completion | id* | InteractionProcess JSON |
InteractionVoteYes | Vote yes | processId*, authorName, authorId | void |
InteractionVoteNo | Vote no | processId*, reason*, authorName, authorId | void |
Virtual File Systems (27 syscalls)
Basic Operations
| Syscall | Description | Parameters | Returns |
|---|
VfsCreate | Create VFS | name*, namespaceName* | VFS JSON |
VfsDestroy | Delete VFS | name*, namespaceName* | void |
VfsGet | Get VFS details | name*, namespaceName* | VFS JSON |
VfsListAll | List all VFS | namespaceName | VFS[] JSON |
File Operations
| Syscall | Description | Parameters | Returns |
|---|
VfsReadText | Read file | vfsName*, namespaceName*, path* | String |
VfsWriteText | Write file | vfsName*, namespaceName*, path*, content* | File JSON |
VfsAppendText | Append to file | vfsName*, namespaceName*, path*, content* | File JSON |
VfsReadLines | Read as lines | vfsName*, namespaceName*, path* | String[] JSON |
VfsWriteLines | Write lines | vfsName*, namespaceName*, path*, lines* | File JSON |
VfsAppendLines | Append lines | vfsName*, namespaceName*, path*, lines* | File JSON |
VfsDeleteFile | Delete file | vfsName*, namespaceName*, path* | void |
Directory Operations
| Syscall | Description | Parameters | Returns |
|---|
VfsListDirectory | List directory | vfsName*, namespaceName*, path* | Entry[] JSON |
VfsMkdir | Create directory | vfsName*, namespaceName*, path* | Directory JSON |
VfsDeleteDirectory | Delete directory | vfsName*, namespaceName*, path*, recursive | void |
VfsExistsFile | Check file exists | vfsName*, namespaceName*, path* | Boolean |
VfsExistsDirectory | Check dir exists | vfsName*, namespaceName*, path* | Boolean |
Advanced Operations
| Syscall | Description | Parameters | Returns |
|---|
VfsCopy | Copy file/dir | vfsName*, namespaceName*, sourcePath*, destinationPath* | Result JSON |
VfsMove | Move/rename | vfsName*, namespaceName*, sourcePath*, destinationPath* | Result JSON |
VfsFind | Find files | vfsName*, namespaceName*, path, pattern, grep, … | Results JSON |
VfsEdit | Edit file | vfsName*, namespaceName*, path*, operations* | Result JSON |
VfsTree | Get tree structure | vfsName*, namespaceName*, path, maxDepth, … | Tree JSON |
VfsBatchRead | Read multiple files | vfsName*, namespaceName*, paths*, maxLinesPerFile | Result JSON |
VfsBatchEdit | Edit multiple files | vfsName*, namespaceName*, edits*, atomic | Result JSON |
Secrets (5 syscalls)
| Syscall | Description | Parameters | Returns |
|---|
SecretCreate | Create secret | name*, value* | Secret JSON |
SecretGet | Get secret value | name* | String |
SecretList | List all secrets | - | Secret[] JSON |
SecretUpdate | Update secret | name*, newName, newValue | Secret JSON |
SecretDelete | Delete secret | name* | void |
Namespaces (4 syscalls)
| Syscall | Description | Parameters | Returns |
|---|
NamespaceList | List namespaces | - | Namespace[] JSON |
NamespaceCreate | Create namespace | name* | Namespace JSON |
NamespaceGet | Get namespace | name* | Namespace JSON |
NamespaceUpdate | Rename namespace | name*, newName* | Namespace JSON |
Code Generation (4 syscalls)
| Syscall | Description | Parameters | Returns |
|---|
CodeGenerationStart | Start code gen | gitUrl*, gitSshKey, gitHttpCredentials, branchSource*, branchWork*, codeGuidelines*, steps*, fileIds*, generateDiffOnCompletion*, claudeAuthentication, engine | ProcessId |
CodeGenerationGet | Get process | processId* | Process JSON |
CodeGenerationList | List processes | - | Process[] JSON |
CodeGenerationAwait | Wait for completion | id* | Process JSON |
Automated Actions (15 syscalls)
Core Operations
| Syscall | Description | Parameters | Returns |
|---|
ActionCreate | Create action | namespaceName*, name*, description, actionsJson* | Action JSON |
ActionGet | Get action | nameOrId* | Action JSON |
ActionList | List actions | namespaceName | Action[] JSON |
ActionUpdate | Update action | actionId*, name*, description, actionsJson* | Action JSON |
ActionDelete | Delete action | actionId* | void |
ActionTrigger | Trigger action | actionId* | ExecutionId |
ActionHistory | Get history | actionId*, limit | History[] JSON |
Schedule Management
| Syscall | Description | Parameters | Returns |
|---|
ActionScheduleAdd | Add cron schedule | actionId*, scheduleName, minute, hour, dayOfMonth, month, dayOfWeek, second, enabled | Action JSON |
ActionScheduleEnable | Enable schedule | actionId*, scheduleId* | Action JSON |
ActionScheduleDisable | Disable schedule | actionId*, scheduleId* | Action JSON |
ActionScheduleRemove | Remove schedule | actionId*, scheduleId* | Action JSON |
Message Trigger Management
| Syscall | Description | Parameters | Returns |
|---|
ActionMsgTriggerAdd | Add message trigger | actionId*, triggerName, triggerType*, eventFilter, enabled | Action JSON |
ActionMsgTriggerEnable | Enable trigger | actionId*, triggerId* | Action JSON |
ActionMsgTriggerDisable | Disable trigger | actionId*, triggerId* | Action JSON |
ActionMsgTriggerRemove | Remove trigger | actionId*, triggerId* | Action JSON |
Other Syscalls
| Category | Syscall | Description |
|---|
| Email | SendEmail(recipient*, subject*, body*, isHtml*) | Send email |
| Files | FileGetText(fileId*) | Get file text |
| Files | FileSearch(partitionId*, query*) | Search with embeddings |
| Files | FileDelete(fileId*) | Delete file |
| Image | ImageGenerate(model*, prompt*, partitionId*, aspectRatio*) | Generate image |
| WebHooks | WebHookCreate, WebHookList, WebHookUpdate, WebHookDelete | Webhook management |
| Connectors | ConnectorList, ConnectorGet, ConnectorDelete | Connector management |
| ExtOps | ExtOpList, ExtOpGet, ExtOpDelete | External operation management |
| Partitions | PartitionList, PartitionCreate, PartitionDelete | Partition management |
| Processes | ProcessKill(processId*, processType*) | Kill process |
| AI Models | AiModelList() | 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:
- Detection: Scans for pattern
@prompt("filename") or @json("filename")
- Validation: Verifies the referenced file exists in the project directories
- Code Generation: Creates synthetic functions that return file contents as strings
- Replacement: Replaces references with generated function calls
File Resolution
| Reference | Source Directory | File Extension |
|---|
@prompt("name") | prompts/ | .md |
@json("name") | json/ | .json |
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)
| Opcode | Value | Symbol | Description |
|---|
StackCreate | 1 | STK+ | Create new stack frame |
StackDestroy | 2 | STK- | Destroy current stack frame |
Exit | 3 | EXIT | Terminate execution |
VariableSet | 4 | VAR | Set variable to literal |
VariableIncrement | 5 | VAR++ | Increment numeric variable |
VariableDecrement | 6 | VAR-- | Decrement numeric variable |
SysCall | 7 | SYS | Invoke system call |
Jump | 8 | JMP | Unconditional jump |
VariableScopeCreate | 9 | SCP+ | Create variable scope |
VariableScopeDestroy | 10 | SCP- | Destroy variable scope |
JumpIf | 11 | JMPIF | Conditional jump |
Return | 12 | RET | Return from function |
Throw | 13 | THR | Throw error |
ErrorHandlerCreate | 14 | ERR+ | Register error handler |
ErrorHandlerDestroy | 15 | ERR- | Unregister error handler |
VariableSetFromLastReturnValue | 16 | VARRET | Set from return value |
VariableSetFromLastErrorValue | 17 | VARERR | Set from error |
VariableSetFromLastSysCallValue | 18 | VARSYS | Set from syscall |
NoOp | 19 | NOOP | No operation |
VariableMath | 20 | MATH | Arithmetic operation |
VariableCopy | 21 | VARC | Copy variable |
Compare | 22 | CMP | Compare values |
LogicalNot | 23 | NOT | Logical negation |
VariableSetFromArgument | 24 | VARARG | Set from argument |
PushArgumentToStack | 25 | PUSHARG | Push function argument |
Stack Limits
| Resource | Maximum |
|---|
| Stack Frames | 1000 |
| Variable Scopes per Frame | 1000 |
| Error Handlers per Frame | 100 |
Memory Model
All values are stored as strings internally. Type conversions happen on demand:
| Type | C# Type | Storage Format |
|---|
| String | string | Raw string |
| Integer | int | Parseable integer |
| Decimal | decimal | Parseable decimal |
| Boolean | bool | ”True” or “False” |
| Guid | Guid | Standard GUID format |
| DateTime | DateTime | Parseable date/time |
| JsonObject | JsonObject | Valid JSON object |
| JsonArray | JsonArray | Valid JSON array |
Error Handling Flow
When an exception occurs:
- Search current stack frame for error handler
- If found: jump to handler, set
LastErrorValue
- If not found: destroy frame, search parent frame
- 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.