Skip to content
Open
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
1 change: 1 addition & 0 deletions packages/appkit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,7 @@
"get-port": "7.2.0",
"js-yaml": "4.1.1",
"magic-string": "0.30.21",
"mlflow-tracing": "^0.1.3",
"obug": "2.1.1",
"pg": "8.18.0",
"picocolors": "1.1.1",
Expand Down
256 changes: 163 additions & 93 deletions packages/appkit/src/plugins/agents/agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,12 @@ import { agentStreamDefaults } from "./defaults";
import { EventChannel } from "./event-channel";
import { AgentEventTranslator } from "./event-translator";
import manifest from "./manifest.json";
import {
currentTraceId,
initAgentTracing,
linkTraceToRun,
withAgentSpan,
} from "./mlflow";
import {
approvalRequestSchema,
cancelRequestSchema,
Expand Down Expand Up @@ -130,7 +136,11 @@ interface RunState {
}

export class AgentsPlugin extends Plugin implements ToolProvider {
static manifest = manifest as PluginManifest;
// Routed through `unknown`: the optional resources have differing `fields`
// keys (serving `name`, experiment `experimentId`), which TS widens to an
// incompatible union on the JSON import. The shape is validated at runtime
// against the plugin-manifest schema.
static manifest = manifest as unknown as PluginManifest;
static phase: PluginPhase = "deferred";

protected declare config: AgentsPluginConfig;
Expand Down Expand Up @@ -273,6 +283,7 @@ export class AgentsPlugin extends Plugin implements ToolProvider {
}

async setup() {
await initAgentTracing();
const { agents, defaultAgentName } = await this.buildAgentRegistry();
this.agents = agents;
this.defaultAgentName = defaultAgentName;
Expand Down Expand Up @@ -1070,61 +1081,97 @@ export class AgentsPlugin extends Plugin implements ToolProvider {
outboundEvents.push(evt);
}

const pluginNames = this.context
? this.context
.getPluginNames()
.filter((n) => n !== this.name && n !== "server")
: [];
const fullPrompt = composePromptForAgent(
registered,
this.config.baseSystemPrompt,
// Root MLflow span for the turn (AGENT). Tool calls dispatched while
// the adapter streams nest under it via the SDK's active context.
// No-op passthrough unless an MLflow experiment is bound.
await withAgentSpan(
{
agentName: registered.name,
pluginNames,
toolNames: tools.map((t) => t.name),
name: registered.name ?? "agent",
type: "AGENT",
inputs: {
messages: thread.messages.map((m) => ({
role: m.role,
content: m.content,
})),
},
},
);
async (span) => {
// Link this turn's trace to an eval run when the eval runner
// supplied one, so the trace shows under the MLflow evaluation run.
const evalRunId = (req.body as { mlflowRunId?: string })
?.mlflowRunId;
if (evalRunId) linkTraceToRun(evalRunId);

const pluginNames = this.context
? this.context
.getPluginNames()
.filter((n) => n !== this.name && n !== "server")
: [];
const fullPrompt = composePromptForAgent(
registered,
this.config.baseSystemPrompt,
{
agentName: registered.name,
pluginNames,
toolNames: tools.map((t) => t.name),
},
);

const messagesWithSystem: Message[] = [
{
id: "system",
role: "system",
content: fullPrompt,
createdAt: new Date(),
},
...thread.messages,
];
const messagesWithSystem: Message[] = [
{
id: "system",
role: "system",
content: fullPrompt,
createdAt: new Date(),
},
...thread.messages,
];

const stream = registered.adapter.run(
{
messages: messagesWithSystem,
tools,
threadId: thread.id,
signal,
},
{ executeTool, signal },
);

const stream = registered.adapter.run(
{
messages: messagesWithSystem,
tools,
threadId: thread.id,
signal,
},
{ executeTool, signal },
);
// The accumulation rule (deltas append, `message` replaces) is
// shared with `runAgent` and `runSubAgent`; see
// `consumeAdapterStream` for the rationale.
const fullContent = await consumeAdapterStream(stream, {
signal,
onEvent: (event) => {
for (const translated of translator.translate(event)) {
outboundEvents.push(translated);
}
},
});

if (fullContent) {
span?.setOutputs({ role: "assistant", content: fullContent });
await this.threadStore.addMessage(thread.id, userId, {
id: randomUUID(),
role: "assistant",
content: fullContent,
createdAt: new Date(),
});
}

// The accumulation rule (deltas append, `message` replaces) is shared
// with `runAgent` and `runSubAgent`; see `consumeAdapterStream` for
// the rationale.
const fullContent = await consumeAdapterStream(stream, {
signal,
onEvent: (event) => {
for (const translated of translator.translate(event)) {
outboundEvents.push(translated);
// Surface the MLflow trace id so eval runs can attach assessments
// to this turn's trace. No-op when tracing is disabled.
const mlflowTraceId = currentTraceId();
if (mlflowTraceId) {
for (const evt of translator.translate({
type: "metadata",
data: { mlflowTraceId },
})) {
outboundEvents.push(evt);
}
}
},
});

if (fullContent) {
await this.threadStore.addMessage(thread.id, userId, {
id: randomUUID(),
role: "assistant",
content: fullContent,
createdAt: new Date(),
});
}
);

for (const evt of translator.finalize()) outboundEvents.push(evt);
} catch (error) {
Expand Down Expand Up @@ -1389,51 +1436,74 @@ export class AgentsPlugin extends Plugin implements ToolProvider {
}
}

let result: unknown;
if (entry.source === "toolkit") {
if (!this.context) {
throw new Error(
"Plugin tool execution requires PluginContext; this should never happen through createApp",
);
}
result = await this.context.executeTool(
runState.req,
entry.pluginName,
entry.localName,
args,
runState.signal,
runState.limits.toolCallTimeoutMs,
);
} else if (entry.source === "function") {
// Function tools declare their parameters as a JSON-object schema,
// so adapters always serialize `args` as an object. A non-object
// value here means the upstream model emitted malformed tool-call
// JSON; surface a clear error rather than silently passing through
// a wrong-shape value the tool will then choke on.
if (typeof args !== "object" || args === null || Array.isArray(args)) {
throw new Error(
`Function tool '${name}' received non-object arguments (got ${args === null ? "null" : Array.isArray(args) ? "array" : typeof args}); expected a JSON object.`,
);
}
result = await entry.functionTool.execute(
args as Record<string, unknown>,
);
} else if (entry.source === "mcp") {
if (!this.mcpClient) throw new Error("MCP client not connected");
const oboToken = runState.req.headers["x-forwarded-access-token"];
const mcpAuth =
typeof oboToken === "string"
? { Authorization: `Bearer ${oboToken}` }
: undefined;
result = await this.mcpClient.callTool(entry.mcpToolName, args, mcpAuth);
} else if (entry.source === "subagent") {
const childAgent = this.agents.get(entry.agentName);
if (!childAgent)
throw new Error(`Sub-agent not found: ${entry.agentName}`);
result = await this.runSubAgent(runState, childAgent, args, depth + 1);
}
// MLflow TOOL span — nests under the turn's AGENT span. Wraps the
// execution only (not the approval wait above, which is human latency).
const toolResult = await withAgentSpan(
{ name, type: "TOOL", inputs: args },
async (span) => {
let result: unknown;
if (entry.source === "toolkit") {
if (!this.context) {
throw new Error(
"Plugin tool execution requires PluginContext; this should never happen through createApp",
);
}
result = await this.context.executeTool(
runState.req,
entry.pluginName,
entry.localName,
args,
runState.signal,
runState.limits.toolCallTimeoutMs,
);
} else if (entry.source === "function") {
// Function tools declare their parameters as a JSON-object schema,
// so adapters always serialize `args` as an object. A non-object
// value here means the upstream model emitted malformed tool-call
// JSON; surface a clear error rather than silently passing through
// a wrong-shape value the tool will then choke on.
if (
typeof args !== "object" ||
args === null ||
Array.isArray(args)
) {
throw new Error(
`Function tool '${name}' received non-object arguments (got ${args === null ? "null" : Array.isArray(args) ? "array" : typeof args}); expected a JSON object.`,
);
}
result = await entry.functionTool.execute(
args as Record<string, unknown>,
);
} else if (entry.source === "mcp") {
if (!this.mcpClient) throw new Error("MCP client not connected");
const oboToken = runState.req.headers["x-forwarded-access-token"];
const mcpAuth =
typeof oboToken === "string"
? { Authorization: `Bearer ${oboToken}` }
: undefined;
result = await this.mcpClient.callTool(
entry.mcpToolName,
args,
mcpAuth,
);
} else if (entry.source === "subagent") {
const childAgent = this.agents.get(entry.agentName);
if (!childAgent)
throw new Error(`Sub-agent not found: ${entry.agentName}`);
result = await this.runSubAgent(
runState,
childAgent,
args,
depth + 1,
);
}

span?.setOutputs(result);
return result;
},
);

return normalizeToolResult(result);
return normalizeToolResult(toolResult);
}

/**
Expand Down
13 changes: 13 additions & 0 deletions packages/appkit/src/plugins/agents/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,19 @@
"description": "Default LLM serving endpoint name"
}
}
},
{
"type": "experiment",
"alias": "MLflow experiment for agent traces",
"resourceKey": "agents-mlflow-experiment",
"description": "When bound, agent turns and tool calls are traced to this MLflow experiment via OpenTelemetry. Tracing is a no-op when unset.",
"permission": "CAN_EDIT",
"fields": {
"experimentId": {
"env": "MLFLOW_EXPERIMENT_ID",
"description": "MLflow experiment id traces are logged to"
}
}
}
]
}
Expand Down
Loading