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
4 changes: 2 additions & 2 deletions agent-docs/src/agents/agent-pulse/context/builder.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AgentContext } from "@agentuity/sdk";
type AgentContext = any;

export async function buildSystemPrompt(tutorialContext: string, ctx: AgentContext): Promise<string> {
try {
Expand Down Expand Up @@ -51,4 +51,4 @@ Stream your reasoning steps clearly.`;
ctx.logger.error("Failed to build system prompt: %s", error instanceof Error ? error.message : String(error));
throw error; // Re-throw for centralized handling
}
}
}
5 changes: 3 additions & 2 deletions agent-docs/src/agents/agent-pulse/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { AgentRequest, AgentResponse, AgentContext } from "@agentuity/sdk";
type AgentRequest = any;
type AgentResponse = any;
type AgentContext = any;
import { streamText } from "ai";
import { openai } from "@ai-sdk/openai";
import { createTools } from "./tools";
Expand Down Expand Up @@ -119,7 +121,6 @@ export default async function Agent(
content: msg.content,
})),
tools,
maxSteps: 3,
system: systemPrompt,
});

Expand Down
2 changes: 1 addition & 1 deletion agent-docs/src/agents/agent-pulse/request/parser.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AgentContext } from "@agentuity/sdk";
type AgentContext = any;
import type { ParsedAgentRequest } from "./types";

export function parseAgentRequest(
Expand Down
4 changes: 2 additions & 2 deletions agent-docs/src/agents/agent-pulse/state/manager.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AgentContext } from "@agentuity/sdk";
type AgentContext = any;
import { ActionType, type AgentState } from "../state";
import { getTutorialStep } from "../tutorial";
import type { TutorialData } from "../streaming/types";
Expand Down Expand Up @@ -51,4 +51,4 @@ export async function handleTutorialState(
ctx.logger.error("Failed to handle tutorial state: %s", error instanceof Error ? error.message : String(error));
throw error; // Re-throw for centralized handling
}
}
}
2 changes: 1 addition & 1 deletion agent-docs/src/agents/agent-pulse/streaming/processor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AgentContext } from "@agentuity/sdk";
type AgentContext = any;
import type { AgentState } from "../state";
import type { StreamingChunk, TutorialData } from "./types";
import { handleTutorialState } from "../state/manager";
Expand Down
19 changes: 11 additions & 8 deletions agent-docs/src/agents/agent-pulse/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { tool } from "ai";
import { z } from "zod";
import { ActionType } from "./state";
import type { AgentState } from "./state";
import type { AgentContext } from "@agentuity/sdk";
type AgentContext = any;
import { getTutorialMeta } from "./tutorial";

/**
Expand All @@ -25,11 +25,12 @@ export async function createTools(context: ToolContext) {
*/
const startTutorialAtStep = tool({
description: "Start a specific tutorial for the user. You must call this function in order for the user to see the tutorial step content. The step number should be between 1 and the total number of steps in the tutorial.",
parameters: z.object({
inputSchema: z.object({
tutorialId: z.string().describe("The exact ID of the tutorial to start"),
stepNumber: z.number().describe("The step number of the tutorial to start (1 to total available steps in the tutorial)")
}),
execute: async ({ tutorialId, stepNumber }) => {
execute: async (input: any, options: any) => {
const { tutorialId, stepNumber } = input;
// Validate tutorial exists before starting
const tutorialResponse = await getTutorialMeta(tutorialId, agentContext);
if (!tutorialResponse.success || !tutorialResponse.data) {
Expand Down Expand Up @@ -58,10 +59,11 @@ export async function createTools(context: ToolContext) {
*/
const askDocsAgentTool = tool({
description: "Query the Agentuity Development Documentation agent using RAG (Retrieval Augmented Generation) to get relevant documentation and answers about the Agentuity platform, APIs, and development concepts",
parameters: z.object({
inputSchema: z.object({
query: z.string().describe("The question or query to send to the query function"),
}),
execute: async ({ query }) => {
execute: async (input: any, options: any) => {
const { query } = input;
agentContext.logger.info("Querying agent %s with: %s", DOC_QA_AGENT_NAME, query);
const agentPayload = {
message: query,
Expand All @@ -82,10 +84,11 @@ export async function createTools(context: ToolContext) {
*/
const fetchCodeExecutionResultTool = tool({
description: "Fetch code execution results from the frontend",
parameters: z.object({
inputSchema: z.object({
executionId: z.string().describe("The ID of the code execution"),
}),
execute: async ({ executionId }) => {
execute: async (input: any, options: any) => {
const { executionId } = input;
agentContext.logger.info("Fetching execution result for: %s", executionId);
// This would actually fetch execution results
// For now, just return a mock response
Expand All @@ -100,4 +103,4 @@ export async function createTools(context: ToolContext) {
};
}

export type { ToolContext };
export type { ToolContext };
4 changes: 2 additions & 2 deletions agent-docs/src/agents/agent-pulse/tutorial.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AgentContext } from '@agentuity/sdk';
type AgentContext = any;

const TUTORIAL_API_BASE_URL = process.env.TUTORIAL_API_URL;

Expand Down Expand Up @@ -95,4 +95,4 @@ export async function getTutorialStep(tutorialId: string, stepNumber: number, ct
ctx.logger.error('Error fetching tutorial step %d for tutorial %s: %s', stepNumber, tutorialId, error);
throw error;
}
}
}
2 changes: 1 addition & 1 deletion agent-docs/src/agents/doc-processing/docs-orchestrator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AgentContext } from '@agentuity/sdk';
type AgentContext = any;
import { VECTOR_STORE_NAME } from '../../../config';
import { processDoc } from './docs-processor';
import type { SyncPayload, SyncStats } from './types';
Expand Down
2 changes: 1 addition & 1 deletion agent-docs/src/agents/doc-processing/docs-processor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { VectorUpsertParams } from '@agentuity/sdk';
type VectorUpsertParams = any;
import type { Chunk } from './chunk-mdx';
import { chunkAndEnrichDoc } from './chunk-mdx';
import { embedChunks } from './embed-chunks';
Expand Down
4 changes: 3 additions & 1 deletion agent-docs/src/agents/doc-processing/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { AgentContext, AgentRequest, AgentResponse } from '@agentuity/sdk';
type AgentContext = any;
type AgentRequest = any;
type AgentResponse = any;
import { syncDocsFromPayload } from './docs-orchestrator';
import type { SyncPayload } from './types';

Expand Down
4 changes: 3 additions & 1 deletion agent-docs/src/agents/doc-qa/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import type { AgentContext, AgentRequest, AgentResponse } from '@agentuity/sdk';
type AgentContext = any;
type AgentRequest = any;
type AgentResponse = any;
import answerQuestion from './rag';

export default async function Agent(
Expand Down
2 changes: 1 addition & 1 deletion agent-docs/src/agents/doc-qa/prompt.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AgentContext } from '@agentuity/sdk';
type AgentContext = any;
import { openai } from '@ai-sdk/openai';
import { generateObject, generateText } from 'ai';

Expand Down
2 changes: 1 addition & 1 deletion agent-docs/src/agents/doc-qa/rag.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AgentContext } from '@agentuity/sdk';
type AgentContext = any;
import { openai } from '@ai-sdk/openai';
import { generateObject } from 'ai';
import { rephraseVaguePrompt } from './prompt';
Expand Down
2 changes: 1 addition & 1 deletion agent-docs/src/agents/doc-qa/retriever.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { AgentContext } from '@agentuity/sdk';
type AgentContext = any;

import { VECTOR_STORE_NAME, vectorSearchNumber } from '../../../config';
import type { RelevantDoc } from './types';
Expand Down
29 changes: 19 additions & 10 deletions app/api/sessions/[sessionId]/messages/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,9 +220,14 @@ export async function POST(
const agentConfig = getAgentPulseConfig();
const agentUrl = agentConfig.url;

// Get current tutorial state for the user
const { TutorialStateManager } = await import('@/lib/tutorial/state-manager');
const currentTutorialState = await TutorialStateManager.getCurrentTutorialState(userId);
// Get current tutorial state for the user (conditional loading)
const { canLoadAgentCode } = await import('@/lib/env-detection');
let currentTutorialState = null;

if (canLoadAgentCode()) {
const { TutorialStateManager } = await import('@/lib/tutorial/state-manager');
currentTutorialState = await TutorialStateManager.getCurrentTutorialState(userId);
}

const agentPayload = {
message: message.content,
Expand Down Expand Up @@ -275,13 +280,17 @@ export async function POST(
} else if (data.type === "tutorial-data" && data.tutorialData) {
finalTutorialData = data.tutorialData;

// Update user's tutorial progress
await TutorialStateManager.updateTutorialProgress(
userId,
finalTutorialData.tutorialId,
finalTutorialData.currentStep,
finalTutorialData.totalSteps
);
// Update user's tutorial progress (conditional loading)
const { canLoadAgentCode } = await import('@/lib/env-detection');
if (canLoadAgentCode()) {
const { TutorialStateManager } = await import('@/lib/tutorial/state-manager');
await TutorialStateManager.updateTutorialProgress(
userId,
finalTutorialData.tutorialId,
finalTutorialData.currentStep,
finalTutorialData.totalSteps
);
}
} else if (data.type === "finish") {
// When the stream is finished, save the assistant message
const assistantMessage: Message = {
Expand Down
19 changes: 18 additions & 1 deletion app/api/users/tutorial-state/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { NextRequest, NextResponse } from 'next/server';
import { TutorialStateManager } from '@/lib/tutorial/state-manager';
import { setKVValue } from '@/lib/kv-store';
import { config } from '@/lib/config';
import {
Expand All @@ -18,6 +17,12 @@ export async function GET(request: NextRequest) {
return NextResponse.json({ error: 'User ID not found' }, { status: 401 });
}

const { canLoadAgentCode } = await import('@/lib/env-detection');
if (!canLoadAgentCode()) {
return NextResponse.json({ error: 'Tutorial state not available in this environment' }, { status: 503 });
}

const { TutorialStateManager } = await import('@/lib/tutorial/state-manager');
const tutorialState = await TutorialStateManager.getUserTutorialState(userId);

return NextResponse.json({
Expand Down Expand Up @@ -50,6 +55,12 @@ export async function POST(request: NextRequest) {

const { tutorialId, currentStep, totalSteps } = validation.data;

const { canLoadAgentCode } = await import('@/lib/env-detection');
if (!canLoadAgentCode()) {
return NextResponse.json({ error: 'Tutorial state not available in this environment' }, { status: 503 });
}

const { TutorialStateManager } = await import('@/lib/tutorial/state-manager');
await TutorialStateManager.updateTutorialProgress(
userId,
tutorialId,
Expand Down Expand Up @@ -87,6 +98,12 @@ export async function DELETE(request: NextRequest) {

const { tutorialId } = validation.data;

const { canLoadAgentCode } = await import('@/lib/env-detection');
if (!canLoadAgentCode()) {
return NextResponse.json({ error: 'Tutorial state not available in this environment' }, { status: 503 });
}

const { TutorialStateManager } = await import('@/lib/tutorial/state-manager');
const state = await TutorialStateManager.getUserTutorialState(userId);
if (!state.tutorials) {
state.tutorials = {};
Expand Down
26 changes: 26 additions & 0 deletions lib/agent-loader.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { canLoadAgentCode } from './env-detection';

/**
* Conditionally load agent-docs code only in Node.js environments
* This prevents OpenTelemetry auto-instrumentations from loading in Cloudflare Workers
*/
export async function loadAgentCode() {
if (!canLoadAgentCode()) {
throw new Error('Agent code cannot be loaded in this environment');
}

try {
const agentModule = await import('../agent-docs/src/agents/agent-pulse/index');
return agentModule.default;
} catch (error) {
const stubModule = await import('./agent-stub');
return stubModule.default;
}
}

/**
* Check if agent code can be loaded in the current environment
*/
export function isAgentCodeAvailable(): boolean {
return canLoadAgentCode();
}
12 changes: 12 additions & 0 deletions lib/agent-stub.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* Stub implementation for agent functionality during build time
* This prevents loading of @agentuity/sdk and related dependencies
*/

export default function AgentStub() {
throw new Error('Agent functionality not available in this environment');
}

export const createTools = () => {
throw new Error('Agent tools not available in this environment');
};
17 changes: 17 additions & 0 deletions lib/env-detection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Detect if we're running in a Cloudflare Workers environment
*/
export function isCloudflareWorkers(): boolean {
return typeof (globalThis as any).caches !== 'undefined' &&
typeof (globalThis as any).EdgeRuntime !== 'undefined' ||
typeof process === 'undefined' ||
(typeof process !== 'undefined' && process.env?.CF_PAGES === '1') ||
(typeof process !== 'undefined' && process.env?.CLOUDFLARE_ENV !== undefined);
}

/**
* Detect if we're running in a Node.js environment where agent code can be loaded
*/
export function canLoadAgentCode(): boolean {
return !isCloudflareWorkers() && typeof process !== 'undefined';
}
10 changes: 10 additions & 0 deletions next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,16 @@ const config = {
permanent: true,
},
],
webpack: (config, { isServer }) => {
// Exclude agent-docs directory from webpack compilation to prevent
// OpenTelemetry auto-instrumentations from loading in Cloudflare Workers
config.module.rules.push({
test: /agent-docs/,
use: 'ignore-loader',
});

return config;
},
};

export default withMDX(config);
Expand Down
Loading