Skip to content

armgit / ax

Public Imported from GitHub
0

Agent Executor (AX) is Google's open agentic orchestration runtime

Go

Introduce GARService and controller

JBD4cd3212a1b68
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..7fd6df1
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,2 @@
+bin/*
+eventlog/*
\ No newline at end of file
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..261eeb9
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright [yyyy] [name of copyright owner]
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000..7e22f31
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,58 @@
+.PHONY: all build proto test clean install
+
+# Build all binaries
+all: proto build
+
+# Build binaries
+build:
+ @echo "Building gar..."
+ @mkdir -p bin
+ @go build -o bin/gar cmd/gar/main.go
+ @echo "Building local agent example..."
+ @go build -o bin/local_agent examples/local_agent/main.go
+ @echo "Building remote agent example..."
+ @go build -o bin/remote_agent examples/remote_agent/main.go
+ @echo "Build complete!"
+
+# Generate protobuf code
+proto:
+ @echo "Generating protobuf code..."
+ @export PATH=$$PATH:$$(go env GOPATH)/bin && \
+ protoc --go_out=. --go_opt=paths=source_relative \
+ --go-grpc_out=. --go-grpc_opt=paths=source_relative \
+ proto/gar.proto
+ @echo "Protobuf generation complete!"
+
+# Run tests
+test:
+ @echo "Running tests..."
+ @go test -v ./...
+
+# Clean build artifacts
+clean:
+ @echo "Cleaning..."
+ @rm -rf bin/
+ @rm -rf eventlog/
+ @echo "Clean complete!"
+
+# Install gar to GOPATH/bin
+install:
+ @echo "Installing gar..."
+ @go install ./cmd/gar
+ @echo "Install complete!"
+
+# Run local agent example
+run-local:
+ @go run examples/local_agent/main.go
+
+# Run remote agent example
+run-remote:
+ @go run examples/remote_agent/main.go
+
+# Install dependencies
+deps:
+ @echo "Installing dependencies..."
+ @go mod download
+ @go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
+ @go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
+ @echo "Dependencies installed!"
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..866fec3
--- /dev/null
+++ b/README.md
@@ -0,0 +1,463 @@
+# gar
+
+GAR, a short for Google Agent Runtime, is a single-writer agent orchestrator system built in Go. It provides a controller that coordinates agentic loops, manages sessions with event logging, and communicates with both local and remote agents via streaming protocols.
+
+## Features
+
+- **Streaming**: gRPC bidirectional streaming for agent communication
+- **Local & Remote Agents**: Support for both in-process and remote agent deployment
+- **Session Management**: Start, pause, resume, and inspect agentic loop sessions
+- **Agent Registry**: Automatic health monitoring and agent discovery
+
+Built-in consistency and resumability features:
+- **Single-Writer Architecture**: Centralized controller ensures consistent state management
+- **Event Log**: Durable session state with automatic recovery
+- **Lifecycle Events**: PROGRESS and HEARTBEAT events for monitoring agent health
+
+## Overview
+
+```
+┌────────────────────────┐
+│ [Controller] │
+│ - Session Manager │
+│ - Event Log │
+│ - Loop Executor │
+│ - Agent Registry │
+└──────┬──────────┬──────┘
+ │ │
+ (in-process) (gRPC stream)
+ │ │
+ ┌───────┐ ┌───────┐
+ │ Local │ │Remote │
+ │ Agent │ │ Agent │
+ └───────┘ └───────┘
+```
+
+## Installation
+
+Install the gar CLI directly from the repository:
+
+```bash
+go install github.com/google/gar/cmd/gar@latest
+```
+
+### Verify Installation
+
+Check that gar is installed correctly:
+
+```bash
+gar --help
+```
+
+You should see the gar CLI usage information.
+
+## Quick Start
+
+### 1. Run Local Agent Example
+
+```bash
+# Run the local agent example by linking the local agent with controller.
+go run examples/local_agent/main.go
+```
+
+### 2. Run Remote Agent with GAR Server
+
+This example demonstrates how the gar server triggers remote agents through the
+AgentService.Process RPC.
+
+**Terminal 1** - Start the remote agent server:
+```bash
+go run examples/remote_agent/main.go
+```
+
+The remote agent runs as a gRPC server implementing AgentService on port :50051.
+
+**Terminal 2** - Start the gar controller server:
+```bash
+gar serve --addr :8494
+```
+
+The gar server exposes the GARService on port :8494.
+
+**Terminal 3** - Register the remote agent and trigger a session:
+```bash
+# Register the remote agent with gar
+gar register \
+ --server localhost:8494 \
+ --agent-id remote-echo-agent \
+ --name "Echo Agent" \
+ --description "Echoes input in uppercase" \
+ --agent-addr localhost:50051
+
+# Trigger a session - gar will trigger the remote agent via Process RPC
+gar trigger \
+ --server localhost:8494 \
+ --session-id session123 \
+ --input "Hello remote agent"
+
+# List all sessions
+gar list --server localhost:8494
+
+# Inspect session details
+gar inspect --server localhost:8494 --session-id session123
+```
+
+When you start a session, the gar controller:
+1. Receives your session request
+2. Calls the remote agent's `Process` RPC (bidirectional streaming)
+3. Streams input content to the agent
+4. Receives output content back from the agent
+5. Logs everything to the event log
+
+## Usage
+
+### GAR CLI
+
+The `gar` command provides several subcommands:
+
+#### Trigger a Session
+
+```bash
+gar trigger \
+ --server <address> \
+ [--session-id <id>] \
+ [--input <text>] \
+ [--checkpoint <uuid>]
+```
+
+Triggers a new agentic loop session or automatically resumes an existing one. If the session ID already exists, the session will be resumed from its last checkpoint (or a specific checkpoint if provided) with optional new inputs.
+
+Options:
+- `--server`: gRPC controller server address (e.g., "localhost:8494") (required)
+- `--session-id`: Unique session identifier (optional, generates UUID if not provided, or resumes if exists)
+- `--input`: Input message to send to agents
+- `--checkpoint`: Resume from specific checkpoint (empty for latest)
+
+**Examples:**
+
+```bash
+# Trigger a new session
+gar trigger --server localhost:8494 --input "Hello agent"
+
+# Resume an existing session with new input
+gar trigger --server localhost:8494 --session-id abc123 \
+ --input "Continue processing"
+
+# Resume from a specific checkpoint (useful for undoing mistakes or exploring alternatives)
+gar trigger --server localhost:8494 --session-id abc123 \
+ --checkpoint "550e8400-e29b-41d4-a716-446655440000" \
+ --input "Try a different approach"
+```
+
+#### List All Sessions
+
+```bash
+gar list --server <address>
+```
+
+Shows all sessions from the controller server.
+
+Options:
+- `--server`: gRPC controller server address (e.g., "localhost:8494") (required)
+
+#### Inspect a Session
+
+```bash
+gar inspect --server <address> --session-id <id>
+```
+
+Displays session details including:
+- Current state and step
+- Message count
+- Checkpoints
+- Active agents
+
+Options:
+- `--server`: gRPC controller server address (e.g., "localhost:8494") (required)
+- `--session-id`: Session identifier to inspect (required)
+
+#### Register a Remote Agent
+
+```bash
+gar register \
+ --server <address> \
+ --agent-id <id> \
+ --agent-addr <address> \
+ [--name <name>] \
+ [--description <desc>]
+```
+
+Options:
+- `--server`: gRPC controller server address (e.g., "localhost:8494") (required)
+- `--agent-id`: Unique agent identifier (required)
+- `--agent-addr`: gRPC agent server address (e.g., "localhost:50051") (required)
+- `--name`: Human-readable name for the agent
+- `--description`: Description of agent capabilities
+
+#### Run Controller Server
+
+```bash
+gar serve [--addr <address>] [--eventlog-dir <dir>]
+```
+
+Starts the controller as a gRPC server, exposing the GARService API for remote session management and agent registration.
+
+Options:
+- `--addr`: Server address to listen on (default: ":8494")
+- `--eventlog-dir`: Directory for event log files (default: "eventlog")
+
+Example:
+```bash
+# Start server on default port
+gar serve
+
+# Start server on custom port
+gar serve --addr :8080
+```
+
+Once running, clients can connect to the server to:
+- Start and resume sessions remotely
+- Query session status and list sessions
+- Register and unregister agents dynamically
+
+### Checkpoints
+
+Checkpoints provide a mechanism to save and resume session state at specific points. Every content event (both `CONTENT_IN` and `CONTENT_OUT`) automatically creates a checkpoint with a unique UUID.
+
+**Usage Examples:**
+
+```bash
+# Inspect a session to see available checkpoints
+gar inspect --server localhost:8494 --session-id session123
+
+# Resume from a specific checkpoint
+gar trigger --server localhost:8494 --session-id session123 \
+ --checkpoint "550e8400-e29b-41d4-a716-446655440000" \
+ --input "Try different approach"
+```
+
+
+### Event Log Format
+
+Event logs use JSON Lines format (one JSON object per line). Each entry includes the session ID and checkpoint ID (for content events) for traceability:
+
+```json
+{"session_id": "session123", "timestamp": "2026-01-02T10:30:00Z", "type": "CONTENT_IN", "checkpoint_id": "550e8400-e29b-41d4-a716-446655440000", "data": {...}}
+{"session_id": "session123", "timestamp": "2026-01-02T10:30:01Z", "type": "CONTENT_OUT", "checkpoint_id": "6ba7b810-9dad-11d1-80b4-00c04fd430c8", "data": {...}}
+{"session_id": "session123", "timestamp": "2026-01-02T10:30:02Z", "type": "LIFECYCLE", "data": {...}}
+```
+
+**Event Types:**
+- `CONTENT_IN`: Incoming content from user or external source (includes `checkpoint_id`)
+- `CONTENT_OUT`: Outgoing content from agents (includes `checkpoint_id`)
+- `LIFECYCLE`: Agent lifecycle events (no checkpoint)
+
+## Building Custom Agents
+
+### Local Agent
+
+```go
+import (
+ "context"
+ "github.com/google/gar/agent"
+ "github.com/google/gar/proto"
+)
+
+// Define your process function using callback handler
+processFunc := func(ctx context.Context, inputs []*proto.Content, handler agent.OutputHandler) error {
+ for _, content := range inputs {
+ output := &proto.Content{
+ Role: "assistant",
+ Type: "text",
+ Mimetype: "text/plain",
+ Data: "Your response: " + content.Data,
+ }
+ if err := handler(output); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// Define lifecycle function (optional)
+lifecycleFunc := func(ctx context.Context, handler agent.LifecycleHandler) error {
+ // Send lifecycle events via handler callback
+ return handler(&proto.LifecycleEvent{
+ EventType: "PROGRESS",
+ AgentId: "my-agent",
+ Timestamp: time.Now().UnixMilli(),
+ Metadata: map[string]string{"status": "processing"},
+ })
+}
+
+// Define health check function (optional)
+healthCheckFunc := func(ctx context.Context) error {
+ // Return nil if healthy, error otherwise
+ return nil
+}
+
+// Create the agent
+myAgent, err := agent.NewLocalAgent(agent.LocalAgentConfig{
+ ID: "my-agent",
+ ProcessFunc: processFunc,
+ LifecycleFunc: lifecycleFunc, // optional
+ HealthCheckFunc: healthCheckFunc, // optional
+})
+```
+
+### Remote Agent
+
+Remote agents run as gRPC servers implementing the `AgentService` interface defined in `proto/gar.proto`. The gar controller triggers remote agents by calling their `Process` RPC with bidirectional streaming.
+
+```go
+type server struct {
+ proto.UnimplementedAgentServiceServer
+}
+
+// Process handles bidirectional streaming - gar controller calls this RPC
+func (s *server) Process(stream proto.AgentService_ProcessServer) error {
+ for {
+ // Receive input content from gar controller
+ content, err := stream.Recv()
+ if err == io.EOF {
+ return nil
+ }
+ if err != nil {
+ return err
+ }
+
+ // Process the content
+ output := &proto.Content{
+ Role: "assistant",
+ Type: "text",
+ Mimetype: "text/plain",
+ Data: "Processed: " + content.Data,
+ }
+
+ // Send response back to gar controller
+ if err := stream.Send(output); err != nil {
+ return err
+ }
+ }
+}
+
+func (s *server) StreamLifecycle(stream proto.AgentService_StreamLifecycleServer) error {
+ // Stream lifecycle events to gar controller
+ // Send periodic PROGRESS, HEARTBEAT events
+}
+
+func (s *server) HealthCheck(ctx context.Context, req *proto.HealthCheckRequest) (*proto.HealthCheckResponse, error) {
+ // Return health status for gar controller health monitoring
+ return &proto.HealthCheckResponse{
+ Healthy: true,
+ Message: "Agent is healthy",
+ }, nil
+}
+```
+
+**Workflow:**
+1. Remote agent starts as gRPC server on a port (e.g., :50051)
+2. Start gar controller: `gar serve --addr :8494`
+3. Register with gar: `gar register --server localhost:8494 --agent-id my-agent --name "My Agent" --description "Agent description" --agent-addr localhost:50051`
+4. When gar triggers a session, it calls the agent's `Process` RPC
+5. GAR streams input content → Agent processes → Agent streams output back
+
+See `examples/remote_agent/main.go` for a complete implementation.
+
+### Remote Python Agent
+
+Python agents can be built using the GAR agent framework. First, install dependencies and generate Python gRPC code:
+
+```bash
+# Install dependencies
+pip install grpcio grpcio-tools
+
+# Generate Python code from proto file
+python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. proto/gar.proto
+```
+
+Then implement your agent using the framework:
+
+```python
+from gar import Agent
+import proto.gar_pb2 as pb2
+
+def process(content):
+ """Process incoming content and return response"""
+ return pb2.Content(
+ role="assistant",
+ type="text",
+ mimetype="text/plain",
+ data=f"Python processed: {content.data.upper()}"
+ )
+
+# Create and start the agent
+agent = Agent(agent_id="python-agent", process_func=process)
+agent.serve(port=50051)
+```
+
+**Register and use:**
+```bash
+# Start the Python agent
+python agent.py
+
+# Register with gar (in another terminal)
+gar register \
+ --server localhost:8494 \
+ --agent-id python-agent \
+ --name "Python Agent" \
+ --description "Python-based agent" \
+ --agent-addr localhost:50051
+
+# Trigger a session
+gar trigger \
+ --server localhost:8494 \
+ --session-id session123 \
+ --input "Hello Python agent"
+```
+
+## Development
+
+### Generate Protobuf Code
+
+```bash
+make proto
+```
+
+### Run Tests
+
+```bash
+make test
+```
+
+### Clean Build Artifacts
+
+```bash
+make clean
+```
+
+## Future Enhancements
+
+- [ ] Remote agent deployment from a container image
+- [ ] Observability
+- [ ] TLS support for remote agents
+- [ ] Advanced load balancing strategies
+- [ ] Make checkpointing optional
+- [ ] Web UI
+
+## License
+
+Apache 2.0
+
+## Behind the name
+
+In chess, the most powerful piece was originally called the
+[gar](https://en.wikipedia.org/wiki/Queen_(chess)#History)
+before it was renamed to "queen" in Europe. This piece moves
+freely across the board, coordinating the entire position
+and executing strategic plans.
+
+Similarly, GAR orchestrator acts as a powerful coordinator - not
+the primary decision-maker, but rather the executor that manages
+and coordinates multiple agents to fulfill tasks and respond
+to input, typically from humans.
diff --git a/agent/agent.go b/agent/agent.go
new file mode 100644
index 0000000..5060801
--- /dev/null
+++ b/agent/agent.go
@@ -0,0 +1,41 @@
+// Package agent provides interfaces and implementations for local and remote agents.
+// Agents process content through callback handlers and can be registered with the dispatcher.
+package agent
+
+import (
+ "context"
+
+ "github.com/google/gar/proto"
+)
+
+// OutputHandler is a callback function that handles output content from an agent.
+// It is called for each piece of content the agent generates.
+type OutputHandler func(content *proto.Content) error
+
+// LifecycleHandler is a callback function that handles lifecycle events from an agent.
+// It is called for each lifecycle event the agent emits.
+type LifecycleHandler func(event *proto.LifecycleEvent) error
+
+// Agent defines the common interface for both local and remote agents.
+// Agents process content and emit lifecycle events using callback handlers.
+type Agent interface {
+ // Process handles processing of input content.
+ // It calls the output handler for each piece of content generated.
+ // The handler may be called multiple times during processing.
+ Process(ctx context.Context, inputs []*proto.Content, handler OutputHandler) error
+
+ // StreamLifecycle streams lifecycle events from the agent.
+ // It calls the handler for each lifecycle event emitted.
+ // This method runs until the context is cancelled.
+ StreamLifecycle(ctx context.Context, handler LifecycleHandler) error
+
+ // HealthCheck checks if the agent is healthy and responsive.
+ // Returns an error if the agent is unhealthy or unreachable.
+ HealthCheck(ctx context.Context) error
+
+ // ID returns the unique identifier for this agent.
+ ID() string
+
+ // Close gracefully shuts down the agent and releases resources.
+ Close() error
+}
diff --git a/agent/local.go b/agent/local.go
new file mode 100644
index 0000000..96f9dbb
--- /dev/null
+++ b/agent/local.go
@@ -0,0 +1,79 @@
+package agent
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/google/gar/proto"
+)
+
+// LocalAgent wraps a local (in-process) agent implementation.
+// It implements the Agent interface for agents running in the same process as the dispatcher.
+type LocalAgent struct {
+ id string
+ processFunc func(ctx context.Context, inputs []*proto.Content, handler OutputHandler) error
+ lifecycleFunc func(ctx context.Context, handler LifecycleHandler) error
+ healthCheckFunc func(ctx context.Context) error
+}
+
+// LocalAgentConfig configures a local agent.
+type LocalAgentConfig struct {
+ ID string
+ ProcessFunc func(ctx context.Context, inputs []*proto.Content, handler OutputHandler) error
+ LifecycleFunc func(ctx context.Context, handler LifecycleHandler) error
+ HealthCheckFunc func(ctx context.Context) error
+}
+
+// NewLocalAgent creates a new local agent with the provided configuration.
+func NewLocalAgent(config LocalAgentConfig) (*LocalAgent, error) {
+ if config.ID == "" {
+ return nil, fmt.Errorf("agent ID cannot be empty")
+ }
+ if config.ProcessFunc == nil {
+ return nil, fmt.Errorf("ProcessFunc cannot be nil")
+ }
+
+ // Provide defaults for optional functions
+ if config.HealthCheckFunc == nil {
+ config.HealthCheckFunc = func(ctx context.Context) error { return nil }
+ }
+ if config.LifecycleFunc == nil {
+ config.LifecycleFunc = func(ctx context.Context, handler LifecycleHandler) error {
+ // Default: no lifecycle events
+ return nil
+ }
+ }
+
+ return &LocalAgent{
+ id: config.ID,
+ processFunc: config.ProcessFunc,
+ lifecycleFunc: config.LifecycleFunc,
+ healthCheckFunc: config.HealthCheckFunc,
+ }, nil
+}
+
+// Process handles processing of input content with callback handler.
+func (a *LocalAgent) Process(ctx context.Context, inputs []*proto.Content, handler OutputHandler) error {
+ return a.processFunc(ctx, inputs, handler)
+}
+
+// StreamLifecycle streams lifecycle events using callback handler.
+func (a *LocalAgent) StreamLifecycle(ctx context.Context, handler LifecycleHandler) error {
+ return a.lifecycleFunc(ctx, handler)
+}
+
+// HealthCheck checks if the agent is healthy.
+func (a *LocalAgent) HealthCheck(ctx context.Context) error {
+ return a.healthCheckFunc(ctx)
+}
+
+// ID returns the unique identifier for this agent.
+func (a *LocalAgent) ID() string {
+ return a.id
+}
+
+// Close gracefully shuts down the agent.
+func (a *LocalAgent) Close() error {
+ // Local agents don't typically need cleanup, but this can be extended
+ return nil
+}
diff --git a/agent/remote.go b/agent/remote.go
new file mode 100644
index 0000000..b574b2e
--- /dev/null
+++ b/agent/remote.go
@@ -0,0 +1,196 @@
+package agent
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "sync"
+ "time"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials/insecure"
+
+ "github.com/google/gar/proto"
+)
+
+// RemoteAgent is a gRPC client that implements the Agent interface.
+// It communicates with remote agent services over gRPC.
+type RemoteAgent struct {
+ id string
+ address string
+ conn *grpc.ClientConn
+ client proto.AgentServiceClient
+ mu sync.Mutex
+ reconnect bool
+ maxRetries int
+ dialOpts []grpc.DialOption
+}
+
+// RemoteAgentConfig configures a remote agent client.
+type RemoteAgentConfig struct {
+ ID string
+ Address string // gRPC server address (e.g., "localhost:50051")
+ Reconnect bool // Whether to automatically reconnect on failures
+ MaxRetries int // Maximum number of retry attempts (0 = infinite)
+ DialOpts []grpc.DialOption // gRPC dial options for customizing the connection
+}
+
+// NewRemoteAgent creates a new remote agent client.
+func NewRemoteAgent(config RemoteAgentConfig) (*RemoteAgent, error) {
+ if config.ID == "" {
+ return nil, fmt.Errorf("agent ID cannot be empty")
+ }
+ if config.Address == "" {
+ return nil, fmt.Errorf("agent address cannot be empty")
+ }
+
+ agent := &RemoteAgent{
+ id: config.ID,
+ address: config.Address,
+ reconnect: config.Reconnect,
+ maxRetries: config.MaxRetries,
+ dialOpts: config.DialOpts,
+ }
+
+ if err := agent.connect(); err != nil {
+ return nil, fmt.Errorf("failed to connect to remote agent: %w", err)
+ }
+
+ return agent, nil
+}
+
+// connect establishes a gRPC connection to the remote agent.
+func (a *RemoteAgent) connect() error {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+
+ if a.conn != nil {
+ a.conn.Close()
+ }
+
+ // Use provided dial options, or default to insecure credentials
+ opts := a.dialOpts
+ if len(opts) == 0 {
+ opts = []grpc.DialOption{grpc.WithTransportCredentials(insecure.NewCredentials())}
+ }
+
+ conn, err := grpc.NewClient(a.address, opts...)
+ if err != nil {
+ return fmt.Errorf("failed to dial: %w", err)
+ }
+
+ a.conn = conn
+ a.client = proto.NewAgentServiceClient(conn)
+ return nil
+}
+
+// Process handles processing of input content with the remote agent.
+func (a *RemoteAgent) Process(ctx context.Context, inputs []*proto.Content, handler OutputHandler) error {
+ stream, err := a.client.Process(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to create stream: %w", err)
+ }
+
+ // Send all inputs to the remote agent
+ for _, content := range inputs {
+ if err := stream.Send(content); err != nil {
+ return fmt.Errorf("failed to send content: %w", err)
+ }
+ }
+
+ // Close the send direction to signal we're done sending
+ if err := stream.CloseSend(); err != nil {
+ return fmt.Errorf("failed to close send: %w", err)
+ }
+
+ // Receive outputs and call handler for each
+ for {
+ content, err := stream.Recv()
+ if err == io.EOF {
+ // Stream completed successfully
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("failed to receive content: %w", err)
+ }
+
+ // Call the handler with the received content
+ if err := handler(content); err != nil {
+ return fmt.Errorf("handler error: %w", err)
+ }
+
+ // Check for context cancellation
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+ }
+}
+
+// StreamLifecycle streams lifecycle events from the remote agent.
+func (a *RemoteAgent) StreamLifecycle(ctx context.Context, handler LifecycleHandler) error {
+ stream, err := a.client.StreamLifecycle(ctx)
+ if err != nil {
+ return fmt.Errorf("failed to create lifecycle stream: %w", err)
+ }
+
+ // Receive lifecycle events and call handler for each
+ for {
+ event, err := stream.Recv()
+ if err == io.EOF {
+ // Stream completed successfully
+ return nil
+ }
+ if err != nil {
+ return fmt.Errorf("failed to receive lifecycle event: %w", err)
+ }
+
+ // Call the handler with the received event
+ if err := handler(event); err != nil {
+ return fmt.Errorf("handler error: %w", err)
+ }
+
+ // Check for context cancellation
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+ }
+}
+
+// HealthCheck checks if the remote agent is healthy.
+func (a *RemoteAgent) HealthCheck(ctx context.Context) error {
+ ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
+ defer cancel()
+
+ resp, err := a.client.HealthCheck(ctx, &proto.HealthCheckRequest{
+ AgentId: a.id,
+ })
+ if err != nil {
+ return fmt.Errorf("health check failed: %w", err)
+ }
+
+ if !resp.Healthy {
+ return fmt.Errorf("agent unhealthy: %s", resp.Message)
+ }
+
+ return nil
+}
+
+// ID returns the unique identifier for this agent.
+func (a *RemoteAgent) ID() string {
+ return a.id
+}
+
+// Close gracefully shuts down the remote agent connection.
+func (a *RemoteAgent) Close() error {
+ a.mu.Lock()
+ defer a.mu.Unlock()
+
+ if a.conn != nil {
+ return a.conn.Close()
+ }
+ return nil
+}
diff --git a/cmd/gar/main.go b/cmd/gar/main.go
new file mode 100644
index 0000000..2f5a27d
--- /dev/null
+++ b/cmd/gar/main.go
@@ -0,0 +1,337 @@
+// Gar is a CLI tool for managing agent orchestrator sessions.
+// It provides commands to trigger sessions, resume from checkpoints,
+// inspect session state, register agents, and run the controller server.
+package main
+
+import (
+ "context"
+ "flag"
+ "fmt"
+ "io"
+ "os"
+ "os/signal"
+ "syscall"
+ "time"
+
+ "google.golang.org/grpc"
+ "google.golang.org/grpc/credentials/insecure"
+
+ "github.com/google/uuid"
+ "github.com/google/gar/internal/controller"
+ "github.com/google/gar/internal/eventlog"
+ "github.com/google/gar/internal/server"
+ "github.com/google/gar/proto"
+)
+
+var (
+ command string
+ sessionID string
+ eventLogDir string
+ input string
+ checkpointID string
+ agentID string
+ agentName string
+ agentDescription string
+ agentAddr string
+ serveAddr string
+ serverAddr string // gRPC controller server address
+)
+
+func main() {
+ // Define subcommands
+ triggerCmd := flag.NewFlagSet("trigger", flag.ExitOnError)
+ inspectCmd := flag.NewFlagSet("inspect", flag.ExitOnError)
+ registerCmd := flag.NewFlagSet("register", flag.ExitOnError)
+ serveCmd := flag.NewFlagSet("serve", flag.ExitOnError)
+
+ // Trigger command flags
+ triggerCmd.StringVar(&sessionID, "session-id", "", "Session ID (optional, generates UUID if not provided, or resumes existing)")
+ triggerCmd.StringVar(&input, "input", "", "Input message to send")
+ triggerCmd.StringVar(&checkpointID, "checkpoint", "", "Resume from specific checkpoint UUID (empty for latest)")
+ triggerCmd.StringVar(&serverAddr, "server", "", "gRPC controller server address (e.g., localhost:8494)")
+
+ // Inspect command flags
+ inspectCmd.StringVar(&sessionID, "session-id", "", "Session ID (required)")
+ inspectCmd.StringVar(&serverAddr, "server", "", "gRPC controller server address (e.g., localhost:8494)")
+
+ // Register command flags
+ registerCmd.StringVar(&agentID, "agent-id", "", "Agent ID (required)")
+ registerCmd.StringVar(&agentName, "name", "", "Agent name")
+ registerCmd.StringVar(&agentDescription, "description", "", "Agent description")
+ registerCmd.StringVar(&agentAddr, "agent-addr", "", "Agent address (e.g., localhost:50051)")
+ registerCmd.StringVar(&serverAddr, "server", "", "gRPC controller server address (e.g., localhost:8494)")
+
+ // Serve command flags
+ serveCmd.StringVar(&serveAddr, "addr", ":8494", "Server address to listen on")
+ serveCmd.StringVar(&eventLogDir, "eventlog-dir", "eventlog", "Event log directory")
+
+ if len(os.Args) < 2 {
+ printUsage()
+ os.Exit(1)
+ }
+
+ command = os.Args[1]
+
+ switch command {
+ case "trigger":
+ triggerCmd.Parse(os.Args[2:])
+ runTrigger()
+
+ case "inspect":
+ inspectCmd.Parse(os.Args[2:])
+ if sessionID == "" {
+ fmt.Println("Error: --session-id is required")
+ inspectCmd.Usage()
+ os.Exit(1)
+ }
+ runInspect()
+
+ case "register":
+ registerCmd.Parse(os.Args[2:])
+ if agentID == "" || agentAddr == "" {
+ fmt.Println("Error: --agent-id and --agent-addr are required")
+ registerCmd.Usage()
+ os.Exit(1)
+ }
+ runRegister()
+
+ case "serve":
+ serveCmd.Parse(os.Args[2:])
+ runServe()
+
+ default:
+ printUsage()
+ os.Exit(1)
+ }
+}
+
+func eventLogFactory(sessionID, eventLogDir string) controller.EventLogFactory {
+ return func(sessionID string) (eventlog.EventLog, error) {
+ return eventlog.NewFileEventLog(eventlog.FileConfig{
+ SessionID: sessionID,
+ Dir: eventLogDir,
+ })
+ }
+}
+
+// connectToServer creates a gRPC client connection to the controller server.
+func connectToServer() (proto.GARServiceClient, *grpc.ClientConn, error) {
+ conn, err := grpc.NewClient(serverAddr, grpc.WithTransportCredentials(insecure.NewCredentials()))
+ if err != nil {
+ return nil, nil, fmt.Errorf("failed to connect to server: %w", err)
+ }
+ client := proto.NewGARServiceClient(conn)
+ return client, conn, nil
+}
+
+func printUsage() {
+ fmt.Println("Usage: gar <command> [options]")
+ fmt.Println()
+ fmt.Println("Commands:")
+ fmt.Println(" trigger Trigger a new session or resume an existing one")
+ fmt.Println(" list List all sessions")
+ fmt.Println(" inspect Inspect a session")
+ fmt.Println(" register Register a remote agent")
+ fmt.Println(" serve Run controller as a gRPC server")
+ fmt.Println()
+ fmt.Println("Use 'gar <command> -h' for more information about a command.")
+}
+
+func runTrigger() {
+ // Require server address
+ if serverAddr == "" {
+ fmt.Println("Error: --server flag is required")
+ os.Exit(1)
+ }
+
+ // Generate UUID if no session ID provided
+ if sessionID == "" {
+ sessionID = uuid.New().String()
+ fmt.Printf("Generated session ID: %s\n", sessionID)
+ }
+
+ fmt.Printf("Triggering session: %s\n", sessionID)
+
+ // Create input content
+ var inputs []*proto.Content
+ if input != "" {
+ inputs = []*proto.Content{
+ {
+ Role: "user",
+ Type: "text",
+ Mimetype: "text/plain",
+ Data: input,
+ },
+ }
+ }
+
+ // Setup signal handling for graceful shutdown
+ ctx, cancel := context.WithCancel(context.Background())
+ defer cancel()
+
+ sigChan := make(chan os.Signal, 1)
+ signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
+
+ go func() {
+ <-sigChan
+ fmt.Println("\nReceived interrupt, shutting down...")
+ cancel()
+ }()
+
+ // Connect to gRPC server
+ client, conn, err := connectToServer()
+ if err != nil {
+ fmt.Printf("Error connecting to server: %v\n", err)
+ os.Exit(1)
+ }
+ defer conn.Close()
+
+ stream, err := client.TriggerSession(ctx, &proto.TriggerSessionRequest{
+ SessionId: sessionID,
+ Inputs: inputs,
+ CheckpointId: checkpointID,
+ })
+ if err != nil {
+ fmt.Printf("Error triggering session: %v\n", err)
+ os.Exit(1)
+ }
+
+ // Receive and print all responses
+ for {
+ resp, err := stream.Recv()
+ if err == io.EOF {
+ break
+ }
+ if err != nil {
+ fmt.Printf("Error receiving response: %v\n", err)
+ os.Exit(1)
+ }
+
+ if resp.Output != nil {
+ fmt.Printf("[%s] %s\n", resp.State, resp.Output.Data)
+ }
+ }
+
+ fmt.Println("Session completed successfully")
+}
+
+func runInspect() {
+ // Require server address
+ if serverAddr == "" {
+ fmt.Println("Error: --server flag is required")
+ os.Exit(1)
+ }
+
+ fmt.Printf("Inspecting session: %s\n", sessionID)
+
+ // Connect to gRPC server
+ client, conn, err := connectToServer()
+ if err != nil {
+ fmt.Printf("Error connecting to server: %v\n", err)
+ os.Exit(1)
+ }
+ defer conn.Close()
+
+ // Get session details
+ resp, err := client.GetSession(context.Background(), &proto.GetSessionRequest{
+ SessionId: sessionID,
+ })
+ if err != nil {
+ fmt.Printf("Error getting session: %v\n", err)
+ os.Exit(1)
+ }
+
+ session := resp.Session
+
+ // Print session details
+ fmt.Println("\nSession Details:")
+ fmt.Printf(" ID: %s\n", session.SessionId)
+ fmt.Printf(" State: %s\n", session.State)
+ fmt.Printf(" Current Step: %d\n", session.CurrentStep)
+ fmt.Printf(" Created At: %s\n", time.UnixMilli(session.CreatedAt).Format(time.RFC3339))
+ fmt.Printf(" Updated At: %s\n", time.UnixMilli(session.UpdatedAt).Format(time.RFC3339))
+ fmt.Printf(" Message Count: %d\n", session.MessageCount)
+ fmt.Printf(" Checkpoints: %d\n", session.CheckpointCount)
+ fmt.Printf(" Active Agents: %v\n", session.ActiveAgents)
+}
+
+func runRegister() {
+ // Require server address
+ if serverAddr == "" {
+ fmt.Println("Error: --server flag is required")
+ os.Exit(1)
+ }
+
+ fmt.Printf("Registering agent: %s at %s\n", agentID, agentAddr)
+ if agentName != "" {
+ fmt.Printf(" Name: %s\n", agentName)
+ }
+ if agentDescription != "" {
+ fmt.Printf(" Description: %s\n", agentDescription)
+ }
+
+ // Connect to gRPC server
+ client, conn, err := connectToServer()
+ if err != nil {
+ fmt.Printf("Error connecting to server: %v\n", err)
+ os.Exit(1)
+ }
+ defer conn.Close()
+
+ // Register remote agent
+ _, err = client.RegisterAgent(context.Background(), &proto.RegisterAgentRequest{
+ AgentId: agentID,
+ AgentType: "remote",
+ Name: agentName,
+ Description: agentDescription,
+ Address: agentAddr,
+ })
+ if err != nil {
+ fmt.Printf("Error registering agent: %v\n", err)
+ os.Exit(1)
+ }
+
+ fmt.Println("Agent registered successfully")
+}
+
+func runServe() {
+ fmt.Printf("Starting controller server on %s\n", serveAddr)
+
+ c, err := newController()
+ if err != nil {
+ fmt.Printf("Error creating controller: %v\n", err)
+ os.Exit(1)
+ }
+ defer c.Close()
+
+ // Create server
+ srv := server.New(c)
+
+ // Setup signal handling for graceful shutdown
+ sigChan := make(chan os.Signal, 1)
+ signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
+
+ go func() {
+ <-sigChan
+ fmt.Println("\nReceived interrupt, shutting down...")
+ os.Exit(0)
+ }()
+
+ // Start serving
+ if err := srv.Serve(serveAddr); err != nil {
+ fmt.Printf("Error serving: %v\n", err)
+ os.Exit(1)
+ }
+}
+
+func newController() (*controller.Controller, error) {
+ c, err := controller.New(controller.Config{
+ EventLogFactory: eventLogFactory(sessionID, eventLogDir),
+ MaxSteps: 100,
+ HealthCheckInterval: 30 * time.Second,
+ })
+ if err != nil {
+ return nil, err
+ }
+ return c, nil
+}
diff --git a/examples/local_agent/main.go b/examples/local_agent/main.go
new file mode 100644
index 0000000..f1203ee
--- /dev/null
+++ b/examples/local_agent/main.go
@@ -0,0 +1,169 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/google/gar/agent"
+ "github.com/google/gar/internal/controller"
+ "github.com/google/gar/internal/eventlog"
+ "github.com/google/gar/proto"
+)
+
+func main() {
+ fmt.Println("Local Agent Example")
+ fmt.Println("===================")
+
+ // Create a local echo agent
+ echoAgent, err := createEchoAgent("local-echo-agent")
+ if err != nil {
+ fmt.Printf("Error creating agent: %v\n", err)
+ return
+ }
+
+ // Create controller
+ c, err := controller.New(controller.Config{
+ EventLogFactory: func(sessionID string) (eventlog.EventLog, error) {
+ return eventlog.NewFileEventLog(eventlog.FileConfig{
+ SessionID: sessionID,
+ Dir: "eventlog",
+ })
+ },
+ MaxSteps: 10,
+ HealthCheckInterval: 30 * time.Second,
+ })
+ if err != nil {
+ fmt.Printf("Error creating controller: %v\n", err)
+ return
+ }
+ defer c.Close()
+
+ // Register the local agent
+ if err := c.Registry().RegisterLocal(echoAgent, "Echo Agent", "Simple echo agent that uppercases input", map[string]string{
+ "type": "echo",
+ "version": "1.0",
+ }); err != nil {
+ fmt.Printf("Error registering agent: %v\n", err)
+ return
+ }
+
+ fmt.Println("Agent registered successfully")
+
+ // Create input content
+ inputs := []*proto.Content{
+ {
+ Role: "user",
+ Type: "text",
+ Mimetype: "text/plain",
+ Data: "Hello, echo agent!",
+ },
+ }
+
+ // Trigger a session
+ sessionID := uuid.New().String()
+ fmt.Printf("\nTriggering session: %s\n", sessionID)
+
+ ctx := context.Background()
+ if err := c.TriggerSession(ctx, sessionID, inputs, ""); err != nil {
+ fmt.Printf("Error triggering session: %v\n", err)
+ return
+ }
+
+ fmt.Println("\nSession completed!")
+
+ // Inspect the session
+ session, err := c.GetSession(sessionID)
+ if err != nil {
+ fmt.Printf("Error getting session: %v\n", err)
+ return
+ }
+
+ fmt.Printf("\nSession state: %s\n", session.State)
+ fmt.Printf("Total messages: %d\n", len(session.MessageHistory))
+
+ fmt.Println("\nMessage history:")
+ for i, msg := range session.MessageHistory {
+ fmt.Printf(" %d. [%s] %s: %s\n", i+1, msg.Type, msg.Role, msg.Data)
+ }
+}
+
+// createEchoAgent creates a simple echo agent that repeats input with a prefix.
+func createEchoAgent(id string) (*agent.LocalAgent, error) {
+ processFunc := func(ctx context.Context, inputs []*proto.Content, handler agent.OutputHandler) error {
+ // Process each input and call handler with response
+ for _, content := range inputs {
+ // Echo the content back with a prefix
+ response := &proto.Content{
+ Role: "assistant",
+ Type: content.Type,
+ Mimetype: content.Mimetype,
+ Data: fmt.Sprintf("Echo: %s", strings.ToUpper(content.Data)),
+ }
+
+ // Call handler with the response
+ if err := handler(response); err != nil {
+ return err
+ }
+
+ // Check for context cancellation
+ select {
+ case <-ctx.Done():
+ return ctx.Err()
+ default:
+ }
+ }
+
+ return nil
+ }
+
+ lifecycleFunc := func(ctx context.Context, handler agent.LifecycleHandler) error {
+ // Send initial PROGRESS event
+ if err := handler(&proto.LifecycleEvent{
+ EventType: "PROGRESS",
+ AgentId: id,
+ Timestamp: time.Now().UnixMilli(),
+ Metadata: map[string]string{
+ "status": "started",
+ },
+ }); err != nil {
+ return err
+ }
+
+ // Send periodic heartbeats
+ ticker := time.NewTicker(5 * time.Second)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ if err := handler(&proto.LifecycleEvent{
+ EventType: "PROGRESS",
+ AgentId: id,
+ Timestamp: time.Now().UnixMilli(),
+ Metadata: map[string]string{
+ "status": "processing",
+ },
+ }); err != nil {
+ return err
+ }
+ case <-ctx.Done():
+ return ctx.Err()
+ }
+ }
+ }
+
+ healthCheckFunc := func(ctx context.Context) error {
+ // Always healthy
+ return nil
+ }
+
+ return agent.NewLocalAgent(agent.LocalAgentConfig{
+ ID: id,
+ ProcessFunc: processFunc,
+ LifecycleFunc: lifecycleFunc,
+ HealthCheckFunc: healthCheckFunc,
+ })
+}
diff --git a/examples/remote_agent/main.go b/examples/remote_agent/main.go
new file mode 100644
index 0000000..6892586
--- /dev/null
+++ b/examples/remote_agent/main.go
@@ -0,0 +1,146 @@
+package main
+
+import (
+ "context"
+ "fmt"
+ "io"
+ "log"
+ "net"
+ "strings"
+ "time"
+
+ "google.golang.org/grpc"
+
+ "github.com/google/gar/proto"
+)
+
+const port = ":50051"
+
+// server implements the AgentService gRPC server.
+type server struct {
+ proto.UnimplementedAgentServiceServer
+ agentID string
+}
+
+func newServer(agentID string) *server {
+ return &server{
+ agentID: agentID,
+ }
+}
+
+// Process implements bidirectional streaming for content processing.
+// This RPC is called by the gar dispatcher when a session triggers this agent.
+func (s *server) Process(stream proto.AgentService_ProcessServer) error {
+ log.Println("Process stream started - gar dispatcher connected")
+
+ for {
+ // Receive input content from gar dispatcher
+ content, err := stream.Recv()
+ if err == io.EOF {
+ log.Println("Process stream closed by gar dispatcher")
+ return nil
+ }
+ if err != nil {
+ log.Printf("Error receiving from dispatcher: %v", err)
+ return err
+ }
+
+ log.Printf("Received from dispatcher: role=%s, type=%s, data=%s",
+ content.Role, content.Type, content.Data)
+
+ // Process the content (simple uppercase echo)
+ response := &proto.Content{
+ Role: "assistant",
+ Type: content.Type,
+ Mimetype: content.Mimetype,
+ Data: fmt.Sprintf("Remote Echo: %s", strings.ToUpper(content.Data)),
+ }
+
+ // Send response back to gar dispatcher
+ if err := stream.Send(response); err != nil {
+ log.Printf("Error sending to dispatcher: %v", err)
+ return err
+ }
+
+ log.Printf("Sent to dispatcher: %s", response.Data)
+ }
+}
+
+// StreamLifecycle streams lifecycle events from the agent.
+func (s *server) StreamLifecycle(stream proto.AgentService_StreamLifecycleServer) error {
+ log.Println("Lifecycle stream started")
+
+ // Send initial PROGRESS event
+ if err := stream.Send(&proto.LifecycleEvent{
+ EventType: "PROGRESS",
+ AgentId: s.agentID,
+ Timestamp: time.Now().UnixMilli(),
+ Metadata: map[string]string{
+ "status": "started",
+ },
+ }); err != nil {
+ return err
+ }
+
+ // Send periodic heartbeats
+ ticker := time.NewTicker(10 * time.Second)
+ defer ticker.Stop()
+
+ for {
+ select {
+ case <-ticker.C:
+ event := &proto.LifecycleEvent{
+ EventType: "PROGRESS",
+ AgentId: s.agentID,
+ Timestamp: time.Now().UnixMilli(),
+ Metadata: map[string]string{
+ "status": "healthy",
+ },
+ }
+
+ if err := stream.Send(event); err != nil {
+ log.Printf("Error sending lifecycle event: %v", err)
+ return err
+ }
+
+ log.Println("Sent lifecycle event")
+
+ case <-stream.Context().Done():
+ log.Println("Lifecycle stream closed")
+ return nil
+ }
+ }
+}
+
+// HealthCheck checks if the agent is healthy.
+func (s *server) HealthCheck(ctx context.Context, req *proto.HealthCheckRequest) (*proto.HealthCheckResponse, error) {
+ log.Printf("Health check requested for agent: %s", req.AgentId)
+
+ return &proto.HealthCheckResponse{
+ Healthy: true,
+ Message: "Agent is healthy",
+ Metadata: map[string]string{
+ "agent_id": s.agentID,
+ "status": "running",
+ "uptime": "active",
+ },
+ }, nil
+}
+
+func main() {
+ agentID := "remote-echo-agent"
+
+ fmt.Printf("Listening on port: %s\n", port)
+ lis, err := net.Listen("tcp", port)
+ if err != nil {
+ log.Fatalf("Failed to listen: %v", err)
+ }
+
+ grpcServer := grpc.NewServer()
+ proto.RegisterAgentServiceServer(grpcServer, newServer(agentID))
+
+ fmt.Println("\nAgent server is running...")
+ if err := grpcServer.Serve(lis); err != nil {
+ log.Fatalf("Failed to serve: %v", err)
+ }
+}
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..a0a9195
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,16 @@
+module github.com/google/gar
+
+go 1.24.0
+
+require (
+ github.com/google/uuid v1.6.0
+ google.golang.org/grpc v1.78.0
+ google.golang.org/protobuf v1.36.11
+)
+
+require (
+ golang.org/x/net v0.48.0 // indirect
+ golang.org/x/sys v0.40.0 // indirect
+ golang.org/x/text v0.32.0 // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..492863b
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,36 @@
+github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
+github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
+github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
+github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek=
+github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps=
+github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
+github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
+go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
+go.opentelemetry.io/otel v1.38.0 h1:RkfdswUDRimDg0m2Az18RKOsnI8UDzppJAtj01/Ymk8=
+go.opentelemetry.io/otel v1.38.0/go.mod h1:zcmtmQ1+YmQM9wrNsTGV/q/uyusom3P8RxwExxkZhjM=
+go.opentelemetry.io/otel/metric v1.38.0 h1:Kl6lzIYGAh5M159u9NgiRkmoMKjvbsKtYRwgfrA6WpA=
+go.opentelemetry.io/otel/metric v1.38.0/go.mod h1:kB5n/QoRM8YwmUahxvI3bO34eVtQf2i4utNVLr9gEmI=
+go.opentelemetry.io/otel/sdk v1.38.0 h1:l48sr5YbNf2hpCUj/FoGhW9yDkl+Ma+LrVl8qaM5b+E=
+go.opentelemetry.io/otel/sdk v1.38.0/go.mod h1:ghmNdGlVemJI3+ZB5iDEuk4bWA3GkTpW+DOoZMYBVVg=
+go.opentelemetry.io/otel/sdk/metric v1.38.0 h1:aSH66iL0aZqo//xXzQLYozmWrXxyFkBJ6qT5wthqPoM=
+go.opentelemetry.io/otel/sdk/metric v1.38.0/go.mod h1:dg9PBnW9XdQ1Hd6ZnRz689CbtrUp0wMMs9iPcgT9EZA=
+go.opentelemetry.io/otel/trace v1.38.0 h1:Fxk5bKrDZJUH+AMyyIXGcFAPah0oRcT+LuNtJrmcNLE=
+go.opentelemetry.io/otel/trace v1.38.0/go.mod h1:j1P9ivuFsTceSWe1oY+EeW3sc+Pp42sO++GHkg4wwhs=
+golang.org/x/net v0.48.0 h1:zyQRTTrjc33Lhh0fBgT/H3oZq9WuvRR5gPC70xpDiQU=
+golang.org/x/net v0.48.0/go.mod h1:+ndRgGjkh8FGtu1w1FGbEC31if4VrNVMuKTgcAAnQRY=
+golang.org/x/sys v0.40.0 h1:DBZZqJ2Rkml6QMQsZywtnjnnGvHza6BTfYFWY9kjEWQ=
+golang.org/x/sys v0.40.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
+golang.org/x/text v0.32.0 h1:ZD01bjUt1FQ9WJ0ClOL5vxgxOI/sVCNgX1YtKwcY0mU=
+golang.org/x/text v0.32.0/go.mod h1:o/rUWzghvpD5TXrTIBuJU77MTaN0ljMWE47kxGJQ7jY=
+gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk=
+gonum.org/v1/gonum v0.16.0/go.mod h1:fef3am4MQ93R2HHpKnLk4/Tbh/s0+wqD5nfa6Pnwy4E=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b h1:Mv8VFug0MP9e5vUxfBcE3vUkV6CImK3cMNMIDFjmzxU=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20251222181119-0a764e51fe1b/go.mod h1:j9x/tPzZkyxcgEFkiKEEGxfvyumM01BEtsW8xzOahRQ=
+google.golang.org/grpc v1.78.0 h1:K1XZG/yGDJnzMdd/uZHAkVqJE+xIDOcmdSFZkBUicNc=
+google.golang.org/grpc v1.78.0/go.mod h1:I47qjTo4OKbMkjA/aOOwxDIiPSBofUtQUI5EfpWvW7U=
+google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
+google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
diff --git a/internal/controller/controller.go b/internal/controller/controller.go
new file mode 100644
index 0000000..02a8e72
--- /dev/null
+++ b/internal/controller/controller.go
@@ -0,0 +1,162 @@
+// Package controller implements the single-writer orchestrator that coordinates
+// agentic loops, manages sessions, and communicates with local and remote agents.
+package controller
+
+import (
+ "context"
+ "fmt"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/google/gar/proto"
+)
+
+// Controller is the main controller that coordinates all components.
+// It acts as a single-writer system for managing agentic loops.
+type Controller struct {
+ sessionManager *SessionManager
+ registry *Registry
+ loopExecutor *LoopExecutor
+}
+
+// Config configures the controller.
+type Config struct {
+ EventLogFactory EventLogFactory
+ PlanFunc PlanFunc
+ EvaluateFunc EvaluateFunc
+
+ HealthCheckInterval time.Duration
+ MaxSteps int
+}
+
+// New creates a new controller instance.
+func New(config Config) (*Controller, error) {
+ if config.MaxSteps == 0 {
+ config.MaxSteps = 100
+ }
+ if config.HealthCheckInterval == 0 {
+ config.HealthCheckInterval = 30 * time.Second
+ }
+
+ // Initialize session manager with file-based event logs
+ sessionManager := NewSessionManager(config.EventLogFactory)
+
+ // Initialize agent registry
+ registry := NewRegistry(config.HealthCheckInterval)
+
+ // Initialize loop executor
+ loopExecutor, err := NewLoopExecutor(LoopConfig{
+ Registry: registry,
+ SessionManager: sessionManager,
+ MaxSteps: config.MaxSteps,
+ PlanFunc: config.PlanFunc,
+ EvaluateFunc: config.EvaluateFunc,
+ })
+ if err != nil {
+ return nil, fmt.Errorf("failed to create loop executor: %w", err)
+ }
+
+ return &Controller{
+ sessionManager: sessionManager,
+ registry: registry,
+ loopExecutor: loopExecutor,
+ }, nil
+}
+
+// TriggerSession triggers a new agentic loop session or resumes an existing one.
+// If sessionID is empty, a UUID will be generated.
+// If the session already exists, it will be resumed with optional new inputs.
+// If checkpointID is provided, resumes from that specific checkpoint instead of the latest.
+func (d *Controller) TriggerSession(ctx context.Context, sessionID string, inputs []*proto.Content, checkpointID string) error {
+ // Generate UUID if no session ID provided
+ if sessionID == "" {
+ sessionID = uuid.New().String()
+ }
+
+ // Check if session already exists
+ existingSession, err := d.sessionManager.GetSession(sessionID)
+ if err == nil && existingSession != nil {
+ // Session exists - resume it from checkpoint
+ // If checkpoint ID specified, reload from that checkpoint
+ if checkpointID != "" {
+ existingSession, err = d.sessionManager.LoadSessionFromCheckpoint(sessionID, checkpointID)
+ if err != nil {
+ return fmt.Errorf("failed to load from checkpoint: %w", err)
+ }
+ }
+
+ // Add new inputs to the session if provided
+ for _, content := range inputs {
+ if _, err := existingSession.WriteContentIn(content); err != nil {
+ return fmt.Errorf("failed to write input content: %w", err)
+ }
+ }
+
+ // Resume the loop
+ if err := d.loopExecutor.Resume(ctx, sessionID); err != nil {
+ return fmt.Errorf("resume failed: %w", err)
+ }
+ return nil
+ }
+
+ // Session doesn't exist - create new session
+ // Checkpoint ID is ignored for new sessions
+ session, err := d.sessionManager.NewSession(sessionID)
+ if err != nil {
+ return fmt.Errorf("failed to create session: %w", err)
+ }
+
+ // Execute the loop
+ if err := d.loopExecutor.Execute(ctx, session.ID, inputs); err != nil {
+ return fmt.Errorf("execution failed: %w", err)
+ }
+
+ return nil
+}
+
+// GetSession retrieves a session by ID.
+func (d *Controller) GetSession(sessionID string) (*Session, error) {
+ return d.sessionManager.GetSession(sessionID)
+}
+
+// LoadSession loads a session from event log.
+func (d *Controller) LoadSession(sessionID string) (*Session, error) {
+ return d.sessionManager.LoadSession(sessionID)
+}
+
+// ListSessions returns all session IDs.
+func (d *Controller) ListSessions() ([]string, error) {
+ return d.sessionManager.ListSessions()
+}
+
+// CloseSession closes a session.
+func (d *Controller) CloseSession(sessionID string) error {
+ return d.sessionManager.CloseSession(sessionID)
+}
+
+// Registry returns the agent registry.
+func (d *Controller) Registry() *Registry {
+ return d.registry
+}
+
+// SessionManager returns the session manager.
+func (d *Controller) SessionManager() *SessionManager {
+ return d.sessionManager
+}
+
+// LoopExecutor returns the loop executor.
+func (d *Controller) LoopExecutor() *LoopExecutor {
+ return d.loopExecutor
+}
+
+// Close gracefully shuts down the controller.
+func (d *Controller) Close() error {
+ if err := d.registry.Close(); err != nil {
+ return fmt.Errorf("failed to close registry: %w", err)
+ }
+ sessions, _ := d.sessionManager.ListSessions()
+ for _, sessionID := range sessions {
+ _ = d.sessionManager.CloseSession(sessionID)
+ }
+ return nil
+}
diff --git a/internal/controller/loop.go b/internal/controller/loop.go
new file mode 100644
index 0000000..8b36b83
--- /dev/null
+++ b/internal/controller/loop.go
@@ -0,0 +1,272 @@
+package controller
+
+import (
+ "context"
+ "fmt"
+
+ "github.com/google/gar/agent"
+ "github.com/google/gar/proto"
+)
+
+// AgentTask represents a task to be executed by an agent.
+type AgentTask struct {
+ AgentID string
+ Input []*proto.Content
+ Goal string
+ StepIndex int
+}
+
+// LoopExecutor orchestrates the agentic loop workflow.
+// It implements the plan-execute-evaluate-checkpoint cycle.
+type LoopExecutor struct {
+ registry *Registry
+ sessionManager *SessionManager
+ maxSteps int
+ planFunc PlanFunc
+ evaluateFunc EvaluateFunc
+}
+
+// PlanFunc determines the next agent task to execute.
+// It receives the current session state and returns the next task.
+type PlanFunc func(session *Session) (*AgentTask, error)
+
+// EvaluateFunc evaluates the agent's response to determine if the goal is achieved.
+// Returns true if the goal is met and the loop should terminate.
+type EvaluateFunc func(session *Session, task *AgentTask, output []*proto.Content) (bool, error)
+
+// LoopConfig configures the loop executor.
+type LoopConfig struct {
+ Registry *Registry
+ SessionManager *SessionManager
+ MaxSteps int
+ PlanFunc PlanFunc
+ EvaluateFunc EvaluateFunc
+}
+
+// NewLoopExecutor creates a new loop executor.
+func NewLoopExecutor(config LoopConfig) (*LoopExecutor, error) {
+ if config.Registry == nil {
+ return nil, fmt.Errorf("registry cannot be nil")
+ }
+ if config.SessionManager == nil {
+ return nil, fmt.Errorf("session manager cannot be nil")
+ }
+ if config.MaxSteps == 0 {
+ config.MaxSteps = 100 // Default max steps
+ }
+
+ // Provide default plan function if not specified
+ if config.PlanFunc == nil {
+ config.PlanFunc = defaultPlanFunc(config.Registry)
+ }
+
+ // Provide default evaluate function if not specified
+ if config.EvaluateFunc == nil {
+ config.EvaluateFunc = defaultEvaluateFunc
+ }
+
+ return &LoopExecutor{
+ registry: config.Registry,
+ sessionManager: config.SessionManager,
+ maxSteps: config.MaxSteps,
+ planFunc: config.PlanFunc,
+ evaluateFunc: config.EvaluateFunc,
+ }, nil
+}
+
+// Execute starts a new agentic loop execution for the given session.
+func (e *LoopExecutor) Execute(ctx context.Context, sessionID string, inputs []*proto.Content) error {
+ // Get or create session
+ session, err := e.sessionManager.GetSession(sessionID)
+ if err != nil {
+ return fmt.Errorf("failed to get session: %w", err)
+ }
+
+ // Write input content to session
+ for _, content := range inputs {
+ if _, err := session.WriteContentIn(content); err != nil {
+ return fmt.Errorf("failed to write input content: %w", err)
+ }
+ }
+
+ return e.runLoop(ctx, session)
+}
+
+// Resume continues an existing session from its last checkpoint.
+func (e *LoopExecutor) Resume(ctx context.Context, sessionID string) error {
+ // Load session from event log
+ session, err := e.sessionManager.LoadSession(sessionID)
+ if err != nil {
+ return fmt.Errorf("failed to load session: %w", err)
+ }
+
+ // Check if session is in a resumable state
+ if session.State == proto.State_STATE_COMPLETED {
+ return fmt.Errorf("session already completed")
+ }
+ if session.State == proto.State_STATE_FAILED {
+ return fmt.Errorf("session failed and cannot be resumed")
+ }
+
+ // Update state to running
+ session.SetState(proto.State_STATE_RUNNING)
+
+ return e.runLoop(ctx, session)
+}
+
+// runLoop executes the main agentic loop.
+func (e *LoopExecutor) runLoop(ctx context.Context, session *Session) error {
+ for session.CurrentStep < e.maxSteps {
+ // Check context cancellation
+ select {
+ case <-ctx.Done():
+ session.SetState(proto.State_STATE_FAILED)
+ return ctx.Err()
+ default:
+ }
+
+ // Phase 1: Plan - Determine next agent and action
+ task, err := e.planFunc(session)
+ if err != nil {
+ session.SetState(proto.State_STATE_FAILED)
+ return fmt.Errorf("planning failed: %w", err)
+ }
+
+ // If no task, we're done
+ if task == nil {
+ session.SetState(proto.State_STATE_COMPLETED)
+ return nil
+ }
+
+ // Get the agent from registry
+ ag, err := e.registry.Get(task.AgentID)
+ if err != nil {
+ session.SetState(proto.State_STATE_FAILED)
+ return fmt.Errorf("failed to get agent: %w", err)
+ }
+
+ // Phase 2: Execute - Send content to agent and receive response
+ output, err := e.executeTask(ctx, session, ag, task)
+ if err != nil {
+ session.SetState(proto.State_STATE_FAILED)
+ return fmt.Errorf("execution failed: %w", err)
+ }
+
+ // Phase 3: Evaluate - Check if goal achieved
+ goalAchieved, err := e.evaluateFunc(session, task, output)
+ if err != nil {
+ session.SetState(proto.State_STATE_FAILED)
+ return fmt.Errorf("evaluation failed: %w", err)
+ }
+
+ // Phase 4: Advance step
+ session.AdvanceStep()
+
+ // If goal achieved, complete the session
+ if goalAchieved {
+ session.SetState(proto.State_STATE_COMPLETED)
+ return nil
+ }
+ }
+
+ // Max steps reached
+ session.SetState(proto.State_STATE_FAILED)
+ return fmt.Errorf("max steps (%d) reached", e.maxSteps)
+}
+
+// executeTask sends input to an agent and collects output.
+func (e *LoopExecutor) executeTask(ctx context.Context, session *Session, ag agent.Agent, task *AgentTask) ([]*proto.Content, error) {
+ var output []*proto.Content
+
+ // Define output handler to collect responses
+ outputHandler := func(content *proto.Content) error {
+ output = append(output, content)
+ if _, err := session.WriteContentOut(content); err != nil {
+ return fmt.Errorf("failed to write output: %w", err)
+ }
+ return nil
+ }
+
+ // Start lifecycle event monitoring in background
+ lifecycleCtx, cancelLifecycle := context.WithCancel(ctx)
+ defer cancelLifecycle()
+
+ lifecycleHandler := func(event *proto.LifecycleEvent) error {
+ if err := session.WriteLifecycleEvent(event); err != nil {
+ return fmt.Errorf("failed to write lifecycle event: %w", err)
+ }
+ e.HandleLifecycleEvent(session, event)
+ return nil
+ }
+
+ // Start lifecycle monitoring in background goroutine
+ lifecycleErr := make(chan error, 1)
+ go func() {
+ lifecycleErr <- ag.StreamLifecycle(lifecycleCtx, lifecycleHandler)
+ }()
+
+ // Process inputs with the agent
+ if err := ag.Process(ctx, task.Input, outputHandler); err != nil {
+ cancelLifecycle()
+ return nil, fmt.Errorf("agent process failed: %w", err)
+ }
+
+ // Cancel lifecycle monitoring
+ cancelLifecycle()
+
+ return output, nil
+}
+
+// HandleLifecycleEvent processes lifecycle events from agents.
+func (e *LoopExecutor) HandleLifecycleEvent(session *Session, event *proto.LifecycleEvent) {
+ // Handle different event types
+ switch event.EventType {
+ case "PROGRESS":
+ // Log progress events
+ // TODO: Add progress tracking
+ case "HEARTBEAT":
+ // Agent health signal
+ // TODO: Update agent health status in registry
+ }
+}
+
+// defaultPlanFunc is a simple default planning function.
+// It selects the first healthy agent and uses recent message history as input.
+func defaultPlanFunc(registry *Registry) PlanFunc {
+ return func(session *Session) (*AgentTask, error) {
+ // Get the first healthy agent
+ healthyAgents := registry.ListHealthy()
+ if len(healthyAgents) == 0 {
+ return nil, fmt.Errorf("no healthy agents available")
+ }
+
+ agentID := healthyAgents[0]
+
+ // Use last few messages as input (or all if fewer than 10)
+ inputSize := 10
+ startIdx := len(session.MessageHistory) - inputSize
+ if startIdx < 0 {
+ startIdx = 0
+ }
+ input := session.MessageHistory[startIdx:]
+
+ // If no more input, we're done
+ if len(input) == 0 {
+ return nil, nil
+ }
+
+ return &AgentTask{
+ AgentID: agentID,
+ Input: input,
+ Goal: "Process input and generate response",
+ StepIndex: session.CurrentStep,
+ }, nil
+ }
+}
+
+// defaultEvaluateFunc is a simple default evaluation function.
+// It considers the goal achieved after processing one step.
+func defaultEvaluateFunc(session *Session, task *AgentTask, output []*proto.Content) (bool, error) {
+ // Simple evaluation: goal achieved if we got any output
+ return len(output) > 0, nil
+}
diff --git a/internal/controller/registry.go b/internal/controller/registry.go
new file mode 100644
index 0000000..595881a
--- /dev/null
+++ b/internal/controller/registry.go
@@ -0,0 +1,299 @@
+package controller
+
+import (
+ "context"
+ "fmt"
+ "sync"
+ "time"
+
+ "github.com/google/gar/agent"
+)
+
+// AgentType represents the type of agent (local or remote).
+type AgentType string
+
+const (
+ AgentTypeLocal AgentType = "local"
+ AgentTypeRemote AgentType = "remote"
+)
+
+// AgentInfo contains metadata about a registered agent.
+type AgentInfo struct {
+ ID string
+ Name string
+ Description string
+ Type AgentType
+ Healthy bool
+ LastHealthCheck time.Time
+ Metadata map[string]string
+}
+
+// Registry manages a collection of local and remote agents.
+// It provides agent discovery, health monitoring, and load balancing.
+type Registry struct {
+ mu sync.RWMutex
+ agents map[string]agent.Agent
+ agentInfo map[string]*AgentInfo
+ healthCheckTicker *time.Ticker
+ stopHealthCheck chan struct{}
+}
+
+// NewRegistry creates a new agent registry.
+func NewRegistry(healthCheckInterval time.Duration) *Registry {
+ if healthCheckInterval == 0 {
+ healthCheckInterval = 30 * time.Second
+ }
+
+ r := &Registry{
+ agents: make(map[string]agent.Agent),
+ agentInfo: make(map[string]*AgentInfo),
+ stopHealthCheck: make(chan struct{}),
+ }
+
+ // Start background health check if interval is positive
+ if healthCheckInterval > 0 {
+ r.healthCheckTicker = time.NewTicker(healthCheckInterval)
+ go r.runHealthChecks()
+ }
+
+ return r
+}
+
+// RegisterLocal registers a local (in-process) agent.
+func (r *Registry) RegisterLocal(a agent.Agent, name, description string, metadata map[string]string) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ id := a.ID()
+ if _, exists := r.agents[id]; exists {
+ return fmt.Errorf("agent %s already registered", id)
+ }
+
+ r.agents[id] = a
+ r.agentInfo[id] = &AgentInfo{
+ ID: id,
+ Name: name,
+ Description: description,
+ Type: AgentTypeLocal,
+ Healthy: true,
+ LastHealthCheck: time.Now(),
+ Metadata: metadata,
+ }
+
+ return nil
+}
+
+// RegisterRemote registers a remote agent by creating a remote agent client.
+func (r *Registry) RegisterRemote(id, name, description, address string, metadata map[string]string) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ if _, exists := r.agents[id]; exists {
+ return fmt.Errorf("agent %s already registered", id)
+ }
+
+ // Create remote agent client
+ remoteAgent, err := agent.NewRemoteAgent(agent.RemoteAgentConfig{
+ ID: id,
+ Address: address,
+ Reconnect: true,
+ MaxRetries: 3,
+ })
+ if err != nil {
+ return fmt.Errorf("failed to create remote agent: %w", err)
+ }
+
+ r.agents[id] = remoteAgent
+ r.agentInfo[id] = &AgentInfo{
+ ID: id,
+ Name: name,
+ Description: description,
+ Type: AgentTypeRemote,
+ Healthy: false, // Will be checked by health monitor
+ LastHealthCheck: time.Time{},
+ Metadata: metadata,
+ }
+
+ return nil
+}
+
+// Unregister removes an agent from the registry.
+func (r *Registry) Unregister(id string) error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ agent, exists := r.agents[id]
+ if !exists {
+ return fmt.Errorf("agent %s not found", id)
+ }
+
+ // Close the agent
+ if err := agent.Close(); err != nil {
+ return fmt.Errorf("failed to close agent: %w", err)
+ }
+
+ delete(r.agents, id)
+ delete(r.agentInfo, id)
+
+ return nil
+}
+
+// Get retrieves an agent by ID.
+func (r *Registry) Get(id string) (agent.Agent, error) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ a, exists := r.agents[id]
+ if !exists {
+ return nil, fmt.Errorf("agent %s not found", id)
+ }
+
+ return a, nil
+}
+
+// GetInfo retrieves agent metadata by ID.
+func (r *Registry) GetInfo(id string) (*AgentInfo, error) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ info, exists := r.agentInfo[id]
+ if !exists {
+ return nil, fmt.Errorf("agent %s not found", id)
+ }
+
+ return info, nil
+}
+
+// List returns all registered agent IDs.
+func (r *Registry) List() []string {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ ids := make([]string, 0, len(r.agents))
+ for id := range r.agents {
+ ids = append(ids, id)
+ }
+
+ return ids
+}
+
+// ListByType returns all agent IDs of a specific type.
+func (r *Registry) ListByType(agentType AgentType) []string {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ ids := make([]string, 0)
+ for id, info := range r.agentInfo {
+ if info.Type == agentType {
+ ids = append(ids, id)
+ }
+ }
+
+ return ids
+}
+
+// ListHealthy returns all healthy agent IDs.
+func (r *Registry) ListHealthy() []string {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ ids := make([]string, 0)
+ for id, info := range r.agentInfo {
+ if info.Healthy {
+ ids = append(ids, id)
+ }
+ }
+
+ return ids
+}
+
+// SelectAgent selects an agent based on a simple load balancing strategy.
+// Currently uses round-robin among healthy agents of the specified type.
+func (r *Registry) SelectAgent(agentType AgentType) (agent.Agent, error) {
+ r.mu.RLock()
+ defer r.mu.RUnlock()
+
+ // Find healthy agents of the specified type
+ var candidates []string
+ for id, info := range r.agentInfo {
+ if info.Type == agentType && info.Healthy {
+ candidates = append(candidates, id)
+ }
+ }
+
+ if len(candidates) == 0 {
+ return nil, fmt.Errorf("no healthy agents of type %s available", agentType)
+ }
+
+ // Simple round-robin: return first healthy agent
+ // TODO: Implement more sophisticated load balancing
+ selectedID := candidates[0]
+ return r.agents[selectedID], nil
+}
+
+// HealthCheck performs a health check on a specific agent.
+func (r *Registry) HealthCheck(id string) error {
+ a, err := r.Get(id)
+ if err != nil {
+ return err
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
+ defer cancel()
+
+ err = a.HealthCheck(ctx)
+
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ info, exists := r.agentInfo[id]
+ if exists {
+ info.Healthy = (err == nil)
+ info.LastHealthCheck = time.Now()
+ }
+
+ return err
+}
+
+// runHealthChecks runs periodic health checks on all agents.
+func (r *Registry) runHealthChecks() {
+ for {
+ select {
+ case <-r.healthCheckTicker.C:
+ r.performHealthChecks()
+ case <-r.stopHealthCheck:
+ return
+ }
+ }
+}
+
+// performHealthChecks checks the health of all registered agents.
+func (r *Registry) performHealthChecks() {
+ ids := r.List()
+ for _, id := range ids {
+ // Run health check (ignore errors, status is updated in HealthCheck method)
+ _ = r.HealthCheck(id)
+ }
+}
+
+// Close stops the registry and closes all agents.
+func (r *Registry) Close() error {
+ r.mu.Lock()
+ defer r.mu.Unlock()
+
+ // Stop health checks
+ if r.healthCheckTicker != nil {
+ r.healthCheckTicker.Stop()
+ close(r.stopHealthCheck)
+ }
+
+ // Close all agents
+ var firstErr error
+ for id, a := range r.agents {
+ if err := a.Close(); err != nil && firstErr == nil {
+ firstErr = fmt.Errorf("failed to close agent %s: %w", id, err)
+ }
+ }
+
+ return firstErr
+}
diff --git a/internal/controller/session.go b/internal/controller/session.go
new file mode 100644
index 0000000..ea5dc26
--- /dev/null
+++ b/internal/controller/session.go
@@ -0,0 +1,302 @@
+package controller
+
+import (
+ "fmt"
+ "sync"
+ "time"
+
+ "github.com/google/uuid"
+ "github.com/google/gar/internal/eventlog"
+ "github.com/google/gar/proto"
+)
+
+// Session represents an agentic loop execution session.
+// It maintains in-memory state and uses event log for durability.
+type Session struct {
+ ID string
+ State proto.State
+ CurrentStep int
+ ActiveAgents []string
+ MessageHistory []*proto.Content
+ LifecycleEvents []*proto.LifecycleEvent
+ CheckpointIDs []string // Ordered list of checkpoint UUIDs
+ CreatedAt time.Time
+ UpdatedAt time.Time
+ mu sync.RWMutex
+ eventLog eventlog.EventLog
+}
+
+// EventLogFactory is a function that creates EventLog instances for sessions.
+type EventLogFactory func(sessionID string) (eventlog.EventLog, error)
+
+// SessionManager manages multiple sessions.
+type SessionManager struct {
+ mu sync.RWMutex
+ sessions map[string]*Session
+ eventLogFactory EventLogFactory
+}
+
+// NewSessionManager creates a new session manager with a custom EventLog factory.
+func NewSessionManager(factory EventLogFactory) *SessionManager {
+ return &SessionManager{
+ sessions: make(map[string]*Session),
+ eventLogFactory: factory,
+ }
+}
+
+// // NewSessionManagerWithFileEventLog creates a new session manager using file-based event logs.
+// // This is a convenience function for the common case of using file-based event logs.
+// func NewSessionManagerWithFileEventLog(elogFactory EventLogFactory) *SessionManager {
+
+// return NewSessionManager(factory)
+// }
+
+// NewSession creates a new session with the given ID.
+func (sm *SessionManager) NewSession(sessionID string) (*Session, error) {
+ sm.mu.Lock()
+ defer sm.mu.Unlock()
+
+ // Check if session already exists
+ if _, exists := sm.sessions[sessionID]; exists {
+ return nil, fmt.Errorf("session %s already exists", sessionID)
+ }
+
+ // Create event log for this session using the factory
+ el, err := sm.eventLogFactory(sessionID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to create event log: %w", err)
+ }
+
+ now := time.Now()
+ session := &Session{
+ ID: sessionID,
+ State: proto.State_STATE_RUNNING,
+ CurrentStep: 0,
+ ActiveAgents: []string{},
+ MessageHistory: []*proto.Content{},
+ LifecycleEvents: []*proto.LifecycleEvent{},
+ CheckpointIDs: []string{},
+ CreatedAt: now,
+ UpdatedAt: now,
+ eventLog: el,
+ }
+
+ sm.sessions[sessionID] = session
+ return session, nil
+}
+
+// LoadSession loads an existing session from event log.
+func (sm *SessionManager) LoadSession(sessionID string) (*Session, error) {
+ return sm.LoadSessionFromCheckpoint(sessionID, "")
+}
+
+// LoadSessionFromCheckpoint loads an existing session from event log up to a specific checkpoint.
+// If checkpointID is empty, loads to the latest state.
+// If checkpointID is provided, loads up to and including that checkpoint UUID.
+func (sm *SessionManager) LoadSessionFromCheckpoint(sessionID string, checkpointID string) (*Session, error) {
+ sm.mu.Lock()
+ defer sm.mu.Unlock()
+
+ // Check if already loaded - remove it to reload fresh from checkpoint
+ delete(sm.sessions, sessionID)
+
+ // Open event log for replay using the factory
+ replayLog, err := sm.eventLogFactory(sessionID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open event log for replay: %w", err)
+ }
+ defer replayLog.Close()
+
+ // Get all entries from the event log
+ entries, err := replayLog.GetEntries()
+ if err != nil {
+ return nil, fmt.Errorf("failed to get event log entries: %w", err)
+ }
+
+ // Reconstruct session state from event log
+ session := &Session{
+ ID: sessionID,
+ State: proto.State_STATE_RUNNING,
+ CurrentStep: 0,
+ ActiveAgents: []string{},
+ MessageHistory: []*proto.Content{},
+ LifecycleEvents: []*proto.LifecycleEvent{},
+ CheckpointIDs: []string{},
+ CreatedAt: time.Now(),
+ UpdatedAt: time.Now(),
+ }
+
+ targetReached := false
+ checkpointFound := false
+
+ // Replay entries to rebuild state
+ for _, entry := range entries {
+ // If we've reached the target checkpoint, stop processing
+ if targetReached {
+ break
+ }
+
+ switch entry.Type {
+ case eventlog.EventTypeContentIn, eventlog.EventTypeContentOut:
+ content := &proto.Content{
+ Role: getStringFromData(entry.Data, "role"),
+ Type: getStringFromData(entry.Data, "type"),
+ Mimetype: getStringFromData(entry.Data, "mimetype"),
+ Data: getStringFromData(entry.Data, "data"),
+ }
+ session.MessageHistory = append(session.MessageHistory, content)
+
+ // Track checkpoint ID if present
+ if entry.CheckpointID != "" {
+ session.CheckpointIDs = append(session.CheckpointIDs, entry.CheckpointID)
+
+ // Check if this is the target checkpoint
+ if checkpointID != "" && entry.CheckpointID == checkpointID {
+ targetReached = true
+ checkpointFound = true
+ }
+ }
+
+ case eventlog.EventTypeLifecycle:
+ event := &proto.LifecycleEvent{
+ EventType: getStringFromData(entry.Data, "event_type"),
+ AgentId: getStringFromData(entry.Data, "agent_id"),
+ Timestamp: int64(entry.Data["timestamp"].(float64)),
+ }
+ session.LifecycleEvents = append(session.LifecycleEvents, event)
+ }
+
+ session.UpdatedAt = entry.Timestamp
+ }
+
+ // Validate checkpoint ID if provided
+ if checkpointID != "" && !checkpointFound {
+ return nil, fmt.Errorf("checkpoint ID %s not found in session", checkpointID)
+ }
+
+ // Reopen event log for appending using the factory
+ el, err := sm.eventLogFactory(sessionID)
+ if err != nil {
+ return nil, fmt.Errorf("failed to reopen event log: %w", err)
+ }
+ session.eventLog = el
+
+ sm.sessions[sessionID] = session
+ return session, nil
+}
+
+// GetSession retrieves a session by ID.
+func (sm *SessionManager) GetSession(sessionID string) (*Session, error) {
+ sm.mu.RLock()
+ defer sm.mu.RUnlock()
+
+ session, exists := sm.sessions[sessionID]
+ if !exists {
+ return nil, fmt.Errorf("session %s not found", sessionID)
+ }
+
+ return session, nil
+}
+
+// ListSessions returns all session IDs.
+// Note: This currently only works with file-based event logs.
+// TODO: Make this more generic for non-file implementations.
+func (sm *SessionManager) ListSessions() ([]string, error) {
+ return eventlog.ListSessions("eventlog")
+}
+
+// CloseSession closes a session and its event log.
+func (sm *SessionManager) CloseSession(sessionID string) error {
+ sm.mu.Lock()
+ defer sm.mu.Unlock()
+
+ session, exists := sm.sessions[sessionID]
+ if !exists {
+ return fmt.Errorf("session %s not found", sessionID)
+ }
+
+ if err := session.eventLog.Close(); err != nil {
+ return fmt.Errorf("failed to close event log: %w", err)
+ }
+
+ delete(sm.sessions, sessionID)
+ return nil
+}
+
+// WriteContentIn appends an incoming content message to the session with a new checkpoint.
+func (s *Session) WriteContentIn(content *proto.Content) (string, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ // Generate a new checkpoint UUID
+ checkpointID := uuid.New().String()
+
+ if err := s.eventLog.AppendContent(eventlog.EventTypeContentIn, checkpointID, content); err != nil {
+ return "", err
+ }
+
+ s.MessageHistory = append(s.MessageHistory, content)
+ s.CheckpointIDs = append(s.CheckpointIDs, checkpointID)
+ s.UpdatedAt = time.Now()
+ return checkpointID, nil
+}
+
+// WriteContentOut appends an outgoing content message to the session with a new checkpoint.
+func (s *Session) WriteContentOut(content *proto.Content) (string, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ // Generate a new checkpoint UUID
+ checkpointID := uuid.New().String()
+
+ if err := s.eventLog.AppendContent(eventlog.EventTypeContentOut, checkpointID, content); err != nil {
+ return "", err
+ }
+
+ s.MessageHistory = append(s.MessageHistory, content)
+ s.CheckpointIDs = append(s.CheckpointIDs, checkpointID)
+ s.UpdatedAt = time.Now()
+ return checkpointID, nil
+}
+
+// WriteLifecycleEvent appends a lifecycle event to the session.
+func (s *Session) WriteLifecycleEvent(event *proto.LifecycleEvent) error {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if err := s.eventLog.AppendLifecycleEvent(event); err != nil {
+ return err
+ }
+
+ s.LifecycleEvents = append(s.LifecycleEvents, event)
+ s.UpdatedAt = time.Now()
+ return nil
+}
+
+// SetState updates the session state.
+func (s *Session) SetState(state proto.State) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ s.State = state
+ s.UpdatedAt = time.Now()
+}
+
+// AdvanceStep increments the current step.
+func (s *Session) AdvanceStep() {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ s.CurrentStep++
+ s.UpdatedAt = time.Now()
+}
+
+// Helper function to extract string from map[string]interface{}
+func getStringFromData(data map[string]interface{}, key string) string {
+ if val, ok := data[key]; ok {
+ if str, ok := val.(string); ok {
+ return str
+ }
+ }
+ return ""
+}
diff --git a/internal/eventlog/eventlog.go b/internal/eventlog/eventlog.go
new file mode 100644
index 0000000..a329ece
--- /dev/null
+++ b/internal/eventlog/eventlog.go
@@ -0,0 +1,46 @@
+// Package eventlog implements event logging for session durability.
+// Event log entries use JSON Lines format with one log file per session.
+package eventlog
+
+import (
+ "time"
+
+ "github.com/google/gar/proto"
+)
+
+// EventType represents the type of event stored in the event log.
+type EventType string
+
+const (
+ EventTypeContentIn EventType = "CONTENT_IN"
+ EventTypeContentOut EventType = "CONTENT_OUT"
+ EventTypeLifecycle EventType = "LIFECYCLE"
+)
+
+// Entry represents a single entry in the event log.
+type Entry struct {
+ SessionID string `json:"session_id"`
+ Timestamp time.Time `json:"timestamp"`
+ Type EventType `json:"type"`
+ CheckpointID string `json:"checkpoint_id,omitempty"` // UUID for checkpoint tracking
+ Data map[string]interface{} `json:"data"`
+}
+
+// EventLog is the interface that all event log implementations must satisfy.
+// It provides methods for appending events, reading entries, and managing the log lifecycle.
+type EventLog interface {
+ // AppendContent appends a content message to the event log with a checkpoint UUID.
+ AppendContent(direction EventType, checkpointID string, content *proto.Content) error
+
+ // AppendLifecycleEvent appends a lifecycle event to the event log.
+ AppendLifecycleEvent(event *proto.LifecycleEvent) error
+
+ // GetEntries returns all entries from the event log in order.
+ GetEntries() ([]Entry, error)
+
+ // Close closes the event log and releases any resources.
+ Close() error
+
+ // SessionID returns the session ID for this event log.
+ SessionID() string
+}
diff --git a/internal/eventlog/file.go b/internal/eventlog/file.go
new file mode 100644
index 0000000..1fdde64
--- /dev/null
+++ b/internal/eventlog/file.go
@@ -0,0 +1,196 @@
+package eventlog
+
+import (
+ "bufio"
+ "encoding/json"
+ "fmt"
+ "os"
+ "path/filepath"
+ "sync"
+ "time"
+
+ "github.com/google/gar/proto"
+)
+
+// FileEventLog represents a file-based event log for a single session.
+// It provides append-only durability with JSON Lines format.
+type FileEventLog struct {
+ mu sync.Mutex
+ sessionID string
+ filePath string
+ file *os.File
+ writer *bufio.Writer
+}
+
+// FileConfig configures a FileEventLog instance.
+type FileConfig struct {
+ SessionID string
+ Dir string // Directory where event log files are stored
+}
+
+// NewFileEventLog creates a new file-based EventLog instance for the given session.
+// It creates the event log directory and file if they don't exist.
+func NewFileEventLog(config FileConfig) (*FileEventLog, error) {
+ if config.SessionID == "" {
+ return nil, fmt.Errorf("session ID cannot be empty")
+ }
+ if config.Dir == "" {
+ config.Dir = "eventlog"
+ }
+
+ // Create event log directory if it doesn't exist
+ if err := os.MkdirAll(config.Dir, 0755); err != nil {
+ return nil, fmt.Errorf("failed to create event log directory: %w", err)
+ }
+
+ filePath := filepath.Join(config.Dir, fmt.Sprintf("%s.log", config.SessionID))
+
+ // Open file in append mode, create if doesn't exist
+ file, err := os.OpenFile(filePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open event log file: %w", err)
+ }
+
+ return &FileEventLog{
+ sessionID: config.SessionID,
+ filePath: filePath,
+ file: file,
+ writer: bufio.NewWriter(file),
+ }, nil
+}
+
+// NewFileConfig creates a new file-based EventLog instance for the given session.
+// This is a convenience function that wraps NewFileEventLog.
+// Deprecated: Use NewFileEventLog for clarity, or implement your own EventLog.
+func NewFileConfig(config FileConfig) (EventLog, error) {
+ return NewFileEventLog(config)
+}
+
+// Append writes an entry to the event log.
+// Entries are written in JSON Lines format with atomic appends.
+func (e *FileEventLog) Append(entryType EventType, checkpointID string, data map[string]interface{}) error {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+
+ entry := Entry{
+ SessionID: e.sessionID,
+ Timestamp: time.Now(),
+ Type: entryType,
+ CheckpointID: checkpointID,
+ Data: data,
+ }
+
+ jsonData, err := json.Marshal(entry)
+ if err != nil {
+ return fmt.Errorf("failed to marshal entry: %w", err)
+ }
+ if _, err := e.writer.Write(jsonData); err != nil {
+ return fmt.Errorf("failed to write entry: %w", err)
+ }
+ if _, err := e.writer.WriteString("\n"); err != nil {
+ return fmt.Errorf("failed to write newline: %w", err)
+ }
+
+ // Flush to ensure durability
+ if err := e.writer.Flush(); err != nil {
+ return fmt.Errorf("failed to flush: %w", err)
+ }
+ if err := e.file.Sync(); err != nil {
+ return fmt.Errorf("failed to sync: %w", err)
+ }
+ return nil
+}
+
+// AppendContent writes a content message to the event log with a checkpoint UUID.
+func (e *FileEventLog) AppendContent(direction EventType, checkpointID string, content *proto.Content) error {
+ data := map[string]interface{}{
+ "role": content.Role,
+ "type": content.Type,
+ "mimetype": content.Mimetype,
+ "data": content.Data,
+ }
+ return e.Append(direction, checkpointID, data)
+}
+
+// AppendLifecycleEvent writes a lifecycle event to the event log.
+// Lifecycle events don't have checkpoint IDs.
+func (e *FileEventLog) AppendLifecycleEvent(event *proto.LifecycleEvent) error {
+ data := map[string]interface{}{
+ "event_type": event.EventType,
+ "agent_id": event.AgentId,
+ "timestamp": event.Timestamp,
+ "metadata": event.Metadata,
+ }
+ return e.Append(EventTypeLifecycle, "", data)
+}
+
+// Close closes the event log file.
+func (e *FileEventLog) Close() error {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+
+ if err := e.writer.Flush(); err != nil {
+ return fmt.Errorf("failed to flush on close: %w", err)
+ }
+ if err := e.file.Close(); err != nil {
+ return fmt.Errorf("failed to close file: %w", err)
+ }
+ return nil
+}
+
+// FilePath returns the path to the event log file.
+// This method is specific to FileEventLog and not part of the EventLog interface.
+func (e *FileEventLog) FilePath() string {
+ return e.filePath
+}
+
+// SessionID returns the session ID for this event log.
+func (e *FileEventLog) SessionID() string {
+ return e.sessionID
+}
+
+// GetEntries reads and returns all entries from the event log file.
+// Returns entries in order.
+func (e *FileEventLog) GetEntries() ([]Entry, error) {
+ e.mu.Lock()
+ defer e.mu.Unlock()
+
+ // Flush any pending writes first
+ if err := e.writer.Flush(); err != nil {
+ return nil, fmt.Errorf("failed to flush before reading: %w", err)
+ }
+
+ // Check if file exists
+ if _, err := os.Stat(e.filePath); os.IsNotExist(err) {
+ return nil, fmt.Errorf("event log file does not exist")
+ }
+
+ // Open file for reading
+ readFile, err := os.Open(e.filePath)
+ if err != nil {
+ return nil, fmt.Errorf("failed to open event log file for reading: %w", err)
+ }
+ defer readFile.Close()
+
+ var entries []Entry
+ scanner := bufio.NewScanner(readFile)
+
+ lineNum := 0
+ for scanner.Scan() {
+ lineNum++
+ line := scanner.Bytes()
+
+ var entry Entry
+ if err := json.Unmarshal(line, &entry); err != nil {
+ return nil, fmt.Errorf("failed to unmarshal entry at line %d: %w", lineNum, err)
+ }
+
+ entries = append(entries, entry)
+ }
+
+ if err := scanner.Err(); err != nil {
+ return nil, fmt.Errorf("error reading event log file: %w", err)
+ }
+
+ return entries, nil
+}
diff --git a/internal/eventlog/replay.go b/internal/eventlog/replay.go
new file mode 100644
index 0000000..59bd871
--- /dev/null
+++ b/internal/eventlog/replay.go
@@ -0,0 +1,43 @@
+package eventlog
+
+import (
+ "fmt"
+ "os"
+)
+
+const defaultEventLogDir = "eventlog"
+
+// ListSessions returns all session IDs that have event log files.
+func ListSessions(dir string) ([]string, error) {
+ if dir == "" {
+ dir = defaultEventLogDir
+ }
+
+ // Check if directory exists
+ if _, err := os.Stat(dir); os.IsNotExist(err) {
+ return []string{}, nil
+ }
+
+ files, err := os.ReadDir(dir)
+ if err != nil {
+ return nil, fmt.Errorf("failed to read event log directory: %w", err)
+ }
+
+ var sessions []string
+ for _, file := range files {
+ if file.IsDir() {
+ continue
+ }
+
+ // Extract session ID from filename (remove .log extension)
+ name := file.Name()
+ if len(name) > 4 && name[len(name)-4:] == ".log" {
+ sessionID := name[:len(name)-4]
+ sessions = append(sessions, sessionID)
+ }
+ }
+
+ return sessions, nil
+}
+
+// TODO(rakyll): Move Exists, Delete, ListSessions.
diff --git a/internal/server/server.go b/internal/server/server.go
new file mode 100644
index 0000000..80a8bd0
--- /dev/null
+++ b/internal/server/server.go
@@ -0,0 +1,223 @@
+// Package server implements the gRPC server for GARService,
+// exposing session management and agent registration APIs.
+package server
+
+import (
+ "context"
+ "fmt"
+ "net"
+ "sync"
+
+ "google.golang.org/grpc"
+
+ "github.com/google/gar/internal/controller"
+ "github.com/google/gar/proto"
+)
+
+// Server implements the GARService gRPC service.
+type Server struct {
+ proto.UnimplementedGARServiceServer
+
+ mu sync.RWMutex
+ controller *controller.Controller
+}
+
+// New creates a new controller server.
+func New(c *controller.Controller) *Server {
+ return &Server{
+ controller: c,
+ }
+}
+
+// TriggerSession triggers a new agentic loop session with streaming responses.
+func (s *Server) TriggerSession(req *proto.TriggerSessionRequest, stream grpc.ServerStreamingServer[proto.TriggerSessionResponse]) error {
+ s.mu.Lock()
+ sessionID := req.SessionId
+ inputs := req.Inputs
+ checkpointID := req.CheckpointId
+ s.mu.Unlock()
+
+ if sessionID == "" {
+ return fmt.Errorf("session_id is required")
+ }
+
+ // Send initial response
+ statusMsg := "Starting session..."
+ if checkpointID != "" {
+ statusMsg = fmt.Sprintf("Starting session from checkpoint %s...", checkpointID)
+ }
+
+ if err := stream.Send(&proto.TriggerSessionResponse{
+ SessionId: sessionID,
+ State: proto.State_STATE_STARTING,
+ Output: &proto.Content{
+ Role: "system",
+ Type: "text",
+ Mimetype: "text/plain",
+ Data: statusMsg,
+ },
+ }); err != nil {
+ return err
+ }
+
+ // Trigger the session
+ if err := s.controller.TriggerSession(stream.Context(), sessionID, inputs, checkpointID); err != nil {
+ // Send failure response
+ stream.Send(&proto.TriggerSessionResponse{
+ SessionId: sessionID,
+ State: proto.State_STATE_FAILED,
+ Output: &proto.Content{
+ Role: "system",
+ Type: "text",
+ Mimetype: "text/plain",
+ Data: fmt.Sprintf("Failed to trigger session: %v", err),
+ },
+ })
+ return err
+ }
+
+ // Get session state
+ session, err := s.controller.GetSession(sessionID)
+ if err != nil {
+ // Send unknown state response
+ stream.Send(&proto.TriggerSessionResponse{
+ SessionId: sessionID,
+ State: proto.State_STATE_UNKNOWN,
+ Output: &proto.Content{
+ Role: "system",
+ Type: "text",
+ Mimetype: "text/plain",
+ Data: fmt.Sprintf("Session triggered but failed to retrieve state: %v", err),
+ },
+ })
+ return err
+ }
+
+ // Get the latest checkpoint ID if available
+ latestCheckpointID := ""
+ if len(session.CheckpointIDs) > 0 {
+ latestCheckpointID = session.CheckpointIDs[len(session.CheckpointIDs)-1]
+ }
+
+ // Send final success response
+ return stream.Send(&proto.TriggerSessionResponse{
+ SessionId: sessionID,
+ State: session.State,
+ CheckpointId: latestCheckpointID,
+ })
+}
+
+// GetSession retrieves session details.
+func (s *Server) GetSession(ctx context.Context, req *proto.GetSessionRequest) (*proto.GetSessionResponse, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ if req.SessionId == "" {
+ return nil, fmt.Errorf("session_id is required")
+ }
+
+ // Load session if not already loaded
+ session, err := s.controller.GetSession(req.SessionId)
+ if err != nil {
+ // Try loading from event log
+ session, err = s.controller.LoadSession(req.SessionId)
+ if err != nil {
+ return nil, fmt.Errorf("session not found: %w", err)
+ }
+ }
+
+ return &proto.GetSessionResponse{
+ Session: &proto.SessionInfo{
+ SessionId: session.ID,
+ State: session.State,
+ CurrentStep: int32(session.CurrentStep),
+ ActiveAgents: session.ActiveAgents,
+ CreatedAt: session.CreatedAt.UnixMilli(),
+ UpdatedAt: session.UpdatedAt.UnixMilli(),
+ MessageCount: int32(len(session.MessageHistory)),
+ CheckpointCount: int32(len(session.CheckpointIDs)),
+ },
+ }, nil
+}
+
+// ListSessions lists all available sessions.
+func (s *Server) ListSessions(ctx context.Context, req *proto.ListSessionsRequest) (*proto.ListSessionsResponse, error) {
+ s.mu.RLock()
+ defer s.mu.RUnlock()
+
+ sessions, err := s.controller.ListSessions()
+ if err != nil {
+ return nil, fmt.Errorf("failed to list sessions: %w", err)
+ }
+
+ return &proto.ListSessionsResponse{
+ SessionIds: sessions,
+ }, nil
+}
+
+// RegisterAgent registers a new agent with the dispatcher.
+func (s *Server) RegisterAgent(ctx context.Context, req *proto.RegisterAgentRequest) (*proto.RegisterAgentResponse, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if req.AgentId == "" {
+ return nil, fmt.Errorf("agent_id is required")
+ }
+
+ registry := s.controller.Registry()
+
+ // Register based on agent type
+ var err error
+ switch req.AgentType {
+ case "remote":
+ if req.Address == "" {
+ return nil, fmt.Errorf("address is required for remote agents")
+ }
+ err = registry.RegisterRemote(req.AgentId, req.Name, req.Description, req.Address, req.Metadata)
+ case "local":
+ return nil, fmt.Errorf("local agents must be registered programmatically")
+ default:
+ return nil, fmt.Errorf("unknown agent type: %s", req.AgentType)
+ }
+
+ if err != nil {
+ return nil, fmt.Errorf("failed to register agent: %w", err)
+ }
+
+ return &proto.RegisterAgentResponse{}, nil
+}
+
+// UnregisterAgent removes an agent from the dispatcher.
+func (s *Server) UnregisterAgent(ctx context.Context, req *proto.UnregisterAgentRequest) (*proto.UnregisterAgentResponse, error) {
+ s.mu.Lock()
+ defer s.mu.Unlock()
+
+ if req.AgentId == "" {
+ return nil, fmt.Errorf("agent_id is required")
+ }
+
+ registry := s.controller.Registry()
+ if err := registry.Unregister(req.AgentId); err != nil {
+ return nil, fmt.Errorf("failed to unregister agent: %w", err)
+ }
+
+ return &proto.UnregisterAgentResponse{}, nil
+}
+
+// Serve starts the gRPC server on the specified address.
+func (s *Server) Serve(address string, opts ...grpc.ServerOption) error {
+ lis, err := net.Listen("tcp", address)
+ if err != nil {
+ return fmt.Errorf("failed to listen: %w", err)
+ }
+
+ grpcServer := grpc.NewServer(opts...)
+ proto.RegisterGARServiceServer(grpcServer, s)
+
+ fmt.Printf("Controller server listening on %s\n", address)
+ if err := grpcServer.Serve(lis); err != nil {
+ return fmt.Errorf("failed to serve: %w", err)
+ }
+
+ return nil
+}
diff --git a/proto/gar.pb.go b/proto/gar.pb.go
new file mode 100644
index 0000000..17a697c
--- /dev/null
+++ b/proto/gar.pb.go
@@ -0,0 +1,1119 @@
+// Code generated by protoc-gen-go. DO NOT EDIT.
+// versions:
+// protoc-gen-go v1.36.11
+// protoc v3.21.9
+// source: proto/gar.proto
+
+package proto
+
+import (
+ protoreflect "google.golang.org/protobuf/reflect/protoreflect"
+ protoimpl "google.golang.org/protobuf/runtime/protoimpl"
+ reflect "reflect"
+ sync "sync"
+ unsafe "unsafe"
+)
+
+const (
+ // Verify that this generated code is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion)
+ // Verify that runtime/protoimpl is sufficiently up-to-date.
+ _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20)
+)
+
+// State represents the state of a session
+type State int32
+
+const (
+ State_STATE_UNSPECIFIED State = 0 // Unspecified state
+ State_STATE_STARTING State = 1
+ State_STATE_RUNNING State = 2 // Session is currently running
+ State_STATE_COMPLETED State = 3 // Session completed successfully
+ State_STATE_FAILED State = 4 // Session failed
+ State_STATE_UNKNOWN State = 5
+)
+
+// Enum value maps for State.
+var (
+ State_name = map[int32]string{
+ 0: "STATE_UNSPECIFIED",
+ 1: "STATE_STARTING",
+ 2: "STATE_RUNNING",
+ 3: "STATE_COMPLETED",
+ 4: "STATE_FAILED",
+ 5: "STATE_UNKNOWN",
+ }
+ State_value = map[string]int32{
+ "STATE_UNSPECIFIED": 0,
+ "STATE_STARTING": 1,
+ "STATE_RUNNING": 2,
+ "STATE_COMPLETED": 3,
+ "STATE_FAILED": 4,
+ "STATE_UNKNOWN": 5,
+ }
+)
+
+func (x State) Enum() *State {
+ p := new(State)
+ *p = x
+ return p
+}
+
+func (x State) String() string {
+ return protoimpl.X.EnumStringOf(x.Descriptor(), protoreflect.EnumNumber(x))
+}
+
+func (State) Descriptor() protoreflect.EnumDescriptor {
+ return file_proto_gar_proto_enumTypes[0].Descriptor()
+}
+
+func (State) Type() protoreflect.EnumType {
+ return &file_proto_gar_proto_enumTypes[0]
+}
+
+func (x State) Number() protoreflect.EnumNumber {
+ return protoreflect.EnumNumber(x)
+}
+
+// Deprecated: Use State.Descriptor instead.
+func (State) EnumDescriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{0}
+}
+
+// Content represents a message with role, type, mimetype, and data fields
+type Content struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Role string `protobuf:"bytes,1,opt,name=role,proto3" json:"role,omitempty"` // The role of the content (e.g., "user", "assistant", "system")
+ Type string `protobuf:"bytes,2,opt,name=type,proto3" json:"type,omitempty"` // The type of content (e.g., "text", "image")
+ Mimetype string `protobuf:"bytes,3,opt,name=mimetype,proto3" json:"mimetype,omitempty"` // MIME type of the data (e.g., "text/plain", "image/png")
+ Data string `protobuf:"bytes,4,opt,name=data,proto3" json:"data,omitempty"` // The actual content data
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *Content) Reset() {
+ *x = Content{}
+ mi := &file_proto_gar_proto_msgTypes[0]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *Content) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*Content) ProtoMessage() {}
+
+func (x *Content) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[0]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use Content.ProtoReflect.Descriptor instead.
+func (*Content) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{0}
+}
+
+func (x *Content) GetRole() string {
+ if x != nil {
+ return x.Role
+ }
+ return ""
+}
+
+func (x *Content) GetType() string {
+ if x != nil {
+ return x.Type
+ }
+ return ""
+}
+
+func (x *Content) GetMimetype() string {
+ if x != nil {
+ return x.Mimetype
+ }
+ return ""
+}
+
+func (x *Content) GetData() string {
+ if x != nil {
+ return x.Data
+ }
+ return ""
+}
+
+// LifecycleEvent represents events from agent lifecycle
+type LifecycleEvent struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ EventType string `protobuf:"bytes,1,opt,name=event_type,json=eventType,proto3" json:"event_type,omitempty"` // Event type: "PROGRESS", "HEARTBEAT"
+ AgentId string `protobuf:"bytes,2,opt,name=agent_id,json=agentId,proto3" json:"agent_id,omitempty"` // Unique identifier of the agent
+ Timestamp int64 `protobuf:"varint,3,opt,name=timestamp,proto3" json:"timestamp,omitempty"` // Unix timestamp in milliseconds
+ Metadata map[string]string `protobuf:"bytes,4,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` // Additional event metadata
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *LifecycleEvent) Reset() {
+ *x = LifecycleEvent{}
+ mi := &file_proto_gar_proto_msgTypes[1]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *LifecycleEvent) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*LifecycleEvent) ProtoMessage() {}
+
+func (x *LifecycleEvent) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[1]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use LifecycleEvent.ProtoReflect.Descriptor instead.
+func (*LifecycleEvent) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{1}
+}
+
+func (x *LifecycleEvent) GetEventType() string {
+ if x != nil {
+ return x.EventType
+ }
+ return ""
+}
+
+func (x *LifecycleEvent) GetAgentId() string {
+ if x != nil {
+ return x.AgentId
+ }
+ return ""
+}
+
+func (x *LifecycleEvent) GetTimestamp() int64 {
+ if x != nil {
+ return x.Timestamp
+ }
+ return 0
+}
+
+func (x *LifecycleEvent) GetMetadata() map[string]string {
+ if x != nil {
+ return x.Metadata
+ }
+ return nil
+}
+
+// HealthCheckRequest for agent health checks
+type HealthCheckRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ AgentId string `protobuf:"bytes,1,opt,name=agent_id,json=agentId,proto3" json:"agent_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *HealthCheckRequest) Reset() {
+ *x = HealthCheckRequest{}
+ mi := &file_proto_gar_proto_msgTypes[2]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *HealthCheckRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*HealthCheckRequest) ProtoMessage() {}
+
+func (x *HealthCheckRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[2]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use HealthCheckRequest.ProtoReflect.Descriptor instead.
+func (*HealthCheckRequest) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{2}
+}
+
+func (x *HealthCheckRequest) GetAgentId() string {
+ if x != nil {
+ return x.AgentId
+ }
+ return ""
+}
+
+// HealthCheckResponse contains agent health status
+type HealthCheckResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Healthy bool `protobuf:"varint,1,opt,name=healthy,proto3" json:"healthy,omitempty"`
+ Message string `protobuf:"bytes,2,opt,name=message,proto3" json:"message,omitempty"`
+ Metadata map[string]string `protobuf:"bytes,3,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *HealthCheckResponse) Reset() {
+ *x = HealthCheckResponse{}
+ mi := &file_proto_gar_proto_msgTypes[3]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *HealthCheckResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*HealthCheckResponse) ProtoMessage() {}
+
+func (x *HealthCheckResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[3]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use HealthCheckResponse.ProtoReflect.Descriptor instead.
+func (*HealthCheckResponse) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{3}
+}
+
+func (x *HealthCheckResponse) GetHealthy() bool {
+ if x != nil {
+ return x.Healthy
+ }
+ return false
+}
+
+func (x *HealthCheckResponse) GetMessage() string {
+ if x != nil {
+ return x.Message
+ }
+ return ""
+}
+
+func (x *HealthCheckResponse) GetMetadata() map[string]string {
+ if x != nil {
+ return x.Metadata
+ }
+ return nil
+}
+
+// TriggerSessionRequest for triggering a new session
+type TriggerSessionRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"` // Unique session identifier
+ Inputs []*Content `protobuf:"bytes,2,rep,name=inputs,proto3" json:"inputs,omitempty"` // Input content to process
+ CheckpointId string `protobuf:"bytes,3,opt,name=checkpoint_id,json=checkpointId,proto3" json:"checkpoint_id,omitempty"` // Optional: Resume from specific checkpoint UUID (empty for latest)
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *TriggerSessionRequest) Reset() {
+ *x = TriggerSessionRequest{}
+ mi := &file_proto_gar_proto_msgTypes[4]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *TriggerSessionRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*TriggerSessionRequest) ProtoMessage() {}
+
+func (x *TriggerSessionRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[4]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use TriggerSessionRequest.ProtoReflect.Descriptor instead.
+func (*TriggerSessionRequest) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{4}
+}
+
+func (x *TriggerSessionRequest) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *TriggerSessionRequest) GetInputs() []*Content {
+ if x != nil {
+ return x.Inputs
+ }
+ return nil
+}
+
+func (x *TriggerSessionRequest) GetCheckpointId() string {
+ if x != nil {
+ return x.CheckpointId
+ }
+ return ""
+}
+
+// TriggerSessionResponse contains the result of triggering a session
+type TriggerSessionResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ State State `protobuf:"varint,2,opt,name=state,proto3,enum=proto.State" json:"state,omitempty"` // Session state
+ Output *Content `protobuf:"bytes,3,opt,name=output,proto3" json:"output,omitempty"`
+ CheckpointId string `protobuf:"bytes,4,opt,name=checkpoint_id,json=checkpointId,proto3" json:"checkpoint_id,omitempty"` // Checkpoint UUID for this response
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *TriggerSessionResponse) Reset() {
+ *x = TriggerSessionResponse{}
+ mi := &file_proto_gar_proto_msgTypes[5]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *TriggerSessionResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*TriggerSessionResponse) ProtoMessage() {}
+
+func (x *TriggerSessionResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[5]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use TriggerSessionResponse.ProtoReflect.Descriptor instead.
+func (*TriggerSessionResponse) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{5}
+}
+
+func (x *TriggerSessionResponse) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *TriggerSessionResponse) GetState() State {
+ if x != nil {
+ return x.State
+ }
+ return State_STATE_UNSPECIFIED
+}
+
+func (x *TriggerSessionResponse) GetOutput() *Content {
+ if x != nil {
+ return x.Output
+ }
+ return nil
+}
+
+func (x *TriggerSessionResponse) GetCheckpointId() string {
+ if x != nil {
+ return x.CheckpointId
+ }
+ return ""
+}
+
+// GetSessionRequest for retrieving session details
+type GetSessionRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *GetSessionRequest) Reset() {
+ *x = GetSessionRequest{}
+ mi := &file_proto_gar_proto_msgTypes[6]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *GetSessionRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*GetSessionRequest) ProtoMessage() {}
+
+func (x *GetSessionRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[6]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use GetSessionRequest.ProtoReflect.Descriptor instead.
+func (*GetSessionRequest) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{6}
+}
+
+func (x *GetSessionRequest) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+// SessionInfo contains session details
+type SessionInfo struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionId string `protobuf:"bytes,1,opt,name=session_id,json=sessionId,proto3" json:"session_id,omitempty"`
+ State State `protobuf:"varint,2,opt,name=state,proto3,enum=proto.State" json:"state,omitempty"`
+ CurrentStep int32 `protobuf:"varint,3,opt,name=current_step,json=currentStep,proto3" json:"current_step,omitempty"`
+ ActiveAgents []string `protobuf:"bytes,4,rep,name=active_agents,json=activeAgents,proto3" json:"active_agents,omitempty"`
+ CreatedAt int64 `protobuf:"varint,5,opt,name=created_at,json=createdAt,proto3" json:"created_at,omitempty"` // Unix timestamp in milliseconds
+ UpdatedAt int64 `protobuf:"varint,6,opt,name=updated_at,json=updatedAt,proto3" json:"updated_at,omitempty"` // Unix timestamp in milliseconds
+ MessageCount int32 `protobuf:"varint,7,opt,name=message_count,json=messageCount,proto3" json:"message_count,omitempty"`
+ CheckpointCount int32 `protobuf:"varint,8,opt,name=checkpoint_count,json=checkpointCount,proto3" json:"checkpoint_count,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *SessionInfo) Reset() {
+ *x = SessionInfo{}
+ mi := &file_proto_gar_proto_msgTypes[7]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *SessionInfo) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*SessionInfo) ProtoMessage() {}
+
+func (x *SessionInfo) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[7]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use SessionInfo.ProtoReflect.Descriptor instead.
+func (*SessionInfo) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{7}
+}
+
+func (x *SessionInfo) GetSessionId() string {
+ if x != nil {
+ return x.SessionId
+ }
+ return ""
+}
+
+func (x *SessionInfo) GetState() State {
+ if x != nil {
+ return x.State
+ }
+ return State_STATE_UNSPECIFIED
+}
+
+func (x *SessionInfo) GetCurrentStep() int32 {
+ if x != nil {
+ return x.CurrentStep
+ }
+ return 0
+}
+
+func (x *SessionInfo) GetActiveAgents() []string {
+ if x != nil {
+ return x.ActiveAgents
+ }
+ return nil
+}
+
+func (x *SessionInfo) GetCreatedAt() int64 {
+ if x != nil {
+ return x.CreatedAt
+ }
+ return 0
+}
+
+func (x *SessionInfo) GetUpdatedAt() int64 {
+ if x != nil {
+ return x.UpdatedAt
+ }
+ return 0
+}
+
+func (x *SessionInfo) GetMessageCount() int32 {
+ if x != nil {
+ return x.MessageCount
+ }
+ return 0
+}
+
+func (x *SessionInfo) GetCheckpointCount() int32 {
+ if x != nil {
+ return x.CheckpointCount
+ }
+ return 0
+}
+
+// GetSessionResponse contains session information
+type GetSessionResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ Session *SessionInfo `protobuf:"bytes,1,opt,name=session,proto3" json:"session,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *GetSessionResponse) Reset() {
+ *x = GetSessionResponse{}
+ mi := &file_proto_gar_proto_msgTypes[8]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *GetSessionResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*GetSessionResponse) ProtoMessage() {}
+
+func (x *GetSessionResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[8]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use GetSessionResponse.ProtoReflect.Descriptor instead.
+func (*GetSessionResponse) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{8}
+}
+
+func (x *GetSessionResponse) GetSession() *SessionInfo {
+ if x != nil {
+ return x.Session
+ }
+ return nil
+}
+
+// ListSessionsRequest for listing all sessions
+type ListSessionsRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ListSessionsRequest) Reset() {
+ *x = ListSessionsRequest{}
+ mi := &file_proto_gar_proto_msgTypes[9]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ListSessionsRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ListSessionsRequest) ProtoMessage() {}
+
+func (x *ListSessionsRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[9]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ListSessionsRequest.ProtoReflect.Descriptor instead.
+func (*ListSessionsRequest) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{9}
+}
+
+// ListSessionsResponse contains list of session IDs
+type ListSessionsResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ SessionIds []string `protobuf:"bytes,1,rep,name=session_ids,json=sessionIds,proto3" json:"session_ids,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *ListSessionsResponse) Reset() {
+ *x = ListSessionsResponse{}
+ mi := &file_proto_gar_proto_msgTypes[10]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *ListSessionsResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*ListSessionsResponse) ProtoMessage() {}
+
+func (x *ListSessionsResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[10]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use ListSessionsResponse.ProtoReflect.Descriptor instead.
+func (*ListSessionsResponse) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{10}
+}
+
+func (x *ListSessionsResponse) GetSessionIds() []string {
+ if x != nil {
+ return x.SessionIds
+ }
+ return nil
+}
+
+// RegisterAgentRequest for registering an agent
+type RegisterAgentRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ AgentId string `protobuf:"bytes,1,opt,name=agent_id,json=agentId,proto3" json:"agent_id,omitempty"`
+ Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` // Human-readable name for the agent
+ Description string `protobuf:"bytes,3,opt,name=description,proto3" json:"description,omitempty"` // Description of agent capabilities
+ AgentType string `protobuf:"bytes,4,opt,name=agent_type,json=agentType,proto3" json:"agent_type,omitempty"` // "local" or "remote"
+ Address string `protobuf:"bytes,5,opt,name=address,proto3" json:"address,omitempty"` // gRPC address for remote agents
+ Metadata map[string]string `protobuf:"bytes,6,rep,name=metadata,proto3" json:"metadata,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RegisterAgentRequest) Reset() {
+ *x = RegisterAgentRequest{}
+ mi := &file_proto_gar_proto_msgTypes[11]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RegisterAgentRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RegisterAgentRequest) ProtoMessage() {}
+
+func (x *RegisterAgentRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[11]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use RegisterAgentRequest.ProtoReflect.Descriptor instead.
+func (*RegisterAgentRequest) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{11}
+}
+
+func (x *RegisterAgentRequest) GetAgentId() string {
+ if x != nil {
+ return x.AgentId
+ }
+ return ""
+}
+
+func (x *RegisterAgentRequest) GetName() string {
+ if x != nil {
+ return x.Name
+ }
+ return ""
+}
+
+func (x *RegisterAgentRequest) GetDescription() string {
+ if x != nil {
+ return x.Description
+ }
+ return ""
+}
+
+func (x *RegisterAgentRequest) GetAgentType() string {
+ if x != nil {
+ return x.AgentType
+ }
+ return ""
+}
+
+func (x *RegisterAgentRequest) GetAddress() string {
+ if x != nil {
+ return x.Address
+ }
+ return ""
+}
+
+func (x *RegisterAgentRequest) GetMetadata() map[string]string {
+ if x != nil {
+ return x.Metadata
+ }
+ return nil
+}
+
+// RegisterAgentResponse contains registration result
+type RegisterAgentResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *RegisterAgentResponse) Reset() {
+ *x = RegisterAgentResponse{}
+ mi := &file_proto_gar_proto_msgTypes[12]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *RegisterAgentResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*RegisterAgentResponse) ProtoMessage() {}
+
+func (x *RegisterAgentResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[12]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use RegisterAgentResponse.ProtoReflect.Descriptor instead.
+func (*RegisterAgentResponse) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{12}
+}
+
+// UnregisterAgentRequest for unregistering an agent
+type UnregisterAgentRequest struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ AgentId string `protobuf:"bytes,1,opt,name=agent_id,json=agentId,proto3" json:"agent_id,omitempty"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *UnregisterAgentRequest) Reset() {
+ *x = UnregisterAgentRequest{}
+ mi := &file_proto_gar_proto_msgTypes[13]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *UnregisterAgentRequest) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*UnregisterAgentRequest) ProtoMessage() {}
+
+func (x *UnregisterAgentRequest) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[13]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use UnregisterAgentRequest.ProtoReflect.Descriptor instead.
+func (*UnregisterAgentRequest) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{13}
+}
+
+func (x *UnregisterAgentRequest) GetAgentId() string {
+ if x != nil {
+ return x.AgentId
+ }
+ return ""
+}
+
+// UnregisterAgentResponse contains unregistration result
+type UnregisterAgentResponse struct {
+ state protoimpl.MessageState `protogen:"open.v1"`
+ unknownFields protoimpl.UnknownFields
+ sizeCache protoimpl.SizeCache
+}
+
+func (x *UnregisterAgentResponse) Reset() {
+ *x = UnregisterAgentResponse{}
+ mi := &file_proto_gar_proto_msgTypes[14]
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ ms.StoreMessageInfo(mi)
+}
+
+func (x *UnregisterAgentResponse) String() string {
+ return protoimpl.X.MessageStringOf(x)
+}
+
+func (*UnregisterAgentResponse) ProtoMessage() {}
+
+func (x *UnregisterAgentResponse) ProtoReflect() protoreflect.Message {
+ mi := &file_proto_gar_proto_msgTypes[14]
+ if x != nil {
+ ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x))
+ if ms.LoadMessageInfo() == nil {
+ ms.StoreMessageInfo(mi)
+ }
+ return ms
+ }
+ return mi.MessageOf(x)
+}
+
+// Deprecated: Use UnregisterAgentResponse.ProtoReflect.Descriptor instead.
+func (*UnregisterAgentResponse) Descriptor() ([]byte, []int) {
+ return file_proto_gar_proto_rawDescGZIP(), []int{14}
+}
+
+var File_proto_gar_proto protoreflect.FileDescriptor
+
+const file_proto_gar_proto_rawDesc = "" +
+ "\n" +
+ "\x0fproto/gar.proto\x12\x05proto\"a\n" +
+ "\aContent\x12\x12\n" +
+ "\x04role\x18\x01 \x01(\tR\x04role\x12\x12\n" +
+ "\x04type\x18\x02 \x01(\tR\x04type\x12\x1a\n" +
+ "\bmimetype\x18\x03 \x01(\tR\bmimetype\x12\x12\n" +
+ "\x04data\x18\x04 \x01(\tR\x04data\"\xe6\x01\n" +
+ "\x0eLifecycleEvent\x12\x1d\n" +
+ "\n" +
+ "event_type\x18\x01 \x01(\tR\teventType\x12\x19\n" +
+ "\bagent_id\x18\x02 \x01(\tR\aagentId\x12\x1c\n" +
+ "\ttimestamp\x18\x03 \x01(\x03R\ttimestamp\x12?\n" +
+ "\bmetadata\x18\x04 \x03(\v2#.proto.LifecycleEvent.MetadataEntryR\bmetadata\x1a;\n" +
+ "\rMetadataEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"/\n" +
+ "\x12HealthCheckRequest\x12\x19\n" +
+ "\bagent_id\x18\x01 \x01(\tR\aagentId\"\xcc\x01\n" +
+ "\x13HealthCheckResponse\x12\x18\n" +
+ "\ahealthy\x18\x01 \x01(\bR\ahealthy\x12\x18\n" +
+ "\amessage\x18\x02 \x01(\tR\amessage\x12D\n" +
+ "\bmetadata\x18\x03 \x03(\v2(.proto.HealthCheckResponse.MetadataEntryR\bmetadata\x1a;\n" +
+ "\rMetadataEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x83\x01\n" +
+ "\x15TriggerSessionRequest\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\x12&\n" +
+ "\x06inputs\x18\x02 \x03(\v2\x0e.proto.ContentR\x06inputs\x12#\n" +
+ "\rcheckpoint_id\x18\x03 \x01(\tR\fcheckpointId\"\xa8\x01\n" +
+ "\x16TriggerSessionResponse\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\x12\"\n" +
+ "\x05state\x18\x02 \x01(\x0e2\f.proto.StateR\x05state\x12&\n" +
+ "\x06output\x18\x03 \x01(\v2\x0e.proto.ContentR\x06output\x12#\n" +
+ "\rcheckpoint_id\x18\x04 \x01(\tR\fcheckpointId\"2\n" +
+ "\x11GetSessionRequest\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\"\xa6\x02\n" +
+ "\vSessionInfo\x12\x1d\n" +
+ "\n" +
+ "session_id\x18\x01 \x01(\tR\tsessionId\x12\"\n" +
+ "\x05state\x18\x02 \x01(\x0e2\f.proto.StateR\x05state\x12!\n" +
+ "\fcurrent_step\x18\x03 \x01(\x05R\vcurrentStep\x12#\n" +
+ "\ractive_agents\x18\x04 \x03(\tR\factiveAgents\x12\x1d\n" +
+ "\n" +
+ "created_at\x18\x05 \x01(\x03R\tcreatedAt\x12\x1d\n" +
+ "\n" +
+ "updated_at\x18\x06 \x01(\x03R\tupdatedAt\x12#\n" +
+ "\rmessage_count\x18\a \x01(\x05R\fmessageCount\x12)\n" +
+ "\x10checkpoint_count\x18\b \x01(\x05R\x0fcheckpointCount\"B\n" +
+ "\x12GetSessionResponse\x12,\n" +
+ "\asession\x18\x01 \x01(\v2\x12.proto.SessionInfoR\asession\"\x15\n" +
+ "\x13ListSessionsRequest\"7\n" +
+ "\x14ListSessionsResponse\x12\x1f\n" +
+ "\vsession_ids\x18\x01 \x03(\tR\n" +
+ "sessionIds\"\xa4\x02\n" +
+ "\x14RegisterAgentRequest\x12\x19\n" +
+ "\bagent_id\x18\x01 \x01(\tR\aagentId\x12\x12\n" +
+ "\x04name\x18\x02 \x01(\tR\x04name\x12 \n" +
+ "\vdescription\x18\x03 \x01(\tR\vdescription\x12\x1d\n" +
+ "\n" +
+ "agent_type\x18\x04 \x01(\tR\tagentType\x12\x18\n" +
+ "\aaddress\x18\x05 \x01(\tR\aaddress\x12E\n" +
+ "\bmetadata\x18\x06 \x03(\v2).proto.RegisterAgentRequest.MetadataEntryR\bmetadata\x1a;\n" +
+ "\rMetadataEntry\x12\x10\n" +
+ "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" +
+ "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\x17\n" +
+ "\x15RegisterAgentResponse\"3\n" +
+ "\x16UnregisterAgentRequest\x12\x19\n" +
+ "\bagent_id\x18\x01 \x01(\tR\aagentId\"\x19\n" +
+ "\x17UnregisterAgentResponse*\x7f\n" +
+ "\x05State\x12\x15\n" +
+ "\x11STATE_UNSPECIFIED\x10\x00\x12\x12\n" +
+ "\x0eSTATE_STARTING\x10\x01\x12\x11\n" +
+ "\rSTATE_RUNNING\x10\x02\x12\x13\n" +
+ "\x0fSTATE_COMPLETED\x10\x03\x12\x10\n" +
+ "\fSTATE_FAILED\x10\x04\x12\x11\n" +
+ "\rSTATE_UNKNOWN\x10\x052\xc8\x01\n" +
+ "\fAgentService\x12-\n" +
+ "\aProcess\x12\x0e.proto.Content\x1a\x0e.proto.Content(\x010\x01\x12C\n" +
+ "\x0fStreamLifecycle\x12\x15.proto.LifecycleEvent\x1a\x15.proto.LifecycleEvent(\x010\x01\x12D\n" +
+ "\vHealthCheck\x12\x19.proto.HealthCheckRequest\x1a\x1a.proto.HealthCheckResponse2\x87\x03\n" +
+ "\n" +
+ "GARService\x12O\n" +
+ "\x0eTriggerSession\x12\x1c.proto.TriggerSessionRequest\x1a\x1d.proto.TriggerSessionResponse0\x01\x12A\n" +
+ "\n" +
+ "GetSession\x12\x18.proto.GetSessionRequest\x1a\x19.proto.GetSessionResponse\x12G\n" +
+ "\fListSessions\x12\x1a.proto.ListSessionsRequest\x1a\x1b.proto.ListSessionsResponse\x12J\n" +
+ "\rRegisterAgent\x12\x1b.proto.RegisterAgentRequest\x1a\x1c.proto.RegisterAgentResponse\x12P\n" +
+ "\x0fUnregisterAgent\x12\x1d.proto.UnregisterAgentRequest\x1a\x1e.proto.UnregisterAgentResponseB\x1dZ\x1bgithub.com/google/gar/protob\x06proto3"
+
+var (
+ file_proto_gar_proto_rawDescOnce sync.Once
+ file_proto_gar_proto_rawDescData []byte
+)
+
+func file_proto_gar_proto_rawDescGZIP() []byte {
+ file_proto_gar_proto_rawDescOnce.Do(func() {
+ file_proto_gar_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_proto_gar_proto_rawDesc), len(file_proto_gar_proto_rawDesc)))
+ })
+ return file_proto_gar_proto_rawDescData
+}
+
+var file_proto_gar_proto_enumTypes = make([]protoimpl.EnumInfo, 1)
+var file_proto_gar_proto_msgTypes = make([]protoimpl.MessageInfo, 18)
+var file_proto_gar_proto_goTypes = []any{
+ (State)(0), // 0: proto.State
+ (*Content)(nil), // 1: proto.Content
+ (*LifecycleEvent)(nil), // 2: proto.LifecycleEvent
+ (*HealthCheckRequest)(nil), // 3: proto.HealthCheckRequest
+ (*HealthCheckResponse)(nil), // 4: proto.HealthCheckResponse
+ (*TriggerSessionRequest)(nil), // 5: proto.TriggerSessionRequest
+ (*TriggerSessionResponse)(nil), // 6: proto.TriggerSessionResponse
+ (*GetSessionRequest)(nil), // 7: proto.GetSessionRequest
+ (*SessionInfo)(nil), // 8: proto.SessionInfo
+ (*GetSessionResponse)(nil), // 9: proto.GetSessionResponse
+ (*ListSessionsRequest)(nil), // 10: proto.ListSessionsRequest
+ (*ListSessionsResponse)(nil), // 11: proto.ListSessionsResponse
+ (*RegisterAgentRequest)(nil), // 12: proto.RegisterAgentRequest
+ (*RegisterAgentResponse)(nil), // 13: proto.RegisterAgentResponse
+ (*UnregisterAgentRequest)(nil), // 14: proto.UnregisterAgentRequest
+ (*UnregisterAgentResponse)(nil), // 15: proto.UnregisterAgentResponse
+ nil, // 16: proto.LifecycleEvent.MetadataEntry
+ nil, // 17: proto.HealthCheckResponse.MetadataEntry
+ nil, // 18: proto.RegisterAgentRequest.MetadataEntry
+}
+var file_proto_gar_proto_depIdxs = []int32{
+ 16, // 0: proto.LifecycleEvent.metadata:type_name -> proto.LifecycleEvent.MetadataEntry
+ 17, // 1: proto.HealthCheckResponse.metadata:type_name -> proto.HealthCheckResponse.MetadataEntry
+ 1, // 2: proto.TriggerSessionRequest.inputs:type_name -> proto.Content
+ 0, // 3: proto.TriggerSessionResponse.state:type_name -> proto.State
+ 1, // 4: proto.TriggerSessionResponse.output:type_name -> proto.Content
+ 0, // 5: proto.SessionInfo.state:type_name -> proto.State
+ 8, // 6: proto.GetSessionResponse.session:type_name -> proto.SessionInfo
+ 18, // 7: proto.RegisterAgentRequest.metadata:type_name -> proto.RegisterAgentRequest.MetadataEntry
+ 1, // 8: proto.AgentService.Process:input_type -> proto.Content
+ 2, // 9: proto.AgentService.StreamLifecycle:input_type -> proto.LifecycleEvent
+ 3, // 10: proto.AgentService.HealthCheck:input_type -> proto.HealthCheckRequest
+ 5, // 11: proto.GARService.TriggerSession:input_type -> proto.TriggerSessionRequest
+ 7, // 12: proto.GARService.GetSession:input_type -> proto.GetSessionRequest
+ 10, // 13: proto.GARService.ListSessions:input_type -> proto.ListSessionsRequest
+ 12, // 14: proto.GARService.RegisterAgent:input_type -> proto.RegisterAgentRequest
+ 14, // 15: proto.GARService.UnregisterAgent:input_type -> proto.UnregisterAgentRequest
+ 1, // 16: proto.AgentService.Process:output_type -> proto.Content
+ 2, // 17: proto.AgentService.StreamLifecycle:output_type -> proto.LifecycleEvent
+ 4, // 18: proto.AgentService.HealthCheck:output_type -> proto.HealthCheckResponse
+ 6, // 19: proto.GARService.TriggerSession:output_type -> proto.TriggerSessionResponse
+ 9, // 20: proto.GARService.GetSession:output_type -> proto.GetSessionResponse
+ 11, // 21: proto.GARService.ListSessions:output_type -> proto.ListSessionsResponse
+ 13, // 22: proto.GARService.RegisterAgent:output_type -> proto.RegisterAgentResponse
+ 15, // 23: proto.GARService.UnregisterAgent:output_type -> proto.UnregisterAgentResponse
+ 16, // [16:24] is the sub-list for method output_type
+ 8, // [8:16] is the sub-list for method input_type
+ 8, // [8:8] is the sub-list for extension type_name
+ 8, // [8:8] is the sub-list for extension extendee
+ 0, // [0:8] is the sub-list for field type_name
+}
+
+func init() { file_proto_gar_proto_init() }
+func file_proto_gar_proto_init() {
+ if File_proto_gar_proto != nil {
+ return
+ }
+ type x struct{}
+ out := protoimpl.TypeBuilder{
+ File: protoimpl.DescBuilder{
+ GoPackagePath: reflect.TypeOf(x{}).PkgPath(),
+ RawDescriptor: unsafe.Slice(unsafe.StringData(file_proto_gar_proto_rawDesc), len(file_proto_gar_proto_rawDesc)),
+ NumEnums: 1,
+ NumMessages: 18,
+ NumExtensions: 0,
+ NumServices: 2,
+ },
+ GoTypes: file_proto_gar_proto_goTypes,
+ DependencyIndexes: file_proto_gar_proto_depIdxs,
+ EnumInfos: file_proto_gar_proto_enumTypes,
+ MessageInfos: file_proto_gar_proto_msgTypes,
+ }.Build()
+ File_proto_gar_proto = out.File
+ file_proto_gar_proto_goTypes = nil
+ file_proto_gar_proto_depIdxs = nil
+}
diff --git a/proto/gar.proto b/proto/gar.proto
new file mode 100644
index 0000000..069fbe9
--- /dev/null
+++ b/proto/gar.proto
@@ -0,0 +1,145 @@
+syntax = "proto3";
+
+package proto;
+
+option go_package = "github.com/google/gar/proto";
+
+// Content represents a message with role, type, mimetype, and data fields
+message Content {
+ string role = 1; // The role of the content (e.g., "user", "assistant", "system")
+ string type = 2; // The type of content (e.g., "text", "image")
+ string mimetype = 3; // MIME type of the data (e.g., "text/plain", "image/png")
+ string data = 4; // The actual content data
+}
+
+// LifecycleEvent represents events from agent lifecycle
+message LifecycleEvent {
+ string event_type = 1; // Event type: "PROGRESS", "HEARTBEAT"
+ string agent_id = 2; // Unique identifier of the agent
+ int64 timestamp = 3; // Unix timestamp in milliseconds
+ map<string, string> metadata = 4; // Additional event metadata
+}
+
+// HealthCheckRequest for agent health checks
+message HealthCheckRequest {
+ string agent_id = 1;
+}
+
+// HealthCheckResponse contains agent health status
+message HealthCheckResponse {
+ bool healthy = 1;
+ string message = 2;
+ map<string, string> metadata = 3;
+}
+
+// AgentService defines the gRPC service for agent communication
+service AgentService {
+ // Process handles bidirectional streaming of content between dispatcher and agent
+ rpc Process(stream Content) returns (stream Content);
+
+ // StreamLifecycle allows agents to stream lifecycle events to dispatcher
+ rpc StreamLifecycle(stream LifecycleEvent) returns (stream LifecycleEvent);
+
+ // HealthCheck checks if the agent is healthy and responsive
+ rpc HealthCheck(HealthCheckRequest) returns (HealthCheckResponse);
+}
+
+// State represents the state of a session
+enum State {
+ STATE_UNSPECIFIED = 0; // Unspecified state
+ STATE_STARTING = 1;
+ STATE_RUNNING = 2; // Session is currently running
+ STATE_COMPLETED = 3; // Session completed successfully
+ STATE_FAILED = 4; // Session failed
+ STATE_UNKNOWN = 5;
+}
+
+// TriggerSessionRequest for triggering a new session
+message TriggerSessionRequest {
+ string session_id = 1; // Unique session identifier
+ repeated Content inputs = 2; // Input content to process
+ string checkpoint_id = 3; // Optional: Resume from specific checkpoint UUID (empty for latest)
+}
+
+// TriggerSessionResponse contains the result of triggering a session
+message TriggerSessionResponse {
+ string session_id = 1;
+ State state = 2; // Session state
+ Content output = 3;
+ string checkpoint_id = 4; // Checkpoint UUID for this response
+}
+
+
+// GetSessionRequest for retrieving session details
+message GetSessionRequest {
+ string session_id = 1;
+}
+
+// SessionInfo contains session details
+message SessionInfo {
+ string session_id = 1;
+ State state = 2;
+ int32 current_step = 3;
+ repeated string active_agents = 4;
+ int64 created_at = 5; // Unix timestamp in milliseconds
+ int64 updated_at = 6; // Unix timestamp in milliseconds
+ int32 message_count = 7;
+ int32 checkpoint_count = 8;
+}
+
+// GetSessionResponse contains session information
+message GetSessionResponse {
+ SessionInfo session = 1;
+}
+
+// ListSessionsRequest for listing all sessions
+message ListSessionsRequest {
+ // Empty for now, can add pagination later
+}
+
+// ListSessionsResponse contains list of session IDs
+message ListSessionsResponse {
+ repeated string session_ids = 1;
+}
+
+// RegisterAgentRequest for registering an agent
+message RegisterAgentRequest {
+ string agent_id = 1;
+ string name = 2; // Human-readable name for the agent
+ string description = 3; // Description of agent capabilities
+ string agent_type = 4; // "local" or "remote"
+ string address = 5; // gRPC address for remote agents
+ map<string, string> metadata = 6;
+}
+
+// RegisterAgentResponse contains registration result
+message RegisterAgentResponse {
+}
+
+// UnregisterAgentRequest for unregistering an agent
+message UnregisterAgentRequest {
+ string agent_id = 1;
+}
+
+// UnregisterAgentResponse contains unregistration result
+message UnregisterAgentResponse {
+}
+
+// GARService defines the gRPC service for GAR operations
+service GARService {
+ // TriggerSession triggers a new agentic loop session or resumes an existing one with streaming responses
+ // If the session_id already exists, it will be resumed from the last checkpoint
+ rpc TriggerSession(TriggerSessionRequest) returns (stream TriggerSessionResponse);
+
+ // GetSession retrieves session details
+ rpc GetSession(GetSessionRequest) returns (GetSessionResponse);
+
+ // ListSessions lists all available sessions
+ rpc ListSessions(ListSessionsRequest) returns (ListSessionsResponse);
+
+ // RegisterAgent registers a new agent with the controller
+ rpc RegisterAgent(RegisterAgentRequest) returns (RegisterAgentResponse);
+
+ // UnregisterAgent removes an agent from the controller
+ rpc UnregisterAgent(UnregisterAgentRequest) returns (UnregisterAgentResponse);
+}
diff --git a/proto/gar_grpc.pb.go b/proto/gar_grpc.pb.go
new file mode 100644
index 0000000..c49bf53
--- /dev/null
+++ b/proto/gar_grpc.pb.go
@@ -0,0 +1,470 @@
+// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
+// versions:
+// - protoc-gen-go-grpc v1.6.0
+// - protoc v3.21.9
+// source: proto/gar.proto
+
+package proto
+
+import (
+ context "context"
+ grpc "google.golang.org/grpc"
+ codes "google.golang.org/grpc/codes"
+ status "google.golang.org/grpc/status"
+)
+
+// This is a compile-time assertion to ensure that this generated file
+// is compatible with the grpc package it is being compiled against.
+// Requires gRPC-Go v1.64.0 or later.
+const _ = grpc.SupportPackageIsVersion9
+
+const (
+ AgentService_Process_FullMethodName = "/proto.AgentService/Process"
+ AgentService_StreamLifecycle_FullMethodName = "/proto.AgentService/StreamLifecycle"
+ AgentService_HealthCheck_FullMethodName = "/proto.AgentService/HealthCheck"
+)
+
+// AgentServiceClient is the client API for AgentService service.
+//
+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
+//
+// AgentService defines the gRPC service for agent communication
+type AgentServiceClient interface {
+ // Process handles bidirectional streaming of content between dispatcher and agent
+ Process(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[Content, Content], error)
+ // StreamLifecycle allows agents to stream lifecycle events to dispatcher
+ StreamLifecycle(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[LifecycleEvent, LifecycleEvent], error)
+ // HealthCheck checks if the agent is healthy and responsive
+ HealthCheck(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error)
+}
+
+type agentServiceClient struct {
+ cc grpc.ClientConnInterface
+}
+
+func NewAgentServiceClient(cc grpc.ClientConnInterface) AgentServiceClient {
+ return &agentServiceClient{cc}
+}
+
+func (c *agentServiceClient) Process(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[Content, Content], error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ stream, err := c.cc.NewStream(ctx, &AgentService_ServiceDesc.Streams[0], AgentService_Process_FullMethodName, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &grpc.GenericClientStream[Content, Content]{ClientStream: stream}
+ return x, nil
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type AgentService_ProcessClient = grpc.BidiStreamingClient[Content, Content]
+
+func (c *agentServiceClient) StreamLifecycle(ctx context.Context, opts ...grpc.CallOption) (grpc.BidiStreamingClient[LifecycleEvent, LifecycleEvent], error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ stream, err := c.cc.NewStream(ctx, &AgentService_ServiceDesc.Streams[1], AgentService_StreamLifecycle_FullMethodName, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &grpc.GenericClientStream[LifecycleEvent, LifecycleEvent]{ClientStream: stream}
+ return x, nil
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type AgentService_StreamLifecycleClient = grpc.BidiStreamingClient[LifecycleEvent, LifecycleEvent]
+
+func (c *agentServiceClient) HealthCheck(ctx context.Context, in *HealthCheckRequest, opts ...grpc.CallOption) (*HealthCheckResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(HealthCheckResponse)
+ err := c.cc.Invoke(ctx, AgentService_HealthCheck_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// AgentServiceServer is the server API for AgentService service.
+// All implementations must embed UnimplementedAgentServiceServer
+// for forward compatibility.
+//
+// AgentService defines the gRPC service for agent communication
+type AgentServiceServer interface {
+ // Process handles bidirectional streaming of content between dispatcher and agent
+ Process(grpc.BidiStreamingServer[Content, Content]) error
+ // StreamLifecycle allows agents to stream lifecycle events to dispatcher
+ StreamLifecycle(grpc.BidiStreamingServer[LifecycleEvent, LifecycleEvent]) error
+ // HealthCheck checks if the agent is healthy and responsive
+ HealthCheck(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error)
+ mustEmbedUnimplementedAgentServiceServer()
+}
+
+// UnimplementedAgentServiceServer must be embedded to have
+// forward compatible implementations.
+//
+// NOTE: this should be embedded by value instead of pointer to avoid a nil
+// pointer dereference when methods are called.
+type UnimplementedAgentServiceServer struct{}
+
+func (UnimplementedAgentServiceServer) Process(grpc.BidiStreamingServer[Content, Content]) error {
+ return status.Error(codes.Unimplemented, "method Process not implemented")
+}
+func (UnimplementedAgentServiceServer) StreamLifecycle(grpc.BidiStreamingServer[LifecycleEvent, LifecycleEvent]) error {
+ return status.Error(codes.Unimplemented, "method StreamLifecycle not implemented")
+}
+func (UnimplementedAgentServiceServer) HealthCheck(context.Context, *HealthCheckRequest) (*HealthCheckResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method HealthCheck not implemented")
+}
+func (UnimplementedAgentServiceServer) mustEmbedUnimplementedAgentServiceServer() {}
+func (UnimplementedAgentServiceServer) testEmbeddedByValue() {}
+
+// UnsafeAgentServiceServer may be embedded to opt out of forward compatibility for this service.
+// Use of this interface is not recommended, as added methods to AgentServiceServer will
+// result in compilation errors.
+type UnsafeAgentServiceServer interface {
+ mustEmbedUnimplementedAgentServiceServer()
+}
+
+func RegisterAgentServiceServer(s grpc.ServiceRegistrar, srv AgentServiceServer) {
+ // If the following call panics, it indicates UnimplementedAgentServiceServer was
+ // embedded by pointer and is nil. This will cause panics if an
+ // unimplemented method is ever invoked, so we test this at initialization
+ // time to prevent it from happening at runtime later due to I/O.
+ if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
+ t.testEmbeddedByValue()
+ }
+ s.RegisterService(&AgentService_ServiceDesc, srv)
+}
+
+func _AgentService_Process_Handler(srv interface{}, stream grpc.ServerStream) error {
+ return srv.(AgentServiceServer).Process(&grpc.GenericServerStream[Content, Content]{ServerStream: stream})
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type AgentService_ProcessServer = grpc.BidiStreamingServer[Content, Content]
+
+func _AgentService_StreamLifecycle_Handler(srv interface{}, stream grpc.ServerStream) error {
+ return srv.(AgentServiceServer).StreamLifecycle(&grpc.GenericServerStream[LifecycleEvent, LifecycleEvent]{ServerStream: stream})
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type AgentService_StreamLifecycleServer = grpc.BidiStreamingServer[LifecycleEvent, LifecycleEvent]
+
+func _AgentService_HealthCheck_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(HealthCheckRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(AgentServiceServer).HealthCheck(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: AgentService_HealthCheck_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(AgentServiceServer).HealthCheck(ctx, req.(*HealthCheckRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+// AgentService_ServiceDesc is the grpc.ServiceDesc for AgentService service.
+// It's only intended for direct use with grpc.RegisterService,
+// and not to be introspected or modified (even as a copy)
+var AgentService_ServiceDesc = grpc.ServiceDesc{
+ ServiceName: "proto.AgentService",
+ HandlerType: (*AgentServiceServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "HealthCheck",
+ Handler: _AgentService_HealthCheck_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "Process",
+ Handler: _AgentService_Process_Handler,
+ ServerStreams: true,
+ ClientStreams: true,
+ },
+ {
+ StreamName: "StreamLifecycle",
+ Handler: _AgentService_StreamLifecycle_Handler,
+ ServerStreams: true,
+ ClientStreams: true,
+ },
+ },
+ Metadata: "proto/gar.proto",
+}
+
+const (
+ GARService_TriggerSession_FullMethodName = "/proto.GARService/TriggerSession"
+ GARService_GetSession_FullMethodName = "/proto.GARService/GetSession"
+ GARService_ListSessions_FullMethodName = "/proto.GARService/ListSessions"
+ GARService_RegisterAgent_FullMethodName = "/proto.GARService/RegisterAgent"
+ GARService_UnregisterAgent_FullMethodName = "/proto.GARService/UnregisterAgent"
+)
+
+// GARServiceClient is the client API for GARService service.
+//
+// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
+//
+// GARService defines the gRPC service for GAR operations
+type GARServiceClient interface {
+ // TriggerSession triggers a new agentic loop session or resumes an existing one with streaming responses
+ // If the session_id already exists, it will be resumed from the last checkpoint
+ TriggerSession(ctx context.Context, in *TriggerSessionRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[TriggerSessionResponse], error)
+ // GetSession retrieves session details
+ GetSession(ctx context.Context, in *GetSessionRequest, opts ...grpc.CallOption) (*GetSessionResponse, error)
+ // ListSessions lists all available sessions
+ ListSessions(ctx context.Context, in *ListSessionsRequest, opts ...grpc.CallOption) (*ListSessionsResponse, error)
+ // RegisterAgent registers a new agent with the controller
+ RegisterAgent(ctx context.Context, in *RegisterAgentRequest, opts ...grpc.CallOption) (*RegisterAgentResponse, error)
+ // UnregisterAgent removes an agent from the controller
+ UnregisterAgent(ctx context.Context, in *UnregisterAgentRequest, opts ...grpc.CallOption) (*UnregisterAgentResponse, error)
+}
+
+type gARServiceClient struct {
+ cc grpc.ClientConnInterface
+}
+
+func NewGARServiceClient(cc grpc.ClientConnInterface) GARServiceClient {
+ return &gARServiceClient{cc}
+}
+
+func (c *gARServiceClient) TriggerSession(ctx context.Context, in *TriggerSessionRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[TriggerSessionResponse], error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ stream, err := c.cc.NewStream(ctx, &GARService_ServiceDesc.Streams[0], GARService_TriggerSession_FullMethodName, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ x := &grpc.GenericClientStream[TriggerSessionRequest, TriggerSessionResponse]{ClientStream: stream}
+ if err := x.ClientStream.SendMsg(in); err != nil {
+ return nil, err
+ }
+ if err := x.ClientStream.CloseSend(); err != nil {
+ return nil, err
+ }
+ return x, nil
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type GARService_TriggerSessionClient = grpc.ServerStreamingClient[TriggerSessionResponse]
+
+func (c *gARServiceClient) GetSession(ctx context.Context, in *GetSessionRequest, opts ...grpc.CallOption) (*GetSessionResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(GetSessionResponse)
+ err := c.cc.Invoke(ctx, GARService_GetSession_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *gARServiceClient) ListSessions(ctx context.Context, in *ListSessionsRequest, opts ...grpc.CallOption) (*ListSessionsResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(ListSessionsResponse)
+ err := c.cc.Invoke(ctx, GARService_ListSessions_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *gARServiceClient) RegisterAgent(ctx context.Context, in *RegisterAgentRequest, opts ...grpc.CallOption) (*RegisterAgentResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(RegisterAgentResponse)
+ err := c.cc.Invoke(ctx, GARService_RegisterAgent_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+func (c *gARServiceClient) UnregisterAgent(ctx context.Context, in *UnregisterAgentRequest, opts ...grpc.CallOption) (*UnregisterAgentResponse, error) {
+ cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...)
+ out := new(UnregisterAgentResponse)
+ err := c.cc.Invoke(ctx, GARService_UnregisterAgent_FullMethodName, in, out, cOpts...)
+ if err != nil {
+ return nil, err
+ }
+ return out, nil
+}
+
+// GARServiceServer is the server API for GARService service.
+// All implementations must embed UnimplementedGARServiceServer
+// for forward compatibility.
+//
+// GARService defines the gRPC service for GAR operations
+type GARServiceServer interface {
+ // TriggerSession triggers a new agentic loop session or resumes an existing one with streaming responses
+ // If the session_id already exists, it will be resumed from the last checkpoint
+ TriggerSession(*TriggerSessionRequest, grpc.ServerStreamingServer[TriggerSessionResponse]) error
+ // GetSession retrieves session details
+ GetSession(context.Context, *GetSessionRequest) (*GetSessionResponse, error)
+ // ListSessions lists all available sessions
+ ListSessions(context.Context, *ListSessionsRequest) (*ListSessionsResponse, error)
+ // RegisterAgent registers a new agent with the controller
+ RegisterAgent(context.Context, *RegisterAgentRequest) (*RegisterAgentResponse, error)
+ // UnregisterAgent removes an agent from the controller
+ UnregisterAgent(context.Context, *UnregisterAgentRequest) (*UnregisterAgentResponse, error)
+ mustEmbedUnimplementedGARServiceServer()
+}
+
+// UnimplementedGARServiceServer must be embedded to have
+// forward compatible implementations.
+//
+// NOTE: this should be embedded by value instead of pointer to avoid a nil
+// pointer dereference when methods are called.
+type UnimplementedGARServiceServer struct{}
+
+func (UnimplementedGARServiceServer) TriggerSession(*TriggerSessionRequest, grpc.ServerStreamingServer[TriggerSessionResponse]) error {
+ return status.Error(codes.Unimplemented, "method TriggerSession not implemented")
+}
+func (UnimplementedGARServiceServer) GetSession(context.Context, *GetSessionRequest) (*GetSessionResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method GetSession not implemented")
+}
+func (UnimplementedGARServiceServer) ListSessions(context.Context, *ListSessionsRequest) (*ListSessionsResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method ListSessions not implemented")
+}
+func (UnimplementedGARServiceServer) RegisterAgent(context.Context, *RegisterAgentRequest) (*RegisterAgentResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method RegisterAgent not implemented")
+}
+func (UnimplementedGARServiceServer) UnregisterAgent(context.Context, *UnregisterAgentRequest) (*UnregisterAgentResponse, error) {
+ return nil, status.Error(codes.Unimplemented, "method UnregisterAgent not implemented")
+}
+func (UnimplementedGARServiceServer) mustEmbedUnimplementedGARServiceServer() {}
+func (UnimplementedGARServiceServer) testEmbeddedByValue() {}
+
+// UnsafeGARServiceServer may be embedded to opt out of forward compatibility for this service.
+// Use of this interface is not recommended, as added methods to GARServiceServer will
+// result in compilation errors.
+type UnsafeGARServiceServer interface {
+ mustEmbedUnimplementedGARServiceServer()
+}
+
+func RegisterGARServiceServer(s grpc.ServiceRegistrar, srv GARServiceServer) {
+ // If the following call panics, it indicates UnimplementedGARServiceServer was
+ // embedded by pointer and is nil. This will cause panics if an
+ // unimplemented method is ever invoked, so we test this at initialization
+ // time to prevent it from happening at runtime later due to I/O.
+ if t, ok := srv.(interface{ testEmbeddedByValue() }); ok {
+ t.testEmbeddedByValue()
+ }
+ s.RegisterService(&GARService_ServiceDesc, srv)
+}
+
+func _GARService_TriggerSession_Handler(srv interface{}, stream grpc.ServerStream) error {
+ m := new(TriggerSessionRequest)
+ if err := stream.RecvMsg(m); err != nil {
+ return err
+ }
+ return srv.(GARServiceServer).TriggerSession(m, &grpc.GenericServerStream[TriggerSessionRequest, TriggerSessionResponse]{ServerStream: stream})
+}
+
+// This type alias is provided for backwards compatibility with existing code that references the prior non-generic stream type by name.
+type GARService_TriggerSessionServer = grpc.ServerStreamingServer[TriggerSessionResponse]
+
+func _GARService_GetSession_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(GetSessionRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(GARServiceServer).GetSession(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: GARService_GetSession_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(GARServiceServer).GetSession(ctx, req.(*GetSessionRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _GARService_ListSessions_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(ListSessionsRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(GARServiceServer).ListSessions(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: GARService_ListSessions_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(GARServiceServer).ListSessions(ctx, req.(*ListSessionsRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _GARService_RegisterAgent_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(RegisterAgentRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(GARServiceServer).RegisterAgent(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: GARService_RegisterAgent_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(GARServiceServer).RegisterAgent(ctx, req.(*RegisterAgentRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+func _GARService_UnregisterAgent_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) {
+ in := new(UnregisterAgentRequest)
+ if err := dec(in); err != nil {
+ return nil, err
+ }
+ if interceptor == nil {
+ return srv.(GARServiceServer).UnregisterAgent(ctx, in)
+ }
+ info := &grpc.UnaryServerInfo{
+ Server: srv,
+ FullMethod: GARService_UnregisterAgent_FullMethodName,
+ }
+ handler := func(ctx context.Context, req interface{}) (interface{}, error) {
+ return srv.(GARServiceServer).UnregisterAgent(ctx, req.(*UnregisterAgentRequest))
+ }
+ return interceptor(ctx, in, info, handler)
+}
+
+// GARService_ServiceDesc is the grpc.ServiceDesc for GARService service.
+// It's only intended for direct use with grpc.RegisterService,
+// and not to be introspected or modified (even as a copy)
+var GARService_ServiceDesc = grpc.ServiceDesc{
+ ServiceName: "proto.GARService",
+ HandlerType: (*GARServiceServer)(nil),
+ Methods: []grpc.MethodDesc{
+ {
+ MethodName: "GetSession",
+ Handler: _GARService_GetSession_Handler,
+ },
+ {
+ MethodName: "ListSessions",
+ Handler: _GARService_ListSessions_Handler,
+ },
+ {
+ MethodName: "RegisterAgent",
+ Handler: _GARService_RegisterAgent_Handler,
+ },
+ {
+ MethodName: "UnregisterAgent",
+ Handler: _GARService_UnregisterAgent_Handler,
+ },
+ },
+ Streams: []grpc.StreamDesc{
+ {
+ StreamName: "TriggerSession",
+ Handler: _GARService_TriggerSession_Handler,
+ ServerStreams: true,
+ },
+ },
+ Metadata: "proto/gar.proto",
+}
diff --git a/python/example_agent.py b/python/example_agent.py
new file mode 100644
index 0000000..51bf821
--- /dev/null
+++ b/python/example_agent.py
@@ -0,0 +1,24 @@
+#!/usr/bin/env python3
+"""
+Example Python agent using the GAR framework.
+
+This demonstrates a simple agent that uppercases input text.
+"""
+
+from gar import Agent
+import proto.gar_pb2 as pb2
+
+
+def process(content):
+ """Process incoming content and return response"""
+ return pb2.Content(
+ role="assistant",
+ type="text",
+ mimetype="text/plain",
+ data=f"Python processed: {content.data.upper()}"
+ )
+
+
+if __name__ == "__main__":
+ agent = Agent(agent_id="python-agent", process_func=process)
+ agent.serve(port=50051)
diff --git a/python/gar.py b/python/gar.py
new file mode 100644
index 0000000..41e7c83
--- /dev/null
+++ b/python/gar.py
@@ -0,0 +1,141 @@
+"""
+GAR Agent Framework for Python
+
+A simple framework for building Python agents that work with the GAR orchestrator.
+"""
+
+import grpc
+from concurrent import futures
+import time
+from typing import Callable, Iterator, Optional, Dict
+
+
+class Agent:
+ """
+ Agent provides a simple framework for building Python agents.
+
+ Usage:
+ def process(content):
+ return Content(role="assistant", type="text",
+ mimetype="text/plain", data=f"Processed: {content.data}")
+
+ agent = Agent(agent_id="my-agent", process_func=process)
+ agent.serve(port=50051)
+ """
+
+ def __init__(
+ self,
+ agent_id: str,
+ process_func: Callable,
+ lifecycle_func: Optional[Callable] = None,
+ health_check_func: Optional[Callable] = None
+ ):
+ """
+ Initialize an agent.
+
+ Args:
+ agent_id: Unique identifier for this agent
+ process_func: Function that processes Content and returns Content
+ lifecycle_func: Optional function that yields LifecycleEvent objects
+ health_check_func: Optional function that returns (healthy: bool, message: str, metadata: dict)
+ """
+ self.agent_id = agent_id
+ self.process_func = process_func
+ self.lifecycle_func = lifecycle_func
+ self.health_check_func = health_check_func
+
+ def _create_servicer(self, pb2, pb2_grpc):
+ """Create the gRPC servicer implementation."""
+ agent = self
+
+ class AgentServicer(pb2_grpc.AgentServiceServicer):
+ def Process(self, request_iterator, context):
+ for content in request_iterator:
+ response = agent.process_func(content)
+ if response:
+ yield response
+
+ def StreamLifecycle(self, request_iterator, context):
+ if agent.lifecycle_func:
+ for event in agent.lifecycle_func(context):
+ yield event
+ else:
+ # Default: send periodic heartbeats
+ while context.is_active():
+ event = pb2.LifecycleEvent(
+ event_type="HEARTBEAT",
+ agent_id=agent.agent_id,
+ timestamp=int(time.time() * 1000),
+ metadata={"status": "active"}
+ )
+ yield event
+ time.sleep(30)
+
+ def HealthCheck(self, request, context):
+ if agent.health_check_func:
+ healthy, message, metadata = agent.health_check_func()
+ else:
+ healthy, message, metadata = True, "Agent is healthy", {}
+
+ return pb2.HealthCheckResponse(
+ healthy=healthy,
+ message=message,
+ metadata=metadata or {}
+ )
+
+ return AgentServicer()
+
+ def serve(self, port: int = 50051, max_workers: int = 10):
+ """
+ Start the gRPC server.
+
+ Args:
+ port: Port to listen on (default: 50051)
+ max_workers: Maximum number of worker threads (default: 10)
+ """
+ # Import proto files (assuming they've been generated)
+ try:
+ import proto.gar_pb2 as pb2
+ import proto.gar_pb2_grpc as pb2_grpc
+ except ImportError:
+ raise ImportError(
+ "Proto files not found. Generate them first:\n"
+ " python -m grpc_tools.protoc -I. --python_out=. --grpc_python_out=. proto/gar.proto"
+ )
+
+ server = grpc.server(futures.ThreadPoolExecutor(max_workers=max_workers))
+ pb2_grpc.add_AgentServiceServicer_to_server(
+ self._create_servicer(pb2, pb2_grpc),
+ server
+ )
+ server.add_insecure_port(f'[::]:{port}')
+ server.start()
+ print(f"Agent '{self.agent_id}' listening on port {port}")
+
+ try:
+ server.wait_for_termination()
+ except KeyboardInterrupt:
+ print("\nShutting down agent...")
+ server.stop(grace=5)
+
+
+# Convenience function for quick agent creation
+def create_agent(
+ agent_id: str,
+ process_func: Callable,
+ lifecycle_func: Optional[Callable] = None,
+ health_check_func: Optional[Callable] = None,
+ port: int = 50051
+):
+ """
+ Create and start an agent in one call.
+
+ Args:
+ agent_id: Unique identifier for this agent
+ process_func: Function that processes Content and returns Content
+ lifecycle_func: Optional function that yields LifecycleEvent objects
+ health_check_func: Optional function that returns (healthy: bool, message: str, metadata: dict)
+ port: Port to listen on (default: 50051)
+ """
+ agent = Agent(agent_id, process_func, lifecycle_func, health_check_func)
+ agent.serve(port=port)