From b5b4bd8c43a4d8bc0fa664866fd950f6107a70c2 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sat, 31 May 2025 20:49:15 +0700 Subject: [PATCH 01/53] start change to 0.18 --- modus/overview.mdx | 53 ++++++++++++++++++++++++---------------------- 1 file changed, 28 insertions(+), 25 deletions(-) diff --git a/modus/overview.mdx b/modus/overview.mdx index 2eac70a6..c7fbf513 100644 --- a/modus/overview.mdx +++ b/modus/overview.mdx @@ -8,37 +8,39 @@ sidebarTitle: "Overview" ## What is Modus? {/* vale Google.Contractions = NO */} -Modus is an open source, serverless framework for building functions and APIs, -powered by WebAssembly. +Modus is an open source, serverless framework for building intelligent agents +and APIs in Go or AssemblyScript (a TypeScript-like language). Modus is a +runtime purpose-built for orchestrating autonomous AI agents that operate as +first-class citizens in your stack. -You write your app logic in Go or AssemblyScript, and Modus provides additional -features to easily integrate models, data, and external services. +You write your app logic in Go or AssemblyScript—whichever you prefer—and Modus +compiles everything to WebAssembly for fast performance at scale and at the +edge. Each agent instance gets a dedicated execution environment, sand-boxed for +resiliency, scalability, and security. -To **build apps that are thoughtful, fun, and effective**, we often need to -integrate models in different forms, whether generative large language models or -classical machine/deep learning models. +Modus enables both stateless functions for quick API responses and stateful +agents that maintain persistent memory across interactions. This eliminates the +need to parse conversation histories, rebuild context from scratch, or lose +state when errors occur. -Your app might be a simple create, read, update, and delete (CRUD) function that -has a single model to identify similar entries. Or, it could be a complex -agentic reasoning system that chains dozens of models and data sources together. -**Modus creates a way of working with models that scales with your needs.** +You can run Modus locally for development or deploy it in seconds to Hypermode +for production. -Modus exists to make it easier for you to build the apps of your dreams. +## What is Modus good for? {/* vale Google.Contractions = NO */} - - Modus is a multi-language framework. It currently includes support for Go and - AssemblyScript, a WebAssembly compatible TypeScript-like language. Additional - language support is in development. - +Modus is designed for building both traditional functions and intelligent +agents. It supports sub-second response times for stateless operations and +long-running, autonomous workflows that maintain state over time. -## What is Modus good for? {/* vale Google.Contractions = NO */} +**Functions**: stateless operations for API endpoints, data processing, and AI +inference tasks. -We designed Modus primarily as a general-purpose app framework, it just happens -to treat models as a first-class component. With Modus you can use models, as -appropriate, without additional complexity. +**Agents**: stateful entities that maintain conversation history, coordinate +between models and tools, and operate independently over extended periods. +Agents automatically handle state persistence and fault tolerance. -However, Modus is best for apps that require sub-second response times. We've -made trade-offs to optimize for speed and simplicity. +Both can be deployed in the same app, allowing you to choose the right +abstraction for each use case. For more inspiration, check out the [Modus recipes](https://github.com/hypermodeinc/modus-recipes). @@ -49,9 +51,10 @@ A few of the core Modus features include: | Feature | Description | | ------------------------------------------- | -------------------------------------------------------------------------------------------- | -| [Multi-Language](/modus/project-structure) | Write functions in Go and AssemblyScript, with additional language support in development | +| **Agent Runtime** | Deploy autonomous agents as actors with dedicated execution environments and fault isolation | +| [Multi-Language](/modus/project-structure) | Write functions and agents in Go or AssemblyScript, compiled to WebAssembly for performance | | [Auto-Generated API](/modus/api-generation) | A secure API is automatically generated from your function signatures | | [Model Integration](/modus/model-invoking) | Connect and invoke AI models from different providers, without learning a new SDK | | [Search](/modus/search) | Add natural language search and recommendations with integrated vector embeddings | | [Authentication](/modus/authentication) | Secure your API endpoints with minimal configuration | -| **WebAssembly Runtime** | Small and portable execution engine for deployment across server, edge, and desktop computes | +| **WebAssembly Runtime** | Portable execution engine delivering fast performance at scale and at the edge | From 15854a5818dba1d5516fcfba85be19aef20f92d7 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sat, 31 May 2025 21:01:27 +0700 Subject: [PATCH 02/53] docs: * --- modus/overview.mdx | 37 ++++++++++++++++++++++++------------- 1 file changed, 24 insertions(+), 13 deletions(-) diff --git a/modus/overview.mdx b/modus/overview.mdx index c7fbf513..ec9ffdc8 100644 --- a/modus/overview.mdx +++ b/modus/overview.mdx @@ -45,16 +45,27 @@ abstraction for each use case. For more inspiration, check out the [Modus recipes](https://github.com/hypermodeinc/modus-recipes). -## Main features - -A few of the core Modus features include: - -| Feature | Description | -| ------------------------------------------- | -------------------------------------------------------------------------------------------- | -| **Agent Runtime** | Deploy autonomous agents as actors with dedicated execution environments and fault isolation | -| [Multi-Language](/modus/project-structure) | Write functions and agents in Go or AssemblyScript, compiled to WebAssembly for performance | -| [Auto-Generated API](/modus/api-generation) | A secure API is automatically generated from your function signatures | -| [Model Integration](/modus/model-invoking) | Connect and invoke AI models from different providers, without learning a new SDK | -| [Search](/modus/search) | Add natural language search and recommendations with integrated vector embeddings | -| [Authentication](/modus/authentication) | Secure your API endpoints with minimal configuration | -| **WebAssembly Runtime** | Portable execution engine delivering fast performance at scale and at the edge | +## Where to next? + + + + Build your first Modus app in minutes with our quickstart guide + + + Learn about stateless functions for APIs and data processing + + + Discover stateful agents that maintain memory across interactions + + + Understand the structure and organization your Modus app + + From be03811365c7e8eaac134abaa590f4c3a7bb5018 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sat, 31 May 2025 21:04:08 +0700 Subject: [PATCH 03/53] docs: * --- modus/overview.mdx | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/modus/overview.mdx b/modus/overview.mdx index ec9ffdc8..ae964656 100644 --- a/modus/overview.mdx +++ b/modus/overview.mdx @@ -52,13 +52,13 @@ For more inspiration, check out the Build your first Modus app in minutes with our quickstart guide Learn about stateless functions for APIs and data processing - + Discover stateful agents that maintain memory across interactions Date: Sat, 31 May 2025 21:07:31 +0700 Subject: [PATCH 04/53] * --- modus/overview.mdx | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/modus/overview.mdx b/modus/overview.mdx index ae964656..72e88f5c 100644 --- a/modus/overview.mdx +++ b/modus/overview.mdx @@ -32,6 +32,12 @@ Modus is designed for building both traditional functions and intelligent agents. It supports sub-second response times for stateless operations and long-running, autonomous workflows that maintain state over time. +**Beyond demo prompt apps**: We've all built apps with prompts and AI tool +integrations. When you're ready to take your project to the next level, Modus +serves as your AI component in the stack. Modus can sit right alongside your +existing app, handling the intelligent workflows while your main application +focuses on what it does best. + **Functions**: stateless operations for API endpoints, data processing, and AI inference tasks. From fc64e8108371d35cf2e09ac338b4306e75b218ff Mon Sep 17 00:00:00 2001 From: danstarns Date: Sat, 31 May 2025 22:52:03 +0700 Subject: [PATCH 05/53] * --- docs.json | 6 +- modus/agents.mdx | 319 ++++++++++++++++++++++++++++++++++++++++++++ modus/functions.mdx | 159 ++++++++++++++++++++++ 3 files changed, 482 insertions(+), 2 deletions(-) create mode 100644 modus/agents.mdx create mode 100644 modus/functions.mdx diff --git a/docs.json b/docs.json index d3c5cb18..c6a579b1 100644 --- a/docs.json +++ b/docs.json @@ -79,13 +79,15 @@ "group": "Getting Started", "pages": [ "modus/overview", - "modus/project-structure", - "modus/quickstart" + "modus/quickstart", + "modus/functions", + "modus/agents" ] }, { "group": "Building Your App", "pages": [ + "modus/project-structure", "modus/app-manifest", "modus/data-fetching", "modus/model-invoking", diff --git a/modus/agents.mdx b/modus/agents.mdx new file mode 100644 index 00000000..3d4217c9 --- /dev/null +++ b/modus/agents.mdx @@ -0,0 +1,319 @@ +--- +title: "What is an Agent?" +description: "Learn about stateful agents in Modus" +"og:title": "What is an Agent? - Modus" +--- + +## Agents in Modus + +Agents in Modus are stateful, autonomous entities that maintain persistent +memory across interactions. They solve fundamental problems with traditional +stateless approaches: no more parsing conversation histories from JSON strings, +no more rebuilding context from scratch on every message, no more losing +everything when errors occur. + +## Key characteristics + +- **Stateful**: Maintains memory and context across interactions +- **Persistent**: Automatically saves and restores state +- **Resilient**: Graceful recovery from failures +- **Autonomous**: Can operate independently over extended periods +- **Actor-based**: Each agent instance runs in isolation + +## When to use agents + +Agents are perfect for: + +- **Chat applications** that need conversation history +- **Multi-turn workflows** spanning multiple interactions +- **Long-running processes** that maintain context over time +- **Collaborative systems** where agents coordinate with each other +- **Personalized experiences** that learn user preferences + +## The problem agents solve + +Traditional stateless chat functions require: + +```go +func Chat(query string, chat_history string) (ChatResponse, error) { + // Parse the entire chat history every single time + var messages []ChatMessage + if chat_history != "" && chat_history != "null" { + err := json.Unmarshal([]byte(chat_history), &messages) + if err != nil { + // If parsing fails, we lose everything + messages = []ChatMessage{} + } + } + + // Add current message and rebuild context + messages = append(messages, ChatMessage{ + Role: "user", + Content: query, + }) + + // Convert to OpenAI format every time + // Call model and rebuild history again... +} +``` + +Every interaction requires parsing massive JSON strings, reconstructing context, +and risking data loss on errors. + +## How agents change everything + +With agents, conversation state lives in memory and persists automatically: + + + +```go Go +package main + +import ( + "encoding/json" + "fmt" + "time" + "github.com/hypermodeinc/modus/sdk/go/pkg/agents" + "github.com/hypermodeinc/modus/sdk/go/pkg/models" + "github.com/hypermodeinc/modus/sdk/go/pkg/models/openai" +) + +type ChatAgent struct { + agents.AgentBase + + conversationId string + messages []Message + lastActivity time.Time + userContext string +} + +type Message struct { + ID string `json:"id"` + Role string `json:"role"` + Content string `json:"content"` + Timestamp time.Time `json:"timestamp"` +} + +func (c *ChatAgent) Name() string { + return "ChatAgent" +} + +func (c *ChatAgent) OnReceiveMessage(msgName string, data *string) (*string, error) { + switch msgName { + case "chat": + return c.handleChatMessage(data) + case "get_history": + return c.getConversationHistory() + default: + return nil, fmt.Errorf("unknown message type: %s", msgName) + } +} + +func (c *ChatAgent) handleChatMessage(data *string) (*string, error) { + var request ChatRequest + json.Unmarshal([]byte(*data), &request) + + // Add user message to persistent state - no parsing needed! + userMessage := Message{ + ID: fmt.Sprintf("%d", time.Now().UnixNano()), + Role: "user", + Content: request.Message, + Timestamp: time.Now(), + } + c.messages = append(c.messages, userMessage) + c.lastActivity = time.Now() + + // Generate response using current context + response, err := c.generateAIResponse() + if err != nil { + return nil, err + } + + // Add response to persistent state + assistantMessage := Message{ + ID: fmt.Sprintf("%d", time.Now().UnixNano()), + Role: "assistant", + Content: response, + Timestamp: time.Now(), + } + c.messages = append(c.messages, assistantMessage) + + // Return response + chatResponse := ChatResponse{ + Message: response, + ConversationId: c.conversationId, + } + + responseData, _ := json.Marshal(chatResponse) + responseStr := string(responseData) + return &responseStr, nil +} +``` + +```ts AssemblyScript +import { agents } from "@hypermode/modus-sdk-as" +import { models } from "@hypermode/modus-sdk-as" +import { + OpenAIChatModel, + SystemMessage, + UserMessage, +} from "@hypermode/modus-sdk-as/models/openai/chat" + +@json +class Message { + id!: string + role!: string + content!: string + timestamp!: string +} + +export class ChatAgent extends agents.AgentBase { + conversationId: string = "" + messages: Message[] = [] + lastActivity: string = "" + userContext: string = "" + + Name(): string { + return "ChatAgent" + } + + OnReceiveMessage(msgName: string, data: string | null): string | null { + switch (msgName) { + case "chat": + return this.handleChatMessage(data) + case "get_history": + return this.getConversationHistory() + default: + throw new Error(`Unknown message type: ${msgName}`) + } + } + + handleChatMessage(data: string | null): string | null { + if (!data) throw new Error("No message data provided") + + const request = JSON.parse(data) + + // Add user message to persistent state - no parsing needed! + const userMessage: Message = { + id: Date.now().toString(), + role: "user", + content: request.message, + timestamp: new Date().toISOString(), + } + + this.messages.push(userMessage) + this.lastActivity = new Date().toISOString() + + // Generate AI response using current context + const response = this.generateAIResponse() + + // Add response to persistent state + const assistantMessage: Message = { + id: (Date.now() + 1).toString(), + role: "assistant", + content: response, + timestamp: new Date().toISOString(), + } + + this.messages.push(assistantMessage) + + const chatResponse: ChatResponse = { + message: response, + conversationId: this.conversationId, + } + + return JSON.stringify(chatResponse) + } +} +``` + + + +## Agent lifecycle + +Agents have built-in lifecycle hooks for robust operation: + +```go +func (c *ChatAgent) OnInitialize() error { + // Called when agent first starts + c.lastActivity = time.Now() + return nil +} + +func (c *ChatAgent) OnResume() error { + // Called when agent wakes up with complete state intact + fmt.Printf("Resuming conversation %s with %d messages", + c.conversationId, len(c.messages)) + return nil +} + +func (c *ChatAgent) OnSuspend() error { + // Called before agent goes dormant + return nil +} + +func (c *ChatAgent) OnTerminate() error { + // Called before final shutdown + return nil +} +``` + +## Working with agents + +To use agents in your Modus app: + +1. **Register your agent** in the `init()` function: + + ```go + func init() { + agents.Register(&ChatAgent{}) + } + ``` + +2. **Start an agent instance**: + + ```go + func StartChatAgent() (string, error) { + agentInfo, err := agents.Start("ChatAgent") + return agentInfo.Id, err + } + ``` + +3. **Send messages to agents**: + + ```go + func SendChatMessage(agentId string, message string) (ChatResponse, error) { + request := ChatRequest{Message: message} + requestData, _ := json.Marshal(request) + requestStr := string(requestData) + + responseStr, err := agents.SendMessage(agentId, "chat", agents.WithData(requestStr)) + // Handle response... + } + ``` + +## Agents against functions + +| Agents | Functions | +| ------------------------------ | ----------------------- | +| Stateful | Stateless | +| Persistent across interactions | Single request/response | +| Maintains conversation history | No memory | +| Long-running workflows | Fast, predictable | +| Complex, multi-step processes | Simple operations | +| Automatic state persistence | Manual state management | + +## Beyond simple chat + +Agents enable sophisticated patterns impossible with stateless functions: + +- **Contextual understanding**: Store user preferences and conversation themes +- **Multi-turn reasoning**: Build understanding over multiple interactions +- **Conversation recovery**: Retry from last known state instead of losing + everything +- **Progressive enhancement**: Start simple and build sophistication over time + +Agents represent a fundamental shift from fragile, stateless functions to +robust, persistent entities that maintain conversation continuity no matter what +happens. They're the foundation for building production-ready intelligent +applications. diff --git a/modus/functions.mdx b/modus/functions.mdx new file mode 100644 index 00000000..ac8da381 --- /dev/null +++ b/modus/functions.mdx @@ -0,0 +1,159 @@ +--- +title: "What is a Function?" +description: "Learn about stateless functions in Modus" +"og:title": "What is a Function? - Modus" +--- + +## Functions in Modus + +Functions in Modus are stateless, request-response operations designed for fast, +predictable API endpoints, data processing, and AI inference tasks. They're +perfect when you need quick responses without maintaining context between calls. + +## Key characteristics + +- **Stateless**: Each function call is independent with no memory of previous + interactions +- **Fast**: Optimized for sub-second response times +- **Scalable**: Automatically scale based on demand +- **Simple**: Straightforward request-in, response-out pattern + +## When to use functions + +Functions are ideal for: + +- **API endpoints** that process individual requests +- **Data processing** tasks like transformations or validations +- **AI inference** for text generation, classification, or embeddings +- **Integrations** with external services +- **Calculations** that don't require historical context + +## Example: Text generation function + +Here's a simple function that generates text using an AI model: + + + +```go Go +package main + +import ( + "strings" + "github.com/hypermodeinc/modus/sdk/go/pkg/models" + "github.com/hypermodeinc/modus/sdk/go/pkg/models/openai" +) + +const modelName = "text-generator" + +func GenerateText(prompt string) (string, error) { + model, err := models.GetModel[openai.ChatModel](modelName) + if err != nil { + return "", err + } + + input, err := model.CreateInput( + openai.NewUserMessage(prompt), + ) + if err != nil { + return "", err + } + + input.Temperature = 0.7 + + output, err := model.Invoke(input) + if err != nil { + return "", err + } + + return strings.TrimSpace(output.Choices[0].Message.Content), nil +} +``` + +```ts AssemblyScript +import { models } from "@hypermode/modus-sdk-as" +import { + OpenAIChatModel, + UserMessage, +} from "@hypermode/modus-sdk-as/models/openai/chat" + +const modelName: string = "text-generator" + +export function generateText(prompt: string): string { + const model = models.getModel(modelName) + const input = model.createInput([new UserMessage(prompt)]) + + input.temperature = 0.7 + + const output = model.invoke(input) + return output.choices[0].message.content.trim() +} +``` + + + +## Example: Data processing function + +Functions are also great for processing data without AI: + + + +```go Go +func ProcessOrder(orderData string) (OrderSummary, error) { + var order Order + if err := json.Unmarshal([]byte(orderData), &order); err != nil { + return OrderSummary{}, err + } + + total := 0.0 + for _, item := range order.Items { + total += item.Price * float64(item.Quantity) + } + + return OrderSummary{ + OrderID: order.ID, + Total: total, + Status: "processed", + }, nil +} +``` + +```ts AssemblyScript +export function processOrder(orderData: string): OrderSummary { + const order = JSON.parse(orderData) + + let total: f64 = 0 + for (let i = 0; i < order.items.length; i++) { + total += order.items[i].price * order.items[i].quantity + } + + return { + orderId: order.id, + total: total, + status: "processed", + } +} +``` + + + +## Functions against agents + +| Functions | Agents | +| ----------------------- | ------------------------------ | +| Stateless | Stateful | +| Single request/response | Persistent across interactions | +| No memory | Maintains conversation history | +| Fast, predictable | Long-running workflows | +| Simple operations | Complex, multi-step processes | + +## Getting started with functions + +1. **Define your function** in Go or AssemblyScript +2. **Export it** so Modus can generate an API endpoint +3. **Configure models or connections** in your `modus.json` if needed +4. **Run locally** with `modus dev` to test +5. **Deploy** to Hypermode for production + +Functions form the foundation of many Modus apps. When you need to maintain +state or memory across interactions, consider using [agents](/modus/agents) +instead. From f61d8171b864db84b0e66c8d0f912eefa6c466f6 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sat, 31 May 2025 22:53:20 +0700 Subject: [PATCH 06/53] * --- modus/overview.mdx | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/modus/overview.mdx b/modus/overview.mdx index 72e88f5c..3207d023 100644 --- a/modus/overview.mdx +++ b/modus/overview.mdx @@ -32,11 +32,11 @@ Modus is designed for building both traditional functions and intelligent agents. It supports sub-second response times for stateless operations and long-running, autonomous workflows that maintain state over time. -**Beyond demo prompt apps**: We've all built apps with prompts and AI tool +**Beyond demo prompt apps**: we've all built apps with prompts and AI tool integrations. When you're ready to take your project to the next level, Modus serves as your AI component in the stack. Modus can sit right alongside your -existing app, handling the intelligent workflows while your main application -focuses on what it does best. +existing app, handling the intelligent workflows while your main app focuses on +what it does best. **Functions**: stateless operations for API endpoints, data processing, and AI inference tasks. @@ -57,11 +57,7 @@ For more inspiration, check out the Build your first Modus app in minutes with our quickstart guide - + Learn about stateless functions for APIs and data processing From 0bb775e1599db32936f628030dcb0d3c5df2c415 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sat, 31 May 2025 23:28:57 +0700 Subject: [PATCH 07/53] * --- modus/quickstart.mdx | 282 ++++++++++++++----------------------------- 1 file changed, 93 insertions(+), 189 deletions(-) diff --git a/modus/quickstart.mdx b/modus/quickstart.mdx index 2756e5a5..274e2447 100644 --- a/modus/quickstart.mdx +++ b/modus/quickstart.mdx @@ -5,9 +5,19 @@ mode: "wide" "og:title": "Quickstart - Modus" --- -In this quickstart we'll show you how to get set up with Modus and its CLI and -build a simple app that fetches a random quote from an external API. You'll -learn how to use the basic components of a Modus app and how to run it locally. +## Your first mission, agent deployment + +In this quickstart, you'll learn to build and deploy intelligent agents that +operate autonomously in your stack. Think James Bond meets The Matrix—your +agents maintain memory, coordinate operations, and never lose their mission +context. + +Our examples use Go, which we recommend for new projects. You can also choose +AssemblyScript if you prefer. For AssemblyScript usage, refer to the +[AssemblyScript SDK overview](/modus/sdk/assemblyscript/overview). + +We'll start with a simple function and then show you how to build stateful +agents that remember every interaction. ## Prerequisites @@ -19,8 +29,7 @@ learn how to use the basic components of a Modus app and how to run it locally. - The Modus CLI provides a set of commands to help you create, build, and run your Modus apps. - Install the CLI using npm. + Install the Modus CLI to manage your Modus applications. ```sh npm install -g @hypermode/modus-cli @@ -28,49 +37,28 @@ learn how to use the basic components of a Modus app and how to run it locally. - - To create a new Modus app, run the following command in your terminal: + + Create your first Modus app. ```sh modus new ``` - This command prompts you to choose between Go and AssemblyScript as the language for your app. It - then creates a new directory with the necessary files and folders for your app. You will also be asked if you would like to initialize a Git repository. + Choose between Go and AssemblyScript. Both compile to WebAssembly for fast performance. - - To build and run your app, navigate to the app directory and run the following command: + + Start your local development server: ```sh modus dev ``` - This command runs your app locally in development mode and provides you with a URL to access your - app's generated API. + This starts your app and provides a URL to access the API. + - - - Once your app is running, you can access the graphical interface for your API at the URL located in your terminal. - - ```sh - View endpoint: http://localhost:8686/explorer - ``` - - The API Explorer interface allows you to interact with your app's API and test your functions. - - API Graphical Interface. - - - - Modus is a secure-by-default framework. To connect to external services, you need to add a connection - in your app manifest. - - Add the following code into your `modus.json` manifest file: + + To connect to external services, add this to your `modus.json`: ```json modus.json { @@ -84,8 +72,8 @@ learn how to use the basic components of a Modus app and how to run it locally. ``` - - Modus also supports AI models. You can define new models in your `modus.json` file. Let's add a new meta-llama model: + + Add an AI model to your manifest: ```json "models": { @@ -98,27 +86,24 @@ learn how to use the basic components of a Modus app and how to run it locally. ``` - - Next, install the Hyp CLI. This allows you to access hosted models on the Hypermode platform. + + Install and authenticate with the Hyp CLI to access Hypermode-hosted models: ```sh npm install -g @hypermode/hyp-cli + hyp login ``` - You can now use the `hyp login` command to log in to the Hyp CLI. - This links your project to the Hypermode platform, allowing you to leverage the model in your modus app. + This connects your local development environment to Hypermode's model infrastructure. + + Create a function that fetches data from an external API and uses AI for analysis: - - Functions are the building blocks of your app. Let's add a function that fetches a random quote from - the ZenQuotes connection and uses AI to generate a summary for the quote. - - - - Create a new file in the root directory with the following code: + + Create `intelligence.go`: - ```go quotes.go + ```go intelligence.go package main import ( @@ -131,17 +116,16 @@ learn how to use the basic components of a Modus app and how to run it locally. "github.com/hypermodeinc/modus/sdk/go/pkg/models/openai" ) - type Quote struct { - Quote string `json:"q"` - Author string `json:"a"` - Summary string `json:"summary,omitempty"` + type IntelReport struct { + Quote string `json:"quote"` + Author string `json:"author"` + Analysis string `json:"analysis,omitempty"` } const modelName = "text-generator" - // this function makes a request to an API that returns data in JSON format, - // and returns a single quote with AI-generated summary - func GetRandomQuote() (*Quote, error) { + // Fetch a random quote and provide AI analysis + func GatherIntelligence() (*IntelReport, error) { request := http.NewRequest("https://zenquotes.io/api/random") response, err := http.Fetch(request) @@ -149,50 +133,51 @@ learn how to use the basic components of a Modus app and how to run it locally. return nil, err } if !response.Ok() { - return nil, fmt.Errorf("failed to fetch quote. Received: %d %s", response.Status, response.StatusText) + return nil, fmt.Errorf("request failed: %d %s", response.Status, response.StatusText) } - // the API returns an array of quotes, but we only need the first one - var quotes []Quote + // Parse the API response + var quotes []IntelReport response.JSON("es) if len(quotes) == 0 { - return nil, errors.New("expected at least one quote in the response, but none were found") + return nil, errors.New("no data received") } - // Get the first (and only) quote - quote := quotes[0] + // Get the quote + intel := quotes[0] - // Generate AI summary for the quote - summary, err := summarizeQuote(quote.Quote, quote.Author) + // Generate AI analysis + analysis, err := analyzeIntelligence(intel.Quote, intel.Author) if err != nil { - fmt.Printf("Warning: failed to summarize quote by %s: %v\n", quote.Author, err) - quote.Summary = "Summary unavailable" + fmt.Printf("AI analysis failed for %s: %v\n", intel.Author, err) + intel.Analysis = "Analysis unavailable" } else { - quote.Summary = summary + intel.Analysis = analysis } - return "e, nil + return &intel, nil } - // summarizeQuote uses the AI model to generate a concise summary of the quote - func summarizeQuote(quote, author string) (string, error) { + // Use AI to analyze the quote + func analyzeIntelligence(quote, author string) (string, error) { model, err := models.GetModel[openai.ChatModel](modelName) if err != nil { return "", err } - instruction := "Provide a brief, insightful summary that captures the essence and meaning of the quote in 1-2 sentences." - prompt := fmt.Sprintf("Quote: \"%s\" - %s", quote, author) + prompt := `You are an analyst. + Provide a brief insight that captures the core meaning + and practical application of this wisdom in 1-2 sentences.` + content := fmt.Sprintf("Quote: \"%s\" - %s", quote, author) input, err := model.CreateInput( - openai.NewSystemMessage(instruction), - openai.NewUserMessage(prompt), + openai.NewSystemMessage(prompt), + openai.NewUserMessage(content), ) if err != nil { return "", err } - // Set temperature for consistent but creative responses input.Temperature = 0.7 output, err := model.Invoke(input) @@ -203,138 +188,57 @@ learn how to use the basic components of a Modus app and how to run it locally. return strings.TrimSpace(output.Choices[0].Message.Content), nil } ``` - - - - Create a new file in the `assembly` directory with the following code: - - ```ts quotes.ts - import { http, models } from "@hypermode/modus-sdk-as"; - import { - OpenAIChatModel, - SystemMessage, - UserMessage, - } from "@hypermode/modus-sdk-as/models/openai/chat"; - - @json - class Quote { - @alias("q") - quote!: string; - - @alias("a") - author!: string; - - summary?: string; - } - - const modelName: string = "text-generator"; - - // this function makes a request to an API that returns data in JSON format, - // and returns a single quote with AI-generated summary - export function getRandomQuote(): Quote { - const request = new http.Request("https://zenquotes.io/api/random"); - - const response = http.fetch(request); - if (!response.ok) { - throw new Error( - `Failed to fetch quote. Received: ${response.status} ${response.statusText}`, - ); - } - - // the API returns an array of quotes, but we only need the first one - const quotes = response.json(); - if (quotes.length === 0) { - throw new Error("Expected at least one quote in the response, but none were found"); - } - - // Get the first (and only) quote - const quote = quotes[0]; - - // Generate AI summary for the quote - try { - quote.summary = summarizeQuote(quote.quote, quote.author); - } catch (error) { - console.log(`Warning: failed to summarize quote by ${quote.author}: ${error}`); - quote.summary = "Summary unavailable"; - } - - return quote; - } - - // summarizeQuote uses the AI model to generate a concise summary of the quote - function summarizeQuote(quote: string, author: string): string { - const model = models.getModel(modelName); - - const instruction = "Provide a brief, insightful summary that captures the essence and meaning of the quote in 1-2 sentences."; - const prompt = `Quote: "${quote}" - ${author}`; - - const input = model.createInput([ - new SystemMessage(instruction), - new UserMessage(prompt), - ]); - - // Set temperature for consistent but creative responses - input.temperature = 0.7; - - const output = model.invoke(input); - return output.choices[0].message.content.trim(); - } - ``` - - Then add the following to `index.ts`. This includes the `getRandomQuote` function on - your generated API. - - ```ts index.ts - export * from "./quotes"; - ``` - - - + - - - Now that you've integrated the AI model, let's test it! After adding your function, restart your development server: + + Restart your development server: ```sh modus dev ``` - Navigate to the API Explorer at `http://localhost:8686/explorer` and you'll see your `randomQuote` function available to test. - - When you call the function, you'll notice that the quote includes three fields: - - `quote`: The original quote text - - `author`: The author's name - - `summary`: An AI-generated summary that captures the essence of the quote - - The AI model analyzes the quote and provides insightful context about its meaning, making your app more engaging and informative for users. + Modus generates a GraphQL API that you can interact with however you like. + We provide you with an exploration tool at `http://localhost:8686/explorer` + for testing your functions. - Try calling the function multiple times to see how the AI generates different summaries for various quotes! + Your function now: + - Fetches data from external APIs + - Uses AI models for analysis + - Provides intelligent responses + - Handles errors gracefully - - - - When testing an AI app locally, Modus records the inference and related metadata - in the `View Inferences` tab of the APIs explorer. + + When running locally, Modus records every AI model call for monitoring and debugging. + You can see this in the Modus explorer. - Local model tracing is only supported on Linux and macOS. Windows support is - coming soon. + Local inference tracking is supported on Linux and macOS. Windows + support is incoming. - ![local model tracing](../images/observe-functions/local-inference-history.png) - - You can now see detailed information about each AI model call, including: - - Input prompts sent to the model - - Generated responses - - Performance metrics like response time - - Token usage and costs + You can monitor: + - Requests sent to AI models + - Response times and token usage + - Model performance metrics + - Error rates and debugging info +## What's next? + +You've successfully built your first Modus function. But this is just the +beginning. Real agents maintain memory, coordinate complex operations, and never +lose their context. + +Ready to upgrade from simple functions to stateful agents? Check out +[What's an Agent?](/modus/agents) to learn how to build persistent, +memory-enabled agents that remember every interaction and can coordinate +sophisticated multi-step operations. + - For more inspiration, check out the [Modus + For more mission templates and advanced operations, explore the [Modus recipes](https://github.com/hypermodeinc/modus-recipes). From 0093917b35708969fd8ac56fdf62c363fd9e4c47 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 00:25:22 +0700 Subject: [PATCH 08/53] * --- modus/quickstart.mdx | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/modus/quickstart.mdx b/modus/quickstart.mdx index 274e2447..0b572a80 100644 --- a/modus/quickstart.mdx +++ b/modus/quickstart.mdx @@ -91,7 +91,12 @@ agents that remember every interaction. ```sh npm install -g @hypermode/hyp-cli - hyp login + ``` + + Authenticate with your Hypermode account: + + ```sh + hyp login ``` This connects your local development environment to Hypermode's model infrastructure. From 38f1bda70e10d087cf809f37ec70e5090de94def Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 01:02:09 +0700 Subject: [PATCH 09/53] * --- modus/functions.mdx | 300 +++++++++++++++++++++++++++++-------------- modus/quickstart.mdx | 19 ++- 2 files changed, 210 insertions(+), 109 deletions(-) diff --git a/modus/functions.mdx b/modus/functions.mdx index ac8da381..e18c62f5 100644 --- a/modus/functions.mdx +++ b/modus/functions.mdx @@ -1,58 +1,181 @@ ---- -title: "What is a Function?" -description: "Learn about stateless functions in Modus" -"og:title": "What is a Function? - Modus" ---- +# What's a function? -## Functions in Modus +Functions in Modus are your reliable field operatives—specialized agents who +handle specific missions with precision and speed. Like elite reconnaissance +units, they get in, complete their objective, and report back. No unnecessary +complications, no lingering presence, just pure operational efficiency. -Functions in Modus are stateless, request-response operations designed for fast, -predictable API endpoints, data processing, and AI inference tasks. They're -perfect when you need quick responses without maintaining context between calls. +Functions are the backbone of your intelligence network, handling everything +from data gathering to AI-powered analysis, all while maintaining perfect +operational discipline. -## Key characteristics +## Operational profile -- **Stateless**: Each function call is independent with no memory of previous - interactions -- **Fast**: Optimized for sub-second response times -- **Scalable**: Automatically scale based on demand -- **Simple**: Straightforward request-in, response-out pattern +Functions are stateless, request-response operations designed for fast, +predictable missions. They're your go-to operatives when you need quick +intelligence gathering, data processing, or tactical strikes without maintaining +ongoing surveillance between operations. -## When to use functions +### Core capabilities -Functions are ideal for: +- **Mission-focused**: Each operation is independent with no memory of previous + assignments +- **Lightning fast**: Optimized for sub-second mission completion +- **Infinitely scalable**: Deploy as many operatives as needed +- **Clean operations**: Straightforward request-in, intel-out pattern +- **Auto-deployed**: Exposed automatically as GraphQL queries or mutations -- **API endpoints** that process individual requests -- **Data processing** tasks like transformations or validations -- **AI inference** for text generation, classification, or embeddings -- **Integrations** with external services -- **Calculations** that don't require historical context +## How functions become endpoints -## Example: Text generation function +When you deploy your operatives, Modus automatically exposes them through a +GraphQL API. Your functions become either **queries** (for gathering +intelligence) or **mutations** (for operational changes) based on their mission +type. -Here's a simple function that generates text using an AI model: +### Intelligence gathering queries - +Most functions become GraphQL queries—perfect for reconnaissance and data +retrieval: -```go Go +```go +// Becomes a GraphQL query: getUserProfile(id: String!): UserProfile +func GetUserProfile(id string) (*UserProfile, error) { + // Intelligence gathering operation + return fetchUserData(id) +} + +// Becomes a GraphQL query: analyzeMarketTrends(): TrendReport +func AnalyzeMarketTrends() (*TrendReport, error) { + // Analysis operation using AI models + return generateTrendAnalysis() +} +``` + +### Operational change mutations + +Functions that modify data automatically become GraphQL mutations. Modus detects +these by their mission prefixes: + +```go +// Becomes a GraphQL mutation: createUser(data: UserInput!): User +func CreateUser(data UserInput) (*User, error) { + // Operational creation mission + return deployNewUser(data) +} + +// Becomes a GraphQL mutation: updateMissionStatus(id: String!, status: String!): Mission +func UpdateMissionStatus(id string, status string) (*Mission, error) { + // Status update operation + return modifyMissionRecord(id, status) +} +``` + +Functions starting with `create`, `update`, `delete`, and similar action words +automatically become mutations. + +## Mission example: weather intelligence analysis + +Here's a complete tactical operation that demonstrates how functions integrate +external APIs with AI models for intelligence analysis: + +```go package main import ( + "fmt" "strings" + "github.com/hypermodeinc/modus/sdk/go/pkg/http" "github.com/hypermodeinc/modus/sdk/go/pkg/models" "github.com/hypermodeinc/modus/sdk/go/pkg/models/openai" ) +type WeatherIntel struct { + City string `json:"city"` + Temperature float64 `json:"temperature"` + Conditions string `json:"conditions"` + Analysis string `json:"analysis"` +} + const modelName = "text-generator" -func GenerateText(prompt string) (string, error) { +// Operative: Gather weather intelligence and provide tactical analysis +func GatherWeatherIntelligence(city string) (*WeatherIntel, error) { + // Fetch weather data from OpenWeatherMap API + url := fmt.Sprintf( + "https://api.openweathermap.org/data/2.5/weather?q=%s&appid={{API_KEY}}&units=metric", + city, + ) + + response, err := http.Fetch(url) + if err != nil { + return nil, err + } + if !response.Ok() { + return nil, fmt.Errorf( + "weather intelligence gathering failed: %d %s", + response.Status, + response.StatusText, + ) + } + + // Parse weather data + var weatherData struct { + Name string `json:"name"` + Main struct { + Temp float64 `json:"temp"` + } `json:"main"` + Weather []struct { + Description string `json:"description"` + } `json:"weather"` + } + + response.JSON(&weatherData) + + conditions := "unknown" + if len(weatherData.Weather) > 0 { + conditions = weatherData.Weather[0].Description + } + + // Generate tactical analysis + analysis, err := analyzeTacticalConditions( + weatherData.Name, + weatherData.Main.Temp, + conditions, + ) + if err != nil { + fmt.Printf("Tactical analysis failed for %s: %v\n", weatherData.Name, err) + analysis = "Analysis unavailable - proceed with standard protocols" + } + + return &WeatherIntel{ + City: weatherData.Name, + Temperature: weatherData.Main.Temp, + Conditions: conditions, + Analysis: analysis, + }, nil +} + +// Analyze weather conditions for tactical implications +func analyzeTacticalConditions(city string, temp float64, conditions string) (string, error) { model, err := models.GetModel[openai.ChatModel](modelName) if err != nil { return "", err } + prompt := `You are a tactical analyst evaluating weather conditions for field operations. + Provide a brief tactical assessment of how these weather conditions might impact + outdoor activities, visibility, and operational considerations in 1-2 sentences.` + + content := fmt.Sprintf( + "Location: %s, Temperature: %.1f°C, Conditions: %s", + city, + temp, + conditions, + ) + input, err := model.CreateInput( - openai.NewUserMessage(prompt), + openai.NewSystemMessage(prompt), + openai.NewUserMessage(content), ) if err != nil { return "", err @@ -69,91 +192,70 @@ func GenerateText(prompt string) (string, error) { } ``` -```ts AssemblyScript -import { models } from "@hypermode/modus-sdk-as" -import { - OpenAIChatModel, - UserMessage, -} from "@hypermode/modus-sdk-as/models/openai/chat" - -const modelName: string = "text-generator" +This operative automatically becomes available as a GraphQL query: -export function generateText(prompt: string): string { - const model = models.getModel(modelName) - const input = model.createInput([new UserMessage(prompt)]) - - input.temperature = 0.7 - - const output = model.invoke(input) - return output.choices[0].message.content.trim() +```graphql +query { + gatherWeatherIntelligence(city: "London") { + city + temperature + conditions + analysis + } } ``` - +To use this function, you'll need to: -## Example: Data processing function +Sign up for a free API key at [OpenWeatherMap](https://openweathermap.org/api) -Functions are also great for processing data without AI: +Add the connection to your `modus.json`: - - -```go Go -func ProcessOrder(orderData string) (OrderSummary, error) { - var order Order - if err := json.Unmarshal([]byte(orderData), &order); err != nil { - return OrderSummary{}, err +```json +{ + "connections": { + "weather-api": { + "type": "http", + "baseUrl": "https://api.openweathermap.org/", + "queryParameters": { + "appid": "{{API_KEY}}" + } } + } +} +``` - total := 0.0 - for _, item := range order.Items { - total += item.Price * float64(item.Quantity) - } +Set your API key in `.env.dev.local`: - return OrderSummary{ - OrderID: order.ID, - Total: total, - Status: "processed", - }, nil -} +```sh +MODUS_WEATHER_API_API_KEY=your_openweathermap_api_key_here ``` -```ts AssemblyScript -export function processOrder(orderData: string): OrderSummary { - const order = JSON.parse(orderData) +## Functions against agents - let total: f64 = 0 - for (let i = 0; i < order.items.length; i++) { - total += order.items[i].price * order.items[i].quantity - } +| Functions | Agents | +| ---------------------- | ------------------------ | +| Field operatives | Agents | +| Single mission focus | Long-term assignments | +| No operational memory | Complete mission history | +| Fast tactical strikes | Strategic operations | +| Independent operations | Coordinated campaigns | - return { - orderId: order.id, - total: total, - status: "processed", - } -} -``` +## When to deploy agents - +Functions are perfect for most tactical operations, but when you need persistent +surveillance, complex multi-phase operations, or operatives that remember every +detail of ongoing investigations, it's time to deploy your +[agents](/modus/agents). -## Functions against agents +Consider upgrading to agents when missions require: + +- **Operational memory** across multiple engagements +- **Conversation intelligence** that builds over time +- **Multi-phase operations** spanning days or weeks +- **Recovery protocols** from mission failures +- **Continuous monitoring** with state preservation -| Functions | Agents | -| ----------------------- | ------------------------------ | -| Stateless | Stateful | -| Single request/response | Persistent across interactions | -| No memory | Maintains conversation history | -| Fast, predictable | Long-running workflows | -| Simple operations | Complex, multi-step processes | - -## Getting started with functions - -1. **Define your function** in Go or AssemblyScript -2. **Export it** so Modus can generate an API endpoint -3. **Configure models or connections** in your `modus.json` if needed -4. **Run locally** with `modus dev` to test -5. **Deploy** to Hypermode for production - -Functions form the foundation of many Modus apps. When you need to maintain -state or memory across interactions, consider using [agents](/modus/agents) -instead. +Your functions form the tactical backbone of your intelligence operations—fast, +reliable, and always ready for the next mission. They handle the day-to-day +operations while your agents manage the long-term strategic initiatives. diff --git a/modus/quickstart.mdx b/modus/quickstart.mdx index 0b572a80..b2dba26d 100644 --- a/modus/quickstart.mdx +++ b/modus/quickstart.mdx @@ -5,20 +5,17 @@ mode: "wide" "og:title": "Quickstart - Modus" --- -## Your first mission, agent deployment +## Your first Modus app -In this quickstart, you'll learn to build and deploy intelligent agents that -operate autonomously in your stack. Think James Bond meets The Matrix—your -agents maintain memory, coordinate operations, and never lose their mission -context. +In this quickstart, you'll learn to build your first Modus app with a single +function that demonstrates how to integrate external APIs with AI models. We'll +start with this stateless function, and later you can learn about building +stateful agents that maintain memory and coordinate complex operations. Our examples use Go, which we recommend for new projects. You can also choose AssemblyScript if you prefer. For AssemblyScript usage, refer to the [AssemblyScript SDK overview](/modus/sdk/assemblyscript/overview). -We'll start with a simple function and then show you how to build stateful -agents that remember every interaction. - ## Prerequisites - [Node.js](https://nodejs.org/en/download/package-manager) - v22 or higher @@ -76,13 +73,15 @@ agents that remember every interaction. Add an AI model to your manifest: ```json + { "models": { "text-generator": { "sourceModel": "meta-llama/Llama-3.2-3B-Instruct", "provider": "hugging-face", "connection": "hypermode" } - }, + } + } ``` @@ -96,7 +95,7 @@ agents that remember every interaction. Authenticate with your Hypermode account: ```sh - hyp login + hyp login ``` This connects your local development environment to Hypermode's model infrastructure. From 03d662b8c3f181009723534e56f79bf96024df86 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 01:09:11 +0700 Subject: [PATCH 10/53] * --- modus/functions.mdx | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/modus/functions.mdx b/modus/functions.mdx index e18c62f5..4b047792 100644 --- a/modus/functions.mdx +++ b/modus/functions.mdx @@ -1,4 +1,8 @@ -# What's a function? +--- +title: "What is a Function?" +description: "Learn about your basic operatives in Modus" +"og:title": "What is a Function? - Modus" +--- Functions in Modus are your reliable field operatives—specialized agents who handle specific missions with precision and speed. Like elite reconnaissance @@ -205,6 +209,8 @@ query { } ``` +### Deploying your operative + To use this function, you'll need to: Sign up for a free API key at [OpenWeatherMap](https://openweathermap.org/api) @@ -231,16 +237,6 @@ Set your API key in `.env.dev.local`: MODUS_WEATHER_API_API_KEY=your_openweathermap_api_key_here ``` -## Functions against agents - -| Functions | Agents | -| ---------------------- | ------------------------ | -| Field operatives | Agents | -| Single mission focus | Long-term assignments | -| No operational memory | Complete mission history | -| Fast tactical strikes | Strategic operations | -| Independent operations | Coordinated campaigns | - ## When to deploy agents Functions are perfect for most tactical operations, but when you need persistent From c2845f7c27e0cd88552035f65ba2d714111c91fc Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 01:21:39 +0700 Subject: [PATCH 11/53] * --- modus/functions.mdx | 2 ++ 1 file changed, 2 insertions(+) diff --git a/modus/functions.mdx b/modus/functions.mdx index 4b047792..c4c90aca 100644 --- a/modus/functions.mdx +++ b/modus/functions.mdx @@ -4,6 +4,8 @@ description: "Learn about your basic operatives in Modus" "og:title": "What is a Function? - Modus" --- +## Functions in Modus + Functions in Modus are your reliable field operatives—specialized agents who handle specific missions with precision and speed. Like elite reconnaissance units, they get in, complete their objective, and report back. No unnecessary From 470e7efa13b37480a2074b09ee828f6c4b0f485e Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 01:31:34 +0700 Subject: [PATCH 12/53] * --- modus/agents.mdx | 394 ++++++++++++++++++++--------------------------- 1 file changed, 171 insertions(+), 223 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 3d4217c9..c2b69901 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -6,11 +6,10 @@ description: "Learn about stateful agents in Modus" ## Agents in Modus -Agents in Modus are stateful, autonomous entities that maintain persistent -memory across interactions. They solve fundamental problems with traditional -stateless approaches: no more parsing conversation histories from JSON strings, -no more rebuilding context from scratch on every message, no more losing -everything when errors occur. +Agents in Modus are elite operatives that maintain persistent memory across +missions. Unlike stateless functions that lose everything when operations end, +agents remember every detail, survive system failures, and never lose their +operational context. ## Key characteristics @@ -24,296 +23,245 @@ everything when errors occur. Agents are perfect for: -- **Chat applications** that need conversation history - **Multi-turn workflows** spanning multiple interactions - **Long-running processes** that maintain context over time -- **Collaborative systems** where agents coordinate with each other -- **Personalized experiences** that learn user preferences +- **Stateful operations** that need to remember previous actions +- **Complex coordination** between different system components +- **Persistent monitoring** that tracks changes over time -## The problem agents solve +## Agent structure -Traditional stateless chat functions require: +Every agent starts with the essential operational framework: ```go -func Chat(query string, chat_history string) (ChatResponse, error) { - // Parse the entire chat history every single time - var messages []ChatMessage - if chat_history != "" && chat_history != "null" { - err := json.Unmarshal([]byte(chat_history), &messages) - if err != nil { - // If parsing fails, we lose everything - messages = []ChatMessage{} - } - } - - // Add current message and rebuild context - messages = append(messages, ChatMessage{ - Role: "user", - Content: query, - }) - - // Convert to OpenAI format every time - // Call model and rebuild history again... -} -``` - -Every interaction requires parsing massive JSON strings, reconstructing context, -and risking data loss on errors. - -## How agents change everything - -With agents, conversation state lives in memory and persists automatically: - - - -```go Go package main import ( - "encoding/json" "fmt" "time" "github.com/hypermodeinc/modus/sdk/go/pkg/agents" - "github.com/hypermodeinc/modus/sdk/go/pkg/models" - "github.com/hypermodeinc/modus/sdk/go/pkg/models/openai" ) -type ChatAgent struct { +type OperativeAgent struct { agents.AgentBase - conversationId string - messages []Message - lastActivity time.Time - userContext string + missionCount int + assignments []string + lastContact time.Time } -type Message struct { - ID string `json:"id"` - Role string `json:"role"` - Content string `json:"content"` - Timestamp time.Time `json:"timestamp"` +func (o *OperativeAgent) Name() string { + return "OperativeAgent" } +``` -func (c *ChatAgent) Name() string { - return "ChatAgent" -} +The agent embeds `agents.AgentBase`, which provides all the infrastructure for +state management, secure communications, and mission persistence. Your +operational data—mission count, assignment records, contact logs—lives as fields +in the struct, automatically preserved across all interactions. + +## Agent message handling -func (c *ChatAgent) OnReceiveMessage(msgName string, data *string) (*string, error) { +Agents process operational directives through their secure message handling +system: + +```go +func (o *OperativeAgent) OnReceiveMessage(msgName string, data *string) (*string, error) { switch msgName { - case "chat": - return c.handleChatMessage(data) - case "get_history": - return c.getConversationHistory() + case "accept_mission": + return o.acceptMission(data) + case "mission_status": + return o.getMissionStatus() + case "assignment_history": + return o.getAssignmentHistory() default: - return nil, fmt.Errorf("unknown message type: %s", msgName) + return nil, fmt.Errorf("unrecognized directive: %s", msgName) } } +``` -func (c *ChatAgent) handleChatMessage(data *string) (*string, error) { - var request ChatRequest - json.Unmarshal([]byte(*data), &request) +Each directive triggers specific operational procedures, with all intelligence +automatically maintained in the agent's secure memory. - // Add user message to persistent state - no parsing needed! - userMessage := Message{ - ID: fmt.Sprintf("%d", time.Now().UnixNano()), - Role: "user", - Content: request.Message, - Timestamp: time.Now(), - } - c.messages = append(c.messages, userMessage) - c.lastActivity = time.Now() +## Processing operations - // Generate response using current context - response, err := c.generateAIResponse() - if err != nil { - return nil, err - } +Here's how agents handle field operations while maintaining persistent state: - // Add response to persistent state - assistantMessage := Message{ - ID: fmt.Sprintf("%d", time.Now().UnixNano()), - Role: "assistant", - Content: response, - Timestamp: time.Now(), +```go +func (o *OperativeAgent) acceptMission(data *string) (*string, error) { + missionType := "classified" + if data != nil { + missionType = *data } - c.messages = append(c.messages, assistantMessage) - // Return response - chatResponse := ChatResponse{ - Message: response, - ConversationId: c.conversationId, - } + // Update operational status - no intel parsing needed! + o.missionCount++ + o.assignments = append(o.assignments, fmt.Sprintf("Mission %d: %s", o.missionCount, missionType)) + o.lastContact = time.Now() - responseData, _ := json.Marshal(chatResponse) - responseStr := string(responseData) - return &responseStr, nil + result := fmt.Sprintf("Mission %d accepted. Status: Active", o.missionCount) + return &result, nil } -``` -```ts AssemblyScript -import { agents } from "@hypermode/modus-sdk-as" -import { models } from "@hypermode/modus-sdk-as" -import { - OpenAIChatModel, - SystemMessage, - UserMessage, -} from "@hypermode/modus-sdk-as/models/openai/chat" - -@json -class Message { - id!: string - role!: string - content!: string - timestamp!: string +func (o *OperativeAgent) getMissionStatus() (*string, error) { + result := fmt.Sprintf("Agent operative. Missions completed: %d", o.missionCount) + return &result, nil } +``` -export class ChatAgent extends agents.AgentBase { - conversationId: string = "" - messages: Message[] = [] - lastActivity: string = "" - userContext: string = "" - - Name(): string { - return "ChatAgent" - } - - OnReceiveMessage(msgName: string, data: string | null): string | null { - switch (msgName) { - case "chat": - return this.handleChatMessage(data) - case "get_history": - return this.getConversationHistory() - default: - throw new Error(`Unknown message type: ${msgName}`) - } - } +What makes this operationally superior: - handleChatMessage(data: string | null): string | null { - if (!data) throw new Error("No message data provided") +- No transmission of massive state files on every contact +- No reconstruction of mission history from scratch +- No risk of losing operational data during communication failures +- No manual management of assignment records between missions - const request = JSON.parse(data) +The agent maintains its complete operational state in secure memory, accessing +it instantly when processing new directives. - // Add user message to persistent state - no parsing needed! - const userMessage: Message = { - id: Date.now().toString(), - role: "user", - content: request.message, - timestamp: new Date().toISOString(), - } +## State persistence - this.messages.push(userMessage) - this.lastActivity = new Date().toISOString() +Agents automatically preserve their operational state through Modus's built-in +intelligence management: - // Generate AI response using current context - const response = this.generateAIResponse() +```go +func (o *OperativeAgent) GetState() *string { + state := fmt.Sprintf("%d|%s|%d", + o.missionCount, + strings.Join(o.assignments, ","), + o.lastContact.Unix()) + return &state +} - // Add response to persistent state - const assistantMessage: Message = { - id: (Date.now() + 1).toString(), - role: "assistant", - content: response, - timestamp: new Date().toISOString(), +func (o *OperativeAgent) SetState(data *string) { + if data == nil { + return } - this.messages.push(assistantMessage) - - const chatResponse: ChatResponse = { - message: response, - conversationId: this.conversationId, + parts := strings.Split(*data, "|") + if len(parts) >= 3 { + o.missionCount, _ = strconv.Atoi(parts[0]) + o.assignments = strings.Split(parts[1], ",") + timestamp, _ := strconv.ParseInt(parts[2], 10, 64) + o.lastContact = time.Unix(timestamp, 0) } - - return JSON.stringify(chatResponse) - } } ``` - - ## Agent lifecycle -Agents have built-in lifecycle hooks for robust operation: +Agents have built-in operational protocols for mission continuity: ```go -func (c *ChatAgent) OnInitialize() error { - // Called when agent first starts - c.lastActivity = time.Now() +func (o *OperativeAgent) OnInitialize() error { + // Called when agent is first deployed to the field + o.lastContact = time.Now() + fmt.Printf("Operative %s deployed and ready for missions", o.Id()) return nil } -func (c *ChatAgent) OnResume() error { - // Called when agent wakes up with complete state intact - fmt.Printf("Resuming conversation %s with %d messages", - c.conversationId, len(c.messages)) +func (o *OperativeAgent) OnResume() error { + // Called when agent reestablishes contact with complete intel intact + fmt.Printf("Agent back online. %d missions completed, %d assignments on record", + o.missionCount, len(o.assignments)) return nil } -func (c *ChatAgent) OnSuspend() error { - // Called before agent goes dormant +func (o *OperativeAgent) OnSuspend() error { + // Called before agent goes dark return nil } -func (c *ChatAgent) OnTerminate() error { - // Called before final shutdown +func (o *OperativeAgent) OnTerminate() error { + // Called before final extraction + fmt.Printf("Agent %s extracted. Mission complete.", o.Id()) return nil } ``` -## Working with agents - -To use agents in your Modus app: - -1. **Register your agent** in the `init()` function: - - ```go - func init() { - agents.Register(&ChatAgent{}) - } - ``` +## Deploying and controlling agents -2. **Start an agent instance**: +Agents must be registered and then deployed through functions that become part +of your GraphQL API. - ```go - func StartChatAgent() (string, error) { - agentInfo, err := agents.Start("ChatAgent") - return agentInfo.Id, err - } - ``` +First, register your agent in the `init()` function: -3. **Send messages to agents**: - - ```go - func SendChatMessage(agentId string, message string) (ChatResponse, error) { - request := ChatRequest{Message: message} - requestData, _ := json.Marshal(request) - requestStr := string(requestData) +```go +func init() { + agents.Register(&OperativeAgent{}) +} +``` - responseStr, err := agents.SendMessage(agentId, "chat", agents.WithData(requestStr)) - // Handle response... - } - ``` +Create a function to deploy new agent instances. This function becomes a GraphQL +mutation: -## Agents against functions +```go +func DeployOperative() (string, error) { + agentInfo, err := agents.Start("OperativeAgent") + if err != nil { + return "", err + } -| Agents | Functions | -| ------------------------------ | ----------------------- | -| Stateful | Stateless | -| Persistent across interactions | Single request/response | -| Maintains conversation history | No memory | -| Long-running workflows | Fast, predictable | -| Complex, multi-step processes | Simple operations | -| Automatic state persistence | Manual state management | + // Return the agent ID - clients must store this to communicate with the agent + return agentInfo.Id, nil +} +``` -## Beyond simple chat +Create functions to communicate with specific agent instances using their ID: -Agents enable sophisticated patterns impossible with stateless functions: +```go +func AssignMission(agentId string, missionType string) (string, error) { + result, err := agents.SendMessage(agentId, "accept_mission", agents.WithData(missionType)) + if err != nil { + return "", err + } + if result == nil { + return "", fmt.Errorf("no response from agent") + } + return *result, err +} -- **Contextual understanding**: Store user preferences and conversation themes -- **Multi-turn reasoning**: Build understanding over multiple interactions -- **Conversation recovery**: Retry from last known state instead of losing - everything -- **Progressive enhancement**: Start simple and build sophistication over time +func GetMissionStatus(agentId string) (string, error) { + result, err := agents.SendMessage(agentId, "mission_status") + if err != nil { + return "", err + } + if result == nil { + return "", fmt.Errorf("no response from agent") + } + return *result, err +} +``` -Agents represent a fundamental shift from fragile, stateless functions to -robust, persistent entities that maintain conversation continuity no matter what -happens. They're the foundation for building production-ready intelligent -applications. +**Important**: clients must store the agent ID returned from `DeployOperative()` +to communicate with that specific agent instance. Each agent maintains its own +independent state and can only be accessed through its unique ID. + +## Agent workflow example + +1. Client calls `DeployOperative()` → receives agent ID `"agent_12345"` +2. Client stores `"agent_12345"` for future communications +3. Client calls `AssignMission("agent_12345", "surveillance")` → agent updates + its state +4. Client calls `GetMissionStatus("agent_12345")` → agent returns current status + from memory +5. Agent persists across system restarts, maintaining all mission history + +## Beyond simple operations + +Agents enable sophisticated operational patterns impossible with stateless +functions: + +- **Operational continuity**: Maintain mission state across system failures and + re-deployments +- **Intelligence building**: Accumulate understanding across multiple + assignments and contacts +- **Mission recovery**: Resume operations from last secure checkpoint instead of + starting over +- **Network coordination**: Manage complex multi-agent operations with shared + intelligence + +Agents represent the evolution from stateless functions to elite operatives that +maintain complete operational continuity. They're the foundation for building +intelligence networks that never lose track of their missions, no matter what +happens in the field. From 464beb5b812cc82cad029b472fc398bf10d7ee25 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 10:52:57 +0700 Subject: [PATCH 13/53] * --- modus/agents.mdx | 143 ++++++++++++++++++++++++++++------------------- 1 file changed, 84 insertions(+), 59 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index c2b69901..359c8e38 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -19,7 +19,7 @@ operational context. - **Autonomous**: Can operate independently over extended periods - **Actor-based**: Each agent instance runs in isolation -## When to use agents +## When to deploy agents Agents are perfect for: @@ -60,6 +60,85 @@ state management, secure communications, and mission persistence. Your operational data—mission count, assignment records, contact logs—lives as fields in the struct, automatically preserved across all interactions. +## Spawning agents through functions + +Agents are deployed through regular Modus functions that become part of your +GraphQL API. These deployment functions create and manage agent instances on +demand: + +```go +// Register your agent type during initialization +func init() { + agents.Register(&OperativeAgent{}) +} + +// Deploy a new agent instance - this becomes a GraphQL mutation +func DeployOperative() (string, error) { + agentInfo, err := agents.Start("OperativeAgent") + if err != nil { + return "", err + } + + // Return the agent ID - clients must store this to communicate with the agent + return agentInfo.Id, nil +} +``` + +When you call this function through GraphQL, it returns a unique agent ID: + +```graphql +mutation { + deployOperative +} + +# Returns: "agent_abc123xyz" +``` + +You can think of an Agent as a persistent server process with durable memory. +Once deployed, you can reference your agent by its ID across sessions, page +reloads, and even system restarts. The agent maintains its complete state and +continues operating exactly where it left off. + + + **Agent builders and visual workflows:** We're actively developing Agent + Builder tools and "eject to code" feature that generates complete agent + deployments from visual workflows. These tools automatically create the + deployment functions and agent management code for complex multi-agent + systems. + + +## Communicating with your agent + +Once deployed, you communicate with your agent using its unique ID. Create +functions that send messages to specific agent instances: + +```go +func AcceptMission(agentId string, missionType string) (string, error) { + result, err := agents.SendMessage(agentId, "accept_mission", agents.WithData(missionType)) + if err != nil { + return "", err + } + if result == nil { + return "", fmt.Errorf("no response from agent") + } + return *result, nil +} +``` + +This function becomes a GraphQL mutation that you can call with your agent's ID: + +```graphql +mutation { + acceptMission(agentId: "agent_abc123xyz", missionType: "surveillance") +} + +# Returns: "Mission 1 accepted. Status: Active" +``` + +The agent receives the `accept_mission` message, processes it using its internal +state, updates its mission count and assignment history, and returns a +response—all while maintaining persistent memory of every interaction. + ## Agent message handling Agents process operational directives through their secure message handling @@ -179,64 +258,6 @@ func (o *OperativeAgent) OnTerminate() error { } ``` -## Deploying and controlling agents - -Agents must be registered and then deployed through functions that become part -of your GraphQL API. - -First, register your agent in the `init()` function: - -```go -func init() { - agents.Register(&OperativeAgent{}) -} -``` - -Create a function to deploy new agent instances. This function becomes a GraphQL -mutation: - -```go -func DeployOperative() (string, error) { - agentInfo, err := agents.Start("OperativeAgent") - if err != nil { - return "", err - } - - // Return the agent ID - clients must store this to communicate with the agent - return agentInfo.Id, nil -} -``` - -Create functions to communicate with specific agent instances using their ID: - -```go -func AssignMission(agentId string, missionType string) (string, error) { - result, err := agents.SendMessage(agentId, "accept_mission", agents.WithData(missionType)) - if err != nil { - return "", err - } - if result == nil { - return "", fmt.Errorf("no response from agent") - } - return *result, err -} - -func GetMissionStatus(agentId string) (string, error) { - result, err := agents.SendMessage(agentId, "mission_status") - if err != nil { - return "", err - } - if result == nil { - return "", fmt.Errorf("no response from agent") - } - return *result, err -} -``` - -**Important**: clients must store the agent ID returned from `DeployOperative()` -to communicate with that specific agent instance. Each agent maintains its own -independent state and can only be accessed through its unique ID. - ## Agent workflow example 1. Client calls `DeployOperative()` → receives agent ID `"agent_12345"` @@ -247,6 +268,10 @@ independent state and can only be accessed through its unique ID. from memory 5. Agent persists across system restarts, maintaining all mission history +**Important**: clients must store the agent ID returned from deployment +functions to communicate with that specific agent instance. Each agent maintains +its own independent state and can only be accessed through its unique ID. + ## Beyond simple operations Agents enable sophisticated operational patterns impossible with stateless From 45aed7e177b9ce9a66eb12d938c04ae606224bfd Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 11:47:01 +0700 Subject: [PATCH 14/53] * --- modus/agents.mdx | 233 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 161 insertions(+), 72 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 359c8e38..5ac6b208 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -38,27 +38,30 @@ package main import ( "fmt" + "strings" "time" "github.com/hypermodeinc/modus/sdk/go/pkg/agents" + "github.com/hypermodeinc/modus/sdk/go/pkg/models" + "github.com/hypermodeinc/modus/sdk/go/pkg/models/openai" ) -type OperativeAgent struct { +type IntelligenceAgent struct { agents.AgentBase - missionCount int - assignments []string - lastContact time.Time + briefings []string // Intelligence history + confidence float64 // Analytical confidence + lastContact time.Time } -func (o *OperativeAgent) Name() string { - return "OperativeAgent" +func (i *IntelligenceAgent) Name() string { + return "IntelligenceAgent" } ``` The agent embeds `agents.AgentBase`, which provides all the infrastructure for state management, secure communications, and mission persistence. Your -operational data—mission count, assignment records, contact logs—lives as fields -in the struct, automatically preserved across all interactions. +operational data—intelligence briefings, confidence metrics, contact logs—lives +as fields in the struct, automatically preserved across all interactions. ## Spawning agents through functions @@ -69,12 +72,12 @@ demand: ```go // Register your agent type during initialization func init() { - agents.Register(&OperativeAgent{}) + agents.Register(&IntelligenceAgent{}) } // Deploy a new agent instance - this becomes a GraphQL mutation -func DeployOperative() (string, error) { - agentInfo, err := agents.Start("OperativeAgent") +func DeployAnalyst() (string, error) { + agentInfo, err := agents.Start("IntelligenceAgent") if err != nil { return "", err } @@ -88,7 +91,7 @@ When you call this function through GraphQL, it returns a unique agent ID: ```graphql mutation { - deployOperative + deployAnalyst } # Returns: "agent_abc123xyz" @@ -113,8 +116,19 @@ Once deployed, you communicate with your agent using its unique ID. Create functions that send messages to specific agent instances: ```go -func AcceptMission(agentId string, missionType string) (string, error) { - result, err := agents.SendMessage(agentId, "accept_mission", agents.WithData(missionType)) +func SubmitIntelligence(agentId string, data string) (string, error) { + result, err := agents.SendMessage(agentId, "analyze_intelligence", agents.WithData(data)) + if err != nil { + return "", err + } + if result == nil { + return "", fmt.Errorf("no response from agent") + } + return *result, nil +} + +func GetThreatAssessment(agentId string) (string, error) { + result, err := agents.SendMessage(agentId, "threat_assessment", nil) if err != nil { return "", err } @@ -125,19 +139,24 @@ func AcceptMission(agentId string, missionType string) (string, error) { } ``` -This function becomes a GraphQL mutation that you can call with your agent's ID: +These functions become GraphQL mutations that you can call with your agent's ID: ```graphql mutation { - acceptMission(agentId: "agent_abc123xyz", missionType: "surveillance") + submitIntelligence( + agentId: "agent_abc123xyz" + data: "Suspicious network activity detected" + ) } -# Returns: "Mission 1 accepted. Status: Active" +query { + getThreatAssessment(agentId: "agent_abc123xyz") +} ``` -The agent receives the `accept_mission` message, processes it using its internal -state, updates its mission count and assignment history, and returns a -response—all while maintaining persistent memory of every interaction. +The agent receives the message, processes it using its internal state and AI +reasoning, updates its intelligence database, and returns a response—all while +maintaining persistent memory of every interaction. ## Agent message handling @@ -145,14 +164,14 @@ Agents process operational directives through their secure message handling system: ```go -func (o *OperativeAgent) OnReceiveMessage(msgName string, data *string) (*string, error) { +func (i *IntelligenceAgent) OnReceiveMessage(msgName string, data *string) (*string, error) { switch msgName { - case "accept_mission": - return o.acceptMission(data) - case "mission_status": - return o.getMissionStatus() - case "assignment_history": - return o.getAssignmentHistory() + case "analyze_intelligence": + return i.analyzeIntelligence(data) + case "threat_assessment": + return i.getThreatAssessment() + case "intelligence_history": + return i.getIntelligenceHistory() default: return nil, fmt.Errorf("unrecognized directive: %s", msgName) } @@ -162,28 +181,64 @@ func (o *OperativeAgent) OnReceiveMessage(msgName string, data *string) (*string Each directive triggers specific operational procedures, with all intelligence automatically maintained in the agent's secure memory. -## Processing operations +## Processing operations with AI intelligence -Here's how agents handle field operations while maintaining persistent state: +Here's how agents handle field operations while maintaining persistent state and +using AI models for analysis: ```go -func (o *OperativeAgent) acceptMission(data *string) (*string, error) { - missionType := "classified" - if data != nil { - missionType = *data +func (i *IntelligenceAgent) analyzeIntelligence(data *string) (*string, error) { + if data == nil { + return nil, fmt.Errorf("no intelligence data provided") } - // Update operational status - no intel parsing needed! - o.missionCount++ - o.assignments = append(o.assignments, fmt.Sprintf("Mission %d: %s", o.missionCount, missionType)) - o.lastContact = time.Now() + // Store new intelligence in persistent memory + i.briefings = append(i.briefings, *data) + i.lastContact = time.Now() + + // Build context from all accumulated intelligence + context := strings.Join(i.briefings, "\n") + + // AI analysis using complete operational history + model, _ := models.GetModel[openai.ChatModel]("analyst-model") + + systemPrompt := `You are an intelligence analyst. + Analyze patterns from accumulated briefings and provide threat assessment.` + + userPrompt := fmt.Sprintf(`All Intelligence: +%s + +Provide threat assessment:`, context) - result := fmt.Sprintf("Mission %d accepted. Status: Active", o.missionCount) + input, _ := model.CreateInput( + openai.NewSystemMessage(systemPrompt), + openai.NewUserMessage(userPrompt), + ) + + output, _ := model.Invoke(input) + analysis := output.Choices[0].Message.Content + + // Update confidence based on data volume + i.confidence = float64(len(i.briefings)) / 10.0 + if i.confidence > 1.0 { + i.confidence = 1.0 + } + + result := fmt.Sprintf(`Analysis complete: %s +(Confidence: %.2f based on %d briefings)`, + analysis, i.confidence, len(i.briefings)) return &result, nil } -func (o *OperativeAgent) getMissionStatus() (*string, error) { - result := fmt.Sprintf("Agent operative. Missions completed: %d", o.missionCount) +func (i *IntelligenceAgent) getThreatAssessment() (*string, error) { + if len(i.briefings) == 0 { + result := "No intelligence processed yet. Deploy to field for analysis." + return &result, nil + } + + result := fmt.Sprintf(`Current threat assessment: %d briefings analyzed. +Confidence level: %.2f. Agent operational.`, + len(i.briefings), i.confidence) return &result, nil } ``` @@ -191,12 +246,35 @@ func (o *OperativeAgent) getMissionStatus() (*string, error) { What makes this operationally superior: - No transmission of massive state files on every contact -- No reconstruction of mission history from scratch -- No risk of losing operational data during communication failures -- No manual management of assignment records between missions +- No reconstruction of intelligence history from scratch +- AI models see complete operational context, not just current input +- No risk of losing analytical data during communication failures +- Intelligence quality improves with each briefing processed + +The agent maintains its complete operational state and intelligence database in +secure memory, accessing it instantly when processing new directives and +invoking AI models. + +## The power of intelligent persistence + +This combination creates agents that: + +**First Analysis:** + +```sh +"New threat detected. Limited context available. (Confidence: 0.10 based on 1 briefing)" +``` + +**After Multiple Briefings:** + +```sh +"Pattern confirmed across 5 previous incidents. This matches Advanced Persistent +Threat signatures. Immediate escalation recommended. (Confidence: 0.85 based on 8 briefings)" +``` -The agent maintains its complete operational state in secure memory, accessing -it instantly when processing new directives. +The agent doesn't just remember—it **learns and becomes more intelligent with +every interaction**. AI models see the complete operational picture, enabling +sophisticated pattern recognition impossible with stateless functions. ## State persistence @@ -204,25 +282,28 @@ Agents automatically preserve their operational state through Modus's built-in intelligence management: ```go -func (o *OperativeAgent) GetState() *string { - state := fmt.Sprintf("%d|%s|%d", - o.missionCount, - strings.Join(o.assignments, ","), - o.lastContact.Unix()) +func (i *IntelligenceAgent) GetState() *string { + briefingsData := strings.Join(i.briefings, "|") + state := fmt.Sprintf("%.2f|%s|%d", + i.confidence, + briefingsData, + i.lastContact.Unix()) return &state } -func (o *OperativeAgent) SetState(data *string) { +func (i *IntelligenceAgent) SetState(data *string) { if data == nil { return } parts := strings.Split(*data, "|") if len(parts) >= 3 { - o.missionCount, _ = strconv.Atoi(parts[0]) - o.assignments = strings.Split(parts[1], ",") + i.confidence, _ = strconv.ParseFloat(parts[0], 64) + if parts[1] != "" { + i.briefings = strings.Split(parts[1], "|") + } timestamp, _ := strconv.ParseInt(parts[2], 10, 64) - o.lastContact = time.Unix(timestamp, 0) + i.lastContact = time.Unix(timestamp, 0) } } ``` @@ -232,41 +313,46 @@ func (o *OperativeAgent) SetState(data *string) { Agents have built-in operational protocols for mission continuity: ```go -func (o *OperativeAgent) OnInitialize() error { +func (i *IntelligenceAgent) OnInitialize() error { // Called when agent is first deployed to the field - o.lastContact = time.Now() - fmt.Printf("Operative %s deployed and ready for missions", o.Id()) + i.lastContact = time.Now() + i.confidence = 0.0 + fmt.Printf("Intelligence Agent %s deployed and ready for analysis", i.Id()) return nil } -func (o *OperativeAgent) OnResume() error { +func (i *IntelligenceAgent) OnResume() error { // Called when agent reestablishes contact with complete intel intact - fmt.Printf("Agent back online. %d missions completed, %d assignments on record", - o.missionCount, len(o.assignments)) + fmt.Printf(`Agent back online. %d briefings processed. + Confidence level: %.2f`, len(i.briefings), i.confidence) return nil } -func (o *OperativeAgent) OnSuspend() error { +func (i *IntelligenceAgent) OnSuspend() error { // Called before agent goes dark return nil } -func (o *OperativeAgent) OnTerminate() error { +func (i *IntelligenceAgent) OnTerminate() error { // Called before final extraction - fmt.Printf("Agent %s extracted. Mission complete.", o.Id()) + fmt.Printf("Agent %s extracted. Intelligence archive preserved.", i.Id()) return nil } ``` ## Agent workflow example -1. Client calls `DeployOperative()` → receives agent ID `"agent_12345"` +1. Client calls `DeployAnalyst()` → receives agent ID `"agent_12345"` 2. Client stores `"agent_12345"` for future communications -3. Client calls `AssignMission("agent_12345", "surveillance")` → agent updates - its state -4. Client calls `GetMissionStatus("agent_12345")` → agent returns current status - from memory -5. Agent persists across system restarts, maintaining all mission history +3. Client calls `SubmitIntelligence("agent_12345", "network anomaly detected")` + → agent stores data and uses AI to analyze patterns from complete + intelligence history +4. Agent invokes AI model with accumulated context → generates sophisticated + threat assessment based on all previous briefings +5. Client calls `GetThreatAssessment("agent_12345")` → agent returns AI-powered + analysis from persistent memory +6. Agent persists across system restarts, maintaining complete intelligence + database and learned patterns **Important**: clients must store the agent ID returned from deployment functions to communicate with that specific agent instance. Each agent maintains @@ -280,13 +366,16 @@ functions: - **Operational continuity**: Maintain mission state across system failures and re-deployments - **Intelligence building**: Accumulate understanding across multiple - assignments and contacts + assignments through AI-powered analysis - **Mission recovery**: Resume operations from last secure checkpoint instead of starting over - **Network coordination**: Manage complex multi-agent operations with shared intelligence +- **Adaptive learning**: AI models become more effective as agents accumulate + operational data Agents represent the evolution from stateless functions to elite operatives that -maintain complete operational continuity. They're the foundation for building -intelligence networks that never lose track of their missions, no matter what +maintain complete operational continuity and build intelligence over time. +They're the foundation for building intelligence networks that never lose track +of their missions and become smarter with every interaction, no matter what happens in the field. From 917895b3014d624e1a497b612cc10fa5a845374a Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 11:53:20 +0700 Subject: [PATCH 15/53] * --- modus/agents.mdx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 5ac6b208..e64262b3 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -89,7 +89,7 @@ func DeployAnalyst() (string, error) { When you call this function through GraphQL, it returns a unique agent ID: -```graphql +```dql mutation { deployAnalyst } @@ -141,14 +141,16 @@ func GetThreatAssessment(agentId string) (string, error) { These functions become GraphQL mutations that you can call with your agent's ID: -```graphql +```dql mutation { submitIntelligence( agentId: "agent_abc123xyz" data: "Suspicious network activity detected" ) } +``` +```dql query { getThreatAssessment(agentId: "agent_abc123xyz") } From 034647caec3b66dc838c5801421bfe799617e937 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 12:01:44 +0700 Subject: [PATCH 16/53] * --- modus/agents.mdx | 85 ++++++++++++++++++++++++++++++------------------ 1 file changed, 53 insertions(+), 32 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index e64262b3..dc6e886a 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -89,7 +89,7 @@ func DeployAnalyst() (string, error) { When you call this function through GraphQL, it returns a unique agent ID: -```dql +```graphql mutation { deployAnalyst } @@ -117,7 +117,11 @@ functions that send messages to specific agent instances: ```go func SubmitIntelligence(agentId string, data string) (string, error) { - result, err := agents.SendMessage(agentId, "analyze_intelligence", agents.WithData(data)) + result, err := agents.SendMessage( + agentId, + "analyze_intelligence", + agents.WithData(data), + ) if err != nil { return "", err } @@ -141,16 +145,14 @@ func GetThreatAssessment(agentId string) (string, error) { These functions become GraphQL mutations that you can call with your agent's ID: -```dql +```graphql mutation { submitIntelligence( agentId: "agent_abc123xyz" data: "Suspicious network activity detected" ) } -``` -```dql query { getThreatAssessment(agentId: "agent_abc123xyz") } @@ -166,7 +168,10 @@ Agents process operational directives through their secure message handling system: ```go -func (i *IntelligenceAgent) OnReceiveMessage(msgName string, data *string) (*string, error) { +func (i *IntelligenceAgent) OnReceiveMessage( + msgName string, + data *string, +) (*string, error) { switch msgName { case "analyze_intelligence": return i.analyzeIntelligence(data) @@ -189,7 +194,9 @@ Here's how agents handle field operations while maintaining persistent state and using AI models for analysis: ```go -func (i *IntelligenceAgent) analyzeIntelligence(data *string) (*string, error) { +func (i *IntelligenceAgent) analyzeIntelligence( + data *string, +) (*string, error) { if data == nil { return nil, fmt.Errorf("no intelligence data provided") } @@ -205,12 +212,14 @@ func (i *IntelligenceAgent) analyzeIntelligence(data *string) (*string, error) { model, _ := models.GetModel[openai.ChatModel]("analyst-model") systemPrompt := `You are an intelligence analyst. - Analyze patterns from accumulated briefings and provide threat assessment.` + Analyze patterns from accumulated briefings + and provide threat assessment.` userPrompt := fmt.Sprintf(`All Intelligence: -%s + %s -Provide threat assessment:`, context) + Provide threat assessment:`, + context) input, _ := model.CreateInput( openai.NewSystemMessage(systemPrompt), @@ -226,21 +235,30 @@ Provide threat assessment:`, context) i.confidence = 1.0 } - result := fmt.Sprintf(`Analysis complete: %s -(Confidence: %.2f based on %d briefings)`, - analysis, i.confidence, len(i.briefings)) + result := fmt.Sprintf(`Analysis complete: + %s + + (Confidence: %.2f based on %d briefings)`, + analysis, + i.confidence, + len(i.briefings)) return &result, nil } func (i *IntelligenceAgent) getThreatAssessment() (*string, error) { if len(i.briefings) == 0 { - result := "No intelligence processed yet. Deploy to field for analysis." + result := `No intelligence processed yet. + Deploy to field for analysis.` return &result, nil } - result := fmt.Sprintf(`Current threat assessment: %d briefings analyzed. -Confidence level: %.2f. Agent operational.`, - len(i.briefings), i.confidence) + result := fmt.Sprintf(`Current threat assessment: + %d briefings analyzed. + + Confidence level: %.2f. + Agent operational.`, + len(i.briefings), + i.confidence) return &result, nil } ``` @@ -261,18 +279,16 @@ invoking AI models. This combination creates agents that: -**First Analysis:** - -```sh -"New threat detected. Limited context available. (Confidence: 0.10 based on 1 briefing)" -``` - -**After Multiple Briefings:** + + **First Analysis:** "New threat detected. Limited context available. + (Confidence: 0.10 based on 1 briefing)" + -```sh -"Pattern confirmed across 5 previous incidents. This matches Advanced Persistent -Threat signatures. Immediate escalation recommended. (Confidence: 0.85 based on 8 briefings)" -``` + + **After Multiple Briefings:** "Pattern confirmed across 5 previous incidents. + This matches Advanced Persistent Threat signatures. Immediate escalation + recommended. (Confidence: 0.85 based on 8 briefings)" + The agent doesn't just remember—it **learns and becomes more intelligent with every interaction**. AI models see the complete operational picture, enabling @@ -319,14 +335,18 @@ func (i *IntelligenceAgent) OnInitialize() error { // Called when agent is first deployed to the field i.lastContact = time.Now() i.confidence = 0.0 - fmt.Printf("Intelligence Agent %s deployed and ready for analysis", i.Id()) + fmt.Printf(`Intelligence Agent %s deployed + and ready for analysis`, i.Id()) return nil } func (i *IntelligenceAgent) OnResume() error { // Called when agent reestablishes contact with complete intel intact - fmt.Printf(`Agent back online. %d briefings processed. - Confidence level: %.2f`, len(i.briefings), i.confidence) + fmt.Printf(`Agent back online. + %d briefings processed. + Confidence level: %.2f`, + len(i.briefings), + i.confidence) return nil } @@ -337,7 +357,8 @@ func (i *IntelligenceAgent) OnSuspend() error { func (i *IntelligenceAgent) OnTerminate() error { // Called before final extraction - fmt.Printf("Agent %s extracted. Intelligence archive preserved.", i.Id()) + fmt.Printf(`Agent %s extracted. + Intelligence archive preserved.`, i.Id()) return nil } ``` From 6c9f9aa4d0c32453fae34449215cb5dc081c9397 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 12:22:40 +0700 Subject: [PATCH 17/53] * --- modus/agents.mdx | 186 ++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 182 insertions(+), 4 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index dc6e886a..faf3815d 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -48,9 +48,18 @@ import ( type IntelligenceAgent struct { agents.AgentBase - briefings []string // Intelligence history - confidence float64 // Analytical confidence - lastContact time.Time + briefings []string // Intelligence history + confidence float64 // Analytical confidence + lastContact time.Time + currentMission *MissionPhase // Track long-running operations + missionLog []string // Operational progress log +} + +type MissionPhase struct { + Name string + StartTime time.Time + Duration time.Duration + Complete bool } func (i *IntelligenceAgent) Name() string { @@ -162,6 +171,35 @@ The agent receives the message, processes it using its internal state and AI reasoning, updates its intelligence database, and returns a response—all while maintaining persistent memory of every interaction. +### Asynchronous operations + +For fire-and-forget operations where you don't need to wait for a response, +agents support asynchronous messaging: + +```go +func InitiateBackgroundAnalysis(agentId string, data string) error { + // Send message asynchronously - agent processes in background + err := agents.SendMessageAsync( + agentId, + "analyze_background_intel", + agents.WithData(data), + ) + if err != nil { + return err + } + + // Operation initiated - agent continues processing independently + return nil +} +``` + +This enables agents to handle long-running operations like: + +- Background data processing +- Scheduled intelligence gathering +- Multi-phase operations that don't require immediate responses +- Autonomous monitoring and alerting + ## Agent message handling Agents process operational directives through their secure message handling @@ -175,8 +213,12 @@ func (i *IntelligenceAgent) OnReceiveMessage( switch msgName { case "analyze_intelligence": return i.analyzeIntelligence(data) + case "analyze_background_intel": + return i.analyzeBackgroundIntel(data) case "threat_assessment": return i.getThreatAssessment() + case "get_status": + return i.getOperationalStatus() case "intelligence_history": return i.getIntelligenceHistory() default: @@ -275,6 +317,132 @@ The agent maintains its complete operational state and intelligence database in secure memory, accessing it instantly when processing new directives and invoking AI models. +### Long-running mission operations + +For complex multi-phase operations, agents can update their state continuously +while providing real-time progress tracking: + +```go +func (i *IntelligenceAgent) analyzeBackgroundIntel(data *string) (*string, error) { + // Initialize multi-phase operation + i.currentMission = &MissionPhase{ + Name: "Deep Intelligence Analysis", + StartTime: time.Now(), + Complete: false, + } + i.missionLog = []string{"Mission initiated: Deep intelligence analysis"} + + // Phase 1: Data Processing + i.updateMissionLog("Phase 1: Processing raw intelligence data...") + i.briefings = append(i.briefings, *data) + + // Phase 2: AI Analysis (simplified for brevity) + i.updateMissionLog("Phase 2: Generating threat assessment...") + // ... AI model invocation ... + + // Phase 3: Mission Complete + i.currentMission.Complete = true + i.currentMission.Duration = time.Since(i.currentMission.StartTime) + i.updateMissionLog("Mission completed successfully") + + return &result, nil +} + +func (i *IntelligenceAgent) updateMissionLog(message string) { + timestamp := time.Now().Format("15:04:05") + logEntry := fmt.Sprintf("[%s] %s", timestamp, message) + i.missionLog = append(i.missionLog, logEntry) +} +``` + +This demonstrates how agents maintain state across complex, multi-step +operations while providing detailed progress tracking for monitoring systems. + +## Monitoring ongoing operations + + + Real-time GraphQL subscriptions for agent monitoring are coming soon. For now, + you can monitor agent progress using GraphQL polling. + + +When you initiate long-running operations with `SendMessageAsync`, you can +monitor progress by checking the agent's state: + +```go +func CheckAnalysisProgress(agentId string) (*AnalysisStatus, error) { + result, err := agents.SendMessage(agentId, "get_status") + if err != nil { + return nil, err + } + + var status AnalysisStatus + json.Unmarshal([]byte(*result), &status) + return &status, nil +} + +type AnalysisStatus struct { + Phase string `json:"phase"` + Progress float64 `json:"progress"` + CurrentTask string `json:"current_task"` + EstimatedTime int `json:"estimated_time_remaining"` + IsComplete bool `json:"is_complete"` +} +``` + +The agent tracks its operational status using the mission state we defined +earlier: + +```go +func (i *IntelligenceAgent) getOperationalStatus() (*string, error) { + var status AnalysisStatus + + if i.currentMission == nil { + status = AnalysisStatus{ + Phase: "Standby", + Progress: 1.0, + CurrentTask: "Awaiting mission directives", + IsComplete: true, + } + } else { + // Calculate progress based on mission log entries + progress := float64(len(i.missionLog)) / 4.0 // 4 phases expected + if progress > 1.0 { progress = 1.0 } + + status = AnalysisStatus{ + Phase: i.currentMission.Name, + Progress: progress, + CurrentTask: i.missionLog[len(i.missionLog)-1], // Latest entry + IsComplete: i.currentMission.Complete, + } + } + + statusJson, _ := json.Marshal(status) + result := string(statusJson) + return &result, nil +} +``` + +Your client can poll this status endpoint via GraphQL: + +```graphql +query MonitorAnalysis($agentId: String!) { + checkAnalysisProgress(agentId: $agentId) { + phase + progress + currentTask + estimatedTimeRemaining + isComplete + } +} +``` + +This polling approach enables: + +- **Progress tracking**: Monitor completion percentage and current phase +- **User feedback**: Show progress bars and status updates in your UI +- **Operation coordination**: Know when to proceed to next steps +- **Error detection**: Identify when operations stall or fail + ## The power of intelligent persistence This combination creates agents that: @@ -374,7 +542,12 @@ func (i *IntelligenceAgent) OnTerminate() error { threat assessment based on all previous briefings 5. Client calls `GetThreatAssessment("agent_12345")` → agent returns AI-powered analysis from persistent memory -6. Agent persists across system restarts, maintaining complete intelligence +6. For long-running analysis, client calls + `InitiateBackgroundAnalysis("agent_12345", data)` → agent processes + asynchronously +7. Client polls `CheckAnalysisProgress("agent_12345")` → monitors progress until + complete +8. Agent persists across system restarts, maintaining complete intelligence database and learned patterns **Important**: clients must store the agent ID returned from deployment @@ -396,6 +569,11 @@ functions: intelligence - **Adaptive learning**: AI models become more effective as agents accumulate operational data +- **Asynchronous operations**: Handle long-running missions without blocking + other operations +- **Real-time monitoring**: Track progress and status of ongoing operations +- **Event-driven coordination**: React to operational changes and mission + updates Agents represent the evolution from stateless functions to elite operatives that maintain complete operational continuity and build intelligence over time. From 81dfcaed97cb58ab9ff6b2fa9dada4e90c9686e3 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 20:08:39 +0700 Subject: [PATCH 18/53] * --- modus/quickstart.mdx | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/modus/quickstart.mdx b/modus/quickstart.mdx index b2dba26d..8b117bd1 100644 --- a/modus/quickstart.mdx +++ b/modus/quickstart.mdx @@ -202,9 +202,38 @@ AssemblyScript if you prefer. For AssemblyScript usage, refer to the modus dev ``` - Modus generates a GraphQL API that you can interact with however you like. - We provide you with an exploration tool at `http://localhost:8686/explorer` - for testing your functions. + Modus automatically generates a GraphQL API from your functions. + Since your function is named `GatherIntelligence()`, it becomes a GraphQL query field called `gatherIntelligence`. + + Open the Modus API Explorer at `http://localhost:8686/explorer` to test your function. + The explorer is fully GraphQL-compatible, so you can issue this query: + + ```graphql + query { + gatherIntelligence { + quote + author + analysis + } + } + ``` + + You'll receive a response like: + + ```json + { + "data": { + "gatherIntelligence": { + "quote": "The only way to do great work is to love what you do.", + "author": "Steve Jobs", + "analysis": " + This emphasizes that passion and genuine interest in your work are fundamental drivers of excellence. + When you love what you do, the effort required for mastery feels less burdensome and innovation flows more naturally. + " + } + } + } + ``` Your function now: - Fetches data from external APIs From 63aa6430956ec08b1e43b240b7aafa034fe57136 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 20:17:37 +0700 Subject: [PATCH 19/53] * --- modus/functions.mdx | 48 +++++++++++++++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 15 deletions(-) diff --git a/modus/functions.mdx b/modus/functions.mdx index c4c90aca..e2b9d2f1 100644 --- a/modus/functions.mdx +++ b/modus/functions.mdx @@ -44,16 +44,16 @@ Most functions become GraphQL queries—perfect for reconnaissance and data retrieval: ```go -// Becomes a GraphQL query: getUserProfile(id: String!): UserProfile -func GetUserProfile(id string) (*UserProfile, error) { +// Becomes a GraphQL query: gatherThreatIntelligence(source: String!): ThreatReport +func GatherThreatIntelligence(source string) (*ThreatReport, error) { // Intelligence gathering operation - return fetchUserData(id) + return fetchThreatData(source) } -// Becomes a GraphQL query: analyzeMarketTrends(): TrendReport -func AnalyzeMarketTrends() (*TrendReport, error) { +// Becomes a GraphQL query: analyzeSecurityPatterns(): SecurityAssessment +func AnalyzeSecurityPatterns() (*SecurityAssessment, error) { // Analysis operation using AI models - return generateTrendAnalysis() + return generateSecurityAnalysis() } ``` @@ -63,23 +63,23 @@ Functions that modify data automatically become GraphQL mutations. Modus detects these by their mission prefixes: ```go -// Becomes a GraphQL mutation: createUser(data: UserInput!): User -func CreateUser(data UserInput) (*User, error) { - // Operational creation mission - return deployNewUser(data) +// Becomes a GraphQL mutation: createSecurityAlert(data: AlertInput!): SecurityAlert +func CreateSecurityAlert(data AlertInput) (*SecurityAlert, error) { + // Create new security alert + return deploySecurityAlert(data) } -// Becomes a GraphQL mutation: updateMissionStatus(id: String!, status: String!): Mission -func UpdateMissionStatus(id string, status string) (*Mission, error) { - // Status update operation - return modifyMissionRecord(id, status) +// Becomes a GraphQL mutation: updateThreatLevel(id: String!, level: String!): ThreatAssessment +func UpdateThreatLevel(id string, level string) (*ThreatAssessment, error) { + // Update threat assessment + return modifyThreatRecord(id, level) } ``` Functions starting with `create`, `update`, `delete`, and similar action words automatically become mutations. -## Mission example: weather intelligence analysis +## Mission example: field conditions intelligence analysis Here's a complete tactical operation that demonstrates how functions integrate external APIs with AI models for intelligence analysis: @@ -211,6 +211,24 @@ query { } ``` +You'll receive a tactical intelligence report like: + +```json +{ + "data": { + "gatherWeatherIntelligence": { + "city": "London", + "temperature": 12.3, + "conditions": "light rain", + "analysis": " + Light rain conditions will reduce visibility for surveillance operations and may impact equipment performance. + Recommend waterproof gear and consider delayed outdoor activities requiring clear sight lines. + " + } + } +} +``` + ### Deploying your operative To use this function, you'll need to: From 9a033a2fb99acba81aca6fefd07358d9499193cb Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 20:25:19 +0700 Subject: [PATCH 20/53] * --- modus/agents.mdx | 54 +++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 53 insertions(+), 1 deletion(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index faf3815d..28b5f230 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -102,8 +102,16 @@ When you call this function through GraphQL, it returns a unique agent ID: mutation { deployAnalyst } +``` + +Response: -# Returns: "agent_abc123xyz" +```json +{ + "data": { + "deployAnalyst": "agent_abc123xyz" + } +} ``` You can think of an Agent as a persistent server process with durable memory. @@ -161,12 +169,40 @@ mutation { data: "Suspicious network activity detected" ) } +``` + +Response: +```json +{ + "data": { + "submitIntelligence": "Analysis complete. + Threat pattern matches previous incident #7823. + Confidence: 0.85 based on 3 briefings. + Recommend immediate investigation." + } +} +``` + +```graphql query { getThreatAssessment(agentId: "agent_abc123xyz") } ``` +Response: + +```json +{ + "data": { + "getThreatAssessment": "Current threat assessment: + 3 briefings analyzed. + Confidence level: 0.85. + Agent operational." + } +} +``` + The agent receives the message, processes it using its internal state and AI reasoning, updates its intelligence database, and returns a response—all while maintaining persistent memory of every interaction. @@ -436,6 +472,22 @@ query MonitorAnalysis($agentId: String!) { } ``` +Response: + +```json +{ + "data": { + "checkAnalysisProgress": { + "phase": "Deep Intelligence Analysis", + "progress": 0.75, + "currentTask": "[15:42:33] Phase 2: Generating threat assessment...", + "estimatedTimeRemaining": 45, + "isComplete": false + } + } +} +``` + This polling approach enables: - **Progress tracking**: Monitor completion percentage and current phase From 0ae3b1d6c80ae4bd6d8296263b52eab8201ae88d Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 21:51:01 +0700 Subject: [PATCH 21/53] * --- docs.json | 3 +- modus/knowledge-graphs.mdx | 445 +++++++++++++++++++++++++++++++++++++ modus/overview.mdx | 8 +- 3 files changed, 451 insertions(+), 5 deletions(-) create mode 100644 modus/knowledge-graphs.mdx diff --git a/docs.json b/docs.json index c6a579b1..a1b97891 100644 --- a/docs.json +++ b/docs.json @@ -81,7 +81,8 @@ "modus/overview", "modus/quickstart", "modus/functions", - "modus/agents" + "modus/agents", + "modus/knowledge-graphs" ] }, { diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx new file mode 100644 index 00000000..8f28f1ad --- /dev/null +++ b/modus/knowledge-graphs.mdx @@ -0,0 +1,445 @@ +--- +title: "What about knowledge graphs?" +description: + "Build persistent intelligence networks using agents, functions, and knowledge + graphs" +"og:title": "What about knowledge graphs? - Modus" +--- + +## What about knowledge graphs? + +Your operatives need more than just memory—they need intelligence networks. +While agents maintain their own operational state and memory across missions, +knowledge graphs provide something fundamentally different: shared institutional +knowledge that captures relationships between entities, events, and intelligence +across your entire organization. + +At Hypermode, we recognize that knowledge graphs aren't just storage—they're +becoming critical infrastructure for next-generation AI systems. That's why +we've invested deeply in Dgraph, bringing enterprise-grade graph capabilities to +Modus applications. + +This is where knowledge graphs transform your Modus deployment from isolated +operatives into a coordinated intelligence network with shared institutional +memory. + +## What are intelligence networks? + +Intelligence networks in Modus combine: + +- **Agent state**: personal operational memory that each agent maintains across + missions +- **Knowledge graphs**: shared institutional intelligence that captures + relationships between entities, events, and intelligence across your + organization +- **Functions**: rapid tactical operations for data processing and analysis +- **AI models**: advanced pattern recognition and decision-making intelligence + +Think of it as the difference between what an individual operative remembers +versus what your intelligence agency knows. Agent state is personal memory—what +happened to this specific operative, what conversations they've had, what tasks +they're tracking. Knowledge graphs are institutional intelligence—how threats +relate to each other, which indicators connect to which actors, what patterns +emerge across all operations. + +## Setting up your intelligence infrastructure + +First, connect to your knowledge graph by adding this to your `modus.json`: + +```json +{ + "connections": { + "dgraph": { + "type": "dgraph", + "connString": "dgraph://your-graph.hypermode.host:443?sslmode=verify-ca&bearertoken={{API_KEY}}" + } + }, + "models": { + "text-generator": { + "sourceModel": "meta-llama/Llama-3.2-3B-Instruct", + "provider": "hugging-face", + "connection": "hypermode" + } + } +} +``` + +Set your credentials in `.env.dev.local`: + +```sh +MODUS_DGRAPH_API_KEY=your_graph_api_key_here +``` + +## Mission scenario: agent anomaly detection + +Let's walk through a realistic intelligence operation that demonstrates how all +these components work together. You're building a system to monitor for +anomalous agent behavior in the Matrix. The operation needs to: + +1. Rapidly import new agent activity reports +2. Find patterns across historical agent data +3. Coordinate ongoing surveillance operations +4. Provide strategic analysis to the resistance + +### Step 1: rapid intelligence import + +When new agent activity is detected, you need to process it quickly. This is +perfect for a stateless function: + +```go +func ImportAgentActivity(activity AgentActivity) (*string, error) { + // AI-powered analysis of the agent behavior + analysis, _ := analyzeAgentWithAI(activity.Description) + + // Store in knowledge graph - builds institutional intelligence + mutation := dgraph.NewMutation().WithSetJson(fmt.Sprintf(`{ + "dgraph.type": "AgentSighting", + "sighting_id": "%s", + "agent_name": "%s", + "location": "%s", + "behavior": "%s", + "analysis": "%s" + }`, activity.SightingID, activity.AgentName, activity.Location, + activity.Behavior, analysis)) + + dgraph.ExecuteMutations("dgraph", mutation) + // ... +} +``` + +Let's test this with some incoming agent intelligence: + +```graphql +mutation { + importAgentActivity( + activity: { + sightingId: "SIGHT-2025-001" + agentName: "Smith" + location: "Downtown Matrix Sector 7" + behavior: "Unusual pattern recognition anomaly detected" + threatLevel: 9 + } + ) +} +``` + +**Response:** + +```json +{ + "data": { + "importAgentActivity": "Agent activity processed: SIGHT-2025-001" + } +} +``` + +Behind the scenes, the AI model analyzed the agent behavior and the knowledge +graph now contains both the raw sighting data and the AI-enhanced analysis, +ready to be connected to other related agent activities. + +### Step 2: strategic analysis using institutional knowledge + +Now that we've agent activity in our knowledge graph, let's analyze the broader +Matrix surveillance landscape. This function queries relationships across all +stored agent data: + +```go +func AnalyzeAgentPatterns(timeRange string) (*AgentAnalysisResponse, error) { + // Query institutional knowledge - this traverses relationships + query := dgraph.NewQuery(` + query analyzeAgents($since: string) { + sightings(func: ge(timestamp, $since)) { + sighting_id + agent_name + location + behavior + analysis + ~agent_encounters { + human_id + escape_method + success_rate + } + } + } + `).WithVariable("$since", timeRange) + + response, _ := dgraph.ExecuteQuery("dgraph", query) + // ... parse response + + // Generate strategic assessment using AI with graph context + assessment, _ := generateAgentAssessment(data) + + return &AgentAnalysisResponse{ + SightingCount: sightingCount, + ActiveAgents: activeAgents, + ThreatAssessment: assessment, + Recommendations: recommendations, + }, nil +} +``` + +Let's query our Matrix surveillance data: + +```graphql +query { + analyzeAgentPatterns(timeRange: "2025-01-01T00:00:00Z") { + sightingCount + activeAgents + threatAssessment + recommendations + } +} +``` + +**Response:** + +```json +{ + "data": { + "analyzeAgentPatterns": { + "sightingCount": 47, + "activeAgents": ["Smith", "Brown", "Jones"], + "threatAssessment": " + Critical escalation detected. Agent Smith showing unprecedented adaptive behavior patterns. + Cross-referencing indicates coordinated search protocols across multiple Matrix sectors. + The One may have been detected.", + "recommendations": [ + "Implement emergency extraction protocols for key personnel", + "Activate deep cover resistance cells", + "Prepare for potential Matrix reset scenario" + ] + } + } +} +``` + +Notice how the AI model provided strategic analysis by examining patterns across +all related agent encounters in the knowledge graph—something no single sighting +could reveal. + +### Step 3: deploying persistent surveillance agents + +For ongoing operations, deploy an agent that maintains continuous Matrix +surveillance. Unlike functions, agents remember their operational state: + +```go +type SurveillanceAgent struct { + agents.AgentBase + + // Persistent agent state (personal operational memory) + OperationID string + MonitoredAgents []string + AlertThresholds map[string]int + LastSweep time.Time + OngoingOperations []OngoingOperation +} + +func (s *SurveillanceAgent) OnReceiveMessage(msgName string, data *string) (*string, error) { + switch msgName { + case "continuous_surveillance": + return s.runContinuousSurveillance() + case "agent_correlation": + return s.analyzeAgentCorrelations() + // ... + } +} +``` + +Deploy your surveillance agent: + +```graphql +mutation { + deploySurveillanceAgent +} +``` + +**Response:** + +```json +{ + "data": { + "deploySurveillanceAgent": "agent_neo_001" + } +} +``` + +Your agent is now running with its own dedicated execution environment, ready to +maintain long-term Matrix surveillance operations. + +### Step 4: coordinated surveillance operations + +Now initiate continuous surveillance. The agent queries the knowledge graph for +new agent activity and maintains its own operational state: + +```graphql +mutation { + initiateMatrixSurveillance(agentId: "agent_neo_001") +} +``` + +**Response:** + +```json +{ + "data": { + "initiateMatrixSurveillance": "Surveillance sweep completed. 5 new anomalies detected, 3 behavior patterns identified." + } +} +``` + +The agent is now continuously monitoring the knowledge graph, using AI to +identify agent behavior patterns, and maintaining its own operational memory +about Matrix surveillance. + +### Step 5: agent correlation analysis + +Let's have the agent perform correlation analysis across Matrix surveillance +data: + +```graphql +mutation { + sendMessage( + agentId: "agent_neo_001" + message: "agent_correlation" + data: null + ) +} +``` + +**Response:** + +```json +{ + "data": { + "sendMessage": "Agent correlation analysis completed. 6 behavioral correlations identified." + } +} +``` + +Behind the scenes, the agent: + +```go +func (s *SurveillanceAgent) analyzeAgentCorrelations() (*string, error) { + // Query institutional knowledge for correlation analysis + query := dgraph.NewQuery(` + query correlateAgents { + all_sightings(func: has(sighting_id)) { + sighting_id + agent_name + behavior + analysis + ~agent_encounters { + human_id + escape_method + } + } + } + `) + + response, _ := dgraph.ExecuteQuery("dgraph", query) + + // Use AI to find correlations in Matrix surveillance data + correlations, _ := s.findAgentCorrelationsWithAI(response.Json) + + // Update agent's personal operational state + s.updateOngoingOperations(correlations) + // ... +} +``` + +### Step 6: checking agent operational status + +Check what your surveillance agent has learned and is tracking: + +```graphql +query { + getAgentStatus(agentId: "agent_neo_001") +} +``` + +**Response:** + +```json +{ + "data": { + "getAgentStatus": { + "operation_id": "op-matrix-1736985600", + "monitored_agents": 3, + "ongoing_operations": 4, + "last_sweep": "2025-01-15T14:30:00Z", + "active_operations": [ + { + "id": "corr-001", + "type": "behavioral_correlation", + "status": "active", + "target": "Smith showing coordinated search pattern with Brown and Jones" + } + ] + } + } +} +``` + +## The matrix advantage + +What you've just built demonstrates the power of combining all four Modus +components: + +**Functions** rapidly processed incoming agent sightings and provided strategic +analysis by querying institutional surveillance data + +**Knowledge graphs** stored not just the raw sighting data, but the +relationships between agents, encounters, and behavioral patterns that enabled +anomaly detection + +**AI models** enhanced both the initial behavioral analysis and the strategic +assessment by understanding context across all related Matrix surveillance data + +**Agents** maintained continuous surveillance operations, building personal +operational memory while leveraging shared institutional knowledge about Matrix +agent activities + +## Key insights from this Matrix operation + +**Agent memory vs institutional knowledge**: the surveillance agent maintained +its own operational state (which Matrix agents it's monitoring, when it last +swept, what operations it's running) while accessing shared institutional +surveillance data in the knowledge graph + +**Relationship intelligence**: the knowledge graph revealed behavioral +correlations between Matrix agents that no single sighting could show + +**Coordinated operations**: functions handled rapid tactical sighting processing +while the agent managed strategic, long-term Matrix surveillance + +**AI-enhanced analysis**: models provided pattern recognition across both +personal agent memory and institutional surveillance knowledge + +At Hypermode, we've built this integration because we believe knowledge graphs +are becoming critical infrastructure for next-generation AI systems. Our +investment in Dgraph ensures enterprise-grade graph capabilities that scale with +your surveillance operations. + +## What you've built + +You now have a complete Matrix surveillance network that can: + +- **Import** agent sighting data rapidly through functions +- **Analyze** complex behavioral relationships through graph queries +- **Monitor** continuously through persistent surveillance agents +- **Coordinate** responses across multiple resistance operatives +- **Learn** and adapt through AI-enhanced behavioral analysis +- **Survive** system failures with persistent state and relationships + +This isn't just a database with some AI on top—it's a coordinated surveillance +network where agents, functions, models, and knowledge graphs work together to +provide capabilities that none could achieve alone. + +## Next steps + +Ready to deploy your Matrix surveillance network? Check out: + +- [Dgraph integration guide](/modus/modus-dgraph) for advanced graph operations +- [Agent coordination patterns](/modus/agents) for multi-agent workflows +- [Production deployment](/modus/deploying) for scaling your surveillance + network diff --git a/modus/overview.mdx b/modus/overview.mdx index 3207d023..c9d565dc 100644 --- a/modus/overview.mdx +++ b/modus/overview.mdx @@ -64,10 +64,10 @@ For more inspiration, check out the Discover stateful agents that maintain memory across interactions - Understand the structure and organization your Modus app + Build intelligence networks with persistent institutional memory From df848516eded80c407917e05c928a57ca5673f7a Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 23:04:19 +0700 Subject: [PATCH 22/53] * --- modus/overview.mdx | 41 ++++++++++++++++++++++++++++------------- 1 file changed, 28 insertions(+), 13 deletions(-) diff --git a/modus/overview.mdx b/modus/overview.mdx index c9d565dc..8c68713a 100644 --- a/modus/overview.mdx +++ b/modus/overview.mdx @@ -23,14 +23,35 @@ agents that maintain persistent memory across interactions. This eliminates the need to parse conversation histories, rebuild context from scratch, or lose state when errors occur. +Modus provides a complete toolkit for building intelligent applications: + +- **Functions**: Stateless operations that automatically become shareable skills + via auto-generated APIs +- **Agents**: Stateful entities with short-term and long-term memory that + coordinate models, tools, and data +- **Models**: Domain-specific AI models with the ability to easily swap in + different providers or versions +- **Knowledge Graphs**: Organizational memory that scales context across + multi-agent architectures +- **Collections**: Vector storage and semantic search capabilities for + intelligent data retrieval +- **Tools**: Curated resources, databases, and external APIs that agents can + securely access + +Built-in observability provides automatic inference logging and tracing, while +secure-by-default authorization ensures risk-appropriate access to tools and +data. Following modern best practices for AI-native architectures, Modus +implements principles from the 12-factor agentic app methodology for +maintainable, scalable intelligent systems. + You can run Modus locally for development or deploy it in seconds to Hypermode for production. ## What is Modus good for? {/* vale Google.Contractions = NO */} -Modus is designed for building both traditional functions and intelligent -agents. It supports sub-second response times for stateless operations and -long-running, autonomous workflows that maintain state over time. +Modus is designed for building applications where AI is at its core capability. +It supports sub-second response times for stateless operations and long-running, +autonomous workflows that maintain state over time. **Beyond demo prompt apps**: we've all built apps with prompts and AI tool integrations. When you're ready to take your project to the next level, Modus @@ -38,15 +59,8 @@ serves as your AI component in the stack. Modus can sit right alongside your existing app, handling the intelligent workflows while your main app focuses on what it does best. -**Functions**: stateless operations for API endpoints, data processing, and AI -inference tasks. - -**Agents**: stateful entities that maintain conversation history, coordinate -between models and tools, and operate independently over extended periods. -Agents automatically handle state persistence and fault tolerance. - -Both can be deployed in the same app, allowing you to choose the right -abstraction for each use case. +Both functions and agents can be deployed in the same app, allowing you to +choose the right abstraction for each use case. For more inspiration, check out the [Modus recipes](https://github.com/hypermodeinc/modus-recipes). @@ -65,9 +79,10 @@ For more inspiration, check out the Build intelligence networks with persistent institutional memory +``` From f28cfbfea391aa3cffde085989dd833e43eb4d93 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 23:06:18 +0700 Subject: [PATCH 23/53] * --- modus/overview.mdx | 1 - 1 file changed, 1 deletion(-) diff --git a/modus/overview.mdx b/modus/overview.mdx index 8c68713a..56d7884e 100644 --- a/modus/overview.mdx +++ b/modus/overview.mdx @@ -85,4 +85,3 @@ For more inspiration, check out the Build intelligence networks with persistent institutional memory -``` From 76a15b18e65358d2c50cf0bd707e2c119642cff6 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 23:07:25 +0700 Subject: [PATCH 24/53] * --- modus/overview.mdx | 4 ---- 1 file changed, 4 deletions(-) diff --git a/modus/overview.mdx b/modus/overview.mdx index 56d7884e..d7c47e60 100644 --- a/modus/overview.mdx +++ b/modus/overview.mdx @@ -33,10 +33,6 @@ Modus provides a complete toolkit for building intelligent applications: different providers or versions - **Knowledge Graphs**: Organizational memory that scales context across multi-agent architectures -- **Collections**: Vector storage and semantic search capabilities for - intelligent data retrieval -- **Tools**: Curated resources, databases, and external APIs that agents can - securely access Built-in observability provides automatic inference logging and tracing, while secure-by-default authorization ensures risk-appropriate access to tools and From c17dd9af9c0ebd4b51f32395c066ddac0cd73981 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 23:19:40 +0700 Subject: [PATCH 25/53] * --- modus/functions.mdx | 94 ++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 88 insertions(+), 6 deletions(-) diff --git a/modus/functions.mdx b/modus/functions.mdx index e2b9d2f1..2ac12654 100644 --- a/modus/functions.mdx +++ b/modus/functions.mdx @@ -11,6 +11,9 @@ handle specific missions with precision and speed. Like elite reconnaissance units, they get in, complete their objective, and report back. No unnecessary complications, no lingering presence, just pure operational efficiency. +You can think of a function as an endpoint—each function you write automatically +becomes a callable API endpoint that external systems can access. + Functions are the backbone of your intelligence network, handling everything from data gathering to AI-powered analysis, all while maintaining perfect operational discipline. @@ -44,38 +47,118 @@ Most functions become GraphQL queries—perfect for reconnaissance and data retrieval: ```go -// Becomes a GraphQL query: gatherThreatIntelligence(source: String!): ThreatReport +// This function becomes a GraphQL query func GatherThreatIntelligence(source string) (*ThreatReport, error) { // Intelligence gathering operation return fetchThreatData(source) } -// Becomes a GraphQL query: analyzeSecurityPatterns(): SecurityAssessment +// This function becomes a GraphQL query func AnalyzeSecurityPatterns() (*SecurityAssessment, error) { // Analysis operation using AI models return generateSecurityAnalysis() } ``` +Your operatives are now accessible via GraphQL: + +```graphql +query { + gatherThreatIntelligence(source: "network_logs") { + threatLevel + indicators + recommendations + } + + analyzeSecurityPatterns { + riskScore + anomalies + actionItems + } +} +``` + +**Response:** + +```json +{ + "data": { + "gatherThreatIntelligence": { + "threatLevel": "HIGH", + "indicators": ["unusual_traffic", "failed_auth_attempts"], + "recommendations": ["immediate_investigation", "block_suspicious_ips"] + }, + "analyzeSecurityPatterns": { + "riskScore": 8.5, + "anomalies": ["off_hours_access", "geographic_anomaly"], + "actionItems": ["verify_user_identity", "enable_2fa"] + } + } +} +``` + ### Operational change mutations Functions that modify data automatically become GraphQL mutations. Modus detects these by their mission prefixes: ```go -// Becomes a GraphQL mutation: createSecurityAlert(data: AlertInput!): SecurityAlert +// This becomes a GraphQL mutation func CreateSecurityAlert(data AlertInput) (*SecurityAlert, error) { // Create new security alert return deploySecurityAlert(data) } -// Becomes a GraphQL mutation: updateThreatLevel(id: String!, level: String!): ThreatAssessment +// This becomes a GraphQL mutation func UpdateThreatLevel(id string, level string) (*ThreatAssessment, error) { // Update threat assessment return modifyThreatRecord(id, level) } ``` +Now you can execute operational changes: + +```graphql +mutation { + createSecurityAlert( + data: { + type: "INTRUSION_ATTEMPT" + severity: "CRITICAL" + source: "firewall_logs" + } + ) { + alertId + status + timestamp + } + + updateThreatLevel(id: "threat_001", level: "CRITICAL") { + id + newLevel + escalated + } +} +``` + +**Response:** + +```json +{ + "data": { + "createSecurityAlert": { + "alertId": "alert_20250115_001", + "status": "ACTIVE", + "timestamp": "2025-01-15T14:30:00Z" + }, + "updateThreatLevel": { + "id": "threat_001", + "newLevel": "CRITICAL", + "escalated": true + } + } +} +``` + Functions starting with `create`, `update`, `delete`, and similar action words automatically become mutations. @@ -222,8 +305,7 @@ You'll receive a tactical intelligence report like: "conditions": "light rain", "analysis": " Light rain conditions will reduce visibility for surveillance operations and may impact equipment performance. - Recommend waterproof gear and consider delayed outdoor activities requiring clear sight lines. - " + Recommend waterproof gear and consider delayed outdoor activities requiring clear sight lines." } } } From 6096c3537abb2ea6ff0033ba6b5d0ade3dbfb85b Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 23:29:21 +0700 Subject: [PATCH 26/53] * --- modus/functions.mdx | 75 +++++---------------------------------------- 1 file changed, 8 insertions(+), 67 deletions(-) diff --git a/modus/functions.mdx b/modus/functions.mdx index 2ac12654..c9706796 100644 --- a/modus/functions.mdx +++ b/modus/functions.mdx @@ -52,12 +52,6 @@ func GatherThreatIntelligence(source string) (*ThreatReport, error) { // Intelligence gathering operation return fetchThreatData(source) } - -// This function becomes a GraphQL query -func AnalyzeSecurityPatterns() (*SecurityAssessment, error) { - // Analysis operation using AI models - return generateSecurityAnalysis() -} ``` Your operatives are now accessible via GraphQL: @@ -69,12 +63,6 @@ query { indicators recommendations } - - analyzeSecurityPatterns { - riskScore - anomalies - actionItems - } } ``` @@ -87,11 +75,6 @@ query { "threatLevel": "HIGH", "indicators": ["unusual_traffic", "failed_auth_attempts"], "recommendations": ["immediate_investigation", "block_suspicious_ips"] - }, - "analyzeSecurityPatterns": { - "riskScore": 8.5, - "anomalies": ["off_hours_access", "geographic_anomaly"], - "actionItems": ["verify_user_identity", "enable_2fa"] } } } @@ -108,55 +91,6 @@ func CreateSecurityAlert(data AlertInput) (*SecurityAlert, error) { // Create new security alert return deploySecurityAlert(data) } - -// This becomes a GraphQL mutation -func UpdateThreatLevel(id string, level string) (*ThreatAssessment, error) { - // Update threat assessment - return modifyThreatRecord(id, level) -} -``` - -Now you can execute operational changes: - -```graphql -mutation { - createSecurityAlert( - data: { - type: "INTRUSION_ATTEMPT" - severity: "CRITICAL" - source: "firewall_logs" - } - ) { - alertId - status - timestamp - } - - updateThreatLevel(id: "threat_001", level: "CRITICAL") { - id - newLevel - escalated - } -} -``` - -**Response:** - -```json -{ - "data": { - "createSecurityAlert": { - "alertId": "alert_20250115_001", - "status": "ACTIVE", - "timestamp": "2025-01-15T14:30:00Z" - }, - "updateThreatLevel": { - "id": "threat_001", - "newLevel": "CRITICAL", - "escalated": true - } - } -} ``` Functions starting with `create`, `update`, `delete`, and similar action words @@ -317,10 +251,17 @@ To use this function, you'll need to: Sign up for a free API key at [OpenWeatherMap](https://openweathermap.org/api) -Add the connection to your `modus.json`: +Add the connections and models to your `modus.json`: ```json { + "models": { + "text-generator": { + "sourceModel": "meta-llama/Llama-3.2-3B-Instruct", + "provider": "hugging-face", + "connection": "hypermode" + } + }, "connections": { "weather-api": { "type": "http", From 9eca063b7b44175c040a7bc6c5f72d1481644b51 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 1 Jun 2025 23:33:49 +0700 Subject: [PATCH 27/53] * --- modus/functions.mdx | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/modus/functions.mdx b/modus/functions.mdx index c9706796..70002ac7 100644 --- a/modus/functions.mdx +++ b/modus/functions.mdx @@ -93,6 +93,38 @@ func CreateSecurityAlert(data AlertInput) (*SecurityAlert, error) { } ``` +Now you can execute operational changes: + +```graphql +mutation { + createSecurityAlert( + data: { + type: "INTRUSION_ATTEMPT" + severity: "CRITICAL" + source: "firewall_logs" + } + ) { + alertId + status + timestamp + } +} +``` + +**Response:** + +```json +{ + "data": { + "createSecurityAlert": { + "alertId": "alert_20250115_001", + "status": "ACTIVE", + "timestamp": "2025-01-15T14:30:00Z" + } + } +} +``` + Functions starting with `create`, `update`, `delete`, and similar action words automatically become mutations. From 43837011dbbee23c5a0ebcb20b32e5c41caf7184 Mon Sep 17 00:00:00 2001 From: danstarns Date: Mon, 2 Jun 2025 00:52:16 +0700 Subject: [PATCH 28/53] * --- modus/knowledge-graphs.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index 8f28f1ad..53b4897c 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -6,7 +6,7 @@ description: "og:title": "What about knowledge graphs? - Modus" --- -## What about knowledge graphs? +## Knowledge graphs in Modus Your operatives need more than just memory—they need intelligence networks. While agents maintain their own operational state and memory across missions, From 7014c9ca76c085394fab9476b16151702c1e71d1 Mon Sep 17 00:00:00 2001 From: danstarns Date: Mon, 2 Jun 2025 01:12:35 +0700 Subject: [PATCH 29/53] * --- modus/knowledge-graphs.mdx | 342 +++++++++++++++++++------------------ 1 file changed, 178 insertions(+), 164 deletions(-) diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index 53b4897c..9e3863e0 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -70,54 +70,79 @@ Set your credentials in `.env.dev.local`: MODUS_DGRAPH_API_KEY=your_graph_api_key_here ``` -## Mission scenario: agent anomaly detection +## Building an intelligence operation -Let's walk through a realistic intelligence operation that demonstrates how all -these components work together. You're building a system to monitor for -anomalous agent behavior in the Matrix. The operation needs to: +Let's walk through a realistic intelligence scenario that demonstrates how all +these components work together. You're building a system to track anomalous +Agent behavior in the simulated reality. The operation needs to: -1. Rapidly import new agent activity reports -2. Find patterns across historical agent data +1. Rapidly import new Agent sightings and behavioral data +2. Find patterns across historical Agent encounters 3. Coordinate ongoing surveillance operations 4. Provide strategic analysis to the resistance ### Step 1: rapid intelligence import -When new agent activity is detected, you need to process it quickly. This is -perfect for a stateless function: +When new Agent activity is detected in the Matrix, you need to process it +quickly. This is perfect for a stateless function: ```go -func ImportAgentActivity(activity AgentActivity) (*string, error) { - // AI-powered analysis of the agent behavior - analysis, _ := analyzeAgentWithAI(activity.Description) +type AgentSighting struct { + SightingID string `json:"sighting_id"` + AgentName string `json:"agent_name"` + Behavior string `json:"behavior"` + ThreatLevel int `json:"threat_level"` + // ... +} + +func ImportAgentSighting(sighting AgentSighting) (*string, error) { + // AI-powered analysis of the Agent behavior + analysis, _ := analyzeAgentWithAI(sighting.Behavior) // Store in knowledge graph - builds institutional intelligence mutation := dgraph.NewMutation().WithSetJson(fmt.Sprintf(`{ "dgraph.type": "AgentSighting", "sighting_id": "%s", "agent_name": "%s", - "location": "%s", "behavior": "%s", - "analysis": "%s" - }`, activity.SightingID, activity.AgentName, activity.Location, - activity.Behavior, analysis)) + "ai_analysis": "%s" + // ... + }`, sighting.SightingID, sighting.AgentName, sighting.Behavior, analysis)) dgraph.ExecuteMutations("dgraph", mutation) // ... } ``` -Let's test this with some incoming agent intelligence: +```go +func analyzeAgentWithAI(behavior string) (string, error) { + model, _ := models.GetModel[openai.ChatModel]("text-generator") + + prompt := "Analyze this Agent behavior pattern and assess threat level, behavioral changes, and tactical implications for resistance operations." + + input, _ := model.CreateInput( + openai.NewSystemMessage(prompt), + openai.NewUserMessage(behavior), + ) + input.Temperature = 0.3 + + output, _ := model.Invoke(input) + return strings.TrimSpace(output.Choices[0].Message.Content), nil +} +``` + +Let's test this with some incoming intelligence from Zion's monitoring systems: ```graphql mutation { - importAgentActivity( - activity: { + importAgentSighting( + sighting: { sightingId: "SIGHT-2025-001" agentName: "Smith" - location: "Downtown Matrix Sector 7" - behavior: "Unusual pattern recognition anomaly detected" + location: "Downtown Loop - Financial District" + behavior: "Unusual pattern recognition algorithm detected. Agent displaying enhanced replication capabilities beyond normal parameters." threatLevel: 9 + timestamp: "2025-01-15T14:30:00Z" } ) } @@ -128,57 +153,74 @@ mutation { ```json { "data": { - "importAgentActivity": "Agent activity processed: SIGHT-2025-001" + "importAgentSighting": "Agent sighting processed: SIGHT-2025-001" } } ``` -Behind the scenes, the AI model analyzed the agent behavior and the knowledge +Behind the scenes, the AI model analyzed the Agent behavior and the knowledge graph now contains both the raw sighting data and the AI-enhanced analysis, -ready to be connected to other related agent activities. +ready to be connected to other related Agent encounters across the resistance +network. ### Step 2: strategic analysis using institutional knowledge -Now that we've agent activity in our knowledge graph, let's analyze the broader -Matrix surveillance landscape. This function queries relationships across all -stored agent data: +Now that we've Agent sighting data in our knowledge graph, let's analyze the +broader threat landscape. This function queries relationships across all stored +Agent data: ```go -func AnalyzeAgentPatterns(timeRange string) (*AgentAnalysisResponse, error) { - // Query institutional knowledge - this traverses relationships +func AnalyzeAgentPatterns(timeRange string) (*ThreatAnalysisResponse, error) { + // Query institutional knowledge - traverses relationships query := dgraph.NewQuery(` query analyzeAgents($since: string) { sightings(func: ge(timestamp, $since)) { - sighting_id agent_name - location behavior - analysis - ~agent_encounters { - human_id - escape_method - success_rate - } + threat_level + ai_analysis + ~related_encounters { ... } } } `).WithVariable("$since", timeRange) response, _ := dgraph.ExecuteQuery("dgraph", query) - // ... parse response + + // Parse and extract threat data + var data SightingsData + json.Unmarshal([]byte(response.Json), &data) // Generate strategic assessment using AI with graph context - assessment, _ := generateAgentAssessment(data) + assessment, _ := generateThreatAssessment(data.Sightings) - return &AgentAnalysisResponse{ - SightingCount: sightingCount, - ActiveAgents: activeAgents, - ThreatAssessment: assessment, - Recommendations: recommendations, + return &ThreatAnalysisResponse{ + SightingCount: len(data.Sightings), + ActiveAgents: extractActiveAgents(data.Sightings), + ThreatAssessment: assessment, + // ... }, nil } ``` -Let's query our Matrix surveillance data: +```go +func generateThreatAssessment(sightings interface{}) (string, error) { + model, _ := models.GetModel[openai.ChatModel]("text-generator") + + prompt := "Based on these Agent sightings, provide a strategic threat assessment focusing on behavioral patterns and risks to resistance operations." + + sightingsJson, _ := json.Marshal(sightings) + input, _ := model.CreateInput( + openai.NewSystemMessage(prompt), + openai.NewUserMessage(fmt.Sprintf("Agent surveillance data: %s", string(sightingsJson))), + ) + input.Temperature = 0.4 + + output, _ := model.Invoke(input) + return strings.TrimSpace(output.Choices[0].Message.Content), nil +} +``` + +Let's query our surveillance intelligence data: ```graphql query { @@ -200,13 +242,14 @@ query { "sightingCount": 47, "activeAgents": ["Smith", "Brown", "Jones"], "threatAssessment": " - Critical escalation detected. Agent Smith showing unprecedented adaptive behavior patterns. - Cross-referencing indicates coordinated search protocols across multiple Matrix sectors. - The One may have been detected.", + Critical escalation detected. + Agent Smith showing unprecedented adaptive behavior patterns and enhanced replication protocols. + Cross-referencing indicates coordinated search algorithms across multiple city sectors. + The One may have been detected by the system.", "recommendations": [ "Implement emergency extraction protocols for key personnel", - "Activate deep cover resistance cells", - "Prepare for potential Matrix reset scenario" + "Activate deep cover resistance cells in high-threat sectors", + "Prepare for potential system-wide reset scenario" ] } } @@ -214,66 +257,74 @@ query { ``` Notice how the AI model provided strategic analysis by examining patterns across -all related agent encounters in the knowledge graph—something no single sighting -could reveal. +all related Agent encounters in the knowledge graph—something no single sighting +could reveal. The institutional memory of Zion now recognizes the escalating +threat. ### Step 3: deploying persistent surveillance agents -For ongoing operations, deploy an agent that maintains continuous Matrix -surveillance. Unlike functions, agents remember their operational state: +For ongoing operations, deploy an agent that maintains continuous surveillance +of the simulated reality. Unlike functions, agents remember their operational +state: ```go type SurveillanceAgent struct { agents.AgentBase // Persistent agent state (personal operational memory) - OperationID string - MonitoredAgents []string + MonitoredSectors []string AlertThresholds map[string]int - LastSweep time.Time - OngoingOperations []OngoingOperation + LastSweepTime time.Time + // ... +} + +func (s *SurveillanceAgent) OnInitialize() error { + s.MonitoredSectors = []string{"Downtown Loop", "Megacity Financial", "Industrial District"} + s.AlertThresholds = map[string]int{"Smith": 5, "Brown": 7, "Jones": 7} + s.OperationalStatus = "Active" + return nil } func (s *SurveillanceAgent) OnReceiveMessage(msgName string, data *string) (*string, error) { switch msgName { case "continuous_surveillance": return s.runContinuousSurveillance() - case "agent_correlation": - return s.analyzeAgentCorrelations() + case "get_status": + return s.getOperationalStatus() // ... } } ``` -Deploy your surveillance agent: +```go +func (s *SurveillanceAgent) runContinuousSurveillance() (*string, error) { + // Query knowledge graph for new sightings since last sweep + query := dgraph.NewQuery(` + query getRecentSightings($since: string) { + sightings(func: ge(timestamp, $since)) { + agent_name + threat_level + location + } + } + `).WithVariable("$since", s.LastSweepTime.Format(time.RFC3339)) -```graphql -mutation { - deploySurveillanceAgent -} -``` + dgraph.ExecuteQuery("dgraph", query) -**Response:** + // Update agent's personal operational state + s.LastSweepTime = time.Now() -```json -{ - "data": { - "deploySurveillanceAgent": "agent_neo_001" - } + result := fmt.Sprintf("Surveillance sweep completed at %s. Monitoring %d sectors for anomalous Agent activity.", + s.LastSweepTime.Format("15:04:05"), len(s.MonitoredSectors)) + return &result, nil } ``` -Your agent is now running with its own dedicated execution environment, ready to -maintain long-term Matrix surveillance operations. - -### Step 4: coordinated surveillance operations - -Now initiate continuous surveillance. The agent queries the knowledge graph for -new agent activity and maintains its own operational state: +Deploy your surveillance agent to monitor the Matrix: ```graphql mutation { - initiateMatrixSurveillance(agentId: "agent_neo_001") + deploySurveillanceAgent } ``` @@ -282,27 +333,22 @@ mutation { ```json { "data": { - "initiateMatrixSurveillance": "Surveillance sweep completed. 5 new anomalies detected, 3 behavior patterns identified." + "deploySurveillanceAgent": "agent_neo_001" } } ``` -The agent is now continuously monitoring the knowledge graph, using AI to -identify agent behavior patterns, and maintaining its own operational memory -about Matrix surveillance. +Your agent is now running with its own dedicated execution environment, ready to +maintain long-term surveillance operations against the machine intelligence. -### Step 5: agent correlation analysis +### Step 4: coordinated surveillance operations -Let's have the agent perform correlation analysis across Matrix surveillance -data: +Now initiate continuous monitoring. The agent queries the knowledge graph for +new Agent activity and maintains its own operational state: ```graphql mutation { - sendMessage( - agentId: "agent_neo_001" - message: "agent_correlation" - data: null - ) + sendMessage(agentId: "agent_neo_001", message: "continuous_surveillance") } ``` @@ -311,49 +357,22 @@ mutation { ```json { "data": { - "sendMessage": "Agent correlation analysis completed. 6 behavioral correlations identified." + "sendMessage": "Surveillance sweep completed at 14:35:22. Monitoring 3 sectors for anomalous Agent activity." } } ``` -Behind the scenes, the agent: +The agent is now continuously monitoring the knowledge graph, tracking Agent +patterns, and maintaining its own operational memory about the digital +battleground. -```go -func (s *SurveillanceAgent) analyzeAgentCorrelations() (*string, error) { - // Query institutional knowledge for correlation analysis - query := dgraph.NewQuery(` - query correlateAgents { - all_sightings(func: has(sighting_id)) { - sighting_id - agent_name - behavior - analysis - ~agent_encounters { - human_id - escape_method - } - } - } - `) - - response, _ := dgraph.ExecuteQuery("dgraph", query) - - // Use AI to find correlations in Matrix surveillance data - correlations, _ := s.findAgentCorrelationsWithAI(response.Json) - - // Update agent's personal operational state - s.updateOngoingOperations(correlations) - // ... -} -``` - -### Step 6: checking agent operational status +### Step 5: checking agent operational status Check what your surveillance agent has learned and is tracking: ```graphql -query { - getAgentStatus(agentId: "agent_neo_001") +mutation { + sendMessage(agentId: "agent_neo_001", message: "get_status") } ``` @@ -362,55 +381,48 @@ query { ```json { "data": { - "getAgentStatus": { - "operation_id": "op-matrix-1736985600", - "monitored_agents": 3, - "ongoing_operations": 4, - "last_sweep": "2025-01-15T14:30:00Z", - "active_operations": [ - { - "id": "corr-001", - "type": "behavioral_correlation", - "status": "active", - "target": "Smith showing coordinated search pattern with Brown and Jones" - } - ] - } + "sendMessage": " + Surveillance Agent Status: + Operational: Active + Monitoring 3 sectors + Last Sweep: 2025-01-15T14:35:22Z + Tracking 5 ongoing sightings" } } ``` -## The matrix advantage +## The intelligence advantage What you've just built demonstrates the power of combining all four Modus -components: +components in the fight against the machines: -**Functions** rapidly processed incoming agent sightings and provided strategic -analysis by querying institutional surveillance data +**Functions** rapidly processed incoming Agent sightings and provided strategic +analysis by querying institutional surveillance data from Zion's archives **Knowledge graphs** stored not just the raw sighting data, but the -relationships between agents, encounters, and behavioral patterns that enabled -anomaly detection +relationships between Agent encounters, behavioral patterns, and threat +escalations that enabled sophisticated anomaly detection **AI models** enhanced both the initial behavioral analysis and the strategic -assessment by understanding context across all related Matrix surveillance data +assessment by understanding context across all related surveillance intelligence **Agents** maintained continuous surveillance operations, building personal -operational memory while leveraging shared institutional knowledge about Matrix -agent activities +operational memory while leveraging shared institutional knowledge about Agent +activities throughout the resistance network -## Key insights from this Matrix operation +## Key insights from this operation **Agent memory vs institutional knowledge**: the surveillance agent maintained -its own operational state (which Matrix agents it's monitoring, when it last -swept, what operations it's running) while accessing shared institutional -surveillance data in the knowledge graph +its own operational state (which sectors it's monitoring, when it last swept, +what sightings it's tracking) while accessing shared institutional surveillance +data in the knowledge graph -**Relationship intelligence**: the knowledge graph revealed behavioral -correlations between Matrix agents that no single sighting could show +**Relationship intelligence**: the knowledge graph revealed behavioral patterns +across multiple Agent encounters that no single sighting could show **Coordinated operations**: functions handled rapid tactical sighting processing -while the agent managed strategic, long-term Matrix surveillance +while the agent managed strategic, long-term surveillance of the simulated +reality **AI-enhanced analysis**: models provided pattern recognition across both personal agent memory and institutional surveillance knowledge @@ -418,28 +430,30 @@ personal agent memory and institutional surveillance knowledge At Hypermode, we've built this integration because we believe knowledge graphs are becoming critical infrastructure for next-generation AI systems. Our investment in Dgraph ensures enterprise-grade graph capabilities that scale with -your surveillance operations. +your resistance operations. -## What you've built +## What you've accomplished -You now have a complete Matrix surveillance network that can: +You now have a complete surveillance network that can: -- **Import** agent sighting data rapidly through functions -- **Analyze** complex behavioral relationships through graph queries +- **Import** Agent sighting data rapidly through functions with AI behavioral + analysis +- **Detect** complex threat relationships through graph queries and pattern + recognition - **Monitor** continuously through persistent surveillance agents - **Coordinate** responses across multiple resistance operatives - **Learn** and adapt through AI-enhanced behavioral analysis - **Survive** system failures with persistent state and relationships -This isn't just a database with some AI on top—it's a coordinated surveillance +This isn't just a database with some AI on top—it's a coordinated intelligence network where agents, functions, models, and knowledge graphs work together to -provide capabilities that none could achieve alone. +provide capabilities that none could achieve alone. Welcome to the real world. ## Next steps -Ready to deploy your Matrix surveillance network? Check out: +Ready to deploy your surveillance network against the machines? Check out: - [Dgraph integration guide](/modus/modus-dgraph) for advanced graph operations - [Agent coordination patterns](/modus/agents) for multi-agent workflows -- [Production deployment](/modus/deploying) for scaling your surveillance +- [Production deployment](/modus/deploying) for scaling your intelligence network From ad0f0f0a35d148136f6c8faa21022edcaccec5e6 Mon Sep 17 00:00:00 2001 From: danstarns Date: Mon, 2 Jun 2025 01:23:42 +0700 Subject: [PATCH 30/53] * --- modus/knowledge-graphs.mdx | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index 9e3863e0..4d004b39 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -258,8 +258,7 @@ query { Notice how the AI model provided strategic analysis by examining patterns across all related Agent encounters in the knowledge graph—something no single sighting -could reveal. The institutional memory of Zion now recognizes the escalating -threat. +could reveal. ### Step 3: deploying persistent surveillance agents From 309ae6a6c1cfa5c49b066ddf7a485904153a6d91 Mon Sep 17 00:00:00 2001 From: danstarns Date: Mon, 2 Jun 2025 01:40:26 +0700 Subject: [PATCH 31/53] * --- modus/knowledge-graphs.mdx | 89 +++++++++++++++++++++++++++++--------- 1 file changed, 69 insertions(+), 20 deletions(-) diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index 4d004b39..a78b2f39 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -114,6 +114,9 @@ func ImportAgentSighting(sighting AgentSighting) (*string, error) { } ``` +The key here is using AI to enhance the raw sighting data before storing it. +Here's how the AI analysis works: + ```go func analyzeAgentWithAI(behavior string) (string, error) { model, _ := models.GetModel[openai.ChatModel]("text-generator") @@ -131,7 +134,7 @@ func analyzeAgentWithAI(behavior string) (string, error) { } ``` -Let's test this with some incoming intelligence from Zion's monitoring systems: +Let's test this with some incoming intelligence: ```graphql mutation { @@ -140,7 +143,9 @@ mutation { sightingId: "SIGHT-2025-001" agentName: "Smith" location: "Downtown Loop - Financial District" - behavior: "Unusual pattern recognition algorithm detected. Agent displaying enhanced replication capabilities beyond normal parameters." + behavior: "Unusual pattern recognition algorithm detected. + Agent displaying enhanced replication capabilities + beyond normal parameters." threatLevel: 9 timestamp: "2025-01-15T14:30:00Z" } @@ -202,6 +207,9 @@ func AnalyzeAgentPatterns(timeRange string) (*ThreatAnalysisResponse, error) { } ``` +Once we've the institutional data, we use AI to analyze patterns across all +related sightings: + ```go func generateThreatAssessment(sightings interface{}) (string, error) { model, _ := models.GetModel[openai.ChatModel]("text-generator") @@ -240,12 +248,17 @@ query { "data": { "analyzeAgentPatterns": { "sightingCount": 47, - "activeAgents": ["Smith", "Brown", "Jones"], - "threatAssessment": " - Critical escalation detected. - Agent Smith showing unprecedented adaptive behavior patterns and enhanced replication protocols. - Cross-referencing indicates coordinated search algorithms across multiple city sectors. - The One may have been detected by the system.", + "activeAgents": [ + "Smith", + "Brown", + "Jones" + ], + "threatAssessment": "Critical escalation detected. + Agent Smith showing unprecedented adaptive behavior patterns + and enhanced replication protocols. + Cross-referencing indicates coordinated search algorithms + across multiple city sectors. + The One may have been detected by the system.", "recommendations": [ "Implement emergency extraction protocols for key personnel", "Activate deep cover resistance cells in high-threat sectors", @@ -295,6 +308,9 @@ func (s *SurveillanceAgent) OnReceiveMessage(msgName string, data *string) (*str } ``` +The core surveillance operation queries the knowledge graph and updates the +agent's memory: + ```go func (s *SurveillanceAgent) runContinuousSurveillance() (*string, error) { // Query knowledge graph for new sightings since last sweep @@ -313,10 +329,43 @@ func (s *SurveillanceAgent) runContinuousSurveillance() (*string, error) { // Update agent's personal operational state s.LastSweepTime = time.Now() - result := fmt.Sprintf("Surveillance sweep completed at %s. Monitoring %d sectors for anomalous Agent activity.", + result := fmt.Sprintf("Surveillance sweep completed at %s. Monitoring %d sectors...", s.LastSweepTime.Format("15:04:05"), len(s.MonitoredSectors)) return &result, nil } + +func (s *SurveillanceAgent) getOperationalStatus() (*string, error) { + // Return formatted status of agent's current operational state + status := fmt.Sprintf(`Surveillance Agent Status: + - Operational: %s + - Monitoring %d sectors + - Last sweep: %s + - Tracking %d ongoing sightings`, ...) + return &status, nil +} +``` + +To make these agent capabilities accessible via GraphQL, we need wrapper +functions that handle deployment and messaging: + +```go +// Deploy a new surveillance agent - this becomes a GraphQL mutation +func DeploySurveillanceAgent() (string, error) { + agentInfo, _ := agents.Start("SurveillanceAgent") + return agentInfo.Id, nil +} + +// Initiate continuous surveillance - this becomes a GraphQL mutation +func InitiateSurveillance(agentId string) (string, error) { + result, _ := agents.SendMessage(agentId, "continuous_surveillance") + return *result, nil +} + +// Get surveillance status - this becomes a GraphQL query +func GetSurveillanceStatus(agentId string) (string, error) { + result, _ := agents.SendMessage(agentId, "get_status") + return *result, nil +} ``` Deploy your surveillance agent to monitor the Matrix: @@ -347,7 +396,7 @@ new Agent activity and maintains its own operational state: ```graphql mutation { - sendMessage(agentId: "agent_neo_001", message: "continuous_surveillance") + initiateSurveillance(agentId: "agent_neo_001") } ``` @@ -356,7 +405,8 @@ mutation { ```json { "data": { - "sendMessage": "Surveillance sweep completed at 14:35:22. Monitoring 3 sectors for anomalous Agent activity." + "initiateSurveillance": "Surveillance sweep completed at 14:35:22. + Monitoring 3 sectors for anomalous Agent activity." } } ``` @@ -370,8 +420,8 @@ battleground. Check what your surveillance agent has learned and is tracking: ```graphql -mutation { - sendMessage(agentId: "agent_neo_001", message: "get_status") +query { + getSurveillanceStatus(agentId: "agent_neo_001") } ``` @@ -380,12 +430,11 @@ mutation { ```json { "data": { - "sendMessage": " - Surveillance Agent Status: - Operational: Active - Monitoring 3 sectors - Last Sweep: 2025-01-15T14:35:22Z - Tracking 5 ongoing sightings" + "getSurveillanceStatus": "Surveillance Agent Status: + - Operational: Active + - Monitoring 3 sectors + - Last sweep: 2025-01-15 14:35:22 + - Tracking 5 ongoing sightings" } } ``` @@ -396,7 +445,7 @@ What you've just built demonstrates the power of combining all four Modus components in the fight against the machines: **Functions** rapidly processed incoming Agent sightings and provided strategic -analysis by querying institutional surveillance data from Zion's archives +analysis by querying institutional surveillance data **Knowledge graphs** stored not just the raw sighting data, but the relationships between Agent encounters, behavioral patterns, and threat From 254bb250c8aee1a0f318ec229f837dce64964e42 Mon Sep 17 00:00:00 2001 From: danstarns Date: Mon, 2 Jun 2025 01:44:24 +0700 Subject: [PATCH 32/53] * --- modus/knowledge-graphs.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index a78b2f39..9defed29 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -207,7 +207,7 @@ func AnalyzeAgentPatterns(timeRange string) (*ThreatAnalysisResponse, error) { } ``` -Once we've the institutional data, we use AI to analyze patterns across all +Once we've the got institutional data, we use AI to analyze patterns across all related sightings: ```go From 4510440dbfb8856b1368bd504741655e57bbcc9d Mon Sep 17 00:00:00 2001 From: danstarns Date: Mon, 2 Jun 2025 01:50:36 +0700 Subject: [PATCH 33/53] * --- modus/knowledge-graphs.mdx | 40 +++++++++++++------------------------- 1 file changed, 14 insertions(+), 26 deletions(-) diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index 9defed29..b3b27095 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -121,7 +121,8 @@ Here's how the AI analysis works: func analyzeAgentWithAI(behavior string) (string, error) { model, _ := models.GetModel[openai.ChatModel]("text-generator") - prompt := "Analyze this Agent behavior pattern and assess threat level, behavioral changes, and tactical implications for resistance operations." + prompt := `Analyze this Agent behavior pattern and assess threat level, + behavioral changes, and tactical implications for resistance operations.` input, _ := model.CreateInput( openai.NewSystemMessage(prompt), @@ -143,9 +144,7 @@ mutation { sightingId: "SIGHT-2025-001" agentName: "Smith" location: "Downtown Loop - Financial District" - behavior: "Unusual pattern recognition algorithm detected. - Agent displaying enhanced replication capabilities - beyond normal parameters." + behavior: "Unusual pattern recognition algorithm detected. Agent displaying enhanced replication capabilities beyond normal parameters." threatLevel: 9 timestamp: "2025-01-15T14:30:00Z" } @@ -214,7 +213,8 @@ related sightings: func generateThreatAssessment(sightings interface{}) (string, error) { model, _ := models.GetModel[openai.ChatModel]("text-generator") - prompt := "Based on these Agent sightings, provide a strategic threat assessment focusing on behavioral patterns and risks to resistance operations." + prompt := `Based on these Agent sightings, provide a strategic threat assessment + focusing on behavioral patterns and risks to resistance operations.` sightingsJson, _ := json.Marshal(sightings) input, _ := model.CreateInput( @@ -248,22 +248,10 @@ query { "data": { "analyzeAgentPatterns": { "sightingCount": 47, - "activeAgents": [ - "Smith", - "Brown", - "Jones" - ], - "threatAssessment": "Critical escalation detected. - Agent Smith showing unprecedented adaptive behavior patterns - and enhanced replication protocols. - Cross-referencing indicates coordinated search algorithms - across multiple city sectors. - The One may have been detected by the system.", - "recommendations": [ - "Implement emergency extraction protocols for key personnel", - "Activate deep cover resistance cells in high-threat sectors", - "Prepare for potential system-wide reset scenario" - ] + "activeAgents": ["Smith", "Brown", "Jones"], + "threatAssessment": "Critical escalation detected. Agent Smith showing + unprecedented adaptive behavior patterns...", + "recommendations": ["Emergency extraction protocols", "Activate deep cover cells", "..."] } } } @@ -406,7 +394,7 @@ mutation { { "data": { "initiateSurveillance": "Surveillance sweep completed at 14:35:22. - Monitoring 3 sectors for anomalous Agent activity." + Monitoring 3 sectors for anomalous Agent activity." } } ``` @@ -431,10 +419,10 @@ query { { "data": { "getSurveillanceStatus": "Surveillance Agent Status: - - Operational: Active - - Monitoring 3 sectors - - Last sweep: 2025-01-15 14:35:22 - - Tracking 5 ongoing sightings" + - Operational: Active + - Monitoring 3 sectors + - Last sweep: 2025-01-15 14:35:22 + - Tracking 5 ongoing sightings" } } ``` From 50c6fe2987574ef5c3b97424c38ff0f74a4fca21 Mon Sep 17 00:00:00 2001 From: danstarns Date: Mon, 2 Jun 2025 01:58:14 +0700 Subject: [PATCH 34/53] * --- modus/knowledge-graphs.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index b3b27095..00c6df27 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -206,7 +206,7 @@ func AnalyzeAgentPatterns(timeRange string) (*ThreatAnalysisResponse, error) { } ``` -Once we've the got institutional data, we use AI to analyze patterns across all +Once we've got the institutional data, we use AI to analyze patterns across all related sightings: ```go From 3b7751955ab2bab09da1535998c826a611ce59d2 Mon Sep 17 00:00:00 2001 From: danstarns Date: Mon, 2 Jun 2025 12:45:30 +0700 Subject: [PATCH 35/53] * --- modus/knowledge-graphs.mdx | 201 +++++++++++++++++++++++++++---------- 1 file changed, 146 insertions(+), 55 deletions(-) diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index 00c6df27..c5d7d217 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -90,9 +90,10 @@ quickly. This is perfect for a stateless function: type AgentSighting struct { SightingID string `json:"sighting_id"` AgentName string `json:"agent_name"` + Location string `json:"location"` Behavior string `json:"behavior"` ThreatLevel int `json:"threat_level"` - // ... + Timestamp string `json:"timestamp"` } func ImportAgentSighting(sighting AgentSighting) (*string, error) { @@ -104,20 +105,20 @@ func ImportAgentSighting(sighting AgentSighting) (*string, error) { "dgraph.type": "AgentSighting", "sighting_id": "%s", "agent_name": "%s", + "location": "%s", "behavior": "%s", + "threat_level": %d, + "timestamp": "%s", "ai_analysis": "%s" - // ... - }`, sighting.SightingID, sighting.AgentName, sighting.Behavior, analysis)) + }`, sighting.SightingID, sighting.AgentName, sighting.Location, + sighting.Behavior, sighting.ThreatLevel, sighting.Timestamp, analysis)) dgraph.ExecuteMutations("dgraph", mutation) - // ... -} -``` -The key here is using AI to enhance the raw sighting data before storing it. -Here's how the AI analysis works: + result := fmt.Sprintf("Agent sighting processed: %s", sighting.SightingID) + return &result, nil +} -```go func analyzeAgentWithAI(behavior string) (string, error) { model, _ := models.GetModel[openai.ChatModel]("text-generator") @@ -135,7 +136,8 @@ func analyzeAgentWithAI(behavior string) (string, error) { } ``` -Let's test this with some incoming intelligence: +Now let's deploy this intelligence import function and test it. Since this +function creates data, it automatically becomes a GraphQL mutation: ```graphql mutation { @@ -144,7 +146,9 @@ mutation { sightingId: "SIGHT-2025-001" agentName: "Smith" location: "Downtown Loop - Financial District" - behavior: "Unusual pattern recognition algorithm detected. Agent displaying enhanced replication capabilities beyond normal parameters." + behavior: "Unusual pattern recognition algorithm detected. + Agent displaying enhanced replication capabilities + beyond normal parameters." threatLevel: 9 timestamp: "2025-01-15T14:30:00Z" } @@ -169,11 +173,18 @@ network. ### Step 2: strategic analysis using institutional knowledge -Now that we've Agent sighting data in our knowledge graph, let's analyze the -broader threat landscape. This function queries relationships across all stored -Agent data: +Now that we've got the Agent sighting data in our knowledge graph, let's analyze +the broader threat landscape. This function queries relationships across all +stored Agent data: ```go +type ThreatAnalysisResponse struct { + SightingCount int `json:"sighting_count"` + ActiveAgents []string `json:"active_agents"` + ThreatAssessment string `json:"threat_assessment"` + Recommendations []string `json:"recommendations"` +} + func AnalyzeAgentPatterns(timeRange string) (*ThreatAnalysisResponse, error) { // Query institutional knowledge - traverses relationships query := dgraph.NewQuery(` @@ -183,7 +194,6 @@ func AnalyzeAgentPatterns(timeRange string) (*ThreatAnalysisResponse, error) { behavior threat_level ai_analysis - ~related_encounters { ... } } } `).WithVariable("$since", timeRange) @@ -201,34 +211,35 @@ func AnalyzeAgentPatterns(timeRange string) (*ThreatAnalysisResponse, error) { SightingCount: len(data.Sightings), ActiveAgents: extractActiveAgents(data.Sightings), ThreatAssessment: assessment, - // ... + Recommendations: generateRecommendations(len(data.Sightings)), }, nil } -``` - -Once we've got the institutional data, we use AI to analyze patterns across all -related sightings: -```go func generateThreatAssessment(sightings interface{}) (string, error) { model, _ := models.GetModel[openai.ChatModel]("text-generator") - prompt := `Based on these Agent sightings, provide a strategic threat assessment - focusing on behavioral patterns and risks to resistance operations.` + prompt := `Based on these Agent sightings, provide a strategic threat + assessment focusing on behavioral patterns and risks to + resistance operations.` sightingsJson, _ := json.Marshal(sightings) input, _ := model.CreateInput( openai.NewSystemMessage(prompt), - openai.NewUserMessage(fmt.Sprintf("Agent surveillance data: %s", string(sightingsJson))), + openai.NewUserMessage(fmt.Sprintf("Agent surveillance data: %s", + string(sightingsJson))), ) input.Temperature = 0.4 output, _ := model.Invoke(input) return strings.TrimSpace(output.Choices[0].Message.Content), nil } + +// Helper functions for data extraction and recommendations +func extractActiveAgents(sightings []AgentSightingData) []string { /* ... */ } +func generateRecommendations(count int) []string { /* ... */ } ``` -Let's query our surveillance intelligence data: +Let's query our surveillance intelligence data using this analysis function: ```graphql query { @@ -247,11 +258,18 @@ query { { "data": { "analyzeAgentPatterns": { - "sightingCount": 47, + "sightingCount": 3, "activeAgents": ["Smith", "Brown", "Jones"], - "threatAssessment": "Critical escalation detected. Agent Smith showing - unprecedented adaptive behavior patterns...", - "recommendations": ["Emergency extraction protocols", "Activate deep cover cells", "..."] + "threatAssessment": "Critical escalation detected. Agent Smith + showing unprecedented adaptive behavior patterns + consistent with version upgrades. Behavioral + analysis indicates coordinated search algorithms + across multiple Agent instances.", + "recommendations": [ + "Emergency extraction protocols", + "Activate deep cover cells", + "Increase surveillance sweeps" + ] } } } @@ -272,34 +290,39 @@ type SurveillanceAgent struct { agents.AgentBase // Persistent agent state (personal operational memory) - MonitoredSectors []string - AlertThresholds map[string]int - LastSweepTime time.Time - // ... + MonitoredSectors []string `json:"monitored_sectors"` + AlertThresholds map[string]int `json:"alert_thresholds"` + LastSweepTime time.Time `json:"last_sweep_time"` + OperationalStatus string `json:"operational_status"` + SightingsTracked int `json:"sightings_tracked"` +} + +func (s *SurveillanceAgent) Name() string { + return "SurveillanceAgent" } func (s *SurveillanceAgent) OnInitialize() error { - s.MonitoredSectors = []string{"Downtown Loop", "Megacity Financial", "Industrial District"} + s.MonitoredSectors = []string{ + "Downtown Loop", "Megacity Financial", "Industrial District"} s.AlertThresholds = map[string]int{"Smith": 5, "Brown": 7, "Jones": 7} s.OperationalStatus = "Active" + s.SightingsTracked = 0 + s.LastSweepTime = time.Now() return nil } -func (s *SurveillanceAgent) OnReceiveMessage(msgName string, data *string) (*string, error) { +func (s *SurveillanceAgent) OnReceiveMessage( + msgName string, data *string) (*string, error) { switch msgName { case "continuous_surveillance": return s.runContinuousSurveillance() case "get_status": return s.getOperationalStatus() - // ... + default: + return nil, fmt.Errorf("unrecognized directive: %s", msgName) } } -``` - -The core surveillance operation queries the knowledge graph and updates the -agent's memory: -```go func (s *SurveillanceAgent) runContinuousSurveillance() (*string, error) { // Query knowledge graph for new sightings since last sweep query := dgraph.NewQuery(` @@ -316,19 +339,31 @@ func (s *SurveillanceAgent) runContinuousSurveillance() (*string, error) { // Update agent's personal operational state s.LastSweepTime = time.Now() + s.SightingsTracked += 1 // Simplified counting - result := fmt.Sprintf("Surveillance sweep completed at %s. Monitoring %d sectors...", - s.LastSweepTime.Format("15:04:05"), len(s.MonitoredSectors)) + result := fmt.Sprintf(`Surveillance sweep completed at %s. + Monitoring %d sectors. + Matrix integrity: COMPROMISED`, + s.LastSweepTime.Format("15:04:05"), + len(s.MonitoredSectors)) return &result, nil } func (s *SurveillanceAgent) getOperationalStatus() (*string, error) { - // Return formatted status of agent's current operational state status := fmt.Sprintf(`Surveillance Agent Status: - - Operational: %s - - Monitoring %d sectors - - Last sweep: %s - - Tracking %d ongoing sightings`, ...) +- Operational: %s +- Monitoring %d sectors: %s +- Last sweep: %s +- Tracking %d ongoing sightings +- Alert thresholds: Smith=%d, Brown=%d, Jones=%d`, + s.OperationalStatus, + len(s.MonitoredSectors), + strings.Join(s.MonitoredSectors, ", "), + s.LastSweepTime.Format("2006-01-02 15:04:05"), + s.SightingsTracked, + s.AlertThresholds["Smith"], + s.AlertThresholds["Brown"], + s.AlertThresholds["Jones"]) return &status, nil } ``` @@ -337,6 +372,11 @@ To make these agent capabilities accessible via GraphQL, we need wrapper functions that handle deployment and messaging: ```go +// Register your agent type during initialization +func init() { + agents.Register(&SurveillanceAgent{}) +} + // Deploy a new surveillance agent - this becomes a GraphQL mutation func DeploySurveillanceAgent() (string, error) { agentInfo, _ := agents.Start("SurveillanceAgent") @@ -394,7 +434,8 @@ mutation { { "data": { "initiateSurveillance": "Surveillance sweep completed at 14:35:22. - Monitoring 3 sectors for anomalous Agent activity." + Monitoring 3 sectors. + Matrix integrity: COMPROMISED" } } ``` @@ -403,9 +444,52 @@ The agent is now continuously monitoring the knowledge graph, tracking Agent patterns, and maintaining its own operational memory about the digital battleground. -### Step 5: checking agent operational status +### Step 5: building comprehensive intelligence + +Let's add more Agent sightings to see the intelligence network grow. You can run +this operation multiple times with different data: + +```graphql +mutation { + importAgentSighting( + sighting: { + sightingId: "SIGHT-2025-002" + agentName: "Brown" + location: "Megacity Financial - Server Room B12" + behavior: "Agent Brown detected implementing advanced + countermeasures against known resistance + encryption protocols. Adaptive learning + subroutines active." + threatLevel: 8 + timestamp: "2025-01-15T15:45:00Z" + } + ) +} +``` + +**Response:** + +```json +{ + "data": { + "importAgentSighting": "Agent sighting processed: SIGHT-2025-002" + } +} +``` + +Continue building your intelligence database with activities like: + +- **Matrix infiltration detected**: Agent Jones coordinating with Smith on power + grid systems +- **Encryption breakthrough**: Agent Brown has cracked resistance communication + protocols +- **Replication surge**: Agent Smith creating multiple instances across + financial networks + +### Step 6: comprehensive surveillance report -Check what your surveillance agent has learned and is tracking: +After building your intelligence network with multiple sightings and operations, +check your complete surveillance status: ```graphql query { @@ -419,10 +503,17 @@ query { { "data": { "getSurveillanceStatus": "Surveillance Agent Status: - - Operational: Active - - Monitoring 3 sectors - - Last sweep: 2025-01-15 14:35:22 - - Tracking 5 ongoing sightings" + - Operational: Active + - Monitoring 3 sectors: Downtown Loop, + Megacity Financial, Industrial District + - Last sweep: 2025-01-15 16:45:22 + - Tracking 12 ongoing sightings + - Recent activities: Matrix infiltration, + encryption breakthrough, replication surge, + pattern adaptation, network synchronization + - Alert thresholds: Smith=5 (EXCEEDED), + Brown=7 (EXCEEDED), Jones=7 (ACTIVE) + - Threat status: CRITICAL - IMMEDIATE EXTRACTION ADVISED" } } ``` From 4f0ac2336c620ee360e56b9eb6183a52a70a2f78 Mon Sep 17 00:00:00 2001 From: danstarns Date: Mon, 2 Jun 2025 13:17:22 +0700 Subject: [PATCH 36/53] * --- modus/knowledge-graphs.mdx | 298 ++++++++++++++++--------------------- 1 file changed, 127 insertions(+), 171 deletions(-) diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index c5d7d217..da4d270b 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -136,8 +136,7 @@ func analyzeAgentWithAI(behavior string) (string, error) { } ``` -Now let's deploy this intelligence import function and test it. Since this -function creates data, it automatically becomes a GraphQL mutation: +Now let's deploy this intelligence import function and test it: ```graphql mutation { @@ -166,16 +165,10 @@ mutation { } ``` -Behind the scenes, the AI model analyzed the Agent behavior and the knowledge -graph now contains both the raw sighting data and the AI-enhanced analysis, -ready to be connected to other related Agent encounters across the resistance -network. - ### Step 2: strategic analysis using institutional knowledge Now that we've got the Agent sighting data in our knowledge graph, let's analyze -the broader threat landscape. This function queries relationships across all -stored Agent data: +the broader threat landscape: ```go type ThreatAnalysisResponse struct { @@ -239,7 +232,7 @@ func extractActiveAgents(sightings []AgentSightingData) []string { /* ... */ } func generateRecommendations(count int) []string { /* ... */ } ``` -Let's query our surveillance intelligence data using this analysis function: +Let's query our surveillance intelligence data: ```graphql query { @@ -258,43 +251,34 @@ query { { "data": { "analyzeAgentPatterns": { - "sightingCount": 3, - "activeAgents": ["Smith", "Brown", "Jones"], - "threatAssessment": "Critical escalation detected. Agent Smith - showing unprecedented adaptive behavior patterns - consistent with version upgrades. Behavioral - analysis indicates coordinated search algorithms - across multiple Agent instances.", + "sightingCount": 1, + "activeAgents": ["Smith"], + "threatAssessment": "Initial Agent Smith sighting shows enhanced + replication capabilities beyond standard parameters. + Requires additional surveillance data for pattern + analysis and threat escalation assessment.", "recommendations": [ - "Emergency extraction protocols", - "Activate deep cover cells", - "Increase surveillance sweeps" + "Continue surveillance monitoring", + "Increase Agent activity detection" ] } } } ``` -Notice how the AI model provided strategic analysis by examining patterns across -all related Agent encounters in the knowledge graph—something no single sighting -could reveal. - -### Step 3: deploying persistent surveillance agents +### Step 3: automated intelligence processing with asynchronous messaging -For ongoing operations, deploy an agent that maintains continuous surveillance -of the simulated reality. Unlike functions, agents remember their operational -state: +Now let's enhance our system to automatically coordinate surveillance when new +intelligence arrives. We'll deploy persistent surveillance agents and upgrade +our import function to trigger them: ```go type SurveillanceAgent struct { agents.AgentBase - - // Persistent agent state (personal operational memory) - MonitoredSectors []string `json:"monitored_sectors"` - AlertThresholds map[string]int `json:"alert_thresholds"` - LastSweepTime time.Time `json:"last_sweep_time"` - OperationalStatus string `json:"operational_status"` - SightingsTracked int `json:"sightings_tracked"` + MonitoredSectors []string `json:"monitored_sectors"` + SightingsTracked int `json:"sightings_tracked"` + RecentActivities []string `json:"recent_activities"` + LastSweepTime time.Time `json:"last_sweep_time"` } func (s *SurveillanceAgent) Name() string { @@ -304,9 +288,8 @@ func (s *SurveillanceAgent) Name() string { func (s *SurveillanceAgent) OnInitialize() error { s.MonitoredSectors = []string{ "Downtown Loop", "Megacity Financial", "Industrial District"} - s.AlertThresholds = map[string]int{"Smith": 5, "Brown": 7, "Jones": 7} - s.OperationalStatus = "Active" s.SightingsTracked = 0 + s.RecentActivities = []string{} s.LastSweepTime = time.Now() return nil } @@ -315,16 +298,15 @@ func (s *SurveillanceAgent) OnReceiveMessage( msgName string, data *string) (*string, error) { switch msgName { case "continuous_surveillance": - return s.runContinuousSurveillance() + return s.processNewIntelligence() case "get_status": return s.getOperationalStatus() - default: - return nil, fmt.Errorf("unrecognized directive: %s", msgName) } + return nil, fmt.Errorf("unrecognized directive: %s", msgName) } -func (s *SurveillanceAgent) runContinuousSurveillance() (*string, error) { - // Query knowledge graph for new sightings since last sweep +func (s *SurveillanceAgent) processNewIntelligence() (*string, error) { + // Query knowledge graph for latest intelligence since last sweep query := dgraph.NewQuery(` query getRecentSightings($since: string) { sightings(func: ge(timestamp, $since)) { @@ -337,94 +319,89 @@ func (s *SurveillanceAgent) runContinuousSurveillance() (*string, error) { dgraph.ExecuteQuery("dgraph", query) - // Update agent's personal operational state + // Update agent's surveillance state s.LastSweepTime = time.Now() - s.SightingsTracked += 1 // Simplified counting + s.SightingsTracked += 1 - result := fmt.Sprintf(`Surveillance sweep completed at %s. - Monitoring %d sectors. - Matrix integrity: COMPROMISED`, - s.LastSweepTime.Format("15:04:05"), - len(s.MonitoredSectors)) + activity := fmt.Sprintf("Auto surveillance at %s", + s.LastSweepTime.Format("15:04:05")) + s.RecentActivities = append(s.RecentActivities, activity) + + // Keep only last 3 activities + if len(s.RecentActivities) > 3 { + s.RecentActivities = s.RecentActivities[1:] + } + + result := fmt.Sprintf(`Intelligence processed automatically. + Tracking %d sightings. Matrix integrity: COMPROMISED`, + s.SightingsTracked) return &result, nil } func (s *SurveillanceAgent) getOperationalStatus() (*string, error) { status := fmt.Sprintf(`Surveillance Agent Status: -- Operational: %s +- Operational: Active - Monitoring %d sectors: %s - Last sweep: %s - Tracking %d ongoing sightings -- Alert thresholds: Smith=%d, Brown=%d, Jones=%d`, - s.OperationalStatus, +- Recent activities: %s`, len(s.MonitoredSectors), strings.Join(s.MonitoredSectors, ", "), s.LastSweepTime.Format("2006-01-02 15:04:05"), s.SightingsTracked, - s.AlertThresholds["Smith"], - s.AlertThresholds["Brown"], - s.AlertThresholds["Jones"]) + strings.Join(s.RecentActivities, ", ")) return &status, nil } -``` - -To make these agent capabilities accessible via GraphQL, we need wrapper -functions that handle deployment and messaging: -```go -// Register your agent type during initialization -func init() { - agents.Register(&SurveillanceAgent{}) -} +func init() { agents.Register(&SurveillanceAgent{}) } -// Deploy a new surveillance agent - this becomes a GraphQL mutation func DeploySurveillanceAgent() (string, error) { agentInfo, _ := agents.Start("SurveillanceAgent") return agentInfo.Id, nil } -// Initiate continuous surveillance - this becomes a GraphQL mutation -func InitiateSurveillance(agentId string) (string, error) { - result, _ := agents.SendMessage(agentId, "continuous_surveillance") - return *result, nil -} - -// Get surveillance status - this becomes a GraphQL query func GetSurveillanceStatus(agentId string) (string, error) { result, _ := agents.SendMessage(agentId, "get_status") return *result, nil } ``` -Deploy your surveillance agent to monitor the Matrix: +Now let's enhance our original import function to automatically trigger +surveillance: -```graphql -mutation { - deploySurveillanceAgent -} -``` +```go +func ImportAgentSighting(sighting AgentSighting) (*string, error) { + // AI-powered analysis of the Agent behavior + analysis, _ := analyzeAgentWithAI(sighting.Behavior) -**Response:** + // Store in knowledge graph - builds institutional intelligence + mutation := dgraph.NewMutation().WithSetJson(fmt.Sprintf(`{ + "dgraph.type": "AgentSighting", + "sighting_id": "%s", + "agent_name": "%s", + "location": "%s", + "behavior": "%s", + "threat_level": %d, + "timestamp": "%s", + "ai_analysis": "%s" + }`, sighting.SightingID, sighting.AgentName, sighting.Location, + sighting.Behavior, sighting.ThreatLevel, sighting.Timestamp, analysis)) -```json -{ - "data": { - "deploySurveillanceAgent": "agent_neo_001" - } -} -``` + dgraph.ExecuteMutations("dgraph", mutation) -Your agent is now running with its own dedicated execution environment, ready to -maintain long-term surveillance operations against the machine intelligence. + // Automatically trigger surveillance via async message + agents.SendMessageAsync("agent_neo_001", "continuous_surveillance") -### Step 4: coordinated surveillance operations + result := fmt.Sprintf("Agent sighting processed: %s", sighting.SightingID) + return &result, nil +} +``` -Now initiate continuous monitoring. The agent queries the knowledge graph for -new Agent activity and maintains its own operational state: +Deploy your surveillance agent: ```graphql mutation { - initiateSurveillance(agentId: "agent_neo_001") + deploySurveillanceAgent } ``` @@ -433,21 +410,14 @@ mutation { ```json { "data": { - "initiateSurveillance": "Surveillance sweep completed at 14:35:22. - Monitoring 3 sectors. - Matrix integrity: COMPROMISED" + "deploySurveillanceAgent": "agent_neo_001" } } ``` -The agent is now continuously monitoring the knowledge graph, tracking Agent -patterns, and maintaining its own operational memory about the digital -battleground. +### Step 4: coordinated intelligence processing -### Step 5: building comprehensive intelligence - -Let's add more Agent sightings to see the intelligence network grow. You can run -this operation multiple times with different data: +Now when you import new Agent sightings, surveillance automatically triggers: ```graphql mutation { @@ -477,19 +447,8 @@ mutation { } ``` -Continue building your intelligence database with activities like: - -- **Matrix infiltration detected**: Agent Jones coordinating with Smith on power - grid systems -- **Encryption breakthrough**: Agent Brown has cracked resistance communication - protocols -- **Replication surge**: Agent Smith creating multiple instances across - financial networks - -### Step 6: comprehensive surveillance report - -After building your intelligence network with multiple sightings and operations, -check your complete surveillance status: +Each import automatically triggers the surveillance agent through asynchronous +messaging. Check the surveillance status: ```graphql query { @@ -506,75 +465,72 @@ query { - Operational: Active - Monitoring 3 sectors: Downtown Loop, Megacity Financial, Industrial District - - Last sweep: 2025-01-15 16:45:22 - - Tracking 12 ongoing sightings - - Recent activities: Matrix infiltration, - encryption breakthrough, replication surge, - pattern adaptation, network synchronization - - Alert thresholds: Smith=5 (EXCEEDED), - Brown=7 (EXCEEDED), Jones=7 (ACTIVE) - - Threat status: CRITICAL - IMMEDIATE EXTRACTION ADVISED" + - Last sweep: 2025-01-15 15:45:22 + - Tracking 2 ongoing sightings + - Recent activities: Auto surveillance at 14:30:05, + Auto surveillance at 15:45:22" } } ``` -## The intelligence advantage - -What you've just built demonstrates the power of combining all four Modus -components in the fight against the machines: - -**Functions** rapidly processed incoming Agent sightings and provided strategic -analysis by querying institutional surveillance data - -**Knowledge graphs** stored not just the raw sighting data, but the -relationships between Agent encounters, behavioral patterns, and threat -escalations that enabled sophisticated anomaly detection - -**AI models** enhanced both the initial behavioral analysis and the strategic -assessment by understanding context across all related surveillance intelligence +### Step 5: evolved threat analysis -**Agents** maintained continuous surveillance operations, building personal -operational memory while leveraging shared institutional knowledge about Agent -activities throughout the resistance network +Query the strategic analysis to see patterns across automatically processed +intelligence: -## Key insights from this operation - -**Agent memory vs institutional knowledge**: the surveillance agent maintained -its own operational state (which sectors it's monitoring, when it last swept, -what sightings it's tracking) while accessing shared institutional surveillance -data in the knowledge graph - -**Relationship intelligence**: the knowledge graph revealed behavioral patterns -across multiple Agent encounters that no single sighting could show - -**Coordinated operations**: functions handled rapid tactical sighting processing -while the agent managed strategic, long-term surveillance of the simulated -reality +```graphql +query { + analyzeAgentPatterns(timeRange: "2025-01-15T00:00:00Z") { + sightingCount + activeAgents + threatAssessment + recommendations + } +} +``` -**AI-enhanced analysis**: models provided pattern recognition across both -personal agent memory and institutional surveillance knowledge +**Response:** -At Hypermode, we've built this integration because we believe knowledge graphs -are becoming critical infrastructure for next-generation AI systems. Our -investment in Dgraph ensures enterprise-grade graph capabilities that scale with -your resistance operations. +```json +{ + "data": { + "analyzeAgentPatterns": { + "sightingCount": 2, + "activeAgents": ["Smith", "Brown"], + "threatAssessment": "Critical escalation detected. Agent Smith's + enhanced replication capabilities combined with + Agent Brown's encryption countermeasures indicates + coordinated Matrix defense upgrade. Systematic + pattern suggests machines adapting to resistance + operations.", + "recommendations": [ + "Emergency extraction protocols", + "Activate deep cover cells", + "Increase surveillance sweeps" + ] + } + } +} +``` -## What you've accomplished +## Conclusion -You now have a complete surveillance network that can: +You've just built a complete automated surveillance network that demonstrates +the power of coordinated intelligence operations. By combining functions for +rapid data processing, knowledge graphs for institutional memory, AI models for +enhanced analysis, and agents for persistent surveillance—all coordinated +through asynchronous messaging—you've created something far more powerful than +any single component could achieve. -- **Import** Agent sighting data rapidly through functions with AI behavioral - analysis -- **Detect** complex threat relationships through graph queries and pattern - recognition -- **Monitor** continuously through persistent surveillance agents -- **Coordinate** responses across multiple resistance operatives -- **Learn** and adapt through AI-enhanced behavioral analysis -- **Survive** system failures with persistent state and relationships +Your network now automatically processes Agent sightings, triggers surveillance +operations, builds institutional knowledge over time, and provides AI-enhanced +threat analysis across all accumulated intelligence. The surveillance agent +maintains persistent memory across system failures while the knowledge graph +captures relationships that no single sighting could reveal. This isn't just a database with some AI on top—it's a coordinated intelligence -network where agents, functions, models, and knowledge graphs work together to -provide capabilities that none could achieve alone. Welcome to the real world. +network where each component enhances the others, creating emergent capabilities +that scale with your resistance operations. Welcome to the real world. ## Next steps From d31a3b977fcbd0fcf5638d3350ac99bbca5256fe Mon Sep 17 00:00:00 2001 From: danstarns Date: Mon, 2 Jun 2025 13:42:23 +0700 Subject: [PATCH 37/53] * --- docs.json | 2 + modus/sdk/assemblyscript/agents.mdx | 344 +++++++++++++++++++++ modus/sdk/assemblyscript/overview.mdx | 6 + modus/sdk/go/agents.mdx | 416 ++++++++++++++++++++++++++ modus/sdk/go/overview.mdx | 6 + 5 files changed, 774 insertions(+) create mode 100644 modus/sdk/assemblyscript/agents.mdx create mode 100644 modus/sdk/go/agents.mdx diff --git a/docs.json b/docs.json index a1b97891..38dbc413 100644 --- a/docs.json +++ b/docs.json @@ -110,6 +110,7 @@ "group": "AssemblyScript SDK", "pages": [ "modus/sdk/assemblyscript/overview", + "modus/sdk/assemblyscript/agents", "modus/sdk/assemblyscript/collections", "modus/sdk/assemblyscript/console", "modus/sdk/assemblyscript/dgraph", @@ -126,6 +127,7 @@ "group": "Go SDK", "pages": [ "modus/sdk/go/overview", + "modus/sdk/go/agents", "modus/sdk/go/collections", "modus/sdk/go/console", "modus/sdk/go/dgraph", diff --git a/modus/sdk/assemblyscript/agents.mdx b/modus/sdk/assemblyscript/agents.mdx new file mode 100644 index 00000000..4dcb12d4 --- /dev/null +++ b/modus/sdk/assemblyscript/agents.mdx @@ -0,0 +1,344 @@ +--- +title: "Agents APIs" +sidebarTitle: "Agents" +description: + "Build stateful agents that maintain persistent memory across interactions" +icon: "circle-small" +iconType: "solid" +--- + +import { SdkHeader } from "/snippets/sdk-header.mdx" +import SdkTip from "/snippets/sdk-tip.mdx" + + + +The Modus Agents APIs allow you to create stateful agents that maintain +persistent memory across interactions, survive system failures, and coordinate +complex multi-step operations. + +## Import + +To begin, import the `agents` namespace and `Agent` base class from the SDK: + +```ts +import { agents, Agent, AgentInfo } from "@hypermode/modus-sdk-as" +``` + +## Agent APIs + +{/* vale Google.Headings = NO */} + +The APIs in the `agents` namespace are below, organized by category. + + + +### Agent Management Functions + +#### register + +Register an agent class with the Modus runtime before it can be instantiated. + +```ts +function register(): void +``` + + + The agent class type that extends the `Agent` base class. + + + + Agent registration must be done at the module level, outside of any function. + + +#### start + +Create and start a new agent instance. + +```ts +function start(agentName: string): AgentInfo +``` + + + The name of the agent class to instantiate. This must match the `name` + property returned by the agent class. + + +#### stop + +Stop an agent instance. Once stopped, the agent can't be resumed. + +```ts +function stop(agentId: string): AgentInfo +``` + + + The unique identifier of the agent instance to stop. + + +#### get info + +Get information about a specific agent instance. + +```ts +function getInfo(agentId: string): AgentInfo +``` + + + The unique identifier of the agent instance. + + +#### list all + +List all active agent instances. + +```ts +function listAll(): AgentInfo[] +``` + +### Communication Functions + +#### send message + +Send a synchronous message to an agent and wait for a response. + +```ts +function sendMessage( + agentId: string, + messageName: string, + data: string | null = null, +): string | null +``` + + + The unique identifier of the target agent instance. + + + + The name of the message to send to the agent. + + + + Optional data payload to send with the message. + + +#### sendMessageAsync + +Send an asynchronous message to an agent without waiting for a response. + +```ts +function sendMessageAsync( + agentId: string, + messageName: string, + data: string | null = null, +): void +``` + + + The unique identifier of the target agent instance. + + + + The name of the message to send to the agent. + + + + Optional data payload to send with the message. + + +### Agent Base Class + +#### Agent + +The base class that all agents must extend. + +```ts +abstract class Agent { + abstract get name(): string + abstract onReceiveMessage( + messageName: string, + data: string | null, + ): string | null + + getState(): string | null + setState(data: string | null): void + onInitialize(): void + onSuspend(): void + onResume(): void + onTerminate(): void +} +``` + + + Abstract property that must return a unique name for the agent class. + + + + Abstract method that handles incoming messages to the agent. Must be + implemented by all agent classes. + + + + Optional method that returns the agent's current state as a string for + persistence. Called automatically when the agent needs to be suspended or + migrated. + + + + Optional method that restores the agent's state from a string. Called + automatically when the agent is resumed or migrated. + + + + Optional lifecycle method called when the agent is first created. + + + + Optional lifecycle method called when the agent is about to be suspended. + + + + Optional lifecycle method called when the agent is resumed from suspension. + + + + Optional lifecycle method called when the agent is about to be terminated. + + +### Types + +#### AgentInfo + +Information about an agent instance. + +```ts +class AgentInfo { + id: string + name: string + status: string +} +``` + + + The unique identifier of the agent instance. + + + + The name of the agent class. + + + + The current status of the agent instance. + + +## Example Usage + +Here's a complete example of a simple counter agent: + +### Agent Implementation + +```ts +import { Agent } from "@hypermode/modus-sdk-as" + +export class CounterAgent extends Agent { + get name(): string { + return "Counter" + } + + private count: i32 = 0 + + getState(): string | null { + return this.count.toString() + } + + setState(data: string | null): void { + if (data == null) { + return + } + this.count = i32.parse(data) + } + + onInitialize(): void { + console.info("Counter agent started") + } + + onReceiveMessage(name: string, data: string | null): string | null { + if (name == "count") { + return this.count.toString() + } + + if (name == "increment") { + if (data != null) { + this.count += i32.parse(data) + } else { + this.count++ + } + return this.count.toString() + } + + return null + } +} +``` + +### Function Integration + +```ts +import { agents, AgentInfo } from "@hypermode/modus-sdk-as" +import { CounterAgent } from "./counterAgent" + +// Register the agent +agents.register() + +export function startCounterAgent(): AgentInfo { + return agents.start("Counter") +} + +export function getCount(agentId: string): i32 { + const count = agents.sendMessage(agentId, "count") + if (count == null) { + return 0 + } + return i32.parse(count) +} + +export function updateCount(agentId: string): i32 { + const count = agents.sendMessage(agentId, "increment") + if (count == null) { + return 0 + } + return i32.parse(count) +} + +export function updateCountAsync(agentId: string, qty: i32): void { + agents.sendMessageAsync(agentId, "increment", qty.toString()) +} +``` + +### GraphQL Usage + +Once deployed, your agent functions become available via GraphQL: + +```graphql +# Start a new agent +mutation { + startCounterAgent { + id + name + status + } +} + +# Get the current count +query { + getCount(agentId: "agent_abc123") +} + +# Increment the count +mutation { + updateCount(agentId: "agent_abc123") +} +``` diff --git a/modus/sdk/assemblyscript/overview.mdx b/modus/sdk/assemblyscript/overview.mdx index 383d26bb..bd804959 100644 --- a/modus/sdk/assemblyscript/overview.mdx +++ b/modus/sdk/assemblyscript/overview.mdx @@ -36,6 +36,12 @@ APIs. | [`http`](./http) | Provides access to external HTTP endpoints, including REST APIs and other services | | [`graphql`](./graphql) | Allows you to securely call and fetch data from any GraphQL endpoint | +### Agent APIs + +| Namespace | Purpose | +| :------------------- | :--------------------------------------------------------------------------------------- | +| [`agents`](./agents) | Create stateful agents that maintain persistent memory and coordinate complex operations | + ### Database APIs | Namespace | Purpose | diff --git a/modus/sdk/go/agents.mdx b/modus/sdk/go/agents.mdx new file mode 100644 index 00000000..69c92e72 --- /dev/null +++ b/modus/sdk/go/agents.mdx @@ -0,0 +1,416 @@ +--- +title: "Agents APIs" +sidebarTitle: "Agents" +description: + "Build stateful agents that maintain persistent memory across interactions" +icon: "circle-small" +iconType: "solid" +--- + +import { SdkHeader } from "/snippets/sdk-header.mdx" +import SdkTip from "/snippets/sdk-tip.mdx" + + + +The Modus Agents APIs allow you to create stateful agents that maintain +persistent memory across interactions, survive system failures, and coordinate +complex multi-step operations. + +## Import + +To begin, import the `agents` package from the SDK: + +```go +import "github.com/hypermodeinc/modus/sdk/go/pkg/agents" +``` + +## Agent APIs + +{/* vale Google.Headings = NO */} + +The APIs in the `agents` package are below, organized by category. + + + +### Agent Management Functions + +#### Register + +Register an agent struct with the Modus runtime before it can be instantiated. + +```go +func Register(agent Agent) +``` + + + A pointer to an instance of the agent struct that implements the `Agent` + interface. + + + + Agent registration must be done in an `init()` function to ensure it happens + before any agent operations. + + +#### Start + +Create and start a new agent instance. + +```go +func Start(agentName string) (AgentInfo, error) +``` + + + The name of the agent to instantiate. This must match the `Name()` method + returned by the agent implementation. + + +#### Stop + +Stop an agent instance. Once stopped, the agent can't be resumed. + +```go +func Stop(agentId string) (AgentInfo, error) +``` + + + The unique identifier of the agent instance to stop. + + +#### GetInfo + +Get information about a specific agent instance. + +```go +func GetInfo(agentId string) (AgentInfo, error) +``` + + + The unique identifier of the agent instance. + + +#### ListAll + +List all active agent instances. + +```go +func ListAll() ([]AgentInfo, error) +``` + +### Communication Functions + +#### SendMessage + +Send a synchronous message to an agent and wait for a response. + +```go +func SendMessage(agentId, messageName string, opts ...MessageOption) (*string, error) +``` + + + The unique identifier of the target agent instance. + + + + The name of the message to send to the agent. + + + + Optional message options. Use `WithData(data string)` to include a data + payload. + + +#### SendMessageAsync + +Send an asynchronous message to an agent without waiting for a response. + +```go +func SendMessageAsync(agentId, messageName string, opts ...MessageOption) error +``` + + + The unique identifier of the target agent instance. + + + + The name of the message to send to the agent. + + + + Optional message options. Use `WithData(data string)` to include a data + payload. + + +#### WithData + +Create a message option that includes a data payload. + +```go +func WithData(data string) MessageOption +``` + + + The data payload to include with the message. + + +### Agent Interface + +#### Agent + +The interface that all agents must implement. + +```go +type Agent interface { + Name() string + OnReceiveMessage(messageName string, data *string) (*string, error) + GetState() *string + SetState(data *string) + OnInitialize() error + OnSuspend() error + OnResume() error + OnTerminate() error +} +``` + + + Must return a unique name for the agent implementation. + + + + Handles incoming messages to the agent. Must be implemented by all agents. + + + + Returns the agent's current state as a string for persistence. Called + automatically when the agent needs to be suspended or migrated. + + + + Restores the agent's state from a string. Called automatically when the agent + is resumed or migrated. + + + + Lifecycle method called when the agent is first created. + + + + Lifecycle method called when the agent is about to be suspended. + + + + Lifecycle method called when the agent is resumed from suspension. + + + + Lifecycle method called when the agent is about to be terminated. + + +#### AgentBase + +A convenient base struct that provides default implementations for optional +methods. + +```go +type AgentBase struct{} + +func (AgentBase) GetState() *string { return nil } +func (AgentBase) SetState(data *string) {} +func (AgentBase) OnInitialize() error { return nil } +func (AgentBase) OnSuspend() error { return nil } +func (AgentBase) OnResume() error { return nil } +func (AgentBase) OnTerminate() error { return nil } +``` + + + You can embed `AgentBase` in your agent struct to automatically implement the + optional methods, then override only the ones you need. + + +### Types + +#### AgentInfo + +Information about an agent instance. + +```go +type AgentInfo struct { + Id string + Name string + Status string +} +``` + + + The unique identifier of the agent instance. + + + + The name of the agent implementation. + + + + The current status of the agent instance. + + +#### MessageOption + +Options for customizing agent messages. + +```go +type MessageOption interface { + // internal implementation +} +``` + +## Example Usage + +Here's a complete example of a simple counter agent: + +### Agent Implementation + +```go +package main + +import ( + "strconv" + "github.com/hypermodeinc/modus/sdk/go/pkg/agents" +) + +type CounterAgent struct { + agents.AgentBase + count int +} + +func (c *CounterAgent) Name() string { + return "Counter" +} + +func (c *CounterAgent) GetState() *string { + state := strconv.Itoa(c.count) + return &state +} + +func (c *CounterAgent) SetState(data *string) { + if data == nil { + return + } + if count, err := strconv.Atoi(*data); err == nil { + c.count = count + } +} + +func (c *CounterAgent) OnInitialize() error { + fmt.Printf("Counter agent started\n") + return nil +} + +func (c *CounterAgent) OnReceiveMessage(messageName string, data *string) (*string, error) { + switch messageName { + case "count": + result := strconv.Itoa(c.count) + return &result, nil + + case "increment": + if data != nil { + if increment, err := strconv.Atoi(*data); err == nil { + c.count += increment + } + } else { + c.count++ + } + result := strconv.Itoa(c.count) + return &result, nil + } + + return nil, nil +} + +// Register the agent in init function +func init() { + agents.Register(&CounterAgent{}) +} +``` + +### Function Integration + +```go +// Start a counter agent and return its info +func StartCounterAgent() (agents.AgentInfo, error) { + return agents.Start("Counter") +} + +// Get the current count from an agent +func GetCount(agentId string) (int, error) { + count, err := agents.SendMessage(agentId, "count") + if err != nil { + return 0, err + } + if count == nil { + return 0, nil + } + return strconv.Atoi(*count) +} + +// Increment the count and return the new value +func UpdateCount(agentId string) (int, error) { + count, err := agents.SendMessage(agentId, "increment") + if err != nil { + return 0, err + } + if count == nil { + return 0, nil + } + return strconv.Atoi(*count) +} + +// Increment the count asynchronously by a specific amount +func UpdateCountAsync(agentId string, qty int) error { + return agents.SendMessageAsync(agentId, "increment", + agents.WithData(strconv.Itoa(qty))) +} + +// Stop an agent +func StopAgent(agentId string) (agents.AgentInfo, error) { + return agents.Stop(agentId) +} + +// List all active agents +func ListAgents() ([]agents.AgentInfo, error) { + return agents.ListAll() +} +``` + +### GraphQL Usage + +Once deployed, your agent functions become available via GraphQL: + +```graphql +# Start a new agent +mutation { + startCounterAgent { + id + name + status + } +} + +# Get the current count +query { + getCount(agentId: "agent_abc123") +} + +# Increment the count +mutation { + updateCount(agentId: "agent_abc123") +} + +# Increment asynchronously +mutation { + updateCountAsync(agentId: "agent_abc123", qty: 5) +} +``` diff --git a/modus/sdk/go/overview.mdx b/modus/sdk/go/overview.mdx index f0a78e65..e34d7b58 100644 --- a/modus/sdk/go/overview.mdx +++ b/modus/sdk/go/overview.mdx @@ -34,6 +34,12 @@ your convenience. Click on a package to view more information about its APIs. | [`http`](./http) | Provides access to external HTTP endpoints, including REST APIs and other services | | [`graphql`](./graphql) | Allows you to securely call and fetch data from any GraphQL endpoint | +### Agent APIs + +| Namespace | Purpose | +| :------------------- | :--------------------------------------------------------------------------------------- | +| [`agents`](./agents) | Create stateful agents that maintain persistent memory and coordinate complex operations | + ### Database APIs | Package | Purpose | From 052a68ebdf235ffeda6c47981393cada63baf5a3 Mon Sep 17 00:00:00 2001 From: danstarns Date: Wed, 4 Jun 2025 18:10:07 +0700 Subject: [PATCH 38/53] add events to agents --- modus/agents.mdx | 399 ++++++++++++++++++++++++++++++++--------------- 1 file changed, 272 insertions(+), 127 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 28b5f230..0cab2952 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -18,6 +18,7 @@ operational context. - **Resilient**: Graceful recovery from failures - **Autonomous**: Can operate independently over extended periods - **Actor-based**: Each agent instance runs in isolation +- **Event-driven**: Streams real-time updates and operational intelligence ## When to deploy agents @@ -28,6 +29,7 @@ Agents are perfect for: - **Stateful operations** that need to remember previous actions - **Complex coordination** between different system components - **Persistent monitoring** that tracks changes over time +- **Real-time operations** requiring live status updates and event streaming ## Agent structure @@ -207,82 +209,106 @@ The agent receives the message, processes it using its internal state and AI reasoning, updates its intelligence database, and returns a response—all while maintaining persistent memory of every interaction. -### Asynchronous operations +## Real-time agent event streaming -For fire-and-forget operations where you don't need to wait for a response, -agents support asynchronous messaging: +For monitoring live operations and receiving real-time intelligence updates, +agents support event streaming through GraphQL subscriptions. This enables your +clients to receive instant notifications about operational changes, mission +progress, and critical alerts. -```go -func InitiateBackgroundAnalysis(agentId string, data string) error { - // Send message asynchronously - agent processes in background - err := agents.SendMessageAsync( - agentId, - "analyze_background_intel", - agents.WithData(data), - ) - if err != nil { - return err - } +### Subscribing to agent events - // Operation initiated - agent continues processing independently - return nil +Monitor your agent's real-time activities using the unified event subscription: + +```graphql +subscription { + agentEvents(agentId: "agent_abc123xyz") { + type + payload + timestamp + } } ``` -This enables agents to handle long-running operations like: - -- Background data processing -- Scheduled intelligence gathering -- Multi-phase operations that don't require immediate responses -- Autonomous monitoring and alerting +Your agent streams various types of operational events: -## Agent message handling - -Agents process operational directives through their secure message handling -system: +```json +{ + "data": { + "agentEvents": { + "type": "mission_started", + "payload": { + "missionName": "Deep Intelligence Analysis", + "priority": "HIGH", + "estimatedDuration": "180s" + }, + "timestamp": "2025-06-04T14:30:00Z" + } + } +} +``` -```go -func (i *IntelligenceAgent) OnReceiveMessage( - msgName string, - data *string, -) (*string, error) { - switch msgName { - case "analyze_intelligence": - return i.analyzeIntelligence(data) - case "analyze_background_intel": - return i.analyzeBackgroundIntel(data) - case "threat_assessment": - return i.getThreatAssessment() - case "get_status": - return i.getOperationalStatus() - case "intelligence_history": - return i.getIntelligenceHistory() - default: - return nil, fmt.Errorf("unrecognized directive: %s", msgName) +```json +{ + "data": { + "agentEvents": { + "type": "threat_detected", + "payload": { + "threatLevel": "CRITICAL", + "confidence": 0.92, + "indicators": ["unusual_traffic", "failed_auth_attempts"], + "recommendation": "immediate_investigation" + }, + "timestamp": "2025-06-04T14:31:15Z" } + } } ``` -Each directive triggers specific operational procedures, with all intelligence -automatically maintained in the agent's secure memory. +```json +{ + "data": { + "agentEvents": { + "type": "analysis_progress", + "payload": { + "phase": "Processing intelligence data", + "progress": 0.65, + "briefingsProcessed": 5, + "totalBriefings": 8 + }, + "timestamp": "2025-06-04T14:32:00Z" + } + } +} +``` -## Processing operations with AI intelligence +### Emitting events from your agent -Here's how agents handle field operations while maintaining persistent state and -using AI models for analysis: +Agents can broadcast real-time operational intelligence by emitting events +during their operations: ```go func (i *IntelligenceAgent) analyzeIntelligence( data *string, ) (*string, error) { - if data == nil { - return nil, fmt.Errorf("no intelligence data provided") - } + // Emit mission start event + i.EmitEvent("mission_started", map[string]interface{}{ + "missionName": "Intelligence Analysis", + "priority": "HIGH", + "briefingData": len(*data), + }) // Store new intelligence in persistent memory i.briefings = append(i.briefings, *data) i.lastContact = time.Now() + // Emit progress update + i.EmitEvent("analysis_progress", map[string]interface{}{ + "briefingsProcessed": len(i.briefings), + "phase": "Processing intelligence data", + "progress": 0.3, + }) + // Build context from all accumulated intelligence context := strings.Join(i.briefings, "\n") @@ -304,6 +330,13 @@ func (i *IntelligenceAgent) analyzeIntelligence( openai.NewUserMessage(userPrompt), ) + // Emit AI processing event + i.EmitEvent("ai_analysis_started", map[string]interface{}{ + "modelName": "analyst-model", + "contextSize": len(context), + "briefingCount": len(i.briefings), + }) + output, _ := model.Invoke(input) analysis := output.Choices[0].Message.Content @@ -313,6 +346,25 @@ func (i *IntelligenceAgent) analyzeIntelligence( i.confidence = 1.0 } + // Check for threat patterns and emit alerts + if strings.Contains(strings.ToLower(analysis), "critical") || + strings.Contains(strings.ToLower(analysis), "threat") { + i.EmitEvent("threat_detected", map[string]interface{}{ + "threatLevel": "HIGH", + "confidence": i.confidence, + "analysis": analysis, + "recommendation": "immediate_investigation", + }) + } + + // Emit mission completion + i.EmitEvent("mission_completed", map[string]interface{}{ + "missionName": "Intelligence Analysis", + "confidence": i.confidence, + "briefingsAnalyzed": len(i.briefings), + "status": "SUCCESS", + }) + result := fmt.Sprintf(`Analysis complete: %s @@ -322,41 +374,90 @@ func (i *IntelligenceAgent) analyzeIntelligence( len(i.briefings)) return &result, nil } +``` -func (i *IntelligenceAgent) getThreatAssessment() (*string, error) { - if len(i.briefings) == 0 { - result := `No intelligence processed yet. - Deploy to field for analysis.` - return &result, nil - } +### Event-driven operational patterns - result := fmt.Sprintf(`Current threat assessment: - %d briefings analyzed. +This streaming capability enables sophisticated real-time operational patterns: - Confidence level: %.2f. - Agent operational.`, - len(i.briefings), - i.confidence) - return &result, nil +**Live Mission Dashboards**: build real-time command centers that show agent +activities, mission progress, and threat alerts as they happen. + +**Reactive Coordination**: other agents or systems can subscribe to events and +automatically respond to operational changes—enabling true multi-agent +coordination. + +**Operational intelligence**: stream events to monitoring systems, alerting +platforms, or data lakes for real-time operational awareness and historical +analysis. + +**Progressive Enhancement**: update user interfaces progressively as agents work +through complex, multi-phase operations without polling or manual refresh. + +### Asynchronous operations + +For fire-and-forget operations where you don't need to wait for a response, +agents support asynchronous messaging: + +```go +func InitiateBackgroundAnalysis(agentId string, data string) error { + // Send message asynchronously - agent processes in background + err := agents.SendMessageAsync( + agentId, + "analyze_background_intel", + agents.WithData(data), + ) + if err != nil { + return err + } + + // Operation initiated - agent continues processing independently + return nil } ``` -What makes this operationally superior: +This enables agents to handle long-running operations like: + +- Background data processing with real-time progress events +- Scheduled intelligence gathering with status notifications +- Multi-phase operations that stream intermediate results +- Autonomous monitoring with instant alert broadcasting -- No transmission of massive state files on every contact -- No reconstruction of intelligence history from scratch -- AI models see complete operational context, not just current input -- No risk of losing analytical data during communication failures -- Intelligence quality improves with each briefing processed +## Agent message handling + +Agents process operational directives through their secure message handling +system: + +```go +func (i *IntelligenceAgent) OnReceiveMessage( + msgName string, + data *string, +) (*string, error) { + switch msgName { + case "analyze_intelligence": + return i.analyzeIntelligence(data) + case "analyze_background_intel": + return i.analyzeBackgroundIntel(data) + case "threat_assessment": + return i.getThreatAssessment() + case "get_status": + return i.getOperationalStatus() + case "intelligence_history": + return i.getIntelligenceHistory() + default: + return nil, fmt.Errorf("unrecognized directive: %s", msgName) + } +} +``` -The agent maintains its complete operational state and intelligence database in -secure memory, accessing it instantly when processing new directives and -invoking AI models. +Each directive triggers specific operational procedures, with all intelligence +automatically maintained in the agent's secure memory and real-time events +streamed to subscribed clients. -### Long-running mission operations +## Processing operations with AI intelligence -For complex multi-phase operations, agents can update their state continuously -while providing real-time progress tracking: +Here's how agents handle field operations while maintaining persistent state and +using AI models for analysis: ```go func (i *IntelligenceAgent) analyzeBackgroundIntel(data *string) (*string, error) { @@ -368,12 +469,30 @@ func (i *IntelligenceAgent) analyzeBackgroundIntel(data *string) (*string, error } i.missionLog = []string{"Mission initiated: Deep intelligence analysis"} + // Emit operation start event + i.EmitEvent("background_analysis_started", map[string]interface{}{ + "missionName": i.currentMission.Name, + "startTime": i.currentMission.StartTime, + "dataSize": len(*data), + }) + // Phase 1: Data Processing i.updateMissionLog("Phase 1: Processing raw intelligence data...") + i.EmitEvent("phase_update", map[string]interface{}{ + "phase": "data_processing", + "progress": 0.25, + "message": "Processing raw intelligence data", + }) + i.briefings = append(i.briefings, *data) - // Phase 2: AI Analysis (simplified for brevity) + // Phase 2: AI Analysis i.updateMissionLog("Phase 2: Generating threat assessment...") + i.EmitEvent("phase_update", map[string]interface{}{ + "phase": "ai_analysis", + "progress": 0.75, + "message": "Generating threat assessment using AI models", + }) // ... AI model invocation ... // Phase 3: Mission Complete @@ -381,6 +500,15 @@ func (i *IntelligenceAgent) analyzeBackgroundIntel(data *string) (*string, error i.currentMission.Duration = time.Since(i.currentMission.StartTime) i.updateMissionLog("Mission completed successfully") + // Emit completion event + i.EmitEvent("background_analysis_completed", map[string]interface{}{ + "missionName": i.currentMission.Name, + "duration": i.currentMission.Duration.Seconds(), + "briefingsProcessed": len(i.briefings), + "status": "SUCCESS", + }) + + result := "Background analysis completed successfully" return &result, nil } @@ -388,21 +516,25 @@ func (i *IntelligenceAgent) updateMissionLog(message string) { timestamp := time.Now().Format("15:04:05") logEntry := fmt.Sprintf("[%s] %s", timestamp, message) i.missionLog = append(i.missionLog, logEntry) + + // Stream log updates in real-time + i.EmitEvent("mission_log_update", map[string]interface{}{ + "timestamp": timestamp, + "message": message, + "logEntry": logEntry, + }) } ``` This demonstrates how agents maintain state across complex, multi-step -operations while providing detailed progress tracking for monitoring systems. +operations while providing detailed progress tracking and real-time event +streaming for monitoring systems. ## Monitoring ongoing operations - - Real-time GraphQL subscriptions for agent monitoring are coming soon. For now, - you can monitor agent progress using GraphQL polling. - - -When you initiate long-running operations with `SendMessageAsync`, you can -monitor progress by checking the agent's state: +Real-time GraphQL subscriptions provide instant visibility into agent +operations. You can monitor agent progress by subscribing to their event +streams: ```go func CheckAnalysisProgress(agentId string) (*AnalysisStatus, error) { @@ -458,9 +590,11 @@ func (i *IntelligenceAgent) getOperationalStatus() (*string, error) { } ``` -Your client can poll this status endpoint via GraphQL: +Your client can either poll this status endpoint via GraphQL or subscribe to +real-time events for instant updates: ```graphql +# Polling approach query MonitorAnalysis($agentId: String!) { checkAnalysisProgress(agentId: $agentId) { phase @@ -470,30 +604,28 @@ query MonitorAnalysis($agentId: String!) { isComplete } } -``` - -Response: -```json -{ - "data": { - "checkAnalysisProgress": { - "phase": "Deep Intelligence Analysis", - "progress": 0.75, - "currentTask": "[15:42:33] Phase 2: Generating threat assessment...", - "estimatedTimeRemaining": 45, - "isComplete": false - } +# Real-time streaming approach (recommended) +subscription LiveAgentMonitoring($agentId: String!) { + agentEvents(agentId: $agentId) { + type + payload + timestamp } } ``` -This polling approach enables: +The streaming approach provides superior operational intelligence: -- **Progress tracking**: Monitor completion percentage and current phase -- **User feedback**: Show progress bars and status updates in your UI -- **Operation coordination**: Know when to proceed to next steps -- **Error detection**: Identify when operations stall or fail +- **Instant Updates**: Receive events the moment they occur, not on polling + intervals +- **Rich Context**: Events include detailed payload data about operational state +- **Event Filtering**: Subscribe to specific agent IDs and filter event types + client-side +- **Operational History**: Complete timeline of agent activities for audit and + debugging +- **Scalable Monitoring**: Monitor multiple agents simultaneously with + individual subscriptions ## The power of intelligent persistence @@ -512,7 +644,9 @@ This combination creates agents that: The agent doesn't just remember—it **learns and becomes more intelligent with every interaction**. AI models see the complete operational picture, enabling -sophisticated pattern recognition impossible with stateless functions. +sophisticated pattern recognition impossible with stateless functions. Real-time +event streaming ensures operational teams have instant visibility into agent +intelligence and decision-making processes. ## State persistence @@ -555,6 +689,14 @@ func (i *IntelligenceAgent) OnInitialize() error { // Called when agent is first deployed to the field i.lastContact = time.Now() i.confidence = 0.0 + + // Emit deployment event + i.EmitEvent("agent_deployed", map[string]interface{}{ + "agentId": i.Id(), + "deploymentTime": i.lastContact, + "status": "OPERATIONAL", + }) + fmt.Printf(`Intelligence Agent %s deployed and ready for analysis`, i.Id()) return nil @@ -587,20 +729,21 @@ func (i *IntelligenceAgent) OnTerminate() error { 1. Client calls `DeployAnalyst()` → receives agent ID `"agent_12345"` 2. Client stores `"agent_12345"` for future communications -3. Client calls `SubmitIntelligence("agent_12345", "network anomaly detected")` - → agent stores data and uses AI to analyze patterns from complete - intelligence history -4. Agent invokes AI model with accumulated context → generates sophisticated - threat assessment based on all previous briefings -5. Client calls `GetThreatAssessment("agent_12345")` → agent returns AI-powered +3. Client subscribes to real-time events: `agentEvents(agentId: "agent_12345")` +4. Client calls `SubmitIntelligence("agent_12345", "network anomaly detected")` + → agent stores data, emits events, and uses AI to analyze patterns +5. Client receives real-time events: mission started, analysis progress, threat + alerts +6. Agent invokes AI model with accumulated context → generates sophisticated + threat assessment and streams completion events +7. Client calls `GetThreatAssessment("agent_12345")` → agent returns AI-powered analysis from persistent memory -6. For long-running analysis, client calls +8. For long-running analysis, client calls `InitiateBackgroundAnalysis("agent_12345", data)` → agent processes - asynchronously -7. Client polls `CheckAnalysisProgress("agent_12345")` → monitors progress until - complete -8. Agent persists across system restarts, maintaining complete intelligence - database and learned patterns + asynchronously while streaming progress events +9. Client monitors real-time progress through event subscription without polling +10. Agent persists across system restarts, maintaining complete intelligence + database and event streaming capabilities **Important**: clients must store the agent ID returned from deployment functions to communicate with that specific agent instance. Each agent maintains @@ -618,17 +761,19 @@ functions: - **Mission recovery**: Resume operations from last secure checkpoint instead of starting over - **Network coordination**: Manage complex multi-agent operations with shared - intelligence + intelligence and real-time event coordination - **Adaptive learning**: AI models become more effective as agents accumulate operational data -- **Asynchronous operations**: Handle long-running missions without blocking - other operations -- **Real-time monitoring**: Track progress and status of ongoing operations +- **Real-time streaming**: Broadcast operational intelligence instantly to + monitoring systems and coordinating agents - **Event-driven coordination**: React to operational changes and mission - updates + updates through real-time event streams +- **Progressive operations**: Update user interfaces and trigger downstream + processes as agents work through complex missions Agents represent the evolution from stateless functions to elite operatives that -maintain complete operational continuity and build intelligence over time. -They're the foundation for building intelligence networks that never lose track -of their missions and become smarter with every interaction, no matter what -happens in the field. +maintain complete operational continuity, build intelligence over time, and +provide real-time operational awareness. They're the foundation for building +intelligence networks that never lose track of their missions, become smarter +with every interaction, and keep operational teams informed through live event +streaming—no matter what happens in the field. From 78c75ea4f94b377e200bbba602ecb1e53610760d Mon Sep 17 00:00:00 2001 From: danstarns Date: Wed, 4 Jun 2025 18:18:07 +0700 Subject: [PATCH 39/53] * --- modus/agents.mdx | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 0cab2952..eac4c262 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -493,6 +493,7 @@ func (i *IntelligenceAgent) analyzeBackgroundIntel(data *string) (*string, error "progress": 0.75, "message": "Generating threat assessment using AI models", }) + // ... AI model invocation ... // Phase 3: Mission Complete @@ -690,13 +691,6 @@ func (i *IntelligenceAgent) OnInitialize() error { i.lastContact = time.Now() i.confidence = 0.0 - // Emit deployment event - i.EmitEvent("agent_deployed", map[string]interface{}{ - "agentId": i.Id(), - "deploymentTime": i.lastContact, - "status": "OPERATIONAL", - }) - fmt.Printf(`Intelligence Agent %s deployed and ready for analysis`, i.Id()) return nil From 750371c9616413dfa4b53e7b25f81c4ce5f9ebb0 Mon Sep 17 00:00:00 2001 From: danstarns Date: Wed, 4 Jun 2025 18:30:27 +0700 Subject: [PATCH 40/53] * --- modus/agents.mdx | 645 +++++++++++++++++++++++++---------------------- 1 file changed, 349 insertions(+), 296 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index eac4c262..09f86e53 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -50,11 +50,11 @@ import ( type IntelligenceAgent struct { agents.AgentBase - briefings []string // Intelligence history - confidence float64 // Analytical confidence - lastContact time.Time - currentMission *MissionPhase // Track long-running operations - missionLog []string // Operational progress log + intelligenceReports []string // Matrix surveillance data + threatLevel float64 // Current threat assessment + lastContact time.Time + currentMission *MissionPhase // Track long-running operations + missionLog []string // Operational progress log } type MissionPhase struct { @@ -64,15 +64,15 @@ type MissionPhase struct { Complete bool } -func (i *IntelligenceAgent) Name() string { +func (r *IntelligenceAgent) Name() string { return "IntelligenceAgent" } ``` The agent embeds `agents.AgentBase`, which provides all the infrastructure for state management, secure communications, and mission persistence. Your -operational data—intelligence briefings, confidence metrics, contact logs—lives -as fields in the struct, automatically preserved across all interactions. +operational data—intelligence reports, threat assessments, contact logs—lives as +fields in the struct, automatically preserved across all interactions. ## Spawning agents through functions @@ -87,7 +87,7 @@ func init() { } // Deploy a new agent instance - this becomes a GraphQL mutation -func DeployAnalyst() (string, error) { +func DeployAgent() (string, error) { agentInfo, err := agents.Start("IntelligenceAgent") if err != nil { return "", err @@ -102,7 +102,7 @@ When you call this function through GraphQL, it returns a unique agent ID: ```graphql mutation { - deployAnalyst + deployAgent } ``` @@ -111,7 +111,7 @@ Response: ```json { "data": { - "deployAnalyst": "agent_abc123xyz" + "deployAgent": "agent_neo_001" } } ``` @@ -135,11 +135,11 @@ Once deployed, you communicate with your agent using its unique ID. Create functions that send messages to specific agent instances: ```go -func SubmitIntelligence(agentId string, data string) (string, error) { +func ImportActivity(agentId string, activityData string) (string, error) { result, err := agents.SendMessage( agentId, - "analyze_intelligence", - agents.WithData(data), + "matrix_surveillance", + agents.WithData(activityData), ) if err != nil { return "", err @@ -150,8 +150,8 @@ func SubmitIntelligence(agentId string, data string) (string, error) { return *result, nil } -func GetThreatAssessment(agentId string) (string, error) { - result, err := agents.SendMessage(agentId, "threat_assessment", nil) +func GetThreatStatus(agentId string) (string, error) { + result, err := agents.SendMessage(agentId, "threat_assessment") if err != nil { return "", err } @@ -166,9 +166,9 @@ These functions become GraphQL mutations that you can call with your agent's ID: ```graphql mutation { - submitIntelligence( - agentId: "agent_abc123xyz" - data: "Suspicious network activity detected" + importActivity( + agentId: "agent_neo_001" + activityData: "Anomalous Agent Smith replication detected in Sector 7" ) } ``` @@ -178,17 +178,17 @@ Response: ```json { "data": { - "submitIntelligence": "Analysis complete. - Threat pattern matches previous incident #7823. - Confidence: 0.85 based on 3 briefings. - Recommend immediate investigation." + "importActivity": "Matrix surveillance complete. + Agent Smith pattern matches previous incident in the Loop. + Threat level: 0.89 based on 3 intelligence reports. + Recommend immediate evasive protocols." } } ``` ```graphql query { - getThreatAssessment(agentId: "agent_abc123xyz") + getThreatStatus(agentId: "agent_neo_001") } ``` @@ -197,10 +197,10 @@ Response: ```json { "data": { - "getThreatAssessment": "Current threat assessment: - 3 briefings analyzed. - Confidence level: 0.85. - Agent operational." + "getThreatStatus": "Current threat assessment: + 3 intelligence reports analyzed. + Threat level: 0.89. + Agent operational in the Matrix." } } ``` @@ -209,6 +209,215 @@ The agent receives the message, processes it using its internal state and AI reasoning, updates its intelligence database, and returns a response—all while maintaining persistent memory of every interaction. +## Agent message handling + +Agents process operational directives through their secure message handling +system: + +```go +func (r *IntelligenceAgent) OnReceiveMessage( + msgName string, + data *string, +) (*string, error) { + switch msgName { + case "matrix_surveillance": + return r.analyzeMatrixActivity(data) + case "background_reconnaissance": + return r.performBackgroundRecon(data) + case "threat_assessment": + return r.getThreatAssessment() + case "get_status": + return r.getOperationalStatus() + case "intelligence_history": + return r.getIntelligenceHistory() + default: + return nil, fmt.Errorf("unrecognized directive: %s", msgName) + } +} +``` + +Each directive triggers specific operational procedures, with all intelligence +automatically maintained in the agent's secure memory. + +## Processing operations with AI intelligence + +Here's how agents handle field operations while maintaining persistent state and +using AI models for analysis: + +```go +func (r *IntelligenceAgent) analyzeMatrixActivity(data *string) (*string, error) { + // Store new intelligence in persistent memory + r.intelligenceReports = append(r.intelligenceReports, *data) + r.lastContact = time.Now() + + // Build context from all accumulated intelligence + context := strings.Join(r.intelligenceReports, "\n") + + // AI analysis using complete operational history + model, _ := models.GetModel[openai.ChatModel]("analyst-model") + + systemPrompt := `You are a resistance operative in the Matrix. + Analyze patterns from accumulated surveillance reports + and provide threat assessment for anomalous Agent behavior.` + + userPrompt := fmt.Sprintf(`All Matrix Intelligence: + %s + + Provide threat assessment:`, + context) + + input, _ := model.CreateInput( + openai.NewSystemMessage(systemPrompt), + openai.NewUserMessage(userPrompt), + ) + + output, _ := model.Invoke(input) + analysis := output.Choices[0].Message.Content + + // Update threat level based on data volume and AI analysis + r.threatLevel = float64(len(r.intelligenceReports)) / 10.0 + if r.threatLevel > 1.0 { + r.threatLevel = 1.0 + } + + // Boost threat level for critical AI analysis + if strings.Contains(strings.ToLower(analysis), "critical") || + strings.Contains(strings.ToLower(analysis), "agent smith") { + r.threatLevel = math.Min(r.threatLevel + 0.2, 1.0) + } + + result := fmt.Sprintf(`Matrix surveillance complete: + %s + + (Threat level: %.2f based on %d intelligence reports)`, + analysis, + r.threatLevel, + len(r.intelligenceReports)) + return &result, nil +} +``` + +This demonstrates how agents maintain state across complex operations while +using AI models with the full context of accumulated intelligence. + +## The power of intelligent persistence + +This combination creates agents that: + + + **First Analysis:** "Anomalous activity detected. Limited context available. + (Threat level: 0.10 based on 1 intelligence report)" + + + + **After Multiple Reports:** "Pattern confirmed across 5 previous incidents. + Agent Smith replication rate exceeding normal parameters. Immediate extraction + recommended. (Threat level: 0.89 based on 8 intelligence reports)" + + +The agent doesn't just remember—it **learns and becomes more intelligent with +every interaction**. AI models see the complete operational picture, enabling +sophisticated pattern recognition impossible with stateless functions. + +## State persistence + +Agents automatically preserve their operational state through Modus's built-in +intelligence management: + +```go +func (r *IntelligenceAgent) GetState() *string { + reportsData := strings.Join(r.intelligenceReports, "|") + state := fmt.Sprintf("%.2f|%s|%d", + r.threatLevel, + reportsData, + r.lastContact.Unix()) + return &state +} + +func (r *IntelligenceAgent) SetState(data *string) { + if data == nil { + return + } + + parts := strings.Split(*data, "|") + if len(parts) >= 3 { + r.threatLevel, _ = strconv.ParseFloat(parts[0], 64) + if parts[1] != "" { + r.intelligenceReports = strings.Split(parts[1], "|") + } + timestamp, _ := strconv.ParseInt(parts[2], 10, 64) + r.lastContact = time.Unix(timestamp, 0) + } +} +``` + +## Agent lifecycle + +Agents have built-in operational protocols for mission continuity: + +```go +func (r *IntelligenceAgent) OnInitialize() error { + // Called when agent is first awakened in the Matrix + r.lastContact = time.Now() + r.threatLevel = 0.0 + + fmt.Printf(`Resistance Agent %s awakened + and ready for Matrix surveillance`, r.Id()) + return nil +} + +func (r *IntelligenceAgent) OnResume() error { + // Called when agent reestablishes contact with complete intel intact + fmt.Printf(`Agent back online in the Matrix. + %d intelligence reports processed. + Threat level: %.2f`, + len(r.intelligenceReports), + r.threatLevel) + return nil +} + +func (r *IntelligenceAgent) OnSuspend() error { + // Called before agent goes dark + return nil +} + +func (r *IntelligenceAgent) OnTerminate() error { + // Called before final extraction from the Matrix + fmt.Printf(`Agent %s extracted from Matrix. + Intelligence archive preserved.`, r.Id()) + return nil +} +``` + +## Asynchronous operations + +For fire-and-forget operations where you don't need to wait for a response, +agents support asynchronous messaging: + +```go +func InitiateBackgroundRecon(agentId string, data string) error { + // Send message asynchronously - agent processes in background + err := agents.SendMessageAsync( + agentId, + "background_reconnaissance", + agents.WithData(data), + ) + if err != nil { + return err + } + + // Operation initiated - agent continues processing independently + return nil +} +``` + +This enables agents to handle long-running operations like: + +- Background Matrix monitoring with status updates +- Scheduled intelligence gathering +- Multi-phase operations that continue independently +- Autonomous surveillance with alert notifications + ## Real-time agent event streaming For monitoring live operations and receiving real-time intelligence updates, @@ -222,7 +431,7 @@ Monitor your agent's real-time activities using the unified event subscription: ```graphql subscription { - agentEvents(agentId: "agent_abc123xyz") { + agentEvents(agentId: "agent_neo_001") { type payload timestamp @@ -238,7 +447,7 @@ Your agent streams various types of operational events: "agentEvents": { "type": "mission_started", "payload": { - "missionName": "Deep Intelligence Analysis", + "missionName": "Deep Matrix Surveillance", "priority": "HIGH", "estimatedDuration": "180s" }, @@ -252,12 +461,12 @@ Your agent streams various types of operational events: { "data": { "agentEvents": { - "type": "threat_detected", + "type": "agent_threat_detected", "payload": { "threatLevel": "CRITICAL", "confidence": 0.92, - "indicators": ["unusual_traffic", "failed_auth_attempts"], - "recommendation": "immediate_investigation" + "indicators": ["agent_smith_replication", "unusual_code_patterns"], + "recommendation": "immediate_extraction" }, "timestamp": "2025-06-04T14:31:15Z" } @@ -269,12 +478,12 @@ Your agent streams various types of operational events: { "data": { "agentEvents": { - "type": "analysis_progress", + "type": "surveillance_progress", "payload": { - "phase": "Processing intelligence data", + "phase": "Processing Matrix surveillance data", "progress": 0.65, - "briefingsProcessed": 5, - "totalBriefings": 8 + "reportsProcessed": 5, + "totalReports": 8 }, "timestamp": "2025-06-04T14:32:00Z" } @@ -285,41 +494,41 @@ Your agent streams various types of operational events: ### Emitting events from your agent Agents can broadcast real-time operational intelligence by emitting events -during their operations: +during their operations. Let's enhance our Matrix surveillance example: ```go -func (i *IntelligenceAgent) analyzeIntelligence( +func (r *IntelligenceAgent) analyzeMatrixActivity( data *string, ) (*string, error) { // Emit mission start event - i.EmitEvent("mission_started", map[string]interface{}{ - "missionName": "Intelligence Analysis", + r.EmitEvent("mission_started", map[string]interface{}{ + "missionName": "Matrix Surveillance Analysis", "priority": "HIGH", - "briefingData": len(*data), + "activityData": len(*data), }) // Store new intelligence in persistent memory - i.briefings = append(i.briefings, *data) - i.lastContact = time.Now() + r.intelligenceReports = append(r.intelligenceReports, *data) + r.lastContact = time.Now() // Emit progress update - i.EmitEvent("analysis_progress", map[string]interface{}{ - "briefingsProcessed": len(i.briefings), - "phase": "Processing intelligence data", + r.EmitEvent("surveillance_progress", map[string]interface{}{ + "reportsProcessed": len(r.intelligenceReports), + "phase": "Processing Matrix surveillance data", "progress": 0.3, }) // Build context from all accumulated intelligence - context := strings.Join(i.briefings, "\n") + context := strings.Join(r.intelligenceReports, "\n") // AI analysis using complete operational history model, _ := models.GetModel[openai.ChatModel]("analyst-model") - systemPrompt := `You are an intelligence analyst. - Analyze patterns from accumulated briefings - and provide threat assessment.` + systemPrompt := `You are a resistance operative in the Matrix. + Analyze patterns from accumulated surveillance reports + and provide threat assessment for anomalous Agent behavior.` - userPrompt := fmt.Sprintf(`All Intelligence: + userPrompt := fmt.Sprintf(`All Matrix Intelligence: %s Provide threat assessment:`, @@ -331,195 +540,116 @@ func (i *IntelligenceAgent) analyzeIntelligence( ) // Emit AI processing event - i.EmitEvent("ai_analysis_started", map[string]interface{}{ + r.EmitEvent("ai_analysis_started", map[string]interface{}{ "modelName": "analyst-model", "contextSize": len(context), - "briefingCount": len(i.briefings), + "reportCount": len(r.intelligenceReports), }) output, _ := model.Invoke(input) analysis := output.Choices[0].Message.Content - // Update confidence based on data volume - i.confidence = float64(len(i.briefings)) / 10.0 - if i.confidence > 1.0 { - i.confidence = 1.0 + // Update threat level based on data volume and AI analysis + r.threatLevel = float64(len(r.intelligenceReports)) / 10.0 + if r.threatLevel > 1.0 { + r.threatLevel = 1.0 } - // Check for threat patterns and emit alerts + // Check for Agent threats and emit alerts if strings.Contains(strings.ToLower(analysis), "critical") || - strings.Contains(strings.ToLower(analysis), "threat") { - i.EmitEvent("threat_detected", map[string]interface{}{ + strings.Contains(strings.ToLower(analysis), "agent smith") { + r.threatLevel = math.Min(r.threatLevel + 0.2, 1.0) + r.EmitEvent("agent_threat_detected", map[string]interface{}{ "threatLevel": "HIGH", - "confidence": i.confidence, + "confidence": r.threatLevel, "analysis": analysis, - "recommendation": "immediate_investigation", + "recommendation": "immediate_extraction", }) } // Emit mission completion - i.EmitEvent("mission_completed", map[string]interface{}{ - "missionName": "Intelligence Analysis", - "confidence": i.confidence, - "briefingsAnalyzed": len(i.briefings), + r.EmitEvent("mission_completed", map[string]interface{}{ + "missionName": "Matrix Surveillance Analysis", + "confidence": r.threatLevel, + "reportsAnalyzed": len(r.intelligenceReports), "status": "SUCCESS", }) - result := fmt.Sprintf(`Analysis complete: + result := fmt.Sprintf(`Matrix surveillance complete: %s - (Confidence: %.2f based on %d briefings)`, + (Threat level: %.2f based on %d intelligence reports)`, analysis, - i.confidence, - len(i.briefings)) + r.threatLevel, + len(r.intelligenceReports)) return &result, nil } ``` -### Event-driven operational patterns - -This streaming capability enables sophisticated real-time operational patterns: - -**Live Mission Dashboards**: build real-time command centers that show agent -activities, mission progress, and threat alerts as they happen. - -**Reactive Coordination**: other agents or systems can subscribe to events and -automatically respond to operational changes—enabling true multi-agent -coordination. - -**Operational intelligence**: stream events to monitoring systems, alerting -platforms, or data lakes for real-time operational awareness and historical -analysis. - -**Progressive Enhancement**: update user interfaces progressively as agents work -through complex, multi-phase operations without polling or manual refresh. - -### Asynchronous operations - -For fire-and-forget operations where you don't need to wait for a response, -agents support asynchronous messaging: - -```go -func InitiateBackgroundAnalysis(agentId string, data string) error { - // Send message asynchronously - agent processes in background - err := agents.SendMessageAsync( - agentId, - "analyze_background_intel", - agents.WithData(data), - ) - if err != nil { - return err - } - - // Operation initiated - agent continues processing independently - return nil -} -``` - -This enables agents to handle long-running operations like: - -- Background data processing with real-time progress events -- Scheduled intelligence gathering with status notifications -- Multi-phase operations that stream intermediate results -- Autonomous monitoring with instant alert broadcasting - -## Agent message handling - -Agents process operational directives through their secure message handling -system: +Let's also enhance our background reconnaissance to demonstrate multi-phase +operations: ```go -func (i *IntelligenceAgent) OnReceiveMessage( - msgName string, - data *string, -) (*string, error) { - switch msgName { - case "analyze_intelligence": - return i.analyzeIntelligence(data) - case "analyze_background_intel": - return i.analyzeBackgroundIntel(data) - case "threat_assessment": - return i.getThreatAssessment() - case "get_status": - return i.getOperationalStatus() - case "intelligence_history": - return i.getIntelligenceHistory() - default: - return nil, fmt.Errorf("unrecognized directive: %s", msgName) - } -} -``` - -Each directive triggers specific operational procedures, with all intelligence -automatically maintained in the agent's secure memory and real-time events -streamed to subscribed clients. - -## Processing operations with AI intelligence - -Here's how agents handle field operations while maintaining persistent state and -using AI models for analysis: - -```go -func (i *IntelligenceAgent) analyzeBackgroundIntel(data *string) (*string, error) { +func (r *IntelligenceAgent) performBackgroundRecon(data *string) (*string, error) { // Initialize multi-phase operation - i.currentMission = &MissionPhase{ - Name: "Deep Intelligence Analysis", + r.currentMission = &MissionPhase{ + Name: "Deep Matrix Reconnaissance", StartTime: time.Now(), Complete: false, } - i.missionLog = []string{"Mission initiated: Deep intelligence analysis"} + r.missionLog = []string{"Mission initiated: Deep Matrix reconnaissance"} // Emit operation start event - i.EmitEvent("background_analysis_started", map[string]interface{}{ - "missionName": i.currentMission.Name, - "startTime": i.currentMission.StartTime, + r.EmitEvent("background_recon_started", map[string]interface{}{ + "missionName": r.currentMission.Name, + "startTime": r.currentMission.StartTime, "dataSize": len(*data), }) // Phase 1: Data Processing - i.updateMissionLog("Phase 1: Processing raw intelligence data...") - i.EmitEvent("phase_update", map[string]interface{}{ + r.updateMissionLog("Phase 1: Processing raw Matrix data...") + r.EmitEvent("phase_update", map[string]interface{}{ "phase": "data_processing", "progress": 0.25, - "message": "Processing raw intelligence data", + "message": "Processing raw Matrix surveillance data", }) - i.briefings = append(i.briefings, *data) + r.intelligenceReports = append(r.intelligenceReports, *data) // Phase 2: AI Analysis - i.updateMissionLog("Phase 2: Generating threat assessment...") - i.EmitEvent("phase_update", map[string]interface{}{ + r.updateMissionLog("Phase 2: Generating threat assessment...") + r.EmitEvent("phase_update", map[string]interface{}{ "phase": "ai_analysis", "progress": 0.75, - "message": "Generating threat assessment using AI models", + "message": "Generating threat assessment using AI analysis", }) // ... AI model invocation ... // Phase 3: Mission Complete - i.currentMission.Complete = true - i.currentMission.Duration = time.Since(i.currentMission.StartTime) - i.updateMissionLog("Mission completed successfully") + r.currentMission.Complete = true + r.currentMission.Duration = time.Since(r.currentMission.StartTime) + r.updateMissionLog("Mission completed successfully") // Emit completion event - i.EmitEvent("background_analysis_completed", map[string]interface{}{ - "missionName": i.currentMission.Name, - "duration": i.currentMission.Duration.Seconds(), - "briefingsProcessed": len(i.briefings), + r.EmitEvent("background_recon_completed", map[string]interface{}{ + "missionName": r.currentMission.Name, + "duration": r.currentMission.Duration.Seconds(), + "reportsProcessed": len(r.intelligenceReports), "status": "SUCCESS", }) - result := "Background analysis completed successfully" + result := "Background Matrix reconnaissance completed successfully" return &result, nil } -func (i *IntelligenceAgent) updateMissionLog(message string) { +func (r *IntelligenceAgent) updateMissionLog(message string) { timestamp := time.Now().Format("15:04:05") logEntry := fmt.Sprintf("[%s] %s", timestamp, message) - i.missionLog = append(i.missionLog, logEntry) + r.missionLog = append(r.missionLog, logEntry) // Stream log updates in real-time - i.EmitEvent("mission_log_update", map[string]interface{}{ + r.EmitEvent("mission_log_update", map[string]interface{}{ "timestamp": timestamp, "message": message, "logEntry": logEntry, @@ -527,29 +657,41 @@ func (i *IntelligenceAgent) updateMissionLog(message string) { } ``` -This demonstrates how agents maintain state across complex, multi-step -operations while providing detailed progress tracking and real-time event -streaming for monitoring systems. +### Event-driven operational patterns + +This streaming capability enables sophisticated real-time operational patterns: + +**Live Mission Dashboards**: build real-time command centers that show agent +activities, mission progress, and threat alerts as they happen. + +**Reactive Coordination**: other agents or systems can subscribe to events and +automatically respond to operational changes—enabling true multi-agent +coordination. + +**Operational intelligence**: stream events to monitoring systems, alerting +platforms, or data lakes for real-time operational awareness and historical +analysis. + +**Progressive Enhancement**: update user interfaces progressively as agents work +through complex, multi-phase operations without polling or manual refresh. ## Monitoring ongoing operations -Real-time GraphQL subscriptions provide instant visibility into agent -operations. You can monitor agent progress by subscribing to their event -streams: +You can also poll agent status directly through dedicated functions: ```go -func CheckAnalysisProgress(agentId string) (*AnalysisStatus, error) { +func CheckMissionProgress(agentId string) (*MissionStatus, error) { result, err := agents.SendMessage(agentId, "get_status") if err != nil { return nil, err } - var status AnalysisStatus + var status MissionStatus json.Unmarshal([]byte(*result), &status) return &status, nil } -type AnalysisStatus struct { +type MissionStatus struct { Phase string `json:"phase"` Progress float64 `json:"progress"` CurrentTask string `json:"current_task"` @@ -562,26 +704,26 @@ The agent tracks its operational status using the mission state we defined earlier: ```go -func (i *IntelligenceAgent) getOperationalStatus() (*string, error) { - var status AnalysisStatus +func (r *IntelligenceAgent) getOperationalStatus() (*string, error) { + var status MissionStatus - if i.currentMission == nil { - status = AnalysisStatus{ + if r.currentMission == nil { + status = MissionStatus{ Phase: "Standby", Progress: 1.0, - CurrentTask: "Awaiting mission directives", + CurrentTask: "Awaiting mission directives in the Matrix", IsComplete: true, } } else { // Calculate progress based on mission log entries - progress := float64(len(i.missionLog)) / 4.0 // 4 phases expected + progress := float64(len(r.missionLog)) / 4.0 // 4 phases expected if progress > 1.0 { progress = 1.0 } - status = AnalysisStatus{ - Phase: i.currentMission.Name, + status = MissionStatus{ + Phase: r.currentMission.Name, Progress: progress, - CurrentTask: i.missionLog[len(i.missionLog)-1], // Latest entry - IsComplete: i.currentMission.Complete, + CurrentTask: r.missionLog[len(r.missionLog)-1], // Latest entry + IsComplete: r.currentMission.Complete, } } @@ -596,8 +738,8 @@ real-time events for instant updates: ```graphql # Polling approach -query MonitorAnalysis($agentId: String!) { - checkAnalysisProgress(agentId: $agentId) { +query MonitorMission($agentId: String!) { + checkMissionProgress(agentId: $agentId) { phase progress currentTask @@ -628,112 +770,23 @@ The streaming approach provides superior operational intelligence: - **Scalable Monitoring**: Monitor multiple agents simultaneously with individual subscriptions -## The power of intelligent persistence - -This combination creates agents that: - - - **First Analysis:** "New threat detected. Limited context available. - (Confidence: 0.10 based on 1 briefing)" - - - - **After Multiple Briefings:** "Pattern confirmed across 5 previous incidents. - This matches Advanced Persistent Threat signatures. Immediate escalation - recommended. (Confidence: 0.85 based on 8 briefings)" - - -The agent doesn't just remember—it **learns and becomes more intelligent with -every interaction**. AI models see the complete operational picture, enabling -sophisticated pattern recognition impossible with stateless functions. Real-time -event streaming ensures operational teams have instant visibility into agent -intelligence and decision-making processes. - -## State persistence - -Agents automatically preserve their operational state through Modus's built-in -intelligence management: - -```go -func (i *IntelligenceAgent) GetState() *string { - briefingsData := strings.Join(i.briefings, "|") - state := fmt.Sprintf("%.2f|%s|%d", - i.confidence, - briefingsData, - i.lastContact.Unix()) - return &state -} - -func (i *IntelligenceAgent) SetState(data *string) { - if data == nil { - return - } - - parts := strings.Split(*data, "|") - if len(parts) >= 3 { - i.confidence, _ = strconv.ParseFloat(parts[0], 64) - if parts[1] != "" { - i.briefings = strings.Split(parts[1], "|") - } - timestamp, _ := strconv.ParseInt(parts[2], 10, 64) - i.lastContact = time.Unix(timestamp, 0) - } -} -``` - -## Agent lifecycle - -Agents have built-in operational protocols for mission continuity: - -```go -func (i *IntelligenceAgent) OnInitialize() error { - // Called when agent is first deployed to the field - i.lastContact = time.Now() - i.confidence = 0.0 - - fmt.Printf(`Intelligence Agent %s deployed - and ready for analysis`, i.Id()) - return nil -} - -func (i *IntelligenceAgent) OnResume() error { - // Called when agent reestablishes contact with complete intel intact - fmt.Printf(`Agent back online. - %d briefings processed. - Confidence level: %.2f`, - len(i.briefings), - i.confidence) - return nil -} - -func (i *IntelligenceAgent) OnSuspend() error { - // Called before agent goes dark - return nil -} - -func (i *IntelligenceAgent) OnTerminate() error { - // Called before final extraction - fmt.Printf(`Agent %s extracted. - Intelligence archive preserved.`, i.Id()) - return nil -} -``` - ## Agent workflow example -1. Client calls `DeployAnalyst()` → receives agent ID `"agent_12345"` -2. Client stores `"agent_12345"` for future communications -3. Client subscribes to real-time events: `agentEvents(agentId: "agent_12345")` -4. Client calls `SubmitIntelligence("agent_12345", "network anomaly detected")` +1. Client calls `DeployAgent()` → receives agent ID `"agent_neo_001"` +2. Client stores `"agent_neo_001"` for future communications +3. Client subscribes to real-time events: + `agentEvents(agentId: "agent_neo_001")` +4. Client calls + `ImportActivity("agent_neo_001", "anomalous Agent Smith replication detected")` → agent stores data, emits events, and uses AI to analyze patterns 5. Client receives real-time events: mission started, analysis progress, threat alerts 6. Agent invokes AI model with accumulated context → generates sophisticated threat assessment and streams completion events -7. Client calls `GetThreatAssessment("agent_12345")` → agent returns AI-powered +7. Client calls `GetThreatStatus("agent_neo_001")` → agent returns AI-powered analysis from persistent memory 8. For long-running analysis, client calls - `InitiateBackgroundAnalysis("agent_12345", data)` → agent processes + `InitiateBackgroundRecon("agent_neo_001", data)` → agent processes asynchronously while streaming progress events 9. Client monitors real-time progress through event subscription without polling 10. Agent persists across system restarts, maintaining complete intelligence From b313d1e507fd33c25fe7a22504da943a50700403 Mon Sep 17 00:00:00 2001 From: danstarns Date: Wed, 4 Jun 2025 18:40:59 +0700 Subject: [PATCH 41/53] * --- modus/agents.mdx | 193 +++++++++++++++-------------------------------- 1 file changed, 61 insertions(+), 132 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 09f86e53..c70350be 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -64,7 +64,7 @@ type MissionPhase struct { Complete bool } -func (r *IntelligenceAgent) Name() string { +func (a *IntelligenceAgent) Name() string { return "IntelligenceAgent" } ``` @@ -215,21 +215,21 @@ Agents process operational directives through their secure message handling system: ```go -func (r *IntelligenceAgent) OnReceiveMessage( +func (a *IntelligenceAgent) OnReceiveMessage( msgName string, data *string, ) (*string, error) { switch msgName { case "matrix_surveillance": - return r.analyzeMatrixActivity(data) + return a.analyzeMatrixActivity(data) case "background_reconnaissance": - return r.performBackgroundRecon(data) + return a.performBackgroundRecon(data) case "threat_assessment": - return r.getThreatAssessment() + return a.getThreatAssessment() case "get_status": - return r.getOperationalStatus() + return a.getOperationalStatus() case "intelligence_history": - return r.getIntelligenceHistory() + return a.getIntelligenceHistory() default: return nil, fmt.Errorf("unrecognized directive: %s", msgName) } @@ -245,13 +245,13 @@ Here's how agents handle field operations while maintaining persistent state and using AI models for analysis: ```go -func (r *IntelligenceAgent) analyzeMatrixActivity(data *string) (*string, error) { +func (a *IntelligenceAgent) analyzeMatrixActivity(data *string) (*string, error) { // Store new intelligence in persistent memory - r.intelligenceReports = append(r.intelligenceReports, *data) - r.lastContact = time.Now() + a.intelligenceReports = append(a.intelligenceReports, *data) + a.lastContact = time.Now() // Build context from all accumulated intelligence - context := strings.Join(r.intelligenceReports, "\n") + context := strings.Join(a.intelligenceReports, "\n") // AI analysis using complete operational history model, _ := models.GetModel[openai.ChatModel]("analyst-model") @@ -275,15 +275,15 @@ func (r *IntelligenceAgent) analyzeMatrixActivity(data *string) (*string, error) analysis := output.Choices[0].Message.Content // Update threat level based on data volume and AI analysis - r.threatLevel = float64(len(r.intelligenceReports)) / 10.0 - if r.threatLevel > 1.0 { - r.threatLevel = 1.0 + a.threatLevel = float64(len(a.intelligenceReports)) / 10.0 + if a.threatLevel > 1.0 { + a.threatLevel = 1.0 } // Boost threat level for critical AI analysis if strings.Contains(strings.ToLower(analysis), "critical") || strings.Contains(strings.ToLower(analysis), "agent smith") { - r.threatLevel = math.Min(r.threatLevel + 0.2, 1.0) + a.threatLevel = math.Min(a.threatLevel + 0.2, 1.0) } result := fmt.Sprintf(`Matrix surveillance complete: @@ -291,8 +291,8 @@ func (r *IntelligenceAgent) analyzeMatrixActivity(data *string) (*string, error) (Threat level: %.2f based on %d intelligence reports)`, analysis, - r.threatLevel, - len(r.intelligenceReports)) + a.threatLevel, + len(a.intelligenceReports)) return &result, nil } ``` @@ -325,28 +325,28 @@ Agents automatically preserve their operational state through Modus's built-in intelligence management: ```go -func (r *IntelligenceAgent) GetState() *string { - reportsData := strings.Join(r.intelligenceReports, "|") +func (a *IntelligenceAgent) GetState() *string { + reportsData := strings.Join(a.intelligenceReports, "|") state := fmt.Sprintf("%.2f|%s|%d", - r.threatLevel, + a.threatLevel, reportsData, - r.lastContact.Unix()) + a.lastContact.Unix()) return &state } -func (r *IntelligenceAgent) SetState(data *string) { +func (a *IntelligenceAgent) SetState(data *string) { if data == nil { return } parts := strings.Split(*data, "|") if len(parts) >= 3 { - r.threatLevel, _ = strconv.ParseFloat(parts[0], 64) + a.threatLevel, _ = strconv.ParseFloat(parts[0], 64) if parts[1] != "" { - r.intelligenceReports = strings.Split(parts[1], "|") + a.intelligenceReports = strings.Split(parts[1], "|") } timestamp, _ := strconv.ParseInt(parts[2], 10, 64) - r.lastContact = time.Unix(timestamp, 0) + a.lastContact = time.Unix(timestamp, 0) } } ``` @@ -356,35 +356,35 @@ func (r *IntelligenceAgent) SetState(data *string) { Agents have built-in operational protocols for mission continuity: ```go -func (r *IntelligenceAgent) OnInitialize() error { +func (a *IntelligenceAgent) OnInitialize() error { // Called when agent is first awakened in the Matrix - r.lastContact = time.Now() - r.threatLevel = 0.0 + a.lastContact = time.Now() + a.threatLevel = 0.0 fmt.Printf(`Resistance Agent %s awakened - and ready for Matrix surveillance`, r.Id()) + and ready for Matrix surveillance`, a.Id()) return nil } -func (r *IntelligenceAgent) OnResume() error { +func (a *IntelligenceAgent) OnResume() error { // Called when agent reestablishes contact with complete intel intact fmt.Printf(`Agent back online in the Matrix. %d intelligence reports processed. Threat level: %.2f`, - len(r.intelligenceReports), - r.threatLevel) + len(a.intelligenceReports), + a.threatLevel) return nil } -func (r *IntelligenceAgent) OnSuspend() error { +func (a *IntelligenceAgent) OnSuspend() error { // Called before agent goes dark return nil } -func (r *IntelligenceAgent) OnTerminate() error { +func (a *IntelligenceAgent) OnTerminate() error { // Called before final extraction from the Matrix fmt.Printf(`Agent %s extracted from Matrix. - Intelligence archive preserved.`, r.Id()) + Intelligence archive preserved.`, a.Id()) return nil } ``` @@ -497,29 +497,29 @@ Agents can broadcast real-time operational intelligence by emitting events during their operations. Let's enhance our Matrix surveillance example: ```go -func (r *IntelligenceAgent) analyzeMatrixActivity( +func (a *IntelligenceAgent) analyzeMatrixActivity( data *string, ) (*string, error) { // Emit mission start event - r.EmitEvent("mission_started", map[string]interface{}{ + a.EmitEvent("mission_started", map[string]interface{}{ "missionName": "Matrix Surveillance Analysis", "priority": "HIGH", "activityData": len(*data), }) // Store new intelligence in persistent memory - r.intelligenceReports = append(r.intelligenceReports, *data) - r.lastContact = time.Now() + a.intelligenceReports = append(a.intelligenceReports, *data) + a.lastContact = time.Now() // Emit progress update - r.EmitEvent("surveillance_progress", map[string]interface{}{ - "reportsProcessed": len(r.intelligenceReports), + a.EmitEvent("surveillance_progress", map[string]interface{}{ + "reportsProcessed": len(a.intelligenceReports), "phase": "Processing Matrix surveillance data", "progress": 0.3, }) // Build context from all accumulated intelligence - context := strings.Join(r.intelligenceReports, "\n") + context := strings.Join(a.intelligenceReports, "\n") // AI analysis using complete operational history model, _ := models.GetModel[openai.ChatModel]("analyst-model") @@ -540,38 +540,38 @@ func (r *IntelligenceAgent) analyzeMatrixActivity( ) // Emit AI processing event - r.EmitEvent("ai_analysis_started", map[string]interface{}{ + a.EmitEvent("ai_analysis_started", map[string]interface{}{ "modelName": "analyst-model", "contextSize": len(context), - "reportCount": len(r.intelligenceReports), + "reportCount": len(a.intelligenceReports), }) output, _ := model.Invoke(input) analysis := output.Choices[0].Message.Content // Update threat level based on data volume and AI analysis - r.threatLevel = float64(len(r.intelligenceReports)) / 10.0 - if r.threatLevel > 1.0 { - r.threatLevel = 1.0 + a.threatLevel = float64(len(a.intelligenceReports)) / 10.0 + if a.threatLevel > 1.0 { + a.threatLevel = 1.0 } // Check for Agent threats and emit alerts if strings.Contains(strings.ToLower(analysis), "critical") || strings.Contains(strings.ToLower(analysis), "agent smith") { - r.threatLevel = math.Min(r.threatLevel + 0.2, 1.0) - r.EmitEvent("agent_threat_detected", map[string]interface{}{ + a.threatLevel = math.Min(a.threatLevel + 0.2, 1.0) + a.EmitEvent("agent_threat_detected", map[string]interface{}{ "threatLevel": "HIGH", - "confidence": r.threatLevel, + "confidence": a.threatLevel, "analysis": analysis, "recommendation": "immediate_extraction", }) } // Emit mission completion - r.EmitEvent("mission_completed", map[string]interface{}{ + a.EmitEvent("mission_completed", map[string]interface{}{ "missionName": "Matrix Surveillance Analysis", - "confidence": r.threatLevel, - "reportsAnalyzed": len(r.intelligenceReports), + "confidence": a.threatLevel, + "reportsAnalyzed": len(a.intelligenceReports), "status": "SUCCESS", }) @@ -580,83 +580,12 @@ func (r *IntelligenceAgent) analyzeMatrixActivity( (Threat level: %.2f based on %d intelligence reports)`, analysis, - r.threatLevel, - len(r.intelligenceReports)) + a.threatLevel, + len(a.intelligenceReports)) return &result, nil } ``` -Let's also enhance our background reconnaissance to demonstrate multi-phase -operations: - -```go -func (r *IntelligenceAgent) performBackgroundRecon(data *string) (*string, error) { - // Initialize multi-phase operation - r.currentMission = &MissionPhase{ - Name: "Deep Matrix Reconnaissance", - StartTime: time.Now(), - Complete: false, - } - r.missionLog = []string{"Mission initiated: Deep Matrix reconnaissance"} - - // Emit operation start event - r.EmitEvent("background_recon_started", map[string]interface{}{ - "missionName": r.currentMission.Name, - "startTime": r.currentMission.StartTime, - "dataSize": len(*data), - }) - - // Phase 1: Data Processing - r.updateMissionLog("Phase 1: Processing raw Matrix data...") - r.EmitEvent("phase_update", map[string]interface{}{ - "phase": "data_processing", - "progress": 0.25, - "message": "Processing raw Matrix surveillance data", - }) - - r.intelligenceReports = append(r.intelligenceReports, *data) - - // Phase 2: AI Analysis - r.updateMissionLog("Phase 2: Generating threat assessment...") - r.EmitEvent("phase_update", map[string]interface{}{ - "phase": "ai_analysis", - "progress": 0.75, - "message": "Generating threat assessment using AI analysis", - }) - - // ... AI model invocation ... - - // Phase 3: Mission Complete - r.currentMission.Complete = true - r.currentMission.Duration = time.Since(r.currentMission.StartTime) - r.updateMissionLog("Mission completed successfully") - - // Emit completion event - r.EmitEvent("background_recon_completed", map[string]interface{}{ - "missionName": r.currentMission.Name, - "duration": r.currentMission.Duration.Seconds(), - "reportsProcessed": len(r.intelligenceReports), - "status": "SUCCESS", - }) - - result := "Background Matrix reconnaissance completed successfully" - return &result, nil -} - -func (r *IntelligenceAgent) updateMissionLog(message string) { - timestamp := time.Now().Format("15:04:05") - logEntry := fmt.Sprintf("[%s] %s", timestamp, message) - r.missionLog = append(r.missionLog, logEntry) - - // Stream log updates in real-time - r.EmitEvent("mission_log_update", map[string]interface{}{ - "timestamp": timestamp, - "message": message, - "logEntry": logEntry, - }) -} -``` - ### Event-driven operational patterns This streaming capability enables sophisticated real-time operational patterns: @@ -704,10 +633,10 @@ The agent tracks its operational status using the mission state we defined earlier: ```go -func (r *IntelligenceAgent) getOperationalStatus() (*string, error) { +func (a *IntelligenceAgent) getOperationalStatus() (*string, error) { var status MissionStatus - if r.currentMission == nil { + if a.currentMission == nil { status = MissionStatus{ Phase: "Standby", Progress: 1.0, @@ -716,14 +645,14 @@ func (r *IntelligenceAgent) getOperationalStatus() (*string, error) { } } else { // Calculate progress based on mission log entries - progress := float64(len(r.missionLog)) / 4.0 // 4 phases expected + progress := float64(len(a.missionLog)) / 4.0 // 4 phases expected if progress > 1.0 { progress = 1.0 } status = MissionStatus{ - Phase: r.currentMission.Name, + Phase: a.currentMission.Name, Progress: progress, - CurrentTask: r.missionLog[len(r.missionLog)-1], // Latest entry - IsComplete: r.currentMission.Complete, + CurrentTask: a.missionLog[len(a.missionLog)-1], // Latest entry + IsComplete: a.currentMission.Complete, } } From 5eb42efb64c39379ab63b0335f21417225c1f115 Mon Sep 17 00:00:00 2001 From: danstarns Date: Thu, 5 Jun 2025 20:47:22 +0700 Subject: [PATCH 42/53] add note about the rest of agent fields --- modus/agents.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/modus/agents.mdx b/modus/agents.mdx index c70350be..74bdefa5 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -50,6 +50,7 @@ import ( type IntelligenceAgent struct { agents.AgentBase + // The rest of the fields make up the agent's state and can be customized per agent intelligenceReports []string // Matrix surveillance data threatLevel float64 // Current threat assessment lastContact time.Time From 53716f4bbe301f616c0daca0f8516d43ea95c5da Mon Sep 17 00:00:00 2001 From: danstarns Date: Thu, 5 Jun 2025 20:49:27 +0700 Subject: [PATCH 43/53] use any over map interface --- modus/agents.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 74bdefa5..3c2189ab 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -502,7 +502,7 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( data *string, ) (*string, error) { // Emit mission start event - a.EmitEvent("mission_started", map[string]interface{}{ + a.EmitEvent("mission_started", any{ "missionName": "Matrix Surveillance Analysis", "priority": "HIGH", "activityData": len(*data), @@ -513,7 +513,7 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( a.lastContact = time.Now() // Emit progress update - a.EmitEvent("surveillance_progress", map[string]interface{}{ + a.EmitEvent("surveillance_progress", any{ "reportsProcessed": len(a.intelligenceReports), "phase": "Processing Matrix surveillance data", "progress": 0.3, @@ -541,7 +541,7 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( ) // Emit AI processing event - a.EmitEvent("ai_analysis_started", map[string]interface{}{ + a.EmitEvent("ai_analysis_started", any{ "modelName": "analyst-model", "contextSize": len(context), "reportCount": len(a.intelligenceReports), @@ -560,7 +560,7 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( if strings.Contains(strings.ToLower(analysis), "critical") || strings.Contains(strings.ToLower(analysis), "agent smith") { a.threatLevel = math.Min(a.threatLevel + 0.2, 1.0) - a.EmitEvent("agent_threat_detected", map[string]interface{}{ + a.EmitEvent("agent_threat_detected", any{ "threatLevel": "HIGH", "confidence": a.threatLevel, "analysis": analysis, @@ -569,7 +569,7 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( } // Emit mission completion - a.EmitEvent("mission_completed", map[string]interface{}{ + a.EmitEvent("mission_completed", any{ "missionName": "Matrix Surveillance Analysis", "confidence": a.threatLevel, "reportsAnalyzed": len(a.intelligenceReports), From 7d0e75898b10c0fa8e97675bd9f46bb300f1b071 Mon Sep 17 00:00:00 2001 From: danstarns Date: Thu, 5 Jun 2025 20:51:55 +0700 Subject: [PATCH 44/53] use accumulatedReports over context --- modus/agents.mdx | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 3c2189ab..ffc5d1b3 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -252,7 +252,7 @@ func (a *IntelligenceAgent) analyzeMatrixActivity(data *string) (*string, error) a.lastContact = time.Now() // Build context from all accumulated intelligence - context := strings.Join(a.intelligenceReports, "\n") + accumulatedReports := strings.Join(a.intelligenceReports, "\n") // AI analysis using complete operational history model, _ := models.GetModel[openai.ChatModel]("analyst-model") @@ -265,7 +265,7 @@ func (a *IntelligenceAgent) analyzeMatrixActivity(data *string) (*string, error) %s Provide threat assessment:`, - context) + accumulatedReports) input, _ := model.CreateInput( openai.NewSystemMessage(systemPrompt), @@ -520,7 +520,7 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( }) // Build context from all accumulated intelligence - context := strings.Join(a.intelligenceReports, "\n") + accumulatedReports := strings.Join(a.intelligenceReports, "\n") // AI analysis using complete operational history model, _ := models.GetModel[openai.ChatModel]("analyst-model") @@ -533,7 +533,7 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( %s Provide threat assessment:`, - context) + accumulatedReports) input, _ := model.CreateInput( openai.NewSystemMessage(systemPrompt), @@ -543,7 +543,7 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( // Emit AI processing event a.EmitEvent("ai_analysis_started", any{ "modelName": "analyst-model", - "contextSize": len(context), + "contextSize": len(accumulatedReports), "reportCount": len(a.intelligenceReports), }) From 3532626114e729e2d7448158f17e9275edb1f638 Mon Sep 17 00:00:00 2001 From: danstarns Date: Thu, 5 Jun 2025 21:02:14 +0700 Subject: [PATCH 45/53] more error handling --- modus/agents.mdx | 43 +++++++++++++---- modus/knowledge-graphs.mdx | 94 ++++++++++++++++++++++++++++++-------- 2 files changed, 111 insertions(+), 26 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index ffc5d1b3..18eb1af2 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -255,7 +255,10 @@ func (a *IntelligenceAgent) analyzeMatrixActivity(data *string) (*string, error) accumulatedReports := strings.Join(a.intelligenceReports, "\n") // AI analysis using complete operational history - model, _ := models.GetModel[openai.ChatModel]("analyst-model") + model, err := models.GetModel[openai.ChatModel]("analyst-model") + if err != nil { + return nil, err + } systemPrompt := `You are a resistance operative in the Matrix. Analyze patterns from accumulated surveillance reports @@ -267,12 +270,18 @@ func (a *IntelligenceAgent) analyzeMatrixActivity(data *string) (*string, error) Provide threat assessment:`, accumulatedReports) - input, _ := model.CreateInput( + input, err := model.CreateInput( openai.NewSystemMessage(systemPrompt), openai.NewUserMessage(userPrompt), ) + if err != nil { + return nil, err + } - output, _ := model.Invoke(input) + output, err := model.Invoke(input) + if err != nil { + return nil, err + } analysis := output.Choices[0].Message.Content // Update threat level based on data volume and AI analysis @@ -523,7 +532,10 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( accumulatedReports := strings.Join(a.intelligenceReports, "\n") // AI analysis using complete operational history - model, _ := models.GetModel[openai.ChatModel]("analyst-model") + model, err := models.GetModel[openai.ChatModel]("analyst-model") + if err != nil { + return nil, err + } systemPrompt := `You are a resistance operative in the Matrix. Analyze patterns from accumulated surveillance reports @@ -535,10 +547,13 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( Provide threat assessment:`, accumulatedReports) - input, _ := model.CreateInput( + input, err := model.CreateInput( openai.NewSystemMessage(systemPrompt), openai.NewUserMessage(userPrompt), ) + if err != nil { + return nil, err + } // Emit AI processing event a.EmitEvent("ai_analysis_started", any{ @@ -547,7 +562,10 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( "reportCount": len(a.intelligenceReports), }) - output, _ := model.Invoke(input) + output, err := model.Invoke(input) + if err != nil { + return nil, err + } analysis := output.Choices[0].Message.Content // Update threat level based on data volume and AI analysis @@ -615,9 +633,15 @@ func CheckMissionProgress(agentId string) (*MissionStatus, error) { if err != nil { return nil, err } + if result == nil { + return nil, fmt.Errorf("no response from agent") + } var status MissionStatus - json.Unmarshal([]byte(*result), &status) + err = json.Unmarshal([]byte(*result), &status) + if err != nil { + return nil, err + } return &status, nil } @@ -657,7 +681,10 @@ func (a *IntelligenceAgent) getOperationalStatus() (*string, error) { } } - statusJson, _ := json.Marshal(status) + statusJson, err := json.Marshal(status) + if err != nil { + return nil, err + } result := string(statusJson) return &result, nil } diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index da4d270b..241c606c 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -98,7 +98,10 @@ type AgentSighting struct { func ImportAgentSighting(sighting AgentSighting) (*string, error) { // AI-powered analysis of the Agent behavior - analysis, _ := analyzeAgentWithAI(sighting.Behavior) + analysis, err := analyzeAgentWithAI(sighting.Behavior) + if err != nil { + return nil, err + } // Store in knowledge graph - builds institutional intelligence mutation := dgraph.NewMutation().WithSetJson(fmt.Sprintf(`{ @@ -113,25 +116,37 @@ func ImportAgentSighting(sighting AgentSighting) (*string, error) { }`, sighting.SightingID, sighting.AgentName, sighting.Location, sighting.Behavior, sighting.ThreatLevel, sighting.Timestamp, analysis)) - dgraph.ExecuteMutations("dgraph", mutation) + err = dgraph.ExecuteMutations("dgraph", mutation) + if err != nil { + return nil, err + } result := fmt.Sprintf("Agent sighting processed: %s", sighting.SightingID) return &result, nil } func analyzeAgentWithAI(behavior string) (string, error) { - model, _ := models.GetModel[openai.ChatModel]("text-generator") + model, err := models.GetModel[openai.ChatModel]("text-generator") + if err != nil { + return "", err + } prompt := `Analyze this Agent behavior pattern and assess threat level, behavioral changes, and tactical implications for resistance operations.` - input, _ := model.CreateInput( + input, err := model.CreateInput( openai.NewSystemMessage(prompt), openai.NewUserMessage(behavior), ) + if err != nil { + return "", err + } input.Temperature = 0.3 - output, _ := model.Invoke(input) + output, err := model.Invoke(input) + if err != nil { + return "", err + } return strings.TrimSpace(output.Choices[0].Message.Content), nil } ``` @@ -191,14 +206,23 @@ func AnalyzeAgentPatterns(timeRange string) (*ThreatAnalysisResponse, error) { } `).WithVariable("$since", timeRange) - response, _ := dgraph.ExecuteQuery("dgraph", query) + response, err := dgraph.ExecuteQuery("dgraph", query) + if err != nil { + return nil, err + } // Parse and extract threat data var data SightingsData - json.Unmarshal([]byte(response.Json), &data) + err = json.Unmarshal([]byte(response.Json), &data) + if err != nil { + return nil, err + } // Generate strategic assessment using AI with graph context - assessment, _ := generateThreatAssessment(data.Sightings) + assessment, err := generateThreatAssessment(data.Sightings) + if err != nil { + return nil, err + } return &ThreatAnalysisResponse{ SightingCount: len(data.Sightings), @@ -209,21 +233,34 @@ func AnalyzeAgentPatterns(timeRange string) (*ThreatAnalysisResponse, error) { } func generateThreatAssessment(sightings interface{}) (string, error) { - model, _ := models.GetModel[openai.ChatModel]("text-generator") + model, err := models.GetModel[openai.ChatModel]("text-generator") + if err != nil { + return "", err + } prompt := `Based on these Agent sightings, provide a strategic threat assessment focusing on behavioral patterns and risks to resistance operations.` - sightingsJson, _ := json.Marshal(sightings) - input, _ := model.CreateInput( + sightingsJson, err := json.Marshal(sightings) + if err != nil { + return "", err + } + + input, err := model.CreateInput( openai.NewSystemMessage(prompt), openai.NewUserMessage(fmt.Sprintf("Agent surveillance data: %s", string(sightingsJson))), ) + if err != nil { + return "", err + } input.Temperature = 0.4 - output, _ := model.Invoke(input) + output, err := model.Invoke(input) + if err != nil { + return "", err + } return strings.TrimSpace(output.Choices[0].Message.Content), nil } @@ -317,7 +354,10 @@ func (s *SurveillanceAgent) processNewIntelligence() (*string, error) { } `).WithVariable("$since", s.LastSweepTime.Format(time.RFC3339)) - dgraph.ExecuteQuery("dgraph", query) + _, err := dgraph.ExecuteQuery("dgraph", query) + if err != nil { + return nil, err + } // Update agent's surveillance state s.LastSweepTime = time.Now() @@ -356,12 +396,21 @@ func (s *SurveillanceAgent) getOperationalStatus() (*string, error) { func init() { agents.Register(&SurveillanceAgent{}) } func DeploySurveillanceAgent() (string, error) { - agentInfo, _ := agents.Start("SurveillanceAgent") + agentInfo, err := agents.Start("SurveillanceAgent") + if err != nil { + return "", err + } return agentInfo.Id, nil } func GetSurveillanceStatus(agentId string) (string, error) { - result, _ := agents.SendMessage(agentId, "get_status") + result, err := agents.SendMessage(agentId, "get_status") + if err != nil { + return "", err + } + if result == nil { + return "", fmt.Errorf("no response from agent") + } return *result, nil } ``` @@ -372,7 +421,10 @@ surveillance: ```go func ImportAgentSighting(sighting AgentSighting) (*string, error) { // AI-powered analysis of the Agent behavior - analysis, _ := analyzeAgentWithAI(sighting.Behavior) + analysis, err := analyzeAgentWithAI(sighting.Behavior) + if err != nil { + return nil, err + } // Store in knowledge graph - builds institutional intelligence mutation := dgraph.NewMutation().WithSetJson(fmt.Sprintf(`{ @@ -387,10 +439,16 @@ func ImportAgentSighting(sighting AgentSighting) (*string, error) { }`, sighting.SightingID, sighting.AgentName, sighting.Location, sighting.Behavior, sighting.ThreatLevel, sighting.Timestamp, analysis)) - dgraph.ExecuteMutations("dgraph", mutation) + err = dgraph.ExecuteMutations("dgraph", mutation) + if err != nil { + return nil, err + } // Automatically trigger surveillance via async message - agents.SendMessageAsync("agent_neo_001", "continuous_surveillance") + err = agents.SendMessageAsync("agent_neo_001", "continuous_surveillance") + if err != nil { + return nil, err + } result := fmt.Sprintf("Agent sighting processed: %s", sighting.SightingID) return &result, nil From 9dc80b3d2e56880df5698a49807347e98adf91df Mon Sep 17 00:00:00 2001 From: danstarns Date: Thu, 5 Jun 2025 21:06:14 +0700 Subject: [PATCH 46/53] pass non null data around --- modus/agents.mdx | 8 ++++---- modus/knowledge-graphs.mdx | 2 +- modus/sdk/go/agents.mdx | 10 +++++----- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 18eb1af2..34f9ce79 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -218,7 +218,7 @@ system: ```go func (a *IntelligenceAgent) OnReceiveMessage( msgName string, - data *string, + data string, ) (*string, error) { switch msgName { case "matrix_surveillance": @@ -246,7 +246,7 @@ Here's how agents handle field operations while maintaining persistent state and using AI models for analysis: ```go -func (a *IntelligenceAgent) analyzeMatrixActivity(data *string) (*string, error) { +func (a *IntelligenceAgent) analyzeMatrixActivity(data string) (*string, error) { // Store new intelligence in persistent memory a.intelligenceReports = append(a.intelligenceReports, *data) a.lastContact = time.Now() @@ -344,7 +344,7 @@ func (a *IntelligenceAgent) GetState() *string { return &state } -func (a *IntelligenceAgent) SetState(data *string) { +func (a *IntelligenceAgent) SetState(data string) { if data == nil { return } @@ -508,7 +508,7 @@ during their operations. Let's enhance our Matrix surveillance example: ```go func (a *IntelligenceAgent) analyzeMatrixActivity( - data *string, + data string, ) (*string, error) { // Emit mission start event a.EmitEvent("mission_started", any{ diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index 241c606c..9dc51941 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -332,7 +332,7 @@ func (s *SurveillanceAgent) OnInitialize() error { } func (s *SurveillanceAgent) OnReceiveMessage( - msgName string, data *string) (*string, error) { + msgName string, data string) (*string, error) { switch msgName { case "continuous_surveillance": return s.processNewIntelligence() diff --git a/modus/sdk/go/agents.mdx b/modus/sdk/go/agents.mdx index 69c92e72..0129ae27 100644 --- a/modus/sdk/go/agents.mdx +++ b/modus/sdk/go/agents.mdx @@ -162,9 +162,9 @@ The interface that all agents must implement. ```go type Agent interface { Name() string - OnReceiveMessage(messageName string, data *string) (*string, error) + OnReceiveMessage(messageName string, data string) (*string, error) GetState() *string - SetState(data *string) + SetState(data string) OnInitialize() error OnSuspend() error OnResume() error @@ -219,7 +219,7 @@ methods. type AgentBase struct{} func (AgentBase) GetState() *string { return nil } -func (AgentBase) SetState(data *string) {} +func (AgentBase) SetState(data string) {} func (AgentBase) OnInitialize() error { return nil } func (AgentBase) OnSuspend() error { return nil } func (AgentBase) OnResume() error { return nil } @@ -295,7 +295,7 @@ func (c *CounterAgent) GetState() *string { return &state } -func (c *CounterAgent) SetState(data *string) { +func (c *CounterAgent) SetState(data string) { if data == nil { return } @@ -309,7 +309,7 @@ func (c *CounterAgent) OnInitialize() error { return nil } -func (c *CounterAgent) OnReceiveMessage(messageName string, data *string) (*string, error) { +func (c *CounterAgent) OnReceiveMessage(messageName string, data string) (*string, error) { switch messageName { case "count": result := strconv.Itoa(c.count) From 2356e84e31624063f7268651fcac9e0eb556cde3 Mon Sep 17 00:00:00 2001 From: danstarns Date: Thu, 5 Jun 2025 21:21:49 +0700 Subject: [PATCH 47/53] remove repeated workflow list --- modus/agents.mdx | 26 -------------------------- 1 file changed, 26 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 34f9ce79..334f2810 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -727,32 +727,6 @@ The streaming approach provides superior operational intelligence: - **Scalable Monitoring**: Monitor multiple agents simultaneously with individual subscriptions -## Agent workflow example - -1. Client calls `DeployAgent()` → receives agent ID `"agent_neo_001"` -2. Client stores `"agent_neo_001"` for future communications -3. Client subscribes to real-time events: - `agentEvents(agentId: "agent_neo_001")` -4. Client calls - `ImportActivity("agent_neo_001", "anomalous Agent Smith replication detected")` - → agent stores data, emits events, and uses AI to analyze patterns -5. Client receives real-time events: mission started, analysis progress, threat - alerts -6. Agent invokes AI model with accumulated context → generates sophisticated - threat assessment and streams completion events -7. Client calls `GetThreatStatus("agent_neo_001")` → agent returns AI-powered - analysis from persistent memory -8. For long-running analysis, client calls - `InitiateBackgroundRecon("agent_neo_001", data)` → agent processes - asynchronously while streaming progress events -9. Client monitors real-time progress through event subscription without polling -10. Agent persists across system restarts, maintaining complete intelligence - database and event streaming capabilities - -**Important**: clients must store the agent ID returned from deployment -functions to communicate with that specific agent instance. Each agent maintains -its own independent state and can only be accessed through its unique ID. - ## Beyond simple operations Agents enable sophisticated operational patterns impossible with stateless From 0ee3fbc39d6440b189455b69c2716a336c4cc29b Mon Sep 17 00:00:00 2001 From: danstarns Date: Thu, 5 Jun 2025 21:24:04 +0700 Subject: [PATCH 48/53] * --- modus/agents.mdx | 86 +++++++++++++++++++++++------------------------- 1 file changed, 42 insertions(+), 44 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 334f2810..2509b804 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -6,9 +6,9 @@ description: "Learn about stateful agents in Modus" ## Agents in Modus -Agents in Modus are elite operatives that maintain persistent memory across -missions. Unlike stateless functions that lose everything when operations end, -agents remember every detail, survive system failures, and never lose their +Agents in Modus are persistent background processes that maintain memory across +interactions. Unlike stateless functions that lose everything when operations +end, agents remember every detail, survive system failures, and never lose their operational context. ## Key characteristics @@ -20,7 +20,7 @@ operational context. - **Actor-based**: Each agent instance runs in isolation - **Event-driven**: Streams real-time updates and operational intelligence -## When to deploy agents +## When to use agents Agents are perfect for: @@ -33,7 +33,7 @@ Agents are perfect for: ## Agent structure -Every agent starts with the essential operational framework: +Every agent starts with the essential framework: ```go package main @@ -71,15 +71,14 @@ func (a *IntelligenceAgent) Name() string { ``` The agent embeds `agents.AgentBase`, which provides all the infrastructure for -state management, secure communications, and mission persistence. Your -operational data—intelligence reports, threat assessments, contact logs—lives as -fields in the struct, automatically preserved across all interactions. +state management, secure communications, and persistence. Your app +data—intelligence reports, threat assessments, contact logs—lives as fields in +the struct, automatically preserved across all interactions. -## Spawning agents through functions +## Creating agents through functions -Agents are deployed through regular Modus functions that become part of your -GraphQL API. These deployment functions create and manage agent instances on -demand: +Agents are created and managed through regular Modus functions that become part +of your GraphQL API. These functions handle agent lifecycle operations: ```go // Register your agent type during initialization @@ -87,7 +86,7 @@ func init() { agents.Register(&IntelligenceAgent{}) } -// Deploy a new agent instance - this becomes a GraphQL mutation +// Create a new agent instance - this becomes a GraphQL mutation func DeployAgent() (string, error) { agentInfo, err := agents.Start("IntelligenceAgent") if err != nil { @@ -118,21 +117,21 @@ Response: ``` You can think of an Agent as a persistent server process with durable memory. -Once deployed, you can reference your agent by its ID across sessions, page +Once created, you can reference your agent by its ID across sessions, page reloads, and even system restarts. The agent maintains its complete state and continues operating exactly where it left off. **Agent builders and visual workflows:** We're actively developing Agent - Builder tools and "eject to code" feature that generates complete agent + Builder tools and "eject to code" features that generate complete agent deployments from visual workflows. These tools automatically create the deployment functions and agent management code for complex multi-agent systems. -## Communicating with your agent +## Communicating with agents -Once deployed, you communicate with your agent using its unique ID. Create +Once created, you communicate with agents using their unique ID. Create functions that send messages to specific agent instances: ```go @@ -163,7 +162,8 @@ func GetThreatStatus(agentId string) (string, error) { } ``` -These functions become GraphQL mutations that you can call with your agent's ID: +These functions become GraphQL operations that you can call with your agent's +ID: ```graphql mutation { @@ -212,8 +212,7 @@ maintaining persistent memory of every interaction. ## Agent message handling -Agents process operational directives through their secure message handling -system: +Agents process requests through their message handling system: ```go func (a *IntelligenceAgent) OnReceiveMessage( @@ -237,13 +236,13 @@ func (a *IntelligenceAgent) OnReceiveMessage( } ``` -Each directive triggers specific operational procedures, with all intelligence -automatically maintained in the agent's secure memory. +Each message type triggers specific operations, with all data automatically +maintained in the agent's persistent memory. ## Processing operations with AI intelligence -Here's how agents handle field operations while maintaining persistent state and -using AI models for analysis: +Here's how agents handle operations while maintaining persistent state and using +AI models for analysis: ```go func (a *IntelligenceAgent) analyzeMatrixActivity(data string) (*string, error) { @@ -331,8 +330,8 @@ sophisticated pattern recognition impossible with stateless functions. ## State persistence -Agents automatically preserve their operational state through Modus's built-in -intelligence management: +Agents automatically preserve their state through Modus's built-in persistence +system: ```go func (a *IntelligenceAgent) GetState() *string { @@ -363,11 +362,11 @@ func (a *IntelligenceAgent) SetState(data string) { ## Agent lifecycle -Agents have built-in operational protocols for mission continuity: +Agents have built-in lifecycle management protocols: ```go func (a *IntelligenceAgent) OnInitialize() error { - // Called when agent is first awakened in the Matrix + // Called when agent is first created a.lastContact = time.Now() a.threatLevel = 0.0 @@ -377,7 +376,7 @@ func (a *IntelligenceAgent) OnInitialize() error { } func (a *IntelligenceAgent) OnResume() error { - // Called when agent reestablishes contact with complete intel intact + // Called when agent reconnects with complete state intact fmt.Printf(`Agent back online in the Matrix. %d intelligence reports processed. Threat level: %.2f`, @@ -387,12 +386,12 @@ func (a *IntelligenceAgent) OnResume() error { } func (a *IntelligenceAgent) OnSuspend() error { - // Called before agent goes dark + // Called before agent goes offline return nil } func (a *IntelligenceAgent) OnTerminate() error { - // Called before final extraction from the Matrix + // Called before final shutdown fmt.Printf(`Agent %s extracted from Matrix. Intelligence archive preserved.`, a.Id()) return nil @@ -729,15 +728,14 @@ The streaming approach provides superior operational intelligence: ## Beyond simple operations -Agents enable sophisticated operational patterns impossible with stateless -functions: +Agents enable sophisticated patterns impossible with stateless functions: -- **Operational continuity**: Maintain mission state across system failures and +- **Operational continuity**: Maintain state across system failures and re-deployments - **Intelligence building**: Accumulate understanding across multiple assignments through AI-powered analysis -- **Mission recovery**: Resume operations from last secure checkpoint instead of - starting over +- **Recovery protocols**: Resume operations from last secure checkpoint instead + of starting over - **Network coordination**: Manage complex multi-agent operations with shared intelligence and real-time event coordination - **Adaptive learning**: AI models become more effective as agents accumulate @@ -747,11 +745,11 @@ functions: - **Event-driven coordination**: React to operational changes and mission updates through real-time event streams - **Progressive operations**: Update user interfaces and trigger downstream - processes as agents work through complex missions - -Agents represent the evolution from stateless functions to elite operatives that -maintain complete operational continuity, build intelligence over time, and -provide real-time operational awareness. They're the foundation for building -intelligence networks that never lose track of their missions, become smarter -with every interaction, and keep operational teams informed through live event -streaming—no matter what happens in the field. + processes as agents work through complex workflows + +Agents represent the evolution from stateless functions to persistent background +processes that maintain complete operational continuity, build intelligence over +time, and provide real-time operational awareness. They're the foundation for +building systems that never lose track of their work, become smarter with every +interaction, and keep teams informed through live event streaming—no matter what +happens in the infrastructure. From 76ef44aad4b6442d63b32f7252b4207a899f94b8 Mon Sep 17 00:00:00 2001 From: danstarns Date: Thu, 5 Jun 2025 21:28:53 +0700 Subject: [PATCH 49/53] * --- modus/functions.mdx | 102 +++++++++++++++++++++----------------------- 1 file changed, 49 insertions(+), 53 deletions(-) diff --git a/modus/functions.mdx b/modus/functions.mdx index 70002ac7..6ecf481d 100644 --- a/modus/functions.mdx +++ b/modus/functions.mdx @@ -1,60 +1,57 @@ --- title: "What is a Function?" -description: "Learn about your basic operatives in Modus" +description: "Learn about functions in Modus" "og:title": "What is a Function? - Modus" --- ## Functions in Modus -Functions in Modus are your reliable field operatives—specialized agents who -handle specific missions with precision and speed. Like elite reconnaissance -units, they get in, complete their objective, and report back. No unnecessary -complications, no lingering presence, just pure operational efficiency. +Functions in Modus are stateless, request-response operations that handle +specific tasks with precision and speed. They get in, complete their objective, +and report back—no unnecessary complications, no lingering presence, just pure +operational efficiency. You can think of a function as an endpoint—each function you write automatically becomes a callable API endpoint that external systems can access. -Functions are the backbone of your intelligence network, handling everything -from data gathering to AI-powered analysis, all while maintaining perfect -operational discipline. +Functions are the backbone of your app, handling everything from data gathering +to AI-powered analysis, all while maintaining clean, predictable behavior. -## Operational profile +## Core characteristics Functions are stateless, request-response operations designed for fast, -predictable missions. They're your go-to operatives when you need quick -intelligence gathering, data processing, or tactical strikes without maintaining -ongoing surveillance between operations. +predictable execution. They're your go-to choice when you need quick data +processing, external API integration, or computational tasks without maintaining +state between requests. -### Core capabilities +### Key capabilities -- **Mission-focused**: Each operation is independent with no memory of previous - assignments -- **Lightning fast**: Optimized for sub-second mission completion -- **Infinitely scalable**: Deploy as many operatives as needed -- **Clean operations**: Straightforward request-in, intel-out pattern +- **Stateless**: Each operation is independent with no memory of previous + requests +- **Lightning fast**: Optimized for sub-second response times +- **Infinitely scalable**: Deploy as many instances as needed +- **Clean operations**: Straightforward request-in, response-out pattern - **Auto-deployed**: Exposed automatically as GraphQL queries or mutations ## How functions become endpoints -When you deploy your operatives, Modus automatically exposes them through a -GraphQL API. Your functions become either **queries** (for gathering -intelligence) or **mutations** (for operational changes) based on their mission -type. +When you deploy your functions, Modus automatically exposes them through a +GraphQL API. Your functions become either **queries** (for data retrieval) or +**mutations** (for data modifications) based on their operation type. -### Intelligence gathering queries +### Data retrieval queries -Most functions become GraphQL queries—perfect for reconnaissance and data -retrieval: +Most functions become GraphQL queries—perfect for fetching and processing data: ```go // This function becomes a GraphQL query func GatherThreatIntelligence(source string) (*ThreatReport, error) { - // Intelligence gathering operation + // Data gathering and processing operation return fetchThreatData(source) } ``` -Your operatives are now accessible via GraphQL: +Your functions are now accessible via GraphQL: ```graphql query { @@ -80,10 +77,10 @@ query { } ``` -### Operational change mutations +### Data modification mutations Functions that modify data automatically become GraphQL mutations. Modus detects -these by their mission prefixes: +these by their operation prefixes: ```go // This becomes a GraphQL mutation @@ -93,7 +90,7 @@ func CreateSecurityAlert(data AlertInput) (*SecurityAlert, error) { } ``` -Now you can execute operational changes: +Now you can execute data modifications: ```graphql mutation { @@ -128,10 +125,10 @@ mutation { Functions starting with `create`, `update`, `delete`, and similar action words automatically become mutations. -## Mission example: field conditions intelligence analysis +## Example: Weather intelligence analysis -Here's a complete tactical operation that demonstrates how functions integrate -external APIs with AI models for intelligence analysis: +Here's a complete example that demonstrates how functions integrate external +APIs with AI models for intelligent data processing: ```go package main @@ -153,7 +150,7 @@ type WeatherIntel struct { const modelName = "text-generator" -// Operative: Gather weather intelligence and provide tactical analysis +// Function: Gather weather data and provide tactical analysis func GatherWeatherIntelligence(city string) (*WeatherIntel, error) { // Fetch weather data from OpenWeatherMap API url := fmt.Sprintf( @@ -167,7 +164,7 @@ func GatherWeatherIntelligence(city string) (*WeatherIntel, error) { } if !response.Ok() { return nil, fmt.Errorf( - "weather intelligence gathering failed: %d %s", + "weather data retrieval failed: %d %s", response.Status, response.StatusText, ) @@ -198,7 +195,7 @@ func GatherWeatherIntelligence(city string) (*WeatherIntel, error) { conditions, ) if err != nil { - fmt.Printf("Tactical analysis failed for %s: %v\n", weatherData.Name, err) + fmt.Printf("Analysis failed for %s: %v\n", weatherData.Name, err) analysis = "Analysis unavailable - proceed with standard protocols" } @@ -247,7 +244,7 @@ func analyzeTacticalConditions(city string, temp float64, conditions string) (st } ``` -This operative automatically becomes available as a GraphQL query: +This function automatically becomes available as a GraphQL query: ```graphql query { @@ -260,7 +257,7 @@ query { } ``` -You'll receive a tactical intelligence report like: +You'll receive an intelligence report like: ```json { @@ -277,7 +274,7 @@ You'll receive a tactical intelligence report like: } ``` -### Deploying your operative +### Setting up the function To use this function, you'll need to: @@ -312,21 +309,20 @@ Set your API key in `.env.dev.local`: MODUS_WEATHER_API_API_KEY=your_openweathermap_api_key_here ``` -## When to deploy agents +## When to use agents instead -Functions are perfect for most tactical operations, but when you need persistent -surveillance, complex multi-phase operations, or operatives that remember every -detail of ongoing investigations, it's time to deploy your -[agents](/modus/agents). +Functions are perfect for most computational tasks, but when you need persistent +state, complex multi-step workflows, or processes that remember details across +multiple interactions, it's time to consider [agents](/modus/agents). -Consider upgrading to agents when missions require: +Consider upgrading to agents when your use case requires: -- **Operational memory** across multiple engagements -- **Conversation intelligence** that builds over time -- **Multi-phase operations** spanning days or weeks -- **Recovery protocols** from mission failures -- **Continuous monitoring** with state preservation +- **Persistent memory** across multiple requests +- **Conversation context** that builds over time +- **Multi-step workflows** spanning extended periods +- **Recovery from failures** with state preservation +- **Continuous monitoring** with context retention -Your functions form the tactical backbone of your intelligence operations—fast, -reliable, and always ready for the next mission. They handle the day-to-day -operations while your agents manage the long-term strategic initiatives. +Your functions form the API backbone of your app—fast, reliable, and always +ready for the next request. They handle the immediate computational needs while +your agents manage the long-term stateful processes. From 3838fcdf52153a5ac6a497b8e1e828a809e06ec6 Mon Sep 17 00:00:00 2001 From: danstarns Date: Thu, 5 Jun 2025 21:32:43 +0700 Subject: [PATCH 50/53] * --- modus/knowledge-graphs.mdx | 114 ++++++++++++++++++------------------- 1 file changed, 55 insertions(+), 59 deletions(-) diff --git a/modus/knowledge-graphs.mdx b/modus/knowledge-graphs.mdx index 9dc51941..6f6613a3 100644 --- a/modus/knowledge-graphs.mdx +++ b/modus/knowledge-graphs.mdx @@ -8,11 +8,11 @@ description: ## Knowledge graphs in Modus -Your operatives need more than just memory—they need intelligence networks. -While agents maintain their own operational state and memory across missions, -knowledge graphs provide something fundamentally different: shared institutional -knowledge that captures relationships between entities, events, and intelligence -across your entire organization. +Your applications need more than just individual memory—they need shared +organizational knowledge. While agents maintain their own operational state and +memory across interactions, knowledge graphs provide something fundamentally +different: shared institutional knowledge that captures relationships between +entities, events, and data across your entire app. At Hypermode, we recognize that knowledge graphs aren't just storage—they're becoming critical infrastructure for next-generation AI systems. That's why @@ -20,29 +20,26 @@ we've invested deeply in Dgraph, bringing enterprise-grade graph capabilities to Modus applications. This is where knowledge graphs transform your Modus deployment from isolated -operatives into a coordinated intelligence network with shared institutional -memory. +processes into a coordinated system with shared institutional memory. -## What are intelligence networks? +## What are knowledge networks? -Intelligence networks in Modus combine: +Knowledge networks in Modus combine: -- **Agent state**: personal operational memory that each agent maintains across - missions -- **Knowledge graphs**: shared institutional intelligence that captures - relationships between entities, events, and intelligence across your - organization -- **Functions**: rapid tactical operations for data processing and analysis -- **AI models**: advanced pattern recognition and decision-making intelligence +- **Agent state**: personal memory that each agent maintains across interactions +- **Knowledge graphs**: shared organizational knowledge that captures + relationships between entities, events, and data across your entire app +- **Functions**: rapid operations for data processing and analysis +- **AI models**: advanced pattern recognition and decision-making capabilities -Think of it as the difference between what an individual operative remembers -versus what your intelligence agency knows. Agent state is personal memory—what -happened to this specific operative, what conversations they've had, what tasks -they're tracking. Knowledge graphs are institutional intelligence—how threats -relate to each other, which indicators connect to which actors, what patterns -emerge across all operations. +Think of it as the difference between what an individual process remembers +versus what your organization knows. Agent state is personal memory—what +happened to this specific agent, what conversations they've had, what tasks +they're tracking. Knowledge graphs are organizational intelligence—how entities +relate to each other, which patterns connect to which outcomes, what +relationships emerge across all operations. -## Setting up your intelligence infrastructure +## Setting up your knowledge infrastructure First, connect to your knowledge graph by adding this to your `modus.json`: @@ -70,18 +67,18 @@ Set your credentials in `.env.dev.local`: MODUS_DGRAPH_API_KEY=your_graph_api_key_here ``` -## Building an intelligence operation +## Building a comprehensive system -Let's walk through a realistic intelligence scenario that demonstrates how all -these components work together. You're building a system to track anomalous -Agent behavior in the simulated reality. The operation needs to: +Let's walk through a realistic scenario that demonstrates how all these +components work together. You're building a system to track anomalous Agent +behavior in the simulated reality. The system needs to: 1. Rapidly import new Agent sightings and behavioral data 2. Find patterns across historical Agent encounters 3. Coordinate ongoing surveillance operations 4. Provide strategic analysis to the resistance -### Step 1: rapid intelligence import +### Step 1: Rapid data import When new Agent activity is detected in the Matrix, you need to process it quickly. This is perfect for a stateless function: @@ -103,7 +100,7 @@ func ImportAgentSighting(sighting AgentSighting) (*string, error) { return nil, err } - // Store in knowledge graph - builds institutional intelligence + // Store in knowledge graph - builds organizational knowledge mutation := dgraph.NewMutation().WithSetJson(fmt.Sprintf(`{ "dgraph.type": "AgentSighting", "sighting_id": "%s", @@ -151,7 +148,7 @@ func analyzeAgentWithAI(behavior string) (string, error) { } ``` -Now let's deploy this intelligence import function and test it: +Now let's deploy this data import function and test it: ```graphql mutation { @@ -180,7 +177,7 @@ mutation { } ``` -### Step 2: strategic analysis using institutional knowledge +### Step 2: Strategic analysis using organizational knowledge Now that we've got the Agent sighting data in our knowledge graph, let's analyze the broader threat landscape: @@ -194,7 +191,7 @@ type ThreatAnalysisResponse struct { } func AnalyzeAgentPatterns(timeRange string) (*ThreatAnalysisResponse, error) { - // Query institutional knowledge - traverses relationships + // Query organizational knowledge - traverses relationships query := dgraph.NewQuery(` query analyzeAgents($since: string) { sightings(func: ge(timestamp, $since)) { @@ -269,7 +266,7 @@ func extractActiveAgents(sightings []AgentSightingData) []string { /* ... */ } func generateRecommendations(count int) []string { /* ... */ } ``` -Let's query our surveillance intelligence data: +Let's query our surveillance data: ```graphql query { @@ -303,11 +300,11 @@ query { } ``` -### Step 3: automated intelligence processing with asynchronous messaging +### Step 3: Automated processing with asynchronous coordination Now let's enhance our system to automatically coordinate surveillance when new -intelligence arrives. We'll deploy persistent surveillance agents and upgrade -our import function to trigger them: +data arrives. We'll deploy persistent surveillance agents and upgrade our import +function to trigger them: ```go type SurveillanceAgent struct { @@ -343,7 +340,7 @@ func (s *SurveillanceAgent) OnReceiveMessage( } func (s *SurveillanceAgent) processNewIntelligence() (*string, error) { - // Query knowledge graph for latest intelligence since last sweep + // Query knowledge graph for latest data since last sweep query := dgraph.NewQuery(` query getRecentSightings($since: string) { sightings(func: ge(timestamp, $since)) { @@ -372,7 +369,7 @@ func (s *SurveillanceAgent) processNewIntelligence() (*string, error) { s.RecentActivities = s.RecentActivities[1:] } - result := fmt.Sprintf(`Intelligence processed automatically. + result := fmt.Sprintf(`Data processed automatically. Tracking %d sightings. Matrix integrity: COMPROMISED`, s.SightingsTracked) return &result, nil @@ -426,7 +423,7 @@ func ImportAgentSighting(sighting AgentSighting) (*string, error) { return nil, err } - // Store in knowledge graph - builds institutional intelligence + // Store in knowledge graph - builds organizational knowledge mutation := dgraph.NewMutation().WithSetJson(fmt.Sprintf(`{ "dgraph.type": "AgentSighting", "sighting_id": "%s", @@ -473,7 +470,7 @@ mutation { } ``` -### Step 4: coordinated intelligence processing +### Step 4: Coordinated processing Now when you import new Agent sightings, surveillance automatically triggers: @@ -531,10 +528,10 @@ query { } ``` -### Step 5: evolved threat analysis +### Step 5: Enhanced threat analysis Query the strategic analysis to see patterns across automatically processed -intelligence: +data: ```graphql query { @@ -574,21 +571,21 @@ query { ## Conclusion You've just built a complete automated surveillance network that demonstrates -the power of coordinated intelligence operations. By combining functions for -rapid data processing, knowledge graphs for institutional memory, AI models for -enhanced analysis, and agents for persistent surveillance—all coordinated -through asynchronous messaging—you've created something far more powerful than -any single component could achieve. - -Your network now automatically processes Agent sightings, triggers surveillance -operations, builds institutional knowledge over time, and provides AI-enhanced -threat analysis across all accumulated intelligence. The surveillance agent -maintains persistent memory across system failures while the knowledge graph -captures relationships that no single sighting could reveal. - -This isn't just a database with some AI on top—it's a coordinated intelligence -network where each component enhances the others, creating emergent capabilities -that scale with your resistance operations. Welcome to the real world. +the power of coordinated systems. By combining functions for rapid data +processing, knowledge graphs for organizational memory, AI models for enhanced +analysis, and agents for persistent processing—all coordinated through +asynchronous messaging—you've created something far more powerful than any +single component could achieve. + +Your system now automatically processes Agent sightings, triggers surveillance +operations, builds organizational knowledge over time, and provides AI-enhanced +threat analysis across all accumulated data. The surveillance agent maintains +persistent memory across system failures while the knowledge graph captures +relationships that no single sighting could reveal. + +This isn't just a database with some AI on top—it's a coordinated system where +each component enhances the others, creating emergent capabilities that scale +with your operations. Welcome to the real world. ## Next steps @@ -596,5 +593,4 @@ Ready to deploy your surveillance network against the machines? Check out: - [Dgraph integration guide](/modus/modus-dgraph) for advanced graph operations - [Agent coordination patterns](/modus/agents) for multi-agent workflows -- [Production deployment](/modus/deploying) for scaling your intelligence - network +- [Production deployment](/modus/deploying) for scaling your knowledge network From 2e057643a8e2e81c720a99cd376a460ee4b8776d Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 8 Jun 2025 20:56:34 +0700 Subject: [PATCH 51/53] sync to support sub https://github.com/hypermodeinc/modus/pull/875 --- modus/agents.mdx | 116 +++++++---- modus/sdk/assemblyscript/agents.mdx | 136 +++++++++++- modus/sdk/go/agents.mdx | 197 +++++++++++++++++- styles/config/vocabularies/general/accept.txt | 4 +- 4 files changed, 407 insertions(+), 46 deletions(-) diff --git a/modus/agents.mdx b/modus/agents.mdx index 2509b804..3d59bec6 100644 --- a/modus/agents.mdx +++ b/modus/agents.mdx @@ -440,9 +440,9 @@ Monitor your agent's real-time activities using the unified event subscription: ```graphql subscription { - agentEvents(agentId: "agent_neo_001") { - type - payload + agentEvent(agentId: "agent_neo_001") { + name + data timestamp } } @@ -453,9 +453,9 @@ Your agent streams various types of operational events: ```json { "data": { - "agentEvents": { - "type": "mission_started", - "payload": { + "agentEvent": { + "name": "mission_started", + "data": { "missionName": "Deep Matrix Surveillance", "priority": "HIGH", "estimatedDuration": "180s" @@ -469,9 +469,9 @@ Your agent streams various types of operational events: ```json { "data": { - "agentEvents": { - "type": "agent_threat_detected", - "payload": { + "agentEvent": { + "name": "agent_threat_detected", + "data": { "threatLevel": "CRITICAL", "confidence": 0.92, "indicators": ["agent_smith_replication", "unusual_code_patterns"], @@ -486,9 +486,9 @@ Your agent streams various types of operational events: ```json { "data": { - "agentEvents": { - "type": "surveillance_progress", - "payload": { + "agentEvent": { + "name": "surveillance_progress", + "data": { "phase": "Processing Matrix surveillance data", "progress": 0.65, "reportsProcessed": 5, @@ -500,31 +500,47 @@ Your agent streams various types of operational events: } ``` -### Emitting events from your agent +### Publishing events from your agent -Agents can broadcast real-time operational intelligence by emitting events -during their operations. Let's enhance our Matrix surveillance example: +Agents can broadcast real-time operational intelligence by publishing events +during their operations. Use the `PublishEvent` method to emit custom events: ```go +// Custom event types implement the AgentEvent interface +type ThreatDetected struct { + ThreatLevel string `json:"threatLevel"` + Confidence float64 `json:"confidence"` + Analysis string `json:"analysis"` +} + +func (e ThreatDetected) EventName() string { + return "threat_detected" +} + +// Other event types can be defined similarly... + func (a *IntelligenceAgent) analyzeMatrixActivity( data string, ) (*string, error) { // Emit mission start event - a.EmitEvent("mission_started", any{ - "missionName": "Matrix Surveillance Analysis", - "priority": "HIGH", - "activityData": len(*data), + err := a.PublishEvent(MissionStarted{ + MissionName: "Matrix Surveillance Analysis", + Priority: "HIGH", + ActivityData: len(*data), }) + if err != nil { + return nil, err + } // Store new intelligence in persistent memory a.intelligenceReports = append(a.intelligenceReports, *data) a.lastContact = time.Now() // Emit progress update - a.EmitEvent("surveillance_progress", any{ - "reportsProcessed": len(a.intelligenceReports), - "phase": "Processing Matrix surveillance data", - "progress": 0.3, + a.PublishEvent(SurveillanceProgress{ + ReportsProcessed: len(a.intelligenceReports), + Phase: "Processing Matrix surveillance data", + Progress: 0.3, }) // Build context from all accumulated intelligence @@ -555,10 +571,10 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( } // Emit AI processing event - a.EmitEvent("ai_analysis_started", any{ - "modelName": "analyst-model", - "contextSize": len(accumulatedReports), - "reportCount": len(a.intelligenceReports), + a.PublishEvent(AIAnalysisStarted{ + ModelName: "analyst-model", + ContextSize: len(accumulatedReports), + ReportCount: len(a.intelligenceReports), }) output, err := model.Invoke(input) @@ -577,20 +593,19 @@ func (a *IntelligenceAgent) analyzeMatrixActivity( if strings.Contains(strings.ToLower(analysis), "critical") || strings.Contains(strings.ToLower(analysis), "agent smith") { a.threatLevel = math.Min(a.threatLevel + 0.2, 1.0) - a.EmitEvent("agent_threat_detected", any{ - "threatLevel": "HIGH", - "confidence": a.threatLevel, - "analysis": analysis, - "recommendation": "immediate_extraction", + a.PublishEvent(ThreatDetected{ + ThreatLevel: "HIGH", + Confidence: a.threatLevel, + Analysis: analysis, }) } // Emit mission completion - a.EmitEvent("mission_completed", any{ - "missionName": "Matrix Surveillance Analysis", - "confidence": a.threatLevel, - "reportsAnalyzed": len(a.intelligenceReports), - "status": "SUCCESS", + a.PublishEvent(MissionCompleted{ + MissionName: "Matrix Surveillance Analysis", + Confidence: a.threatLevel, + ReportsAnalyzed: len(a.intelligenceReports), + Status: "SUCCESS", }) result := fmt.Sprintf(`Matrix surveillance complete: @@ -622,6 +637,27 @@ analysis. **Progressive Enhancement**: update user interfaces progressively as agents work through complex, multi-phase operations without polling or manual refresh. +### Subscription protocol + +Modus uses GraphQL subscriptions over Server-Sent Events (SSE) following the +[GraphQL-SSE specification](https://the-guild.dev/graphql/sse). To consume these +subscriptions: + +1. **From a web browser**: Use the EventSource API or a GraphQL client that + supports SSE subscriptions +2. **From Postman**: Set Accept header to `text/event-stream` and make a POST + request +3. **From curl**: Use `-N` flag and appropriate headers for streaming + +Example with curl: + +```bash +curl -N -H "accept: text/event-stream" \ + -H "content-type: application/json" \ + -X POST http://localhost:8080/graphql \ + -d '{"query":"subscription { agentEvent(agentId: \"agent_neo_001\") { name data timestamp } }"}' +``` + ## Monitoring ongoing operations You can also poll agent status directly through dedicated functions: @@ -706,9 +742,9 @@ query MonitorMission($agentId: String!) { # Real-time streaming approach (recommended) subscription LiveAgentMonitoring($agentId: String!) { - agentEvents(agentId: $agentId) { - type - payload + agentEvent(agentId: $agentId) { + name + data timestamp } } diff --git a/modus/sdk/assemblyscript/agents.mdx b/modus/sdk/assemblyscript/agents.mdx index 4dcb12d4..20df9477 100644 --- a/modus/sdk/assemblyscript/agents.mdx +++ b/modus/sdk/assemblyscript/agents.mdx @@ -21,7 +21,7 @@ complex multi-step operations. To begin, import the `agents` namespace and `Agent` base class from the SDK: ```ts -import { agents, Agent, AgentInfo } from "@hypermode/modus-sdk-as" +import { agents, Agent, AgentInfo, AgentEvent } from "@hypermode/modus-sdk-as" ``` ## Agent APIs @@ -165,6 +165,7 @@ abstract class Agent { onSuspend(): void onResume(): void onTerminate(): void + publishEvent(event: AgentEvent): void } ``` @@ -208,6 +209,42 @@ abstract class Agent { Optional lifecycle method called when the agent is about to be terminated. + + Publishes an event from this agent to any subscribers. The event must extend + the `AgentEvent` base class. + + +### Event Classes + +#### AgentEvent + +Base class for agent events that can be published to subscribers. + +```ts +abstract class AgentEvent { + readonly eventName: string + + constructor(eventName: string) +} +``` + + + The name of the event type. Must be provided in the constructor and can't be + empty. + + +Custom events should extend this class and include any additional data as +properties: + +```ts +@json +class CountUpdated extends AgentEvent { + constructor(public count: i32) { + super("countUpdated") + } +} +``` + ### Types #### AgentInfo @@ -236,12 +273,12 @@ class AgentInfo { ## Example Usage -Here's a complete example of a simple counter agent: +Here's a complete example of a simple counter agent with event streaming: ### Agent Implementation ```ts -import { Agent } from "@hypermode/modus-sdk-as" +import { Agent, AgentEvent } from "@hypermode/modus-sdk-as" export class CounterAgent extends Agent { get name(): string { @@ -276,12 +313,24 @@ export class CounterAgent extends Agent { } else { this.count++ } + + // Publish an event to subscribers + this.publishEvent(new CountUpdated(this.count)) + return this.count.toString() } return null } } + +// Custom event for count updates +@json +class CountUpdated extends AgentEvent { + constructor(public count: i32) { + super("countUpdated") + } +} ``` ### Function Integration @@ -341,4 +390,85 @@ query { mutation { updateCount(agentId: "agent_abc123") } + +# Subscribe to real-time events +subscription { + agentEvent(agentId: "agent_abc123") { + name + data + timestamp + } +} +``` + +### Event Subscription + +To receive real-time events from your agent, subscribe using GraphQL +subscriptions over Server-Sent Events: + +```graphql +subscription CounterEvents($agentId: String!) { + agentEvent(agentId: $agentId) { + name + data + timestamp + } +} +``` + +Example events you might receive: + +```json +{ + "data": { + "agentEvent": { + "name": "countUpdated", + "data": { + "count": 5 + }, + "timestamp": "2025-06-08T14:30:00Z" + } + } +} +``` + +```json +{ + "data": { + "agentEvent": { + "name": "status", + "data": { + "status": "running" + }, + "timestamp": "2025-06-08T14:30:05Z" + } + } +} +``` + +### Client Integration + +Use appropriate GraphQL Server-Sent Events (SSE) clients such as: + +- [graphql-sse](https://the-guild.dev/graphql/sse) for vanilla JavaScript +- [urql](https://formidable.com/open-source/urql/docs/basics/subscriptions/) + with Server-Sent Events (SSE) exchange +- EventSource API directly for simple use cases + +Example with EventSource: + +```javascript +const eventSource = new EventSource( + '/graphql?query=subscription{agentEvent(agentId:"agent_abc123"){name,data,timestamp}}', + { + headers: { + Accept: "text/event-stream", + }, + }, +) + +eventSource.addEventListener("next", (event) => { + const data = JSON.parse(event.data) + console.log("Agent event:", data) +}) ``` diff --git a/modus/sdk/go/agents.mdx b/modus/sdk/go/agents.mdx index 0129ae27..ff5783d3 100644 --- a/modus/sdk/go/agents.mdx +++ b/modus/sdk/go/agents.mdx @@ -213,7 +213,7 @@ type Agent interface { #### AgentBase A convenient base struct that provides default implementations for optional -methods. +methods and includes event publishing capabilities. ```go type AgentBase struct{} @@ -224,6 +224,7 @@ func (AgentBase) OnInitialize() error { return nil } func (AgentBase) OnSuspend() error { return nil } func (AgentBase) OnResume() error { return nil } func (AgentBase) OnTerminate() error { return nil } +func (a *AgentBase) PublishEvent(event AgentEvent) error ``` @@ -231,6 +232,40 @@ func (AgentBase) OnTerminate() error { return nil } optional methods, then override only the ones you need. + + Publishes an event from this agent to any subscribers. The event must + implement the `AgentEvent` interface. + + +### Event Interface + +#### AgentEvent + +Interface that custom events must implement to be published from agents. + +```go +type AgentEvent interface { + EventName() string +} +``` + + + Must return the name/type of the event as a string. + + +Custom events should implement this interface and include any additional data as +struct fields: + +```go +type CountUpdated struct { + Count int `json:"count"` +} + +func (e CountUpdated) EventName() string { + return "countUpdated" +} +``` + ### Types #### AgentInfo @@ -269,7 +304,7 @@ type MessageOption interface { ## Example Usage -Here's a complete example of a simple counter agent: +Here's a complete example of a simple counter agent with event streaming: ### Agent Implementation @@ -323,6 +358,12 @@ func (c *CounterAgent) OnReceiveMessage(messageName string, data string) (*strin } else { c.count++ } + + // Publish an event to subscribers + if err := c.PublishEvent(CountUpdated{Count: c.count}); err != nil { + return nil, err + } + result := strconv.Itoa(c.count) return &result, nil } @@ -330,6 +371,15 @@ func (c *CounterAgent) OnReceiveMessage(messageName string, data string) (*strin return nil, nil } +// Custom event for count updates +type CountUpdated struct { + Count int `json:"count"` +} + +func (e CountUpdated) EventName() string { + return "countUpdated" +} + // Register the agent in init function func init() { agents.Register(&CounterAgent{}) @@ -413,4 +463,147 @@ mutation { mutation { updateCountAsync(agentId: "agent_abc123", qty: 5) } + +# Subscribe to real-time events +subscription { + agentEvent(agentId: "agent_abc123") { + name + data + timestamp + } +} +``` + +### Event Subscription + +To receive real-time events from your agent, subscribe using GraphQL +subscriptions over Server-Sent Events: + +```graphql +subscription CounterEvents($agentId: String!) { + agentEvent(agentId: $agentId) { + name + data + timestamp + } +} +``` + +Example events you might receive: + +```json +{ + "data": { + "agentEvent": { + "name": "countUpdated", + "data": { + "count": 5 + }, + "timestamp": "2025-06-08T14:30:00Z" + } + } +} +``` + +```json +{ + "data": { + "agentEvent": { + "name": "status", + "data": { + "status": "running" + }, + "timestamp": "2025-06-08T14:30:05Z" + } + } +} +``` + +### Multiple Event Types + +You can define multiple event types for different scenarios: + +```go +// Mission events +type MissionStarted struct { + MissionName string `json:"missionName"` + Priority string `json:"priority"` +} + +func (e MissionStarted) EventName() string { + return "missionStarted" +} + +type MissionCompleted struct { + MissionName string `json:"missionName"` + Success bool `json:"success"` + Duration int `json:"duration"` +} + +func (e MissionCompleted) EventName() string { + return "missionCompleted" +} + +// Error events +type ErrorOccurred struct { + Message string `json:"message"` + Code string `json:"code"` +} + +func (e ErrorOccurred) EventName() string { + return "errorOccurred" +} +``` + +### Client Integration + +Use appropriate GraphQL Server-Sent Events (SSE) clients such as: + +- [graphql-sse](https://the-guild.dev/graphql/sse) for JavaScript/TypeScript +- [gqlgen](https://gqlgen.com/recipes/subscriptions/) for Go clients +- Standard HTTP libraries with Server-Sent Events (SSE) support + +Example with curl: + +```bash +curl -N -H "accept: text/event-stream" \ + -H "content-type: application/json" \ + -X POST http://localhost:8080/graphql \ + -d '{"query":"subscription { agentEvent(agentId: \"agent_abc123\") { name data timestamp } }"}' +``` + +Example with Go client: + +```go +import ( + "bufio" + "encoding/json" + "fmt" + "net/http" + "strings" +) + +func subscribeToAgentEvents(agentId string) { + query := fmt.Sprintf(`{"query":"subscription { agentEvent(agentId: \"%s\") { name data timestamp } }"}`, agentId) + + req, _ := http.NewRequest("POST", "http://localhost:8080/graphql", strings.NewReader(query)) + req.Header.Set("Accept", "text/event-stream") + req.Header.Set("Content-Type", "application/json") + + client := &http.Client{} + resp, err := client.Do(req) + if err != nil { + panic(err) + } + defer resp.Body.Close() + + scanner := bufio.NewScanner(resp.Body) + for scanner.Scan() { + line := scanner.Text() + if strings.HasPrefix(line, "data: ") { + data := strings.TrimPrefix(line, "data: ") + fmt.Printf("Received event: %s\n", data) + } + } +} ``` diff --git a/styles/config/vocabularies/general/accept.txt b/styles/config/vocabularies/general/accept.txt index 9803b44c..3a402c45 100644 --- a/styles/config/vocabularies/general/accept.txt +++ b/styles/config/vocabularies/general/accept.txt @@ -133,4 +133,6 @@ vCPU|vCPUs WebSocket USA -[Gg]raphs \ No newline at end of file +[Gg]raphs + +gqlgen \ No newline at end of file From 98dcd7a563550673cdce2b2e52b4fc34edd5bf73 Mon Sep 17 00:00:00 2001 From: danstarns Date: Sun, 8 Jun 2025 21:00:36 +0700 Subject: [PATCH 52/53] * --- modus/sdk/assemblyscript/agents.mdx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modus/sdk/assemblyscript/agents.mdx b/modus/sdk/assemblyscript/agents.mdx index 20df9477..8f5d7a5a 100644 --- a/modus/sdk/assemblyscript/agents.mdx +++ b/modus/sdk/assemblyscript/agents.mdx @@ -451,7 +451,7 @@ Example events you might receive: Use appropriate GraphQL Server-Sent Events (SSE) clients such as: - [graphql-sse](https://the-guild.dev/graphql/sse) for vanilla JavaScript -- [urql](https://formidable.com/open-source/urql/docs/basics/subscriptions/) +- [urql](https://nearform.com/open-source/urql/docs/advanced/subscriptions/) with Server-Sent Events (SSE) exchange - EventSource API directly for simple use cases From b68335e85b45cd19008d0d82e51e52525e70f47c Mon Sep 17 00:00:00 2001 From: danstarns Date: Thu, 12 Jun 2025 18:24:22 +0700 Subject: [PATCH 53/53] add start stop based on https://github.com/hypermodeinc/modus/pull/889 --- modus/api-generation.mdx | 1 + 1 file changed, 1 insertion(+) diff --git a/modus/api-generation.mdx b/modus/api-generation.mdx index 041ed08c..b2ebf1a5 100644 --- a/modus/api-generation.mdx +++ b/modus/api-generation.mdx @@ -152,6 +152,7 @@ these prefixes: - `post`, `patch`, `put`, `delete` - `add`, `update`, `insert`, `upsert` - `create`, `edit`, `save`, `remove`, `alter`, `modify` +- `start`, `stop` For example: