@cognipeer/agent-sdk 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +177 -103
- package/dist/index.cjs +2014 -421
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +529 -111
- package/dist/index.d.ts +529 -111
- package/dist/index.mjs +2822 -0
- package/dist/index.mjs.map +1 -0
- package/package.json +42 -26
- package/dist/index.js +0 -1212
- package/dist/index.js.map +0 -1
package/dist/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/model.ts","../src/tool.ts","../src/prompts.ts","../src/agent.ts","../src/nodes/resolver.ts","../src/utils/usage.ts","../src/utils/debugLogger.ts","../src/nodes/agentCore.ts","../src/nodes/tools.ts","../src/nodes/toolLimitFinalize.ts","../src/nodes/agent.ts","../src/nodes/contextSummarize.ts","../src/utils/utilTokens.ts","../src/utils/tokenManager.ts","../src/contextTools.ts","../src/graph/decisions.ts","../src/smart/index.ts"],"sourcesContent":["// Generic base chat model contract used internally by agent-sdk.\n// We intentionally keep this minimal and implementation-agnostic so that\n// different framework specific models (LangChain, OpenAI SDK, Anthropic, etc.)\n// can be adapted without adding hard dependencies.\n\nexport interface BaseChatMessagePart {\n type?: string; // e.g. 'text'\n text?: string;\n content?: string; // provider specific\n [key: string]: any;\n}\n\nexport interface BaseChatMessage {\n role: 'system' | 'user' | 'assistant' | 'tool' | string;\n name?: string;\n content: string | BaseChatMessagePart[];\n // Tool call metadata (OpenAI style)\n tool_calls?: Array<{ id: string; type?: string; function?: { name: string; arguments: string } }>;\n tool_call_id?: string; // for tool response messages\n usage?: any; // optional provider usage shape\n response_metadata?: any; // optional provider wrapper metadata\n [key: string]: any; // allow extensions\n}\n\nexport interface BaseChatModel {\n // Invoke should accept an array of BaseChatMessage (system/user/assistant/tool)\n invoke(messages: BaseChatMessage[]): Promise<BaseChatMessage>;\n // Optional tool binding hook. If not present the agent will emulate simple pass-through.\n bindTools? (tools: any[]): BaseChatModel;\n // Optional metadata helpers\n modelName?: string;\n [key: string]: any; // allow arbitrary extensions\n}\n\nexport type SmartModel = BaseChatModel;\n\nexport function isSmartModel(m: any): m is SmartModel {\n return !!m && typeof m === 'object' && typeof m.invoke === 'function';\n}\n\nexport function withTools(model: SmartModel, tools: any[]) {\n if (model?.bindTools) return model.bindTools(tools);\n return model;\n}\n\n// --- Adapters ----------------------------------------------------------------\n\n// Duck-type adapter for LangChain ChatModel / Runnable style objects.\n// We DO NOT import LangChain here; instead we just check for common methods.\n// Usage: fromLangchainModel(new ChatOpenAI(...)) returns a BaseChatModel.\nexport function fromLangchainModel(lcModel: any): BaseChatModel {\n if (!lcModel) throw new Error('fromLangchainModel: model is undefined/null');\n\n const adapted: BaseChatModel = {\n invoke: async (messages: BaseChatMessage[]): Promise<BaseChatMessage> => {\n // LangChain expects an array of LC message objects. If user passed LC messages already\n // they can skip adaptation; but here we accept our generic format and map to minimal LC shape.\n const normalizeContent = (content: any): any => {\n // Allow string passthrough\n if (content == null) return content;\n if (typeof content === 'string') return content;\n if (Array.isArray(content)) {\n return content.map((part: any) => {\n if (!part || typeof part !== 'object') return part;\n if (part.type === 'text') return { type: 'text', text: String(part.text ?? '') };\n if (part.type === 'image_url') {\n const img = (part as any).image_url;\n // Support { url }, { base64, media_type }, or string\n if (typeof img === 'string') return { type: 'image_url', image_url: { url: img } };\n if (img && typeof img === 'object') {\n if ('url' in img) return { type: 'image_url', image_url: img };\n if ('base64' in img) {\n const media = (img as any).media_type || 'image/jpeg';\n const dataUrl = `data:${media};base64,${(img as any).base64}`;\n const detail = (img as any).detail;\n return { type: 'image_url', image_url: { url: dataUrl, detail } };\n }\n }\n // Fallback\n return part;\n }\n return part;\n });\n }\n return content;\n };\n const toLC = (m: BaseChatMessage): any => {\n // If it already looks like an LC BaseMessage (has _getType or id or lc_serializable), pass through.\n if ((m as any)._getType || (m as any).lc_serializable) return m as any;\n const role = m.role;\n // Map role to LC classes via dynamic constructors if available on lcModel or global scope.\n // We avoid importing, so fallback to generic object with role/content; many LC models accept that.\n return { role, content: normalizeContent(m.content), name: m.name, tool_calls: (m as any).tool_calls, tool_call_id: (m as any).tool_call_id };\n };\n const lcMessages = messages.map(toLC);\n const response = await lcModel.invoke(lcMessages);\n // Convert back to BaseChatMessage (attempt best-effort extraction)\n if (response && typeof response === 'object') {\n const content = (response as any).content ?? (response as any).text ?? '';\n return {\n role: (response as any).role || 'assistant',\n content,\n tool_calls: (response as any).tool_calls,\n usage: (response as any).usage,\n response_metadata: (response as any).response_metadata,\n ...response,\n } as BaseChatMessage;\n }\n return { role: 'assistant', content: String(response ?? '') };\n },\n bindTools: (tools: any[]) => {\n // LangChain ChatModel commonly has .bindTools\n if (typeof lcModel.bindTools === 'function') {\n const bound = lcModel.bindTools(tools);\n return fromLangchainModel(bound);\n }\n // If no native support, just return same adapter (tools will be ignored)\n return adapted;\n },\n modelName: lcModel.modelName || lcModel._modelId || lcModel._llmType || lcModel.name,\n _lc: lcModel,\n };\n\n return adapted;\n}\n\n// Placeholder for future adapters (OpenAI SDK, Anthropic, etc.) can follow a similar pattern.\n\n","import { tool, type ToolInterface } from \"@langchain/core/tools\";\nimport { ZodSchema } from \"zod\";\n\nexport type SmartToolFn = (args: any) => Promise<any> | any;\n\nexport function createSmartTool({\n name,\n description,\n schema,\n func,\n}: {\n name: string;\n description?: string;\n schema: ZodSchema,\n func: SmartToolFn;\n}): ToolInterface {\n return tool(async (input) => {\n return func(input);\n }, {\n name,\n description,\n schema\n })\n}\n\n// Alias for future agent-sdk naming; mirrors createSmartTool\nexport function createTool({\n name,\n description,\n schema,\n func,\n}: {\n name: string;\n description?: string;\n schema: ZodSchema;\n func: SmartToolFn;\n}): ToolInterface {\n return createSmartTool({ name, description, schema, func });\n}\n","export function buildSystemPrompt(extra?: string, planning?: boolean, name: string = \"Agent\") {\n const extraTrimmed = extra?.trim();\n const agentHeader = `Agent Name: ${name}`;\n const planningBlock = planning\n ? `<planning>\nPLANNING IS MANDATORY.\n\nRules:\n1) Your FIRST action in every task is a single call to the tool \"manage_todo_list\" with operation=\"write\" and a full, ordered plan (1+ items). Even for trivial tasks, write a one-item plan.\n2) After every non-planning tool call, you MUST immediately call \"manage_todo_list\" with operation=\"write\" (or re-write) to update statuses and append one-line evidence on the affected item only.\n3) Keep exactly ONE item \"in-progress\" at any time; all others are \"not-started\" or \"completed\".\n4) Never reveal the plan text. Never summarize the plan in the assistant messages.\n5) If you ever produce an assistant message without having written a plan in this session, STOP and first write the plan via \"manage_todo_list\".\n</planning>`\n : \"\";\n return [\n agentHeader,\n \"You are an advanced AI agent that is concise, accurate, and helpful.\",\n \"Follow these rules:\",\n \"- Use tools only when they add value; avoid redundant calls.\",\n \"- Never fabricate tool results; if unavailable, say so briefly.\",\n \"- Prefer short, structured answers; use bullet points when helpful.\",\n \"- Keep privacy and safety: do not reveal secrets or sensitive data.\",\n \"- If inputs are ambiguous or missing, ask one concise clarifying question.\",\n \"- Reuse prior tool results already present in the conversation when sufficient.\",\n planningBlock,\n extraTrimmed ? `Extra instructions: ${extraTrimmed}` : \"\",\n ]\n .filter(Boolean)\n .join(\"\\n\");\n}\n","// A minimal agent builder: no system prompt, no summarization, with tool limit and optional structured output finalize.\nimport type { AgentResult as AgentInvokeResult, InvokeConfig, AgentEvent as SmartAgentEvent, AgentOptions as SmartAgentOptions, AgentState as SmartState, AgentInstance as SmartAgentInstance, AgentRuntimeConfig, HandoffDescriptor } from \"./types.js\";\nimport { z, ZodSchema } from \"zod\";\nimport { createResolverNode } from \"./nodes/resolver.js\";\nimport { createAgentCoreNode } from \"./nodes/agentCore.js\";\nimport { createToolsNode } from \"./nodes/tools.js\";\nimport { createToolLimitFinalizeNode } from \"./nodes/toolLimitFinalize.js\";\nimport { createSmartTool } from \"./tool.js\";\n\ntype LiteMessage = { role: string; content: any; name?: string; [k: string]: any };\nconst human = (content: any): LiteMessage => ({ role: 'user', content });\n\nexport function createAgent<TOutput = unknown>(opts: SmartAgentOptions & { outputSchema?: ZodSchema<TOutput> }): SmartAgentInstance<TOutput> {\n const resolver = createResolverNode();\n const agentCore = createAgentCoreNode(opts);\n // Prepare tools list: base tools + structured output finalize if schema provided\n const toolsBase = [...((opts.tools as any) ?? [])];\n if (opts.outputSchema) {\n const responseTool = createSmartTool({\n name: 'response',\n description: 'Finalize the answer by returning the final structured JSON matching the required schema. Call exactly once when you are fully done, then stop.',\n schema: opts.outputSchema as any,\n func: async (data: any) => ({ __finalStructuredOutput: true, data }),\n });\n toolsBase.push(responseTool);\n }\n const toolsNode = createToolsNode(toolsBase, opts);\n const finalizeNode = createToolLimitFinalizeNode(opts);\n\n async function runLoop(initial: SmartState, config?: InvokeConfig): Promise<SmartState> {\n let state = await resolver(initial);\n const maxToolCalls = (opts.limits?.maxToolCalls ?? 10) as number;\n const iterationLimit = Math.max(maxToolCalls * 3 + 10, 40);\n let iterations = 0;\n\n while (iterations < iterationLimit) {\n iterations++;\n\n // Agent step\n state = { ...state, ...(await agentCore(state)) } as SmartState;\n const lastMsg: any = state.messages[state.messages.length - 1];\n const toolCalls: any[] = Array.isArray(lastMsg?.tool_calls) ? lastMsg.tool_calls : [];\n const toolCallCount = state.toolCallCount || 0;\n\n // Tool limit finalize gate\n if (state.ctx?.__finalizedDueToToolLimit) {\n break;\n }\n if (toolCallCount >= maxToolCalls && toolCalls.length > 0) {\n state = { ...state, ...(await finalizeNode(state)) } as SmartState;\n // One more assistant turn will occur, but without more tools ideally\n continue;\n }\n\n if (toolCalls.length === 0) break;\n\n // Run tools\n state = { ...state, ...(await toolsNode(state)) } as SmartState;\n if (state.ctx?.__finalizedDueToStructuredOutput) break;\n }\n\n return state;\n }\n\n const runtime: AgentRuntimeConfig = {\n name: opts.name,\n model: opts.model,\n tools: toolsBase,\n systemPrompt: undefined,\n limits: opts.limits,\n useTodoList: undefined,\n outputSchema: opts.outputSchema as any,\n };\n\n const instance: SmartAgentInstance<TOutput> = {\n invoke: async (input: SmartState, config?: InvokeConfig): Promise<AgentInvokeResult<TOutput>> => {\n const onEvent = config?.onEvent;\n const emit = (e: SmartAgentEvent) => { try { onEvent?.(e); } catch {} };\n const initial: SmartState = {\n messages: input.messages || [],\n summaries: input.summaries || [],\n toolCallCount: input.toolCallCount || 0,\n toolCache: input.toolCache || {},\n toolHistory: input.toolHistory || [],\n toolHistoryArchived: input.toolHistoryArchived || [],\n metadata: input.metadata,\n ctx: { ...(input.ctx || {}), __onEvent: onEvent },\n plan: input.plan || null,\n planVersion: input.planVersion || 0,\n agent: input.agent || runtime,\n usage: input.usage || { perRequest: [], totals: {} },\n };\n\n const res: any = await runLoop(initial, config);\n const finalMsg = res.messages[res.messages.length - 1];\n let content = \"\";\n if (typeof finalMsg?.content === \"string\") content = finalMsg.content;\n else if (Array.isArray(finalMsg?.content)) content = finalMsg.content.map((c: any) => (typeof c === \"string\" ? c : c?.text ?? c?.content ?? \"\")).join(\"\");\n\n let parsed: TOutput | undefined = undefined;\n const schema = opts.outputSchema as ZodSchema<TOutput> | undefined;\n if (schema && (res as any).ctx?.__structuredOutputParsed) {\n parsed = (res as any).ctx.__structuredOutputParsed as TOutput;\n } else if (schema && content) {\n // Fallback: try to parse JSON from assistant message\n let jsonText: string | null = null;\n const fenced = content.match(/```(?:json)?\\n([\\s\\S]*?)```/i);\n if (fenced && fenced[1]) jsonText = fenced[1].trim();\n else {\n const braceIdx = content.indexOf(\"{\");\n const bracketIdx = content.indexOf(\"[\");\n const start = [braceIdx, bracketIdx].filter(i => i >= 0).sort((a, b) => a - b)[0];\n if (start !== undefined) jsonText = content.slice(start).trim();\n }\n try {\n const raw = JSON.parse(jsonText ?? content);\n parsed = schema.parse(raw) as TOutput;\n } catch {}\n }\n\n emit({ type: \"finalAnswer\", content: typeof finalMsg?.content === 'string' ? finalMsg.content : content });\n\n return {\n content,\n output: parsed as TOutput | undefined,\n metadata: { usage: (res as any).usage },\n messages: res.messages,\n state: res as SmartState,\n };\n },\n asTool: ({ toolName, description, inputDescription }: { toolName: string; description?: string; inputDescription?: string }) => {\n const schema = z.object({ input: z.string().describe(inputDescription || \"Input for delegated agent\") });\n return createSmartTool({\n name: toolName,\n description: description || `Delegate task to agent ${opts.name || 'Agent'}`,\n schema,\n func: async ({ input }) => {\n const res = await instance.invoke({ messages: [{ role: 'user', content: input } as any] });\n return { content: res.content };\n }\n });\n },\n asHandoff: ({ toolName, description, schema }: { toolName?: string; description?: string; schema?: ZodSchema<any>; }): HandoffDescriptor => {\n const finalName = toolName || `handoff_to_${runtime.name || 'agent'}`;\n const zschema = schema || z.object({ reason: z.string().describe('Reason for handoff') });\n const tool = createSmartTool({\n name: finalName,\n description: description || `Handoff control to agent ${runtime.name || 'Agent'}`,\n schema: zschema,\n func: async (_args: any) => ({ __handoff: { runtime } })\n });\n return { type: 'handoff', toolName: finalName, description: description || '', schema: zschema, target: instance } as any;\n },\n __runtime: runtime,\n };\n\n if (opts.handoffs && Array.isArray(opts.handoffs)) {\n const handoffTools = opts.handoffs.map(h => {\n const schema = h.schema || z.object({ reason: z.string().describe('Reason for handoff') });\n return createSmartTool({\n name: h.toolName,\n description: h.description || `Handoff to ${h.target.__runtime.name || 'agent'}`,\n schema,\n func: async (_args: any) => ({ __handoff: { runtime: h.target.__runtime } })\n });\n });\n runtime.tools = [...runtime.tools, ...handoffTools];\n }\n\n return instance;\n}\n","import type { SmartState } from \"../types.js\";\n\n// Ensures required state fields exist and normalizes incoming messages\nexport function createResolverNode() {\n return async (state: SmartState): Promise<SmartState> => {\n const messages = Array.isArray(state.messages) ? state.messages : [];\n return {\n ...state,\n messages,\n summaries: state.summaries || [],\n toolCallCount: state.toolCallCount || 0,\n toolCache: state.toolCache || {},\n toolHistory: state.toolHistory || [],\n toolHistoryArchived: state.toolHistoryArchived || [],\n plan: state.plan || null,\n planVersion: state.planVersion || 0,\n } as SmartState;\n };\n}\n","// Normalizes provider-specific usage objects into a common shape.\n// Target shape:\n// {\n// prompt_tokens: number;\n// completion_tokens: number;\n// total_tokens: number;\n// prompt_tokens_details: { cached_tokens: number; audio_tokens: number };\n// completion_tokens_details: { reasoning_tokens: number; audio_tokens: number; accepted_prediction_tokens: number; rejected_prediction_tokens: number };\n// raw?: any; // original provider usage\n// }\n\nexport type NormalizedUsage = {\n prompt_tokens: number;\n completion_tokens: number;\n total_tokens: number;\n prompt_tokens_details: { cached_tokens: number; audio_tokens: number };\n completion_tokens_details: {\n reasoning_tokens: number;\n audio_tokens: number;\n accepted_prediction_tokens: number;\n rejected_prediction_tokens: number;\n };\n raw?: any;\n};\n\nexport function normalizeUsage(raw: any | undefined | null): NormalizedUsage | undefined {\n if (!raw) return undefined;\n // Canonical numeric fields from various provider key aliases.\n const prompt = num(raw.prompt_tokens, raw.input_tokens, raw.promptTokens, raw.total_prompt_tokens);\n const completion = num(raw.completion_tokens, raw.output_tokens, raw.completionTokens, raw.total_completion_tokens);\n // total might be explicitly provided or computed.\n const total = num(\n raw.total_tokens,\n raw.totalTokens,\n (typeof prompt === 'number' ? prompt : 0) + (typeof completion === 'number' ? completion : 0)\n );\n\n // Details: attempt to pull from common nested spots else zeros\n const promptDetailsSrc = raw.prompt_tokens_details || raw.promptTokensDetails || {};\n const completionDetailsSrc = raw.completion_tokens_details || raw.completionTokensDetails || {};\n\n const normalized: NormalizedUsage = {\n prompt_tokens: safe(prompt),\n completion_tokens: safe(completion),\n total_tokens: safe(total || (prompt || 0) + (completion || 0)),\n prompt_tokens_details: {\n cached_tokens: safe(\n promptDetailsSrc.cached_tokens || promptDetailsSrc.cached || raw.cached_input_tokens || raw.cached_prompt_tokens\n ),\n audio_tokens: safe(promptDetailsSrc.audio_tokens),\n },\n completion_tokens_details: {\n reasoning_tokens: safe(completionDetailsSrc.reasoning_tokens),\n audio_tokens: safe(completionDetailsSrc.audio_tokens),\n accepted_prediction_tokens: safe(completionDetailsSrc.accepted_prediction_tokens),\n rejected_prediction_tokens: safe(completionDetailsSrc.rejected_prediction_tokens),\n },\n raw,\n };\n return normalized;\n}\n\nfunction num(...vals: any[]): number | undefined {\n for (const v of vals) {\n if (v === 0) return 0;\n if (v == null) continue;\n const n = Number(v);\n if (!Number.isNaN(n)) return n;\n }\n return undefined;\n}\nfunction safe(v: any): number { const n = Number(v); return Number.isFinite(n) && n >= 0 ? n : 0; }\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Message, SmartAgentOptions, SmartState } from \"../types.js\";\nexport type DebugSession = {\n sessionId: string;\n baseDir: string; // base logs dir\n sessionDir: string; // per-invoke folder\n stepIndex: number;\n callback?: (entry: {\n sessionId: string;\n stepIndex: number;\n fileName: string;\n markdown: string;\n messages: Message[];\n usage?: any;\n modelName?: string;\n limits?: any;\n tools?: any[];\n }) => void;\n};\n\nfunction ensureDir(p: string) {\n if (!fs.existsSync(p)) fs.mkdirSync(p, { recursive: true });\n}\n\nexport function resolveLogsBaseDir(customPath?: string) {\n // Default: project root logs folder\n const root = process.cwd();\n const base = customPath && customPath.trim().length > 0 ? customPath : path.join(root, \"logs\");\n ensureDir(base);\n return base;\n}\n\nexport function createDebugSession(opts: SmartAgentOptions): DebugSession | undefined {\n const dbg = opts.debug;\n if (!dbg?.enabled) return undefined;\n const baseDir = resolveLogsBaseDir(dbg.path);\n const sessionId = new Date().toISOString().replace(/[:.]/g, \"-\");\n const sessionDir = path.join(baseDir, sessionId);\n if (!dbg.callback) ensureDir(sessionDir);\n return { sessionId, baseDir, sessionDir, stepIndex: 0, callback: dbg.callback };\n}\n\nexport function bumpStep(session: DebugSession): number {\n session.stepIndex += 1;\n return session.stepIndex - 1;\n}\n\ntype UsageLike = any;\n\nexport function getModelName(model: any): string | undefined {\n return (\n model?.model ??\n model?.modelName ??\n model?.options?.model ??\n model?.lc_alias ??\n model?.constructor?.name ??\n undefined\n );\n}\n\nexport function serializeAgentTools(tools: any[]): any[] {\n return (tools || []).map((t) => {\n const name = (t as any).name ?? (t as any).lc_alias ?? (t as any).constructor?.name ?? \"tool\";\n const description = (t as any).description ?? (t as any).lc_description ?? undefined;\n const params = (t as any).schema ?? (t as any).lc_kwargs?.schema ?? (t as any).argsSchema ?? undefined;\n return {\n function: {\n name,\n description,\n parameters: params,\n },\n type: \"function\",\n };\n });\n}\n\nfunction formatTools(tools: any[]): string {\n try {\n return JSON.stringify(\n tools.map((t) => ({\n function: t?.function ? {\n name: t.function.name,\n description: t.function.description,\n parameters: t.function.parameters,\n } : undefined,\n type: t?.type,\n })),\n null,\n 4\n );\n } catch {\n return \"[]\";\n }\n}\n\nfunction formatMessages(messages: Message[]): string {\n const lines: string[] = [];\n const push = (s: string = \"\") => lines.push(s);\n for (const m of messages) {\n const anyM: any = m as any;\n const role = (anyM.role || (typeof (anyM.getType) === 'function' ? anyM.getType() : undefined)) as string | undefined;\n if (role === 'system') {\n push(\"### System\\n\");\n push(String(anyM.content));\n push(\"\");\n } else if (role === 'user' || role === 'human') {\n push(\"### User\\n\");\n push(typeof anyM.content === \"string\" ? anyM.content : JSON.stringify(anyM.content, null, 2));\n push(\"\");\n } else if (role === 'assistant' || role === 'ai') {\n push(\"### AI\\n\");\n const toolCalls = Array.isArray(anyM.tool_calls) ? anyM.tool_calls : [];\n if (toolCalls.length) {\n push(\"Tool Calls:\");\n for (const tc of toolCalls) {\n push(\"```\");\n push(JSON.stringify(tc, null, 2));\n push(\"```\");\n }\n }\n push(typeof anyM.content === \"string\" ? anyM.content : JSON.stringify(anyM.content, null, 2));\n push(\"\");\n } else if (role === 'tool') {\n push(\"### ToolResponse\\n\");\n const hdr = { name: anyM.name, tool_call_id: anyM.tool_call_id, executionId: anyM.executionId };\n push(\"```\");\n push(JSON.stringify(hdr, null, 2));\n push(\"```\");\n push(typeof anyM.content === \"string\" ? anyM.content : JSON.stringify(anyM.content, null, 2));\n push(\"\");\n }\n }\n return lines.join(\"\\n\");\n}\n\nexport function formatMarkdown(params: {\n modelName: string | undefined;\n date: string;\n limits?: any;\n usage?: UsageLike;\n tools?: any[];\n messages: Message[];\n}): string {\n const { modelName, date, limits, usage, tools = [], messages } = params;\n const sections: string[] = [];\n const add = (s: string = \"\") => sections.push(s);\n\n add(`# modelName`);\n add(String(modelName ?? \"unknown\"));\n add(\"\");\n\n add(`# date`);\n add(date);\n add(\"\");\n\n add(`# limitler`);\n add(\"```\");\n add(JSON.stringify(limits ?? {}, null, 2));\n add(\"```\");\n add(\"\");\n\n add(`# usage`);\n if (usage) {\n add(\"```\");\n add(JSON.stringify(usage));\n add(\"```\");\n } else {\n add(\"(none)\");\n }\n add(\"\");\n\n add(`# tools`);\n add(\"```\");\n add(formatTools(tools));\n add(\"```\");\n add(\"\");\n\n add(`# Messages`);\n add(formatMessages(messages));\n\n return sections.join(\"\\n\");\n}\n\nexport async function writeStepMarkdown(session: DebugSession, fileName: string, markdown: string, payload?: { messages: Message[]; usage?: any; modelName?: string; limits?: any; tools?: any[] }) {\n if (session.callback) {\n session.callback({\n sessionId: session.sessionId,\n stepIndex: session.stepIndex,\n fileName,\n markdown,\n messages: payload?.messages ?? [],\n usage: payload?.usage,\n modelName: payload?.modelName,\n limits: payload?.limits,\n tools: payload?.tools,\n });\n return;\n }\n const fp = path.join(session.sessionDir, fileName);\n await fs.promises.writeFile(fp, markdown, \"utf8\");\n}\n","import type { ToolInterface } from \"@langchain/core/tools\";\nimport type { Message, SmartAgentOptions, SmartState } from \"../types.js\";\nimport { normalizeUsage } from \"../utils/usage.js\";\nimport { getModelName } from \"../utils/debugLogger.js\";\n\n// Minimal agent node: no system prompt injection. Invokes model with messages as-is.\nexport function createAgentCoreNode(opts: SmartAgentOptions) {\n return async (state: SmartState): Promise<Partial<SmartState>> => {\n const runtime = state.agent || {\n name: opts.name,\n model: opts.model,\n tools: (opts.tools as any) || [],\n systemPrompt: undefined,\n limits: opts.limits,\n useTodoList: undefined,\n outputSchema: (opts as any).outputSchema,\n };\n\n const tools: Array<ToolInterface<any, any, any>> = (runtime.tools as any) ?? [];\n const modelWithTools = (runtime.model)?.bindTools\n ? (runtime.model).bindTools(tools)\n : runtime.model;\n\n const response = await modelWithTools.invoke([...state.messages]);\n const messagesWithResponse: Message[] = [\n ...state.messages,\n response as any,\n ];\n\n // Usage tracking (per-request, aggregated by model)\n const rawUsage = (response as any)?.usage || (response as any)?.response_metadata?.token_usage || (response as any)?.response_metadata?.usage;\n const normalized = normalizeUsage(rawUsage);\n const modelName = getModelName((runtime as any).model || (opts as any).model) || \"unknown_model\";\n if (normalized) {\n const usageState = state.usage || { perRequest: [], totals: {} };\n const id = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n const turn = usageState.perRequest.length + 1;\n const timestamp = new Date().toISOString();\n const cachedInputTok = normalized.prompt_tokens_details?.cached_tokens;\n usageState.perRequest.push({ id, modelName, usage: normalized, timestamp, turn, cachedInput: cachedInputTok });\n const inputTok = normalized.prompt_tokens;\n const outputTok = normalized.completion_tokens;\n const totalTok = normalized.total_tokens;\n const key = modelName as string;\n const agg = usageState.totals[key] || { input: 0, output: 0, total: 0, cachedInput: 0 };\n usageState.totals[key] = {\n input: agg.input + (Number(inputTok) || 0),\n output: agg.output + (Number(outputTok) || 0),\n total: agg.total + (Number(totalTok) || 0),\n cachedInput: agg.cachedInput + (Number(cachedInputTok) || 0),\n };\n (state as any).usage = usageState;\n }\n\n return { messages: messagesWithResponse, usage: (state as any).usage };\n };\n}\n","import { Tool, type ToolInterface } from \"@langchain/core/tools\";\nimport type { SmartAgentEvent, SmartAgentOptions, SmartState, HandoffDescriptor, AgentRuntimeConfig } from \"../types.js\";\nimport { nanoid } from \"nanoid\";\nimport { ToolMessage } from \"@langchain/core/messages\";\n\nexport function createToolsNode(initialTools: Array<ToolInterface<any, any, any>>, opts?: SmartAgentOptions) {\n const baseToolByName = new Map<string, ToolInterface>();\n for (const t of initialTools) baseToolByName.set((t as any).name, t);\n\n return async (state: SmartState): Promise<any> => {\n const runtime = state.agent || {\n name: opts?.name,\n model: opts?.model,\n tools: initialTools,\n limits: opts?.limits,\n systemPrompt: opts?.systemPrompt,\n useTodoList: opts?.useTodoList,\n outputSchema: (opts as any)?.outputSchema,\n } as AgentRuntimeConfig;\n const activeTools: Array<ToolInterface<any, any, any>> = runtime.tools as any;\n const toolByName = new Map<string, ToolInterface>();\n for (const t of activeTools) toolByName.set((t as any).name, t);\n const limits = {\n maxToolCalls: (runtime.limits?.maxToolCalls ?? 10) as number,\n maxParallelTools: Math.max(1, (runtime.limits?.maxParallelTools ?? 1) as number),\n };\n const appended: ToolMessage[] = [];\n const onEvent = (state.ctx as any)?.__onEvent as ((e: SmartAgentEvent) => void) | undefined;\n // Sync latest state into context tools if they carry a stateRef\n for (const t of toolByName.values()) {\n const anyT: any = t as any;\n if (anyT._stateRef && typeof anyT._stateRef === \"object\") {\n anyT._stateRef.toolHistory = state.toolHistory;\n anyT._stateRef.toolHistoryArchived = state.toolHistoryArchived;\n anyT._stateRef.__onEvent = onEvent;\n }\n }\n const last = state.messages[state.messages.length - 1] as any;\n let toolCount = state.toolCallCount || 0;\n const toolCalls: Array<{ id?: string; name: string; args: any }> = Array.isArray(\n last?.tool_calls\n )\n ? last.tool_calls\n : [];\n\n \n const toolHistory = state.toolHistory || [];\n // Enforce global maxToolCalls across turns\n const remaining = Math.max(0, limits.maxToolCalls - toolCount);\n const planned = toolCalls.slice(0, remaining);\n const skipped = toolCalls.slice(remaining);\n\n // Emit immediate messages for any skipped due to limit\n for (const tc of skipped) {\n onEvent?.({ type: \"tool_call\", phase: \"skipped\", name: tc.name, id: tc.id, args: tc.args });\n appended.push(new ToolMessage({\n content: `Skipped tool due to tool-call limit: ${tc.name}`,\n tool_call_id: tc.id || `${tc.name}_${appended.length}`,\n name: tc.name,\n }));\n }\n\n // Helper to run a single tool call\n const runOne = async (tc: { id?: string; name: string; args: any }) => {\n const t = toolByName.get(tc.name);\n if (!t) {\n onEvent?.({ type: \"tool_call\", phase: \"error\", name: tc.name, id: tc.id, args: tc.args, error: { message: \"Tool not found\" } });\n appended.push(\n new ToolMessage({\n content: `Tool not found: ${tc.name}`,\n tool_call_id: tc.id || `${tc.name}_${appended.length}`,\n name: tc.name,\n })\n );\n toolCount += 1;\n return;\n }\n let args: any = tc.args;\n if (typeof args === \"string\") {\n try { args = JSON.parse(args); } catch (_) { /* keep as string */ }\n }\n try {\n const start = Date.now();\n onEvent?.({ type: \"tool_call\", phase: \"start\", name: (t as any).name, id: tc.id, args });\n let output: any;\n const anyTool = t as any;\n if (typeof anyTool.func === \"function\") output = await anyTool.func(args);\n else if (typeof anyTool.invoke === \"function\") output = await anyTool.invoke(args);\n else if (typeof anyTool.call === \"function\") output = await anyTool.call(args);\n else if (typeof anyTool._call === \"function\") output = await anyTool._call(args);\n else if (typeof anyTool.run === \"function\") output = await anyTool.run(args);\n else throw new Error(\"Tool is not invokable\");\n // Detect handoff signature output: we decide that a handoff tool returns { __handoff: AgentRuntimeConfig }\n if (output && typeof output === 'object' && output.__handoff && output.__handoff.runtime) {\n const newRuntime: AgentRuntimeConfig = output.__handoff.runtime;\n // switch active agent; messages unchanged except we reply ok\n const executionId = nanoid();\n toolHistory.push({ executionId, toolName: (t as any).name, args, output: 'handoff:ok', rawOutput: output, timestamp: new Date().toISOString(), tool_call_id: tc.id });\n appended.push(new ToolMessage({ content: 'ok', tool_call_id: tc.id || `${tc.name}_${appended.length}`, name: tc.name }));\n onEvent?.({ type: 'handoff', from: runtime.name, to: newRuntime.name, toolName: (t as any).name });\n state.agent = newRuntime;\n onEvent?.({ type: 'tool_call', phase: 'success', name: (t as any).name, id: tc.id, args, result: 'handoff', durationMs: Date.now() - start });\n toolCount += 1;\n return;\n }\n const content = typeof output === \"string\" ? output : JSON.stringify(output);\n if (output && typeof output === 'object' && output.__finalStructuredOutput) {\n if (!state.ctx) state.ctx = {};\n state.ctx.__structuredOutputParsed = output.data;\n state.ctx.__finalizedDueToStructuredOutput = true;\n }\n const executionId = nanoid();\n toolHistory.push({ executionId, toolName: (t as any).name, args, output, rawOutput: output, timestamp: new Date().toISOString(), tool_call_id: tc.id });\n appended.push(new ToolMessage({ content, tool_call_id: tc.id || `${tc.name}_${appended.length}`, name: tc.name }));\n onEvent?.({ type: \"tool_call\", phase: \"success\", name: (t as any).name, id: tc.id, args, result: output, durationMs: Date.now() - start });\n toolCount += 1;\n } catch (e: any) {\n const executionId = nanoid();\n toolHistory.push({ executionId, toolName: (t as any).name, args, output: `Error executing tool: ${e?.message || String(e)}`, rawOutput: null, timestamp: new Date().toISOString(), tool_call_id: tc.id });\n appended.push(new ToolMessage({ content: `Error executing tool: ${e?.message || String(e)}`, tool_call_id: tc.id || `${tc.name}_${appended.length}`, name: tc.name }));\n onEvent?.({ type: \"tool_call\", phase: \"error\", name: (t as any).name, id: tc.id, args, error: { message: e?.message || String(e) } });\n toolCount += 1;\n }\n };\n\n // Run with limited parallelism\n const concurrency = Math.max(1, limits.maxParallelTools);\n for (let i = 0; i < planned.length; i += concurrency) {\n const batch = planned.slice(i, i + concurrency);\n await Promise.all(batch.map(runOne));\n }\n\n return { messages: [...state.messages, ...appended], toolCallCount: toolCount, toolHistory, agent: state.agent };\n };\n}\n","import type { SmartAgentOptions, SmartState } from \"../types.js\";\n\n// This node is reached when tool-call limit is hit. It appends a short instruction\n// telling the agent to produce an answer with the current information and avoid further tools.\nexport function createToolLimitFinalizeNode(_opts: SmartAgentOptions) {\n return async (state: SmartState): Promise<Partial<SmartState>> => {\n const notice = { role: 'system', content: \"Tool-call limit reached. Produce the best possible final answer using the available context and prior tool outputs. Do not call any more tools.\" } as any;\n const ctx = { ...(state.ctx || {}), __finalizedDueToToolLimit: true };\n return { messages: [...state.messages, notice], ctx };\n };\n}\n","import type { ToolInterface } from \"@langchain/core/tools\";\nimport type { Message, SmartAgentOptions, SmartState } from \"../types.js\";\nimport { buildSystemPrompt } from \"../prompts.js\";\nimport { writeStepMarkdown, formatMarkdown, bumpStep, getModelName, serializeAgentTools } from \"../utils/debugLogger.js\";\nimport { normalizeUsage } from \"../utils/usage.js\";\n\nexport function createAgentNode(opts: SmartAgentOptions) {\n return async (state: SmartState): Promise<Partial<SmartState>> => {\n // Prefer dynamic runtime config from state.agent, fallback to initial opts\n const runtime = state.agent || {\n name: opts.name,\n model: opts.model,\n tools: (opts.tools as any) || [],\n systemPrompt: opts.systemPrompt,\n limits: opts.limits,\n useTodoList: opts.useTodoList,\n outputSchema: (opts as any).outputSchema,\n };\n const tools: Array<ToolInterface<any, any, any>> = (runtime.tools as any) ?? [];\n const limits = {\n maxToolCalls: runtime.limits?.maxToolCalls ?? 10,\n toolOutputTokenLimit: runtime.limits?.toolOutputTokenLimit ?? 5000,\n contextTokenLimit: runtime.limits?.contextTokenLimit ?? 60000,\n summaryTokenLimit: runtime.limits?.summaryTokenLimit ?? 50000,\n };\n const modelWithTools = (runtime.model)?.bindTools\n ? (runtime.model).bindTools(tools)\n : runtime.model;\n // 3) Prepend a single, fresh system prompt for this turn only\n const structuredOutputHint = runtime.outputSchema\n ? [\n 'A structured output schema is active.',\n 'Do NOT output the final JSON directly as an assistant message.',\n 'When completely finished, call tool `response` passing the final JSON matching the schema as its arguments (direct object).',\n 'Call it exactly once then STOP producing further assistant messages.'\n ].join('\\n')\n : '';\n\n const systemMsg = {\n role: 'system',\n content: buildSystemPrompt(\n [runtime.systemPrompt, structuredOutputHint].filter(Boolean).join(\"\\n\"),\n runtime.useTodoList === true,\n runtime.name || \"Agent\"\n )\n } as any;\n const messages = [systemMsg, ...state.messages];\n\n // Debug logging before/after model call\n const debugSession = (state.ctx)?.__debugSession;\n\n const response = await modelWithTools.invoke([systemMsg, ...state.messages]);\n // For logs, include the system prompt we just used, but do not persist it in state\n const messagesWithResponse: Message[] = [\n ...messages\n ,\n response as any\n ];\n\n const messagesWithSystem = [\n systemMsg,\n ...messagesWithResponse\n ]\n\n // ---- Usage tracking (per-request) ----\n const rawUsage = (response as any)?.usage || (response as any)?.response_metadata?.token_usage || (response as any)?.response_metadata?.usage;\n const normalized = normalizeUsage(rawUsage);\n const modelName = getModelName((runtime as any).model || (opts as any).model) || \"unknown_model\";\n if (normalized) {\n const usageState = state.usage || { perRequest: [], totals: {} };\n const id = `${Date.now()}_${Math.random().toString(36).slice(2, 8)}`;\n const turn = usageState.perRequest.length + 1;\n const timestamp = new Date().toISOString();\n const cachedInputTok = normalized.prompt_tokens_details.cached_tokens;\n usageState.perRequest.push({ id, modelName, usage: normalized, timestamp, turn, cachedInput: cachedInputTok });\n // Normalize token counts to aggregate totals\n const inputTok = normalized.prompt_tokens;\n const outputTok = normalized.completion_tokens;\n const totalTok = normalized.total_tokens;\n const key = modelName as string;\n const agg = usageState.totals[key] || { input: 0, output: 0, total: 0, cachedInput: 0 };\n usageState.totals[key] = {\n input: agg.input + (Number(inputTok) || 0),\n output: agg.output + (Number(outputTok) || 0),\n total: agg.total + (Number(totalTok) || 0),\n cachedInput: agg.cachedInput + (Number(cachedInputTok) || 0),\n };\n // Attach back so next nodes see updated state\n (state as any).usage = usageState;\n }\n\n if (debugSession) {\n const idx = bumpStep(debugSession);\n const fileName = `${String(idx).padStart(2, \"0\")}.md`;\n const markdown = formatMarkdown({\n modelName: getModelName((runtime as any).model || (opts as any).model),\n date: new Date().toISOString(),\n limits: runtime.limits,\n // IMPORTANT: log only per-request normalized usage\n usage: normalized,\n tools: serializeAgentTools(tools),\n messages: messagesWithSystem\n });\n await writeStepMarkdown(debugSession, fileName, markdown, {\n messages: messagesWithSystem,\n usage: normalized,\n modelName: getModelName((runtime as any).model || (opts as any).model),\n limits: runtime.limits,\n tools: serializeAgentTools(tools),\n });\n }\n\n return { messages: messagesWithResponse, usage: (state as any).usage };\n };\n}\n","// Lightweight message helpers to avoid hard dependency on LangChain\ntype LiteMsg = { role: string; content: any; name?: string; [k: string]: any };\nconst systemMessage = (content: string): LiteMsg => ({ role: 'system', content });\nconst humanMessage = (content: string): LiteMsg => ({ role: 'user', content });\n// tool messages use role 'tool'\nconst toolMessage = (name: string, content: any, tool_call_id?: string): LiteMsg => ({ role: 'tool', name, content, tool_call_id });\nimport type { SmartAgentEvent, SmartAgentOptions, SmartState } from \"../types.js\";\nimport { nanoid } from \"nanoid\";\nimport { countApproxTokens } from \"../utils/utilTokens.js\";\n\n// This node performs archival and message rewriting when a summarization pass is required.\n// It moves all prior tool responses into the archive, stamping them with ids, and then injects\n// a synthetic tool call + response pair that represents the summarization action.\nexport function createContextSummarizeNode(opts: SmartAgentOptions) {\n return async (state: SmartState): Promise<Partial<SmartState>> => {\n const messages = state.messages || [];\n const summaryTokenLimit = (opts.limits as any)?.summaryTokenLimit ?? (opts.limits as any)?.summary_token_limit ?? 100000;\n const model = (opts as any).model;\n\n // Identify all tool calls and responses prior to the last assistant/tool-call turn\n // We'll archive tool responses and mark them as summarized with executionId tags.\n const archived = state.toolHistoryArchived ? [...state.toolHistoryArchived] : [];\n const live = state.toolHistory ? [...state.toolHistory] : [];\n\n // Build a quick lookup by tool_call_id from both archived and live to support cross-turn rewriting\n const byCallId = new Map<string, any>();\n for (const item of archived) {\n if (item.tool_call_id) byCallId.set(item.tool_call_id, item);\n }\n for (const item of live) {\n if (item.tool_call_id) byCallId.set(item.tool_call_id, item);\n }\n\n // Ensure every history item has an executionId\n for (const item of live) {\n if (!item.executionId) item.executionId = nanoid();\n }\n\n // We don't mutate tool calls themselves; we only mark tool responses in messages\n // with a placeholder content containing the execution id.\n // Helper: flatten message content to string\n const getText = (m: any) => {\n if (!m) return \"\";\n const c = m.content;\n if (typeof c === \"string\") return c;\n if (Array.isArray(c)) return c.map((p: any) => (typeof p === \"string\" ? p : p?.text ?? p?.content ?? \"\")).join(\"\");\n return String(c ?? \"\");\n };\n\n // Build a robust, compact system instruction\n const sysText = \"You are a concise summarization assistant for a tool-using agent. Summarize prior tool executions into a compact brief that preserves key facts, decisions, and outputs. Reference executionId values where helpful. Avoid repeating raw data; prefer synthesis.\";\n const sys = systemMessage(sysText);\n\n // Token-aware chunking and iterative summarization to respect provider limits\n let summaryText = \"\";\n try {\n const limit = Math.max(1000, Number(summaryTokenLimit) || 100000);\n const safetyBuffer = Math.floor(Math.min(4000, limit * 0.05)); // keep 5% or up to 4k as buffer\n const perCallBudget = Math.max(500, limit - safetyBuffer);\n const safeToolPair = (opts as any)?.safeToolPair !== false; // default true\n\n // Create chunks ensuring (when enabled) that an AI tool-call message and its ToolMessage responses\n // are not split across different chunks. We allow slight token overflow to keep pairs intact.\n const chunks: any[][] = [];\n let current: any[] = [];\n let currentTokens = countApproxTokens(sysText);\n // Track pending tool call ids from the last AI message added to current chunk.\n let pendingToolCalls: Set<string> = new Set();\n\n const extractToolCallIds = (msg: any): string[] => {\n const tc = msg?.additional_kwargs?.tool_calls;\n if (!Array.isArray(tc) || tc.length === 0) return [];\n return tc.map((c: any) => c?.id).filter((id: any) => typeof id === \"string\");\n };\n\n for (let i = 0; i < messages.length; i++) {\n const m = messages[i];\n const text = getText(m);\n const tks = countApproxTokens(text);\n const isAIWithToolCalls = safeToolPair && (m as any)?.role === 'assistant' && extractToolCallIds(m).length > 0;\n const isToolMsg = safeToolPair && (m as any)?.role === 'tool';\n const toolCallId = isToolMsg ? (m as any).tool_call_id : undefined;\n\n // If adding this message would exceed budget, decide whether to split or to keep grouping with tool pairs.\n const wouldExceed = currentTokens + tks > perCallBudget && current.length > 0;\n\n if (wouldExceed) {\n let forceAddToCurrent = false;\n if (safeToolPair) {\n // Case 1: We're in the middle of unresolved tool calls and this is one of their responses -> keep going (overflow ok)\n if (isToolMsg && toolCallId && pendingToolCalls.has(toolCallId)) {\n forceAddToCurrent = true;\n } else if (isAIWithToolCalls) {\n // Starting a new AI tool call set: better to start a new chunk if current has content.\n // We'll push current chunk first to avoid mixing separate tool call groups.\n } else if (pendingToolCalls.size > 0) {\n // We're still expecting tool responses but this message is not a matching tool response.\n // Conclude current chunk now to avoid losing alignment; start new chunk.\n }\n }\n\n if (!forceAddToCurrent) {\n // Close current chunk if we are not force-keeping this message inside it.\n if (current.length > 0) {\n chunks.push(current);\n }\n current = [];\n currentTokens = countApproxTokens(sysText);\n pendingToolCalls = new Set();\n }\n }\n\n // Add the message to current chunk\n current.push(m);\n currentTokens += tks;\n\n // If we just added an AI tool-call message, register its tool call ids as pending.\n if (isAIWithToolCalls) {\n for (const id of extractToolCallIds(m)) pendingToolCalls.add(id);\n }\n // If it's a tool message that resolves a pending call id, mark it resolved.\n if (isToolMsg && toolCallId && pendingToolCalls.has(toolCallId)) {\n pendingToolCalls.delete(toolCallId);\n }\n\n // If we've exceeded budget AND there are no more pending tool call responses expected, we can safely flush.\n if (currentTokens >= perCallBudget && pendingToolCalls.size === 0) {\n chunks.push(current);\n current = [];\n currentTokens = countApproxTokens(sysText);\n pendingToolCalls = new Set();\n }\n }\n if (current.length > 0) {\n chunks.push(current);\n }\n\n // For each chunk, ask model to summarize that chunk\n const partials: string[] = [];\n for (const chunk of chunks) {\n let resp: any = null;\n try {\n resp = await (model?.invoke ? model.invoke([sys, ...chunk]) : null);\n const c = resp?.content;\n const text = typeof c === \"string\" ? c : Array.isArray(c) ? c.map((p: any) => (typeof p === \"string\" ? p : p?.text ?? p?.content ?? \"\")).join(\"\") : \"\";\n partials.push((text || \"\").trim());\n } catch (e) {\n // If a chunk fails, continue with a placeholder\n console.error(\"Summarization chunk failed:\", e);\n partials.push(\"[summary unavailable for one chunk]\");\n }\n }\n\n // If more than one partial, iteratively merge them under the same token budget\n const mergeSysText = \"You merge partial summaries into a single cohesive, non-redundant summary that preserves key facts and decisions. Be concise.\";\n const mergeSys = systemMessage(mergeSysText);\n\n const mergeIteratively = async (texts: string[]): Promise<string> => {\n if (texts.length === 0) return \"\";\n if (texts.length === 1) return texts[0];\n // Build groups such that each merge call stays under budget\n const groups: string[][] = [];\n let group: string[] = [];\n let toks = countApproxTokens(mergeSysText);\n for (const t of texts) {\n const tt = `- ${t}`;\n const tk = countApproxTokens(tt);\n if (toks + tk > perCallBudget && group.length > 0) {\n groups.push(group);\n group = [];\n toks = countApproxTokens(mergeSysText);\n }\n group.push(tt);\n toks += tk;\n }\n if (group.length > 0) groups.push(group);\n\n const next: string[] = [];\n for (const g of groups) {\n const mergePrompt = humanMessage(`Merge the following partial summaries into a single concise brief. Avoid duplication, keep key facts and decisions.\\n\\n${g.join(\"\\n\")}\\n\\nMerged summary:`);\n try {\n const r: any = await (model?.invoke ? model.invoke([mergeSys, mergePrompt]) : null);\n const cc = r?.content;\n const txt = typeof cc === \"string\" ? cc : Array.isArray(cc) ? cc.map((p: any) => (typeof p === \"string\" ? p : p?.text ?? p?.content ?? \"\")).join(\"\") : \"\";\n next.push((txt || \"\").trim());\n } catch (e) {\n console.error(\"Merge summarization failed:\", e);\n next.push(g.join(\" \"));\n }\n }\n return mergeIteratively(next);\n };\n\n summaryText = await mergeIteratively(partials);\n if (!summaryText) summaryText = \"Context summarized.\";\n } catch (e) {\n console.error(\"Error during context summarization:\", e);\n summaryText = \"Context summarized.\";\n }\n const rewritten: any[] = [];\n const alreadySummarized = (content: any) => {\n const text = typeof content === \"string\" ? content : Array.isArray(content) ? content.map((p: any) => (typeof p === \"string\" ? p : p?.text ?? p?.content ?? \"\")).join(\"\") : String(content ?? \"\");\n return /\\bSUMMARIZED\\b/.test(text);\n };\n for (const m of messages) {\n if (m.getType() === \"tool\") {\n const toolMessageObj = m as any;\n // Skip if already summarized\n if (alreadySummarized((toolMessageObj as any).content) || toolMessageObj.name === \"context_summarize\" || toolMessageObj.name === 'manage_todo_list') {\n rewritten.push(m);\n continue;\n }\n const callId = (toolMessageObj as any).tool_call_id as string | undefined;\n const safeId = callId || `summarized_${nanoid(6)}`;\n let hist = callId ? byCallId.get(callId) : undefined;\n if (!hist) {\n // Create a stub history entry if we don't have one (cross-invoke case)\n hist = {\n executionId: nanoid(),\n toolName: (toolMessageObj as any).name || \"unknown_tool\",\n args: null,\n output: typeof (toolMessageObj as any).content === \"string\" ? (toolMessageObj as any).content : (Array.isArray((toolMessageObj as any).content) ? (toolMessageObj as any).content.map((p: any) => (typeof p === \"string\" ? p : p?.text ?? p?.content ?? \"\")).join(\"\") : String((toolMessageObj as any).content ?? \"\")),\n rawOutput: undefined,\n timestamp: new Date().toISOString(),\n summarized: true,\n messageId: undefined,\n tool_call_id: callId,\n fromCache: false,\n };\n if (callId) byCallId.set(callId, hist);\n // Persist stub to archive so it can be recovered by get_tool_response\n archived.push({ ...hist });\n }\n if (!hist.executionId) hist.executionId = nanoid();\n hist.summarized = true;\n // Replace message content with summarized reference\n rewritten.push({\n role: 'tool',\n content: `SUMMARIZED executionId:'${hist.executionId}'`,\n tool_call_id: safeId,\n name: (toolMessage as any).name,\n });\n continue;\n }\n rewritten.push(m);\n }\n\n // After rewriting, create a synthetic assistant \"tool call\" to represent summarization\n const summarizeCallId = `summarize_${nanoid(6)}`;\n const summarizeArgs = { reason: \"Exceeded token limit: summarize prior tool outputs for context.\" };\n const syntheticAssistant = {\n role: 'assistant',\n content: \"\",\n additional_kwargs: {\n tool_calls: [\n { id: summarizeCallId, type: \"function\", function: { name: \"context_summarize\", arguments: JSON.stringify(summarizeArgs) } },\n ],\n },\n } as any;\n\n // And its synthetic tool response containing the actual summary content\n const summaryExecId = nanoid();\n const syntheticToolResp = {\n role: 'tool',\n content: `${summaryText}`,\n tool_call_id: summarizeCallId,\n name: \"context_summarize\",\n } as any;\n\n // Return updated message list and move all current tool history items into archive\n // Mark all live items as summarized and merge with archived; de-duplicate by tool_call_id\n for (const item of live) item.summarized = true;\n const merged = [...archived, ...live];\n const dedupMap = new Map<string | undefined, any>();\n for (const it of merged) {\n const key = it.tool_call_id || `${it.toolName}:${it.timestamp}`;\n // Prefer the latest information (live overwrites archived)\n dedupMap.set(key, { ...it });\n }\n const newArchived = Array.from(dedupMap.values());\n const onEvent = (state.ctx as any)?.__onEvent as ((e: SmartAgentEvent) => void) | undefined;\n onEvent?.({ type: \"summarization\", summary: summaryText, archivedCount: newArchived.length });\n return {\n messages: [...rewritten, syntheticAssistant as any, syntheticToolResp],\n toolHistoryArchived: newArchived,\n toolHistory: [],\n ctx: { ...(state.ctx || {}), __contextSummarized: true },\n };\n };\n}\n","export function countApproxTokens(text: string) {\n if (!text) return 0;\n // Rough heuristic: 1 token ~ 4 chars\n return Math.ceil(text.length / 4);\n}\n","import { HumanMessage, ToolMessage } from \"@langchain/core/messages\";\nimport { countApproxTokens } from \"./utilTokens.js\";\nimport { Message } from \"../types.js\";\n\nexport type TokenLimits = {\n contextTokenLimit: number;\n summaryTokenLimit: number;\n};\n\nexport async function applyTokenLimits({\n state,\n model,\n limits,\n}: {\n state: { messages: Message[]; summaries?: string[] };\n model: any;\n limits: {\n contextTokenLimit: number;\n summaryTokenLimit: number;\n };\n}) {\n const messages = state.messages || [];\n const budget = limits.contextTokenLimit;\n let total = messages.reduce((acc, m) => acc + countApproxTokens(String((m as any).content || \"\")), 0);\n if (total <= budget) return state;\n\n const newMessages: Message[] = [...messages];\n\n return { ...state, messages: newMessages };\n}\n\nfunction safeJson(v: any) {\n try {\n return typeof v === \"string\" ? v : JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n","import { tool } from \"@langchain/core/tools\";\nimport { z } from \"zod\";\n// no message helpers needed here\n\n// Create context tools like get_tool_response, manage_todo_list\nexport function createContextTools(\n stateRef: { toolHistory?: any[]; toolHistoryArchived?: any[]; todoList?: any[] },\n opts?: { planningEnabled?: boolean; outputSchema?: any }\n) {\n const tools = [] as any[];\n\n if (opts?.planningEnabled) {\n const manageTodo = tool(\n async ({ operation, todoList }) => {\n const onEvent = (manageTodo as any)._stateRef?.__onEvent as undefined | ((e: any) => void);\n if (operation === \"read\") {\n const list = stateRef.todoList || [];\n onEvent?.({ type: \"plan\", source: \"manage_todo_list\", operation: \"read\", todoList: list });\n return list;\n }\n if (Array.isArray(todoList)) {\n stateRef.todoList = todoList;\n }\n const payload = {\n status: \"ok\",\n operation,\n count: Array.isArray(todoList) ? todoList.length : undefined,\n } as const;\n onEvent?.({ type: \"plan\", source: \"manage_todo_list\", operation: \"write\", todoList });\n return payload;\n },\n {\n name: \"manage_todo_list\",\n description:\n \"Manage a structured todo list to track progress and plan tasks throughout your coding session. Use this tool VERY frequently to ensure task visibility and proper planning.\\n\\nWhen to use this tool:\\n- Complex multi-step work requiring planning and tracking\\n- When user provides multiple tasks or requests (numbered/comma-separated)\\n- After receiving new instructions that require multiple steps\\n- BEFORE starting work on any todo (mark as in-progress)\\n- IMMEDIATELY after completing each todo (mark completed individually)\\n- When breaking down larger tasks into smaller actionable steps\\n- To give users visibility into your progress and planning\\n\\nWhen NOT to use:\\n- Single, trivial tasks that can be completed in one step\\n- Purely conversational/informational requests\\n- When just reading files or performing simple searches\\n\\nCRITICAL workflow:\\n1. Plan tasks by writing todo list with specific, actionable items\\n2. Complete the work for that specific todo\\n3. Mark that todo as completed IMMEDIATELY\\n4. Move to next todo and repeat\\n\\nTodo states:\\n- not-started: Todo not yet begun\\n- in-progress: Currently working (limit ONE at a time)\\n- completed: Finished successfully\\n\\nIMPORTANT: Mark todos completed as soon as they are done. Do not batch completions.\",\n schema: z.object({\n operation: z.enum([\"write\", \"read\"]),\n todoList: z.array(z.object({\n id: z.number().int().positive().describe(\"Sequential id starting from 1\"),\n title: z.string().min(1),\n description: z.string().min(1),\n status: z.enum([\"not-started\", \"in-progress\", \"completed\"]),\n evidence: z.string().max(200).optional()\n })).optional()\n })\n }\n );\n (manageTodo as any)._stateRef = stateRef;\n tools.push(manageTodo);\n }\n\n // get_tool_response retrieves original raw output by executionId\n const getTool = tool(\n async ({ executionId }) => {\n let execution = stateRef.toolHistory?.find((t) => t.executionId === executionId);\n if (!execution) {\n execution = stateRef.toolHistoryArchived?.find((t) => t.executionId === executionId);\n }\n if (execution) {\n return execution.rawOutput || execution.output;\n }\n return \"Execution not found. Please check the executionId.\";\n },\n {\n name: \"get_tool_response\",\n description:\n \"RETRIEVE tool execution response: Use this to access the full output of a tool execution that shows as 'SUMMARIZED' in the tool history.\",\n schema: z.object({ executionId: z.string().describe(\"Tool execution id\") }),\n }\n );\n // mark mutable stateRef for toolsNode sync\n (getTool as any)._stateRef = stateRef;\n tools.push(getTool);\n\n // Structured output finalize tool (response) if outputSchema provided\n if (opts?.outputSchema) {\n const responseTool = tool(\n async (data: any) => {\n // Validate directly against provided schema\n try {\n const validated = opts.outputSchema.parse ? opts.outputSchema.parse(data) : data;\n // store parsed in a sentinel for toolsNode to pick up (toolsNode already looks for __finalStructuredOutput?)\n return { __finalStructuredOutput: true, data: validated };\n } catch (e: any) {\n return { error: 'Schema validation failed', details: e?.message };\n }\n },\n {\n name: 'response',\n description: 'Finalize the answer by returning the final structured JSON matching the required schema. Call exactly once when you are fully done, then stop.',\n // Use schema directly; if not Zod, fall back to any-object\n schema: opts.outputSchema.shape ? opts.outputSchema : z.any(),\n }\n );\n (responseTool as any)._stateRef = stateRef;\n tools.push(responseTool);\n }\n\n return tools;\n}\n","import { SmartState, SmartAgentOptions } from \"../types.js\";\nimport { countApproxTokens } from \"../utils/utilTokens.js\";\n\n/** Shared helper to compute whether we exceed token limit */\nfunction needsSummarization(state: SmartState, opts: SmartAgentOptions, summarizationEnabled: boolean): boolean {\n const maxTok = opts.limits?.maxToken;\n if (!maxTok || !summarizationEnabled) return false;\n try {\n const allText = (state.messages || [])\n .map((m: any) => typeof m.content === \"string\" ? m.content : Array.isArray(m.content) ? m.content.map((c: any) => (typeof c === 'string' ? c : c?.text ?? c?.content ?? '')).join('') : '')\n .join(\"\\n\");\n const tokenCount = countApproxTokens(allText);\n return tokenCount > maxTok;\n } catch {\n return false;\n }\n}\n\nexport function resolverDecisionFactory(opts: SmartAgentOptions, summarizationEnabled: boolean) {\n return function resolverDecision(state: SmartState) {\n return needsSummarization(state, opts, summarizationEnabled) ? \"contextSummarize\" : \"agent\";\n };\n}\n\nexport function toolsDecisionFactory(opts: SmartAgentOptions, summarizationEnabled: boolean) {\n return function toolsDecision(state: SmartState) {\n const max = (opts.limits?.maxToolCalls ?? 10) as number;\n const count = state.toolCallCount || 0;\n if (count >= max) return \"toolLimitFinalize\";\n return needsSummarization(state, opts, summarizationEnabled) ? \"contextSummarize\" : \"agent\";\n };\n}\n\nexport function finalizeDecisionFactory(opts: SmartAgentOptions, summarizationEnabled: boolean) {\n return function finalizeDecision(state: SmartState) {\n return needsSummarization(state, opts, summarizationEnabled) ? \"contextSummarize\" : \"agent\";\n };\n}\n","import type { AgentResult as AgentInvokeResult, InvokeConfig, AgentOptions as SmartAgentOptions, AgentState as SmartState, AgentInstance as SmartAgentInstance } from \"../types.js\";\nimport { ZodSchema, z } from \"zod\";\nimport { createAgent } from \"../agent.js\";\nimport { createContextTools } from \"../contextTools.js\";\nimport { createContextSummarizeNode } from \"../nodes/contextSummarize.js\";\nimport { buildSystemPrompt } from \"../prompts.js\";\nimport { resolverDecisionFactory, toolsDecisionFactory } from \"../graph/decisions.js\";\n\n// SmartAgent on top of core createAgent: adds system prompt, optional planning context tools, and token-aware summarization.\nexport function createSmartAgent<TOutput = unknown>(opts: SmartAgentOptions & { outputSchema?: ZodSchema<TOutput> }): SmartAgentInstance<TOutput> {\n // Prepare context tools (todo + get_tool_response). Avoid duplicating response tool; base agent will add it if schema provided.\n const stateRef: any = { toolHistory: undefined, toolHistoryArchived: undefined, todoList: undefined };\n const planningEnabled = opts.useTodoList === true;\n const contextTools = createContextTools(stateRef, { planningEnabled, outputSchema: undefined });\n const mergedTools = [...((opts.tools as any) ?? []), ...contextTools];\n\n // Compose base agent\n const base = createAgent<TOutput>({ ...opts, tools: mergedTools });\n\n const summarizationEnabled = opts.summarization !== false; // default true\n const summarizer = summarizationEnabled ? createContextSummarizeNode(opts) : undefined;\n const decideBefore = resolverDecisionFactory(opts, summarizationEnabled);\n const decideAfter = toolsDecisionFactory(opts, summarizationEnabled);\n\n const structuredOutputHint = opts.outputSchema\n ? [\n 'A structured output schema is active.',\n 'Do NOT output the final JSON directly as an assistant message.',\n 'When completely finished, call tool `response` passing the final JSON matching the schema as its arguments (direct object).',\n 'Call it exactly once then STOP producing further assistant messages.'\n ].join('\\n')\n : '';\n\n function systemMessage(): any {\n const sys = buildSystemPrompt(\n [opts.systemPrompt, structuredOutputHint].filter(Boolean).join(\"\\n\"),\n opts.useTodoList === true,\n opts.name || \"Agent\"\n );\n return { role: 'system', content: sys } as any;\n }\n\n const instance: SmartAgentInstance<TOutput> = {\n invoke: async (input: SmartState, config?: InvokeConfig): Promise<AgentInvokeResult<TOutput>> => {\n // wire stateRef for context tools\n stateRef.toolHistory = input.toolHistory;\n stateRef.toolHistoryArchived = input.toolHistoryArchived;\n\n // Prepend a single system message once\n const alreadyHasSystem = Array.isArray(input.messages) && input.messages[0]?.role === 'system';\n const seedMessages = alreadyHasSystem ? [...(input.messages || [])] : [systemMessage(), ...(input.messages || [])];\n let state: SmartState = { ...input, messages: seedMessages } as SmartState;\n let lastResult: AgentInvokeResult<TOutput> | null = null;\n const iterationLimit = Math.max((opts.limits?.maxToolCalls ?? 10) * 3 + 5, 30);\n\n for (let i = 0; i < iterationLimit; i++) {\n // Pre-agent summarization decision\n const next = summarizationEnabled ? decideBefore(state) : 'agent';\n if (next === 'contextSummarize' && summarizer) {\n const delta = await summarizer(state);\n state = { ...state, ...delta } as SmartState;\n continue; // run decision again before calling base\n }\n\n // Delegate a full turn to base agent (includes tools + tool-limit finalize + structured output finalize)\n const res = await base.invoke(state, config);\n lastResult = res as AgentInvokeResult<TOutput>;\n state = (res.state as SmartState) || { ...state, messages: res.messages };\n\n // If structured output finalize triggered, base already stopped with parsed output\n if ((state as any).ctx?.__finalizedDueToStructuredOutput) break;\n\n // Post-tools summarization decision\n if (summarizationEnabled) {\n const after = decideAfter(state);\n if (after === 'contextSummarize' && summarizer) {\n const delta = await summarizer(state);\n state = { ...state, ...delta } as SmartState;\n // Loop will attempt another agent pass\n continue;\n }\n }\n\n // If base produced an assistant message without tool calls (its normal stop), we're done.\n break;\n }\n\n // Fall back if base was never invoked (edge case)\n if (!lastResult) {\n const res = await base.invoke(state, config);\n lastResult = res as AgentInvokeResult<TOutput>;\n }\n\n return lastResult as AgentInvokeResult<TOutput>;\n },\n asTool: base.asTool,\n asHandoff: base.asHandoff,\n __runtime: base.__runtime,\n };\n\n return instance;\n}\n"],"mappings":";AAoCO,SAAS,aAAa,GAAyB;AACpD,SAAO,CAAC,CAAC,KAAK,OA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