Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions packages/coding-agent/skills/agent-observe/SKILL.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
---
name: agent-observe
description: Read-only observation of active Prime Agent sessions through the local daemon. Use to list agents, inspect session status, and read bounded recent-message previews without mutating other sessions.
---

# Agent Observe

Observe active Prime Agent sessions through the local daemon. This skill is
read-only: it can list sessions, inspect one session, and fetch bounded recent
message previews. It cannot prompt, steer, clear, kill, rename, or otherwise
mutate another session.

Call directly from the kernel:

```python
agents = await agent_observe.list_agents()
worker = await agent_observe.get_agent("worker")
recent = await agent_observe.recent_messages("worker", limit=6)
```

## API

- `await agent_observe.list_agents()` returns `current` and `agents`. Each
agent includes active session id, session id, optional name, runtime kind,
cwd, status, streaming state, message count, pending count, and a latest
message preview.
- `await agent_observe.get_agent(target)` returns one agent summary. `target`
is resolved like other live-session selectors: active id, session id/name, or
unambiguous suffix.
- `await agent_observe.recent_messages(target, limit=8, max_chars=800)`
returns up to `limit` recent bounded message previews for the target session.
`limit` must be 1-50, and `max_chars` must be 80-2000.

## Safety

- This skill is read-only and exposes no mutation commands.
- Message access is bounded by count and per-message character limit.
- Prefer status and recent previews for orchestration. Ask the user before
using observed context to steer or message another session.
8 changes: 8 additions & 0 deletions packages/coding-agent/skills/agent-observe/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[project]
name = "agent-observe"
version = "0.1.0"
description = "Read-only Prime Agent session observation skill"
Comment on lines +1 to +4

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High agent-observe/pyproject.toml:1

The pyproject.toml is missing the [build-system] section required for editable installation. When uv pip install --editable falls back to setuptools (which happens without an explicit build-system), the src/agent_observe/ layout may not be discovered correctly, causing the skill to fail to install and be silently unavailable at runtime.

+[build-system]
+requires = ["hatchling"]
+build-backend = "hatchling.build"
+
+[tool.hatch.build.targets.wheel]
+packages = ["src/agent_observe"]
+
 [project]
 name = "agent-observe"
 version = "0.1.0"
 description = "Read-only Prime Agent session observation skill"
 requires-python = ">=3.10"
 
 [tool.prime_agent.skill]
 import = "agent_observe"
🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
In file @packages/coding-agent/skills/agent-observe/pyproject.toml around lines 1-4:

The `pyproject.toml` is missing the `[build-system]` section required for editable installation. When `uv pip install --editable` falls back to setuptools (which happens without an explicit build-system), the `src/agent_observe/` layout may not be discovered correctly, causing the skill to fail to install and be silently unavailable at runtime.

requires-python = ">=3.10"

[tool.prime_agent.skill]
import = "agent_observe"
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Read-only Prime Agent session observation skill.

All session lookup and data access live in the TypeScript daemon. These
functions only call the host bridge exposed inside the Prime Agent IPython
kernel.
"""

from __future__ import annotations

from typing import Any

from rlm import host_request


async def list_agents() -> dict[str, Any]:
"""List active daemon sessions visible to this agent."""
return await host_request("agent_observe.list")


async def get_agent(target: str) -> dict[str, Any]:
"""Read one active session summary by active id, session id/name, or suffix."""
if not isinstance(target, str):
raise TypeError(f"target must be str, got {type(target).__name__}")
return await host_request("agent_observe.get", {"target": target})


async def recent_messages(
target: str,
limit: int = 8,
max_chars: int = 800,
) -> dict[str, Any]:
"""Read bounded recent message previews from an active session.

Args:
target: Active session id, session id/name, or unambiguous suffix.
limit: Number of recent messages to return. Host validates 1-50.
max_chars: Per-message preview size. Host validates 80-2000.
"""
if not isinstance(target, str):
raise TypeError(f"target must be str, got {type(target).__name__}")
if not isinstance(limit, int):
raise TypeError(f"limit must be int, got {type(limit).__name__}")
if not isinstance(max_chars, int):
raise TypeError(f"max_chars must be int, got {type(max_chars).__name__}")
return await host_request(
"agent_observe.recent",
{
"target": target,
"limit": limit,
"max_chars": max_chars,
},
)
193 changes: 193 additions & 0 deletions packages/coding-agent/src/core/agent-observe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,193 @@
import type { AgentMessage } from "@earendil-works/pi-agent-core";

export const AGENT_OBSERVE_SKILL_NAME = "agent-observe";
export const AGENT_OBSERVE_IMPORT_NAME = "agent_observe";

export interface AgentObserveAgentSummary {
activeSessionId: string;
sessionId: string;
sessionName?: string;
runtimeKind?: "top-level" | "subagent";
cwd: string;
status: string;
isCurrent: boolean;
isStreaming: boolean;
isCompacting: boolean;
attachedClients: number;
messageCount: number;
pendingMessageCount: number;
parentActiveSessionId?: string;
parentSessionId?: string;
rlmChildId?: string;
rlmParentNodeId?: string;
firstMessage?: string;
latestMessage?: AgentObserveMessagePreview;
}

export interface AgentObserveListResult {
current: AgentObserveAgentSummary;
agents: AgentObserveAgentSummary[];
}

export interface AgentObserveAgentSnapshot {
agent: AgentObserveAgentSummary;
}

export interface AgentObserveRecentMessagesInput {
target: string;
limit?: number;
maxChars?: number;
}

export interface AgentObserveRecentMessagesResult {
agent: AgentObserveAgentSummary;
messages: AgentObserveMessagePreview[];
limit: number;
maxChars: number;
truncated: boolean;
}

export interface AgentObserveMessagePreview {
index: number;
role: string;
timestamp?: number;
text: string;
truncated: boolean;
toolCalls?: string[];
customType?: string;
}

export interface AgentObserveController {
listAgents(): AgentObserveListResult;
getAgent(target: string): AgentObserveAgentSnapshot;
recentMessages(input: AgentObserveRecentMessagesInput): AgentObserveRecentMessagesResult;
}

export function createAgentObserveHostHandlers(controller: AgentObserveController) {
return {
"agent_observe.list": async () => controller.listAgents() as unknown as Record<string, unknown>,
"agent_observe.get": async (payload: Record<string, unknown> = {}) => {
if (typeof payload.target !== "string") {
throw new Error("agent_observe.get target must be a string");
}
return controller.getAgent(payload.target) as unknown as Record<string, unknown>;
},
"agent_observe.recent": async (payload: Record<string, unknown> = {}) => {
if (typeof payload.target !== "string") {
throw new Error("agent_observe.recent target must be a string");
}
return controller.recentMessages({
target: payload.target,
limit: normalizeOptionalInteger(payload.limit, "agent_observe.recent limit"),
maxChars: normalizeOptionalInteger(payload.max_chars ?? payload.maxChars, "agent_observe.recent max_chars"),
}) as unknown as Record<string, unknown>;
},
};
}

export function normalizeObserveLimit(limit: number | undefined, defaultLimit = 8): number {
return clampInteger(limit ?? defaultLimit, 1, 50, "agent_observe limit");
}

export function normalizeObserveMaxChars(maxChars: number | undefined, defaultMaxChars = 800): number {
return clampInteger(maxChars ?? defaultMaxChars, 80, 2_000, "agent_observe max_chars");
}

export function createAgentObserveMessagePreview(
message: AgentMessage,
index: number,
maxChars: number,
): AgentObserveMessagePreview {
const text = messageText(message);
const clipped = truncate(text, maxChars);
const toolCalls = message.role === "assistant" ? assistantToolCalls(message) : undefined;
return {
index,
role: message.role,
...(message.timestamp ? { timestamp: message.timestamp } : {}),
text: clipped.text,
truncated: clipped.truncated,
...(toolCalls && toolCalls.length > 0 ? { toolCalls } : {}),
...(message.role === "custom" ? { customType: message.customType } : {}),
};
}

function normalizeOptionalInteger(value: unknown, label: string): number | undefined {
if (value === undefined) {
return undefined;
}
if (typeof value !== "number" || !Number.isInteger(value)) {
throw new Error(`${label} must be an integer when provided`);
}
return value;
}

function clampInteger(value: number, min: number, max: number, label: string): number {
if (!Number.isInteger(value)) {
throw new Error(`${label} must be an integer`);
}
if (value < min || value > max) {
throw new Error(`${label} must be between ${min} and ${max}`);
}
return value;
}

function truncate(text: string, maxChars: number): { text: string; truncated: boolean } {
if (text.length <= maxChars) {
return { text, truncated: false };
}
return { text: text.slice(0, maxChars), truncated: true };
}

function messageText(message: AgentMessage): string {
switch (message.role) {
case "user":
case "assistant":
return contentText(message.content);
case "toolResult":
return contentText(message.content);
case "bashExecution":
return [message.command, message.output].filter(Boolean).join("\n");
case "custom":
return typeof message.content === "string" ? message.content : contentText(message.content);
case "branchSummary":
return message.summary;
case "compactionSummary":
return message.summary;
default: {
const exhaustive: never = message;
return JSON.stringify(exhaustive);
}
}
}

function contentText(content: unknown): string {
if (typeof content === "string") {
return content;
}
if (!Array.isArray(content)) {
return "";
}
return content
.map((block) => {
if (!block || typeof block !== "object" || !("type" in block)) {
return "";
}
if (block.type === "text" && "text" in block && typeof block.text === "string") {
return block.text;
}
if (block.type === "image") {
return "[image]";
}
if (block.type === "toolCall" && "name" in block && typeof block.name === "string") {
return `[tool_call:${block.name}]`;
}
return "";
})
.filter(Boolean)
.join("\n");
}

function assistantToolCalls(message: Extract<AgentMessage, { role: "assistant" }>): string[] {
return message.content.filter((block) => block.type === "toolCall").map((block) => block.name);
}
3 changes: 3 additions & 0 deletions packages/coding-agent/src/core/agent-session-services.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { join } from "node:path";
import type { ThinkingLevel } from "@earendil-works/pi-agent-core";
import type { Model } from "@earendil-works/pi-ai";
import { getAgentDir } from "../config.js";
import type { AgentObserveController } from "./agent-observe.js";
import { AuthStorage } from "./auth-storage.js";
import type { SessionStartEvent, ToolDefinition } from "./extensions/index.js";
import { ModelRegistry } from "./model-registry.js";
Expand Down Expand Up @@ -50,6 +51,7 @@ export interface AgentSessionCreationOptions {
initialActiveToolNames?: string[];
allowedToolNames?: string[];
includeGoals?: boolean;
agentObserveController?: AgentObserveController;
rlmDepth?: number;
rlmMaxDepth?: number;
rlmSessionDir?: string;
Expand Down Expand Up @@ -209,6 +211,7 @@ export async function createAgentSessionFromServices(
initialActiveToolNames: options.initialActiveToolNames,
allowedToolNames: options.allowedToolNames,
includeGoals: options.includeGoals,
agentObserveController: options.agentObserveController,
rlmDepth: options.rlmDepth,
rlmMaxDepth: options.rlmMaxDepth,
rlmSessionDir: options.rlmSessionDir,
Expand Down
Loading