Skip to content
Merged
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
8 changes: 6 additions & 2 deletions apps/rag-knowledge-agent/src/app/api/chat/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -134,10 +134,14 @@ export async function POST(request: NextRequest) {
.map((i) => i.stackone_account_id)
.filter((id): id is string => Boolean(id))

logger.log('Chat API - Starting agent loop', {
documentIds: documentIds.length,
console.log('[Chat API] Starting agent loop', {
integrationIdsFromAgent: integrationIds.length,
integrationsFound: integrations.length,
accountIds: accountIds.length,
accountIdPreviews: accountIds.map(id => id.slice(0, 12) + '...'),

@cubic-dev-ai cubic-dev-ai Bot Mar 25, 2026 •

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.

P2: Avoid logging account ID prefixes in production logs; this leaks identifiable integration/account data.

Prompt for AI agents
Check if this issue is valid — if so, understand the root cause and fix it. At apps/rag-knowledge-agent/src/app/api/chat/route.ts, line 141:

<comment>Avoid logging account ID prefixes in production logs; this leaks identifiable integration/account data.</comment>

<file context>
@@ -134,10 +134,14 @@ export async function POST(request: NextRequest) {
+            integrationIdsFromAgent: integrationIds.length,
+            integrationsFound: integrations.length,
             accountIds: accountIds.length,
+            accountIdPreviews: accountIds.map(id => id.slice(0, 12) + '...'),
+            documentIds: documentIds.length,
             documentContext: documentContext.length,
</file context>
Suggested change
accountIdPreviews: accountIds.map(id => id.slice(0, 12) + '...'),
hasAccountIds: accountIds.length > 0,
Fix with Cubic

documentIds: documentIds.length,
documentContext: documentContext.length,
hasStackOneApiKey: !!process.env.STACKONE_API_KEY,
})

let fullResponse = ''
Expand Down
27 changes: 26 additions & 1 deletion apps/rag-knowledge-agent/src/lib/chat/vercel-agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,9 +52,24 @@ export async function* runVercelAgent(
const ragService = new RAGService()

// StackOne utility tools (tool_search + tool_execute): model discovers tools via search, then executes by name
console.log('[Agent] Loading utility tools', { accountIds: accountIds.length, hasApiKey: !!process.env.STACKONE_API_KEY })
if (accountIds.length === 0) {
console.warn(
'[Agent] No StackOne account IDs for this agent — tool_search/tool_execute are disabled. Link integrations to the agent (with a connected StackOne account) and ensure STACKONE_API_KEY is set.'
)
}

const aiSdkUtilityTools = accountIds.length > 0 ? await getStackOneUtilityToolsForAISDK(accountIds) : {}

const systemPrompt = `You are a helpful AI assistant with access to the following tools. Use each when appropriate:
const hasActionTools = Object.keys(aiSdkUtilityTools).length > 0
console.log('[Agent] Utility tools result', { hasActionTools, toolNames: Object.keys(aiSdkUtilityTools) })
if (accountIds.length > 0 && !hasActionTools) {
console.error(
'[Agent] StackOne utility tools failed to load (empty tool_search/tool_execute). Check STACKONE_API_KEY, STACKONE_BASE_URL, and server logs from getStackOneUtilityToolsForAISDK.'
)
}

const systemPromptWithActions = `You are a helpful AI assistant with access to the following tools. Use each when appropriate:

**getInformationFromRAG** – Use when the user asks a question about their documents, when you need to read or search document content, or when you need a document identifier (remote_document_id) or current content to perform an action. Do not use when the request does not involve the user's documents or when you already have the needed content or ids from context.

Expand All @@ -66,6 +81,16 @@ export async function* runVercelAgent(

Respond in natural language. After using tools, summarize outcomes for the user. If a tool returns an error, report it clearly and suggest what the user can check or try.`

const systemPromptRagOnly = `You are a helpful AI assistant with access to **getInformationFromRAG** only (search/read indexed documents). You do **not** have tools to update Google Docs, Drive, or other live apps in this session.

**getInformationFromRAG** – Use when the user asks about their documents, needs content or quotes, or needs a remote_document_id from indexed material.

If the user asks to update, edit, or change a live document in a connected app, explain clearly that realtime actions require this agent to have StackOne integrations linked (with an active connection) and STACKONE_API_KEY configured on the server; you can still help using retrieved document content where applicable.

Respond in natural language. If a tool returns an error, report it clearly.`

const systemPrompt = hasActionTools ? systemPromptWithActions : systemPromptRagOnly

// Add document context to system prompt if available
let enhancedSystemPrompt = systemPrompt
if (documentContext.length > 0) {
Expand Down
24 changes: 15 additions & 9 deletions apps/rag-knowledge-agent/src/lib/stackone/meta-tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -238,16 +238,18 @@ export interface UtilityToolsResult {
*/
async function getToolsForAccounts(accountIds: string[]) {
if (!process.env.STACKONE_API_KEY) {
console.error('[StackOne tools] STACKONE_API_KEY is not configured')
throw new Error('STACKONE_API_KEY is not configured')
}

const toolset = new StackOneToolSet({
baseUrl: process.env.STACKONE_BASE_URL ?? 'https://api.stackone.com',
})
const baseUrl = process.env.STACKONE_BASE_URL ?? 'https://api.stackone.com'
console.log('[StackOne tools] fetchTools starting', { accountCount: accountIds.length, baseUrl })
const toolset = new StackOneToolSet({ baseUrl })
const tools = await toolset.fetchTools({ accountIds })

const accountIdsForLog = accountIds.map((id) => id.slice(0, 12) + '...')
logger.log('[StackOne tools] fetchTools:', { accountCount: accountIds.length, accountIdsForLog, toolCount: tools.toArray().length })
const toolCount = tools.toArray().length
console.log('[StackOne tools] fetchTools result:', { accountIdsForLog, toolCount })

return tools
}
Expand All @@ -261,12 +263,16 @@ async function getToolsForAccounts(accountIds: string[]) {
export async function getStackOneUtilityToolsForAISDK(accountIds: string[]) {
if (accountIds.length === 0) return {}
try {
console.log('[StackOne tools] getStackOneUtilityToolsForAISDK: fetching tools...')
const tools = await getToolsForAccounts(accountIds)
console.log('[StackOne tools] getStackOneUtilityToolsForAISDK: calling utilityTools()...')
const utilityTools = await tools.utilityTools()
console.log('[StackOne tools] getStackOneUtilityToolsForAISDK: getting tool_search and tool_execute...')
const searchTool = utilityTools.getTool('tool_search')
const executeTool = utilityTools.getTool('tool_execute')
console.log('[StackOne tools] getStackOneUtilityToolsForAISDK:', { hasSearchTool: !!searchTool, hasExecuteTool: !!executeTool })
if (!searchTool || !executeTool) {
logger.warn('[StackOne tools] tool_search or tool_execute not available')
console.error('[StackOne tools] tool_search or tool_execute not available from utilityTools()')
return {}
}

Expand Down Expand Up @@ -306,7 +312,7 @@ export async function getStackOneUtilityToolsForAISDK(accountIds: string[]) {
}
return requiredNext as JsonObject
} catch (error) {
logger.log('[StackOne tools] tool_search (AI SDK) error:', error instanceof Error ? error.message : error)
console.error('[StackOne tools] tool_search (AI SDK) error:', error instanceof Error ? error.message : error)
return { error: error instanceof Error ? error.message : String(error) }
}
},
Expand Down Expand Up @@ -343,9 +349,9 @@ export async function getStackOneUtilityToolsForAISDK(accountIds: string[]) {
}
return result
} catch (error) {
logger.log('[StackOne tools] tool_execute (AI SDK) error:', { toolName, error: error instanceof Error ? error.message : String(error) })
console.error('[StackOne tools] tool_execute (AI SDK) error:', { toolName, error: error instanceof Error ? error.message : String(error) })
if (debugPayloads) {
logger.log('[StackOne tools] tool_execute (AI SDK) error detail:', error)
console.error('[StackOne tools] tool_execute (AI SDK) error detail:', error)
}
return { error: error instanceof Error ? error.message : String(error) }
}
Expand All @@ -357,7 +363,7 @@ export async function getStackOneUtilityToolsForAISDK(accountIds: string[]) {
tool_execute: toolExecuteAISDK,
}
} catch (error) {
logger.error('[StackOne tools] Failed to get utility tools for AI SDK:', error)
console.error('[StackOne tools] Failed to get utility tools for AI SDK:', error instanceof Error ? { message: error.message, stack: error.stack } : error)
return {}
}
}
Expand Down
13 changes: 4 additions & 9 deletions apps/rag-knowledge-agent/src/utils/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,25 +3,20 @@
* Set DEBUG=1 or DEBUG_CHAT=1 in .env.local to enable verbose logging.
*/

const isDevelopment = process.env.NODE_ENV === 'development';
const isDebug = isDevelopment && (process.env.DEBUG === '1' || process.env.DEBUG === 'true' || process.env.DEBUG_CHAT === '1' || process.env.DEBUG_CHAT === 'true');
const isDebug = process.env.DEBUG === '1' || process.env.DEBUG === 'true' || process.env.DEBUG_CHAT === '1' || process.env.DEBUG_CHAT === 'true';

export const logger = {
/** Only logs when DEBUG or DEBUG_CHAT is set (in dev). Use for verbose/trace. */
/** Only logs when DEBUG or DEBUG_CHAT is set. Use for verbose/trace. */
log: (...args: unknown[]) => {
if (isDebug) {
console.log(...args);
}
},
warn: (...args: unknown[]) => {
if (isDevelopment) {
console.warn(...args);
}
console.warn(...args);
},
error: (...args: unknown[]) => {
if (isDevelopment) {
console.error(...args);
}
console.error(...args);
},
info: (...args: unknown[]) => {
if (isDebug) {
Expand Down