memeloop 0.0.1
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/dist/anthropic.cjs +72 -0
- package/dist/anthropic.cjs.map +1 -0
- package/dist/anthropic.d.cts +21 -0
- package/dist/anthropic.d.ts +21 -0
- package/dist/anthropic.js +21 -0
- package/dist/anthropic.js.map +1 -0
- package/dist/azure.cjs +72 -0
- package/dist/azure.cjs.map +1 -0
- package/dist/azure.d.cts +21 -0
- package/dist/azure.d.ts +21 -0
- package/dist/azure.js +21 -0
- package/dist/azure.js.map +1 -0
- package/dist/chunk-3CN7DFBL.js +4894 -0
- package/dist/chunk-3CN7DFBL.js.map +1 -0
- package/dist/chunk-4AZ4D7U5.js +32 -0
- package/dist/chunk-4AZ4D7U5.js.map +1 -0
- package/dist/chunk-6ON4XSOV.js +63 -0
- package/dist/chunk-6ON4XSOV.js.map +1 -0
- package/dist/chunk-DJQNGIXX.js +4793 -0
- package/dist/chunk-DJQNGIXX.js.map +1 -0
- package/dist/chunk-FKQP6AOQ.js +32 -0
- package/dist/chunk-FKQP6AOQ.js.map +1 -0
- package/dist/chunk-OVJ7JJBA.js +35 -0
- package/dist/chunk-OVJ7JJBA.js.map +1 -0
- package/dist/chunk-P4UZ7IXC.js +42 -0
- package/dist/chunk-P4UZ7IXC.js.map +1 -0
- package/dist/chunk-YHJ2AEFR.js +4933 -0
- package/dist/chunk-YHJ2AEFR.js.map +1 -0
- package/dist/chunk-YVK7RYRO.js +4973 -0
- package/dist/chunk-YVK7RYRO.js.map +1 -0
- package/dist/code-assistant.json +114 -0
- package/dist/cohere.cjs +72 -0
- package/dist/cohere.cjs.map +1 -0
- package/dist/cohere.d.cts +21 -0
- package/dist/cohere.d.ts +21 -0
- package/dist/cohere.js +21 -0
- package/dist/cohere.js.map +1 -0
- package/dist/deepseek.cjs +72 -0
- package/dist/deepseek.cjs.map +1 -0
- package/dist/deepseek.d.cts +21 -0
- package/dist/deepseek.d.ts +21 -0
- package/dist/deepseek.js +21 -0
- package/dist/deepseek.js.map +1 -0
- package/dist/dist-65U7OYRG.js +1257 -0
- package/dist/dist-65U7OYRG.js.map +1 -0
- package/dist/fetchProvider-Cu4WkU5O.d.cts +819 -0
- package/dist/fetchProvider-Cu4WkU5O.d.ts +819 -0
- package/dist/frontend-ui-ux.json +105 -0
- package/dist/general-assistant.json +95 -0
- package/dist/git-master.json +51 -0
- package/dist/google-vertex.cjs +72 -0
- package/dist/google-vertex.cjs.map +1 -0
- package/dist/google-vertex.d.cts +21 -0
- package/dist/google-vertex.d.ts +21 -0
- package/dist/google-vertex.js +21 -0
- package/dist/google-vertex.js.map +1 -0
- package/dist/google.cjs +72 -0
- package/dist/google.cjs.map +1 -0
- package/dist/google.d.cts +21 -0
- package/dist/google.d.ts +21 -0
- package/dist/google.js +21 -0
- package/dist/google.js.map +1 -0
- package/dist/groq.cjs +72 -0
- package/dist/groq.cjs.map +1 -0
- package/dist/groq.d.cts +21 -0
- package/dist/groq.d.ts +21 -0
- package/dist/groq.js +21 -0
- package/dist/groq.js.map +1 -0
- package/dist/index.cjs +8916 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1816 -0
- package/dist/index.d.mts +3203 -0
- package/dist/index.d.ts +1816 -0
- package/dist/index.js +4040 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +7064 -0
- package/dist/index.mjs.map +1 -0
- package/dist/llm-providers.cjs +311 -0
- package/dist/llm-providers.cjs.map +1 -0
- package/dist/llm-providers.d.cts +111 -0
- package/dist/llm-providers.d.ts +111 -0
- package/dist/llm-providers.js +232 -0
- package/dist/llm-providers.js.map +1 -0
- package/dist/loop-api.cjs +4924 -0
- package/dist/loop-api.cjs.map +1 -0
- package/dist/loop-api.d.cts +11 -0
- package/dist/loop-api.d.ts +11 -0
- package/dist/loop-api.js +189 -0
- package/dist/loop-api.js.map +1 -0
- package/dist/mistral.cjs +72 -0
- package/dist/mistral.cjs.map +1 -0
- package/dist/mistral.d.cts +21 -0
- package/dist/mistral.d.ts +21 -0
- package/dist/mistral.js +21 -0
- package/dist/mistral.js.map +1 -0
- package/dist/multipart-parser-EJCXIUHC.js +372 -0
- package/dist/multipart-parser-EJCXIUHC.js.map +1 -0
- package/dist/openai.cjs +72 -0
- package/dist/openai.cjs.map +1 -0
- package/dist/openai.d.cts +21 -0
- package/dist/openai.d.ts +21 -0
- package/dist/openai.js +21 -0
- package/dist/openai.js.map +1 -0
- package/dist/perplexity.cjs +72 -0
- package/dist/perplexity.cjs.map +1 -0
- package/dist/perplexity.d.cts +21 -0
- package/dist/perplexity.d.ts +21 -0
- package/dist/perplexity.js +21 -0
- package/dist/perplexity.js.map +1 -0
- package/dist/playwright.json +52 -0
- package/dist/promptConcat-BJdazTg5.d.cts +1832 -0
- package/dist/promptConcat-BJdazTg5.d.ts +1832 -0
- package/dist/promptConcat-CAkpni_8.d.cts +1834 -0
- package/dist/promptConcat-CAkpni_8.d.ts +1834 -0
- package/dist/promptConcat-CfH5-GAE.d.cts +1036 -0
- package/dist/promptConcat-ChcAZOOL.d.ts +1036 -0
- package/dist/promptConcat-G5TnJVRy.d.cts +1800 -0
- package/dist/promptConcat-G5TnJVRy.d.ts +1800 -0
- package/dist/promptConcat-L72eowzp.d.ts +1090 -0
- package/dist/promptConcat-eLHdN7K8.d.cts +1090 -0
- package/dist/src-VTSXKG72.js +1409 -0
- package/dist/src-VTSXKG72.js.map +1 -0
- package/dist/togetherai.cjs +72 -0
- package/dist/togetherai.cjs.map +1 -0
- package/dist/togetherai.d.cts +21 -0
- package/dist/togetherai.d.ts +21 -0
- package/dist/togetherai.js +21 -0
- package/dist/togetherai.js.map +1 -0
- package/dist/types-B0Jm2l38.d.cts +767 -0
- package/dist/types-B0Jm2l38.d.ts +767 -0
- package/dist/xai.cjs +72 -0
- package/dist/xai.cjs.map +1 -0
- package/dist/xai.d.cts +21 -0
- package/dist/xai.d.ts +21 -0
- package/dist/xai.js +21 -0
- package/dist/xai.js.map +1 -0
- package/package.json +87 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/loops/agent-agent-loop/builtinLoopSources.ts","../src/loopAPI/scriptLoader.ts","../src/loopAPI/agent-agent-loop/scriptLoader.ts","../src/loopAPI/agent-agent-loop/loop.ts","../src/loops/agent-tool-loop/builtinLoopSources.ts","../src/loopAPI/agent-tool-loop/compaction.ts","../src/loopAPI/agent-tool-loop/scriptLoader.ts","../src/tools/pluginRegistry.ts","../src/promptUtilities/responsePatternUtility.ts","../src/storage/nextLamport.ts","../src/loopAPI/hooks/registry.ts","../src/promptUtilities/promptConcat.ts","../src/tools/structuredToolResult.ts","../src/permission/engine.ts","../src/permission/storage.ts","../src/tools/approval.ts","../src/promptUtilities/responseConcat.ts","../src/loopAPI/agent-tool-loop/historyCompaction.ts","../src/loopAPI/agent-tool-loop/llmStream.ts","../src/promptUtilities/utilities.ts","../src/loopAPI/agent-tool-loop/modelMessages.ts","../src/loopAPI/agent-tool-loop/toolResultMessage.ts","../src/loopAPI/agent-tool-loop/toolCallRunner.ts","../src/loopAPI/agent-tool-loop/toolUseGate.ts","../src/loopAPI/agent-tool-loop/turnPrimitives.ts","../src/loopAPI/agent-tool-loop/scriptRunner.ts","../src/loopAPI/agent-tool-loop/loop.ts","../src/loopAPI/agent-tool-loop/runner.ts","../src/loopAPI/registry.ts","../src/loopAPI/plugins/builtinLoopsPlugin.ts","../src/tools/schemaRegistry.ts","../src/tools/builtins/questionWaitRegistry.ts","../src/tools/builtins/askQuestion.ts","../src/tools/builtins/askUserQuestion.ts","../src/tools/builtins/mcpClient.ts","../src/tools/builtins/mcpForward.ts","../src/tools/builtins/remoteAgent.ts","../src/tools/builtins/spawnAgent.ts","../src/agent/agentProfiles.ts","../src/agent/agentProfileRegistry.ts","../src/tools/builtins/task.ts","../src/tools/builtins/todoWrite.ts","../src/loopAPI/plugins/builtinToolsPlugin.ts","../src/loopAPI/tokenTracker.ts","../src/loopProfiles/builtinProfileSources.ts","../src/loopProfiles/loadBuiltins.ts","../src/promptUtilities/builtinPromptPlugins.ts","../src/runtime.ts","../src/agent/categories.ts","../src/llm/fetchProvider.ts","../src/llm/providerRegistry.ts","../src/conversation/factory.ts","../src/plugin/loader.ts","../src/plugin/registry.ts"],"sourcesContent":["// Generated by scripts/generate-loop-sources.mjs. Edit the sibling .mjs files instead.\n\nexport const AgentAgentLoopQualityGateScriptId = 'builtin:agent-agent-loop/quality-gate';\n\nexport const BUILTIN_AGENT_AGENT_LOOP_QUALITY_GATE_SCRIPT_ID = AgentAgentLoopQualityGateScriptId;\n\nexport const builtinAgentAgentLoopSources: Readonly<Record<string, string>> = {\n [AgentAgentLoopQualityGateScriptId]: [\n '// @ts-check',\n '',\n 'function positiveInteger(value, fallback) {',\n ' const number = Number(value);',\n ' return Number.isFinite(number) && number > 0 ? Math.floor(number) : fallback;',\n '}',\n '',\n 'function asEntries(value, fallback) {',\n ' return Array.isArray(value) && value.length > 0 ? value : fallback;',\n '}',\n '',\n 'function withConversationIds(ctx, entries, phase, iteration) {',\n ' return entries.map((entry, index) => {',\n \" const record = typeof entry === 'string' ? { profile: entry } : entry;\",\n ' return {',\n ' ...record,',\n ' conversationId: record.conversationId ?? `${ctx.input.conversationId}:${phase}:${iteration}:${index}`,',\n ' };',\n ' });',\n '}',\n '',\n 'function resultText(ctx, result) {',\n ' return result.text || ctx.formatAgentResults(result, { includeFailureSection: true });',\n '}',\n '',\n 'function reviewText(ctx, result) {',\n ' return ctx.formatAgentResults(result, { includeFailureSection: true });',\n '}',\n '',\n 'function approved(result) {',\n ' return result.failures.length === 0 &&',\n ' result.results.length > 0 &&',\n ' result.results.every(item => /^\\\\s*APPROVED\\\\b/imu.test(item.text));',\n '}',\n '',\n 'function feedbackBlock(ctx, history) {',\n \" if (history.length === 0) return 'No prior review feedback.';\",\n ' return history.map(entry => [',\n ' `Iteration ${entry.iteration}`,',\n ' `Attempt:\\\\n${resultText(ctx, entry.attempt)}`,',\n ' `Review:\\\\n${reviewText(ctx, entry.review)}`,',\n \" ].join('\\\\n\\\\n')).join('\\\\n\\\\n---\\\\n\\\\n');\",\n '}',\n '',\n 'function workerPrompt(ctx, goal, iteration, previousAttempt, history) {',\n ' if (!previousAttempt) return goal;',\n ' return [',\n \" 'Continue working on the original goal until the reviewer can approve it.',\",\n \" 'Do not summarize the review. Produce the corrected deliverable itself.',\",\n ' `Original goal:\\\\n${goal}`,',\n ' `Previous deliverable:\\\\n${resultText(ctx, previousAttempt)}`,',\n ' `Review history:\\\\n${feedbackBlock(ctx, history)}`,',\n ' `This is revision attempt ${iteration}.`,',\n \" ].join('\\\\n\\\\n');\",\n '}',\n '',\n 'function reviewPrompt(ctx, goal, attempt, history) {',\n ' return [',\n \" 'You are the quality gate for this delegated agent run.',\",\n \" 'Return APPROVED on the first line only when the deliverable fully satisfies the original goal and is ready to send to the user.',\",\n \" 'Return REVISE on the first line when more work is required, followed by concrete blocking issues and exact changes needed.',\",\n \" 'Do not approve partial progress.',\",\n ' `Original goal:\\\\n${goal}`,',\n ' `Candidate deliverable:\\\\n${resultText(ctx, attempt)}`,',\n ' `Earlier review history:\\\\n${feedbackBlock(ctx, history)}`,',\n \" ].join('\\\\n\\\\n');\",\n '}',\n '',\n 'async function runBatch(ctx, mode, input) {',\n \" return mode === 'sequential' ? ctx.runSequential(input) : ctx.runParallel(input);\",\n '}',\n '',\n \"/** @param {import('../../loopAPI/agent-agent-loop/loop.js').AgentAgentScriptContext} ctx */\",\n 'export default async function run(ctx) {',\n ' const metadata = ctx.profile?.metadata ?? {};',\n ' const goal = ctx.input.message;',\n ' const maxIterations = positiveInteger(metadata.maxIterations, 4);',\n \" const mode = metadata.mode === 'sequential' ? 'sequential' : 'parallel';\",\n \" const reviewMode = metadata.reviewMode === 'sequential' ? 'sequential' : 'parallel';\",\n \" const defaultAgents = ctx.getAgentEntries('agents');\",\n \" const workers = asEntries(ctx.getAgentEntries('workers'), asEntries(ctx.getAgentEntries('draftAgents'), defaultAgents));\",\n \" const reviewers = asEntries(ctx.getAgentEntries('reviewers'), asEntries(ctx.getAgentEntries('reviewAgents'), defaultAgents));\",\n \" const fixers = asEntries(ctx.getAgentEntries('fixers'), asEntries(ctx.getAgentEntries('revisionAgents'), workers));\",\n ' const history = [];',\n ' let attempt;',\n '',\n ' if (workers.length === 0 || reviewers.length === 0) {',\n \" ctx.finish('AgentAgent quality gate requires worker and reviewer agents. Configure metadata.workers/reviewers or metadata.agents.');\",\n ' return;',\n ' }',\n '',\n ' for (let iteration = 1; iteration <= maxIterations; iteration += 1) {',\n ' if (ctx.isCancelled()) break;',\n ' const activeWorkers = iteration === 1 ? workers : fixers;',\n ' ctx.emit({',\n \" type: 'thinking',\",\n \" data: { status: 'quality-gate-work', conversationId: ctx.input.conversationId, iteration },\",\n ' });',\n ' attempt = await runBatch(ctx, mode, {',\n \" agents: withConversationIds(ctx, activeWorkers, 'work', iteration),\",\n ' prompt: workerPrompt(ctx, goal, iteration, attempt, history),',\n ' });',\n ' await ctx.checkpoint(`quality-gate:${iteration}:attempt`, attempt);',\n '',\n ' if (attempt.failures.length > 0 && attempt.results.length === 0) {',\n \" history.push({ iteration, attempt, review: { results: [], failures: attempt.failures, text: '' } });\",\n ' continue;',\n ' }',\n '',\n ' ctx.emit({',\n \" type: 'thinking',\",\n \" data: { status: 'quality-gate-review', conversationId: ctx.input.conversationId, iteration },\",\n ' });',\n ' const review = await runBatch(ctx, reviewMode, {',\n \" agents: withConversationIds(ctx, reviewers, 'review', iteration),\",\n ' prompt: reviewPrompt(ctx, goal, attempt, history),',\n ' });',\n ' history.push({ iteration, attempt, review });',\n ' await ctx.checkpoint(`quality-gate:${iteration}:review`, review);',\n '',\n ' if (approved(review)) {',\n ' ctx.finish(resultText(ctx, attempt));',\n ' return;',\n ' }',\n ' }',\n '',\n ' ctx.finish([',\n \" 'Quality gate did not approve the delegated work before the iteration limit.',\",\n \" attempt ? resultText(ctx, attempt) : 'No deliverable was produced.',\",\n \" 'Review trail:',\",\n ' feedbackBlock(ctx, history),',\n \" ].filter(Boolean).join('\\\\n\\\\n'));\",\n '}',\n '',\n ].join('\\n'),\n};\n\nexport function getBuiltinAgentAgentLoopSource(id: string): string | undefined {\n return builtinAgentAgentLoopSources[id];\n}\n","import type { AgentLoopScriptPolicy, LoopProfileScriptReference } from './types.js';\n\nexport type AgentLoopScriptReference = string | LoopProfileScriptReference;\n\nexport interface LoadAgentLoopScriptOptions extends AgentLoopScriptPolicy {\n getBuiltinScriptSource?: (id: string) => string | undefined;\n scriptType?: string;\n}\n\nconst DEFAULT_POLICY = {\n allowBuiltin: true,\n allowFile: false,\n allowNetwork: false,\n allowSource: false,\n allowSpecifier: true,\n} as const;\n\nfunction getExportedScript(moduleExports: unknown): unknown {\n if (typeof moduleExports === 'function') return moduleExports;\n if (!moduleExports || typeof moduleExports !== 'object') return undefined;\n\n const record = moduleExports as Record<string, unknown>;\n return record.default ?? record.run;\n}\n\nfunction sourceToDataSpecifier(source: string, name = 'agent-loop-script.mjs'): string {\n return `data:text/javascript;charset=utf-8,${encodeURIComponent(`${source}\\n//# sourceURL=${name}`)}`;\n}\n\nfunction normalizeScriptReference(scriptReference: AgentLoopScriptReference): LoopProfileScriptReference {\n if (typeof scriptReference !== 'string') return scriptReference;\n if (scriptReference.startsWith('builtin:')) return { kind: 'builtin', id: scriptReference };\n return { kind: 'specifier', specifier: scriptReference };\n}\n\nfunction isFileSpecifier(specifier: string): boolean {\n return specifier.startsWith('file:') || specifier.startsWith('/') || specifier.startsWith('./') || specifier.startsWith('../');\n}\n\nfunction isNetworkSpecifier(specifier: string): boolean {\n return specifier.startsWith('http:') || specifier.startsWith('https:');\n}\n\nfunction isSourceSpecifier(specifier: string): boolean {\n return specifier.startsWith('data:text/javascript') || specifier.startsWith('data:application/javascript');\n}\n\nfunction assertSpecifierAllowed(specifier: string, policy: Required<Pick<LoadAgentLoopScriptOptions, 'allowFile' | 'allowNetwork' | 'allowSource' | 'allowSpecifier'>>): void {\n if (!policy.allowSpecifier) {\n throw new Error('Agent loop script import specifiers are disabled by policy.');\n }\n if (isSourceSpecifier(specifier) && !policy.allowSource) {\n throw new Error('Agent loop script source/data URLs are disabled by policy.');\n }\n if (isFileSpecifier(specifier) && !policy.allowFile) {\n throw new Error('Agent loop script file imports are disabled by policy.');\n }\n if (isNetworkSpecifier(specifier) && !policy.allowNetwork) {\n throw new Error('Agent loop script network imports are disabled by policy.');\n }\n}\n\nexport async function loadAgentLoopScript<TScript>(\n scriptReference: AgentLoopScriptReference,\n options: LoadAgentLoopScriptOptions = {},\n): Promise<TScript> {\n const policy = { ...DEFAULT_POLICY, ...options };\n const importModule = options.importModule ?? ((specifier: string) => import(specifier));\n const normalized = normalizeScriptReference(scriptReference);\n const scriptType = options.scriptType ?? 'Agent loop script';\n let scriptSpecifier: string;\n let isBuiltinScript = false;\n\n if (normalized.kind === 'builtin') {\n if (!policy.allowBuiltin) {\n throw new Error('Built-in agent loop scripts are disabled by policy.');\n }\n const source = options.getBuiltinScriptSource?.(normalized.id);\n if (!source) throw new Error(`Unknown built-in agent loop script: ${normalized.id}`);\n scriptSpecifier = sourceToDataSpecifier(source, normalized.id);\n isBuiltinScript = true;\n } else if (normalized.kind === 'source') {\n if (!policy.allowSource) {\n throw new Error('Agent loop script source strings are disabled by policy.');\n }\n scriptSpecifier = sourceToDataSpecifier(normalized.source, normalized.name);\n } else {\n scriptSpecifier = normalized.specifier;\n }\n\n if (!isBuiltinScript) {\n assertSpecifierAllowed(scriptSpecifier, policy);\n }\n const moduleExports: unknown = await importModule(scriptSpecifier);\n const exportedScript = getExportedScript(moduleExports);\n\n if (typeof exportedScript !== 'function') {\n throw new TypeError(\n `${scriptType} \"${scriptSpecifier}\" must export a default function or named run function.`,\n );\n }\n\n return exportedScript as TScript;\n}\n","import { getBuiltinAgentAgentLoopSource } from '../../loops/agent-agent-loop/builtinLoopSources.js';\nimport { type AgentLoopScriptReference, loadAgentLoopScript } from '../scriptLoader.js';\nimport type { AgentLoopScriptPolicy } from '../types.js';\nimport type { AgentAgentLoopScript } from './loop.js';\n\nexport type LoadAgentAgentLoopScriptOptions = AgentLoopScriptPolicy;\n\nexport type AgentAgentLoopScriptReference = AgentLoopScriptReference;\n\nexport async function loadAgentAgentLoopScript(\n scriptReference: AgentAgentLoopScriptReference,\n options: LoadAgentAgentLoopScriptOptions = {},\n): Promise<AgentAgentLoopScript> {\n return loadAgentLoopScript<AgentAgentLoopScript>(scriptReference, {\n ...options,\n getBuiltinScriptSource: getBuiltinAgentAgentLoopSource,\n scriptType: 'AgentAgentLoop script',\n });\n}\n","/**\n * AgentAgent_Loop — a loop that orchestrates child agents.\n *\n * This loop does NOT call the LLM directly. Instead it coordinates child agents:\n * - running a child agent and feeding its result to another child agent (review / verify)\n * - splitting work across multiple parallel child agents\n * - looping back to a child agent with feedback when a reviewer rejects the output\n *\n * The loop script (.mjs) holds the orchestration logic. This file provides the\n * runtime that invokes the script and manages child agent runs.\n */\n\nimport type { AgentLoopDefinition, AgentLoopGenerator, AgentLoopInput, AgentLoopRuntime, AgentLoopStep, LoopProfile } from '../types.js';\nimport { type AgentAgentLoopScriptReference, loadAgentAgentLoopScript, type LoadAgentAgentLoopScriptOptions } from './scriptLoader.js';\n\nconst LOOP_ID = 'agent-agent-loop';\nconst LOOP_NAME = 'AgentAgent Loop';\nconst LOOP_DESC = 'Orchestrates child agents to collaborate on a task. Supports sequential chaining, parallel execution, and feedback loops.';\n\n/**\n * Typed API passed to a AgentAgent `.mjs` script.\n *\n * The API is intentionally primitive: scripts decide the workflow shape, role\n * names, approval rules, retry limits, and delivery gates. This runtime only\n * handles child-agent execution, progress events, cancellation, state, and\n * checkpoints.\n */\nexport interface AgentAgentLoopScriptArguments {\n /** The parent turn input. `input.message` is the user's original goal. */\n input: AgentLoopInput;\n /** Host/runtime context for advanced integrations. Prefer the typed helpers below when possible. */\n context: AgentAgentLoopContext;\n /** Active profile. Scripts may define their own workflow-specific metadata keys here. */\n profile?: LoopProfile;\n /** Normalized worker agents read from `context.agents` or `profile.metadata.agents`. */\n agents: AgentAgentDescriptor[];\n /**\n * Read raw agent entries from `profile.metadata[key]`; defaults to `agents`.\n * This is deliberately generic so scripts can choose names like `critics`,\n * `builders`, `verifiers`, or any other workflow-specific role.\n */\n getAgentEntries: (key?: string) => AgentAgentConfigEntry[];\n /** Low-level runtime hooks. Prefer `state`, `checkpoint`, `emit`, and run helpers first. */\n runtime?: Partial<AgentLoopRuntime>;\n /** Run one child agent and collect all yielded steps into a text result. */\n runAgent: (input: AgentAgentRunAgentInput) => Promise<AgentAgentRunAgentResult>;\n /** Run child agents concurrently. Use `runSequential` when order matters. */\n runAgents: (inputs: AgentAgentRunAgentInput[]) => Promise<AgentAgentRunAgentResult[]>;\n /** Run a batch of agents in order, aggregating successful output and failures. */\n runSequential: (input?: AgentAgentBatchRunInput) => Promise<AgentAgentBatchRunResult>;\n /** Run a batch of agents concurrently, aggregating successful output and failures. */\n runParallel: (input?: AgentAgentBatchRunInput) => Promise<AgentAgentBatchRunResult>;\n /** Format a batch result for final delivery or an intermediate report. */\n formatAgentResults: (result: AgentAgentBatchRunResult, options?: AgentAgentFormatResultsOptions) => string;\n /** Emit a formatted batch result as the parent loop's final/user-visible message. */\n finishAgentResults: (result: AgentAgentBatchRunResult, options?: AgentAgentFormatResultsOptions) => void;\n /** Emit a raw loop step upstream. Use sparingly; helpers already emit progress. */\n emit: (step: AgentLoopStep) => void;\n /** Emit a user-visible message or step and end the script's work. */\n finish: (message: string | AgentLoopStep) => void;\n /** True when the host cancelled this parent run. Long-running scripts should check this between phases. */\n isCancelled: () => boolean;\n /** Write an observability event through the host runtime logger. */\n log: (event: string, data?: Record<string, unknown>) => void;\n /** Per-run persistent state scoped by the host runtime. */\n state: AgentLoopRuntime['state'];\n /** Record a resumable milestone for long workflows. */\n checkpoint: AgentLoopRuntime['checkpoint'];\n}\n\nexport type AgentAgentScriptContext = AgentAgentLoopScriptArguments;\n\nexport type AgentAgentContext = AgentAgentScriptContext;\n\nexport interface AgentAgentDescriptor {\n /** Child profile id to run. */\n profileId: string;\n /** Prompt override for this child run. Defaults to the parent input message. */\n prompt?: string;\n /** Conversation id override. Defaults to `${parent}:child:${index}` for batch helpers. */\n conversationId?: string;\n /** Optional human-readable role label, e.g. \"implementer\" or \"reviewer\". */\n label?: string;\n [key: string]: unknown;\n}\n\nexport type AgentAgentConfigEntry =\n | string\n | ({\n profileId?: string;\n profile?: string;\n prompt?: string;\n conversationId?: string;\n label?: string;\n } & Record<string, unknown>);\n\nexport interface AgentAgentRunAgentInput {\n /** Child profile id. `profile` is accepted as an ergonomic alias for scripts. */\n profileId?: string;\n profile?: string;\n /** Defaults to the parent input message. */\n prompt?: string;\n conversationId?: string;\n label?: string;\n}\n\nexport interface AgentAgentRunAgentResult {\n profileId: string;\n conversationId: string;\n steps: AgentLoopStep[];\n text: string;\n}\n\nexport interface AgentAgentRunAgentFailure {\n profileId: string;\n conversationId?: string;\n error: string;\n}\n\nexport interface AgentAgentBatchRunInput {\n /** Agents to run. Defaults to `ctx.agents`. */\n agents?: AgentAgentConfigEntry[];\n /** Prompt shared by every agent in this batch. Defaults to the parent input message. */\n prompt?: string;\n /** When false, the first child failure rejects the batch. Defaults to true. */\n continueOnError?: boolean;\n}\n\nexport interface AgentAgentBatchRunResult {\n results: AgentAgentRunAgentResult[];\n failures: AgentAgentRunAgentFailure[];\n text: string;\n}\n\nexport interface AgentAgentFormatResultsOptions {\n emptyMessage?: string;\n failureHeader?: string;\n includeFailureSection?: boolean;\n}\n\nexport type AgentAgentLoopScriptResult =\n | AgentLoopGenerator\n | AgentLoopStep\n | AgentLoopStep[]\n | string\n | undefined;\n\nexport type AgentAgentLoopScript = (\n scriptArguments: AgentAgentLoopScriptArguments,\n) => AgentAgentLoopScriptResult | Promise<AgentAgentLoopScriptResult>;\n\nexport interface AgentAgentLoopContext {\n [key: string]: unknown;\n profile?: LoopProfile;\n runtime?: Partial<AgentLoopRuntime>;\n agents?: AgentAgentConfigEntry[];\n script?: AgentAgentLoopScript;\n loadScript?: (\n script: AgentAgentLoopScriptReference,\n context: AgentAgentLoopContext,\n ) => AgentAgentLoopScript | Promise<AgentAgentLoopScript>;\n scriptPolicy?: LoadAgentAgentLoopScriptOptions;\n}\n\nfunction isAsyncIterable(value: unknown): value is AgentLoopGenerator {\n return Boolean(value && typeof value === 'object' && Symbol.asyncIterator in value);\n}\n\nfunction messageStep(message: string): AgentLoopStep {\n return { type: 'message', data: message };\n}\n\nfunction stepText(step: AgentLoopStep): string | undefined {\n if (step.type !== 'message') return undefined;\n if (typeof step.data === 'string') return step.data;\n if (step.data && typeof step.data === 'object' && 'content' in step.data) {\n const content = (step.data as { content?: unknown }).content;\n return typeof content === 'string' ? content : undefined;\n }\n return undefined;\n}\n\nfunction profileIdFromEntry(entry: AgentAgentConfigEntry): string | undefined {\n if (typeof entry === 'string') return entry;\n return entry.profileId ?? entry.profile;\n}\n\nfunction readProfileAgentEntries(profile?: LoopProfile, key = 'agents'): AgentAgentConfigEntry[] | undefined {\n const metadata = profile?.metadata;\n if (!metadata) return undefined;\n\n const entries = metadata[key];\n if (Array.isArray(entries)) return entries as AgentAgentConfigEntry[];\n\n return undefined;\n}\n\nfunction normalizeAgentAgents(\n input: AgentLoopInput,\n context: AgentAgentLoopContext,\n entries?: AgentAgentConfigEntry[],\n prompt?: string,\n): AgentAgentDescriptor[] {\n const configuredEntries = entries ?? context.agents ?? readProfileAgentEntries(context.profile) ?? [];\n return configuredEntries.flatMap((entry, index) => {\n const profileId = profileIdFromEntry(entry);\n if (!profileId) return [];\n const record = typeof entry === 'string' ? {} : entry;\n return {\n ...record,\n profileId,\n prompt: prompt ?? record.prompt,\n conversationId: record.conversationId ?? `${input.conversationId}:child:${index}`,\n label: record.label,\n };\n });\n}\n\nfunction formatAgentResults(\n result: AgentAgentBatchRunResult,\n options: AgentAgentFormatResultsOptions = {},\n): string {\n const emptyMessage = options.emptyMessage ?? 'No child agent output.';\n const failureHeader = options.failureHeader ?? 'Failed child agents:';\n const includeFailureSection = options.includeFailureSection !== false;\n const sections = [result.text || emptyMessage];\n\n if (includeFailureSection && result.failures.length > 0) {\n sections.push(`${failureHeader}\\n${result.failures.map(failure => `${failure.profileId}: ${failure.error}`).join('\\n')}`);\n }\n\n return sections.filter(Boolean).join('\\n\\n');\n}\n\nfunction createScriptArguments(\n input: AgentLoopInput,\n context: AgentAgentLoopContext,\n emittedSteps: AgentLoopStep[],\n): AgentAgentLoopScriptArguments {\n const agentEntries = context.agents ?? readProfileAgentEntries(context.profile) ?? [];\n const agents = normalizeAgentAgents(input, context, agentEntries);\n const getAgentEntries = (key = 'agents'): AgentAgentConfigEntry[] => {\n if (key === 'agents') return agentEntries;\n return readProfileAgentEntries(context.profile, key) ?? [];\n };\n\n const emit = (step: AgentLoopStep): void => {\n emittedSteps.push(step);\n context.runtime?.emit?.(step);\n };\n\n const log = (event: string, data?: Record<string, unknown>): void => {\n context.runtime?.log?.(event, data);\n };\n\n const isCancelled = (): boolean => context.runtime?.signal?.cancelled === true;\n\n const runAgent = async (childInput: AgentAgentRunAgentInput): Promise<AgentAgentRunAgentResult> => {\n if (isCancelled()) throw new Error('AgentAgent_Loop cancelled before child agent start');\n const profileId = childInput.profileId ?? childInput.profile;\n if (!profileId) throw new Error('ctx.runAgent requires profileId or profile');\n if (!context.runtime?.runChildAgent) throw new Error('ctx.runAgent requires runtime.runChildAgent');\n\n const childConversationId = childInput.conversationId ?? `${input.conversationId}:child:${profileId}:${Date.now().toString(36)}`;\n const prompt = childInput.prompt ?? input.message;\n emit({\n type: 'thinking',\n data: { status: 'child-agent-started', profileId, conversationId: childConversationId },\n });\n\n const steps: AgentLoopStep[] = [];\n const chunks: string[] = [];\n try {\n for await (\n const step of context.runtime.runChildAgent({\n profileId,\n prompt,\n conversationId: childConversationId,\n })\n ) {\n if (isCancelled()) throw new Error('AgentAgent_Loop cancelled during child agent run');\n steps.push(step);\n const text = stepText(step);\n if (text) chunks.push(text);\n emit({\n type: 'thinking',\n data: { status: 'child-agent-step', profileId, conversationId: childConversationId, step },\n });\n }\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n emit({\n type: 'thinking',\n data: { status: 'child-agent-failed', profileId, conversationId: childConversationId, error: message },\n });\n throw error;\n }\n\n emit({\n type: 'thinking',\n data: { status: 'child-agent-completed', profileId, conversationId: childConversationId },\n });\n return { profileId, conversationId: childConversationId, steps, text: chunks.join('').trim() };\n };\n\n const runBatch = async (\n batchInput: AgentAgentBatchRunInput | undefined,\n mode: 'parallel' | 'sequential',\n ): Promise<AgentAgentBatchRunResult> => {\n const batchAgents = normalizeAgentAgents(input, context, batchInput?.agents, batchInput?.prompt);\n const continueOnError = batchInput?.continueOnError !== false;\n const results: AgentAgentRunAgentResult[] = [];\n const failures: AgentAgentRunAgentFailure[] = [];\n\n const runOne = async (agent: AgentAgentDescriptor): Promise<void> => {\n if (isCancelled()) {\n emit({\n type: 'thinking',\n data: { status: 'cancelled', conversationId: input.conversationId },\n });\n return;\n }\n try {\n const result = await runAgent(agent);\n results.push(result);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n failures.push({ profileId: agent.profileId, conversationId: agent.conversationId, error: message });\n if (!continueOnError) throw error;\n }\n };\n\n if (mode === 'parallel') {\n await Promise.all(batchAgents.map(agent => runOne(agent)));\n } else {\n for (const agent of batchAgents) {\n await runOne(agent);\n if (isCancelled()) break;\n }\n }\n\n return { results, failures, text: results.map(result => result.text).filter(Boolean).join('\\n\\n') };\n };\n\n return {\n input,\n context,\n profile: context.profile,\n agents,\n getAgentEntries,\n runtime: context.runtime,\n runAgent,\n runAgents: inputs => Promise.all(inputs.map(runAgent)),\n runSequential: batchInput => runBatch(batchInput, 'sequential'),\n runParallel: batchInput => runBatch(batchInput, 'parallel'),\n formatAgentResults,\n finishAgentResults: (result, options) => {\n emit(messageStep(formatAgentResults(result, options)));\n },\n emit,\n finish: message => {\n emit(typeof message === 'string' ? messageStep(message) : message);\n },\n isCancelled,\n log,\n state: context.runtime?.state ?? {\n get: async () => undefined,\n set: async () => undefined,\n update: async () => undefined,\n },\n checkpoint: context.runtime?.checkpoint ?? (async () => undefined),\n };\n}\n\nasync function* drainEmittedSteps(steps: AgentLoopStep[]): AgentLoopGenerator {\n while (steps.length > 0) {\n const step = steps.shift();\n if (step) yield step;\n }\n}\n\nasync function* runScript(\n script: AgentAgentLoopScript,\n input: AgentLoopInput,\n context: AgentAgentLoopContext,\n): AgentLoopGenerator {\n const emittedSteps: AgentLoopStep[] = [];\n const scriptArguments = createScriptArguments(input, context, emittedSteps);\n const result = await script(scriptArguments);\n\n yield* drainEmittedSteps(emittedSteps);\n if (isAsyncIterable(result)) {\n yield* result;\n yield* drainEmittedSteps(emittedSteps);\n } else if (typeof result === 'string') {\n yield messageStep(result);\n } else if (Array.isArray(result)) {\n yield* result;\n } else if (result) {\n yield result;\n }\n}\n\nfunction asAgentAgentContext(context: { [key: string]: unknown }): AgentAgentLoopContext {\n return context as AgentAgentLoopContext;\n}\n\nasync function resolveScript(\n context: AgentAgentLoopContext,\n): Promise<AgentAgentLoopScript | undefined> {\n if (context.script) return context.script;\n const scriptReference = context.profile?.scriptReference ?? context.profile?.scriptRef ?? context.profile?.script;\n if (scriptReference) {\n if (context.loadScript) return context.loadScript(scriptReference, context);\n return loadAgentAgentLoopScript(scriptReference, context.scriptPolicy);\n }\n return undefined;\n}\n\n/**\n * Create the AgentAgent_Loop definition and register it with the loop registry.\n */\nexport function createAgentAgentLoopDefinition(): AgentLoopDefinition {\n return {\n id: LOOP_ID,\n name: LOOP_NAME,\n description: LOOP_DESC,\n createRunner: (rawContext) => {\n return async function* agentAgentLoop(input) {\n const context = asAgentAgentContext(rawContext);\n const script = await resolveScript(context);\n\n yield {\n type: 'thinking',\n data: { status: 'agent-agent-loop-loop-started', conversationId: input.conversationId },\n };\n context.runtime?.log?.('agent-agent-loop-loop-started', {\n conversationId: input.conversationId,\n profileId: context.profile?.id,\n });\n\n if (script) {\n yield* runScript(script, input, context);\n yield {\n type: 'thinking',\n data: { status: 'completed', conversationId: input.conversationId },\n };\n return;\n }\n\n yield {\n type: 'thinking',\n data: { status: 'script-missing', conversationId: input.conversationId },\n };\n yield {\n type: 'message',\n data: 'AgentAgentLoop requires an explicit loop script. Configure profile.scriptReference or provide context.script.',\n };\n yield {\n type: 'thinking',\n data: { status: 'completed', conversationId: input.conversationId },\n };\n };\n },\n };\n}\n\n/** Export loop id for consumers. */\nexport function getAgentAgentLoopId(): string {\n return LOOP_ID;\n}\n","// Generated by scripts/generate-loop-sources.mjs. Edit the sibling .mjs files instead.\n\nexport const AgentToolLoopDefaultScriptId = 'builtin:agent-tool-loop/default';\n\nexport const BUILTIN_AGENT_TOOL_LOOP_DEFAULT_SCRIPT_ID = AgentToolLoopDefaultScriptId;\n\nexport const builtinAgentToolLoopSources: Readonly<Record<string, string>> = {\n [AgentToolLoopDefaultScriptId]: [\n '// @ts-check',\n '',\n \"/** @param {import('../../loopAPI/agent-tool-loop/loop.js').AgentToolLoopScriptContext} ctx */\",\n 'export default async function* run(ctx) {',\n ' const state = ctx.createState();',\n '',\n ' try {',\n ' const start = await ctx.startTurn(state);',\n ' if (start.step) yield start.step;',\n \" if (start.action === 'stop') return;\",\n '',\n ' while (true) {',\n ' const result = yield* ctx.runIteration(state);',\n \" if (result.action === 'stop') return;\",\n ' }',\n ' } catch (error) {',\n \" await ctx.stopTurn(state, 'error');\",\n ' throw error;',\n ' } finally {',\n ' await ctx.stopTurn(state);',\n ' }',\n '}',\n ].join('\\n'),\n};\n\nexport function getBuiltinAgentToolLoopSource(id: string): string | undefined {\n return builtinAgentToolLoopSources[id];\n}\n","import type { ChatMessage } from '../../conversation/index.js';\nimport type { ILLMProvider } from '../../types.js';\n\nexport interface CompactionOptions {\n /** Maximum token count to aim for after compaction (estimated by char count / 3.5). Default: 0 (no limit). */\n maxTokens?: number;\n /** Number of recent message turns (user+assistant pairs) to preserve. Default: 4. */\n recentTurnsToKeep?: number;\n /** Whether to attempt LLM summarization. Falls back to truncation if LLM unavailable or fails. Default: true. */\n useLlmSummary?: boolean;\n /** Optional LLM provider for summarization. */\n llmProvider?: ILLMProvider;\n}\n\nexport interface CompactionResult {\n /** Compacted messages (summary + recent turns). */\n messages: ChatMessage[];\n /** True if compaction reduced the message count. */\n compacted: boolean;\n /** Number of messages dropped. */\n droppedCount: number;\n /** Summary text generated or fallback notice. */\n summaryText: string;\n}\n\n/**\n * Counts \"turns\" in message history. A turn is a user→assistant pair.\n * Tool messages are grouped with the preceding assistant message.\n */\nfunction countTurns(messages: ChatMessage[]): number {\n let turns = 0;\n for (const message of messages) {\n if (message.role === 'user') {\n turns++;\n }\n }\n return turns;\n}\n\n/**\n * Estimate token count from message content (rough: chars / 3.5).\n */\nfunction estimateTokens(messages: ChatMessage[]): number {\n let total = 0;\n for (const message of messages) {\n const content = typeof message.content === 'string' ? message.content : JSON.stringify(message.content);\n total += content.length / 3.5;\n }\n return Math.ceil(total);\n}\n\n/**\n * Build a fallback summary string from the dropped messages.\n */\nfunction buildTruncationSummary(dropped: ChatMessage[], totalDropped: number): string {\n const turns = countTurns(dropped);\n const oldest = dropped[0];\n const newest = dropped[dropped.length - 1];\n const oldestTime = oldest?.timestamp ? new Date(oldest.timestamp).toISOString() : 'unknown';\n const newestTime = newest?.timestamp ? new Date(newest.timestamp).toISOString() : 'unknown';\n\n return `[context-summary] ${totalDropped} earlier messages (${turns} turns, ${oldestTime} → ${newestTime}) were compacted. Key topics: see recent messages below.`;\n}\n\n/**\n * Creates a summary ChatMessage from the compaction result.\n */\nfunction createSummaryMessage(\n conversationId: string,\n summaryText: string,\n baseMessage: ChatMessage,\n): ChatMessage {\n return {\n messageId: `${conversationId}:compacted:${Date.now().toString(36)}`,\n conversationId,\n originNodeId: baseMessage.originNodeId,\n timestamp: Date.now(),\n lamportClock: -1, // Will be replaced by AgentToolLoop\n role: 'assistant',\n content: summaryText,\n metadata: { compacted: true },\n };\n}\n\n/**\n * Deterministic compaction: keeps recent N turns and replaces older messages\n * with a single summary message.\n */\nexport function compactMessages(\n messages: ChatMessage[],\n options: Omit<CompactionOptions, 'llmProvider' | 'useLlmSummary'> = {},\n): CompactionResult {\n const recentTurnsToKeep = options.recentTurnsToKeep ?? 4;\n\n if (messages.length <= recentTurnsToKeep * 2) {\n return { messages, compacted: false, droppedCount: 0, summaryText: '' };\n }\n\n // Find the cutoff point: keep the last recentTurnsToKeep user messages + everything after them\n const userIndices: number[] = [];\n for (let index = 0; index < messages.length; index++) {\n if (messages[index].role === 'user') {\n userIndices.push(index);\n }\n }\n\n if (userIndices.length <= recentTurnsToKeep) {\n return { messages, compacted: false, droppedCount: 0, summaryText: '' };\n }\n\n // The first message to keep starts at the recentTurnsToKeep-th user message from the end\n const keepStartIndex = userIndices[userIndices.length - recentTurnsToKeep];\n const dropped = messages.slice(0, keepStartIndex);\n const kept = messages.slice(keepStartIndex);\n\n if (dropped.length === 0) {\n return { messages, compacted: false, droppedCount: 0, summaryText: '' };\n }\n\n const conversationId = messages[0]?.conversationId ?? 'unknown';\n const summaryText = buildTruncationSummary(dropped, dropped.length);\n const summaryMessage = createSummaryMessage(conversationId, summaryText, messages[0]);\n\n const compacted: ChatMessage[] = [summaryMessage, ...kept];\n\n // Also prune tool outputs older than the cutoff in the kept section\n // (we already dropped them in the \"dropped\" section)\n\n return {\n messages: compacted,\n compacted: true,\n droppedCount: dropped.length,\n summaryText,\n };\n}\n\n/**\n * Checks whether compaction is needed based on message count threshold.\n * @returns true if message count exceeds threshold (default 50).\n */\nexport function shouldCompact(messages: ChatMessage[], threshold?: number): boolean {\n const t = threshold ?? 50;\n return messages.length > t;\n}\n\n/**\n * Auto-compact: estimates token usage, and if it exceeds maxTokens,\n * performs compaction to keep the context within bounds.\n *\n * Uses the LLM provider for summarization if available, falling back to\n * simple truncation + turn counting.\n */\nexport async function autoCompact(\n messages: ChatMessage[],\n options: CompactionOptions = {},\n): Promise<CompactionResult> {\n const recentTurnsToKeep = options.recentTurnsToKeep ?? 4;\n\n // If we're within budget, no need to compact\n if (options.maxTokens && options.maxTokens > 0) {\n const currentTokens = estimateTokens(messages);\n if (currentTokens <= options.maxTokens) {\n return { messages, compacted: false, droppedCount: 0, summaryText: '' };\n }\n }\n\n // If LLM summarization is requested and provider model is available, try it\n if (options.useLlmSummary !== false && options.llmProvider?.model != null) {\n try {\n const result = await llmCompact(messages, options.llmProvider, recentTurnsToKeep);\n if (result) return result;\n } catch {\n // Fall through to truncation\n }\n }\n\n // Fallback: deterministic truncation\n return compactMessages(messages, { ...options });\n}\n\n/**\n * LLM-based compaction: asks the model to summarize the older conversation turns.\n */\nasync function llmCompact(\n messages: ChatMessage[],\n llmProvider: ILLMProvider,\n recentTurnsToKeep: number,\n): Promise<CompactionResult | null> {\n const userIndices: number[] = [];\n for (let index = 0; index < messages.length; index++) {\n if (messages[index].role === 'user') {\n userIndices.push(index);\n }\n }\n\n if (userIndices.length <= recentTurnsToKeep) {\n return null;\n }\n\n const keepStartIndex = userIndices[userIndices.length - recentTurnsToKeep];\n const toSummarize = messages.slice(0, keepStartIndex);\n const kept = messages.slice(keepStartIndex);\n\n if (toSummarize.length === 0) return null;\n\n const conversationId = messages[0]?.conversationId ?? 'unknown';\n\n // Build a text representation of the messages to summarize\n const conversationText = toSummarize\n .map((m) => {\n const content = typeof m.content === 'string' ? m.content : JSON.stringify(m.content);\n const toolId = typeof m.metadata?.toolId === 'string' ? m.metadata.toolId : 'unknown';\n const roleLabel = m.role === 'tool' ? `[tool: ${toolId}]` : `[${m.role}]`;\n // Keep tool outputs brief in summary\n if (m.role === 'tool' && content.length > 500) {\n return `${roleLabel} ${content.slice(0, 500)}... (truncated)`;\n }\n return `${roleLabel} ${content}`;\n })\n .join('\\n\\n');\n\n const prompt =\n `Summarize the following conversation excerpt. Be concise but capture key decisions, action items, tool calls, and important context. Focus on information useful for continuing the conversation.\n\n<conversation>\n${conversationText.slice(0, 8000)}\n</conversation>\n\nProvide a brief summary (3-5 paragraphs) of the key points.`;\n\n try {\n const summaryText = await generateSummary(llmProvider, prompt);\n if (!summaryText || summaryText.length < 10) return null;\n\n const summaryMessage = createSummaryMessage(\n conversationId,\n `[context-summary] ${summaryText}`,\n messages[0],\n );\n\n return {\n messages: [summaryMessage, ...kept],\n compacted: true,\n droppedCount: toSummarize.length,\n summaryText,\n };\n } catch {\n return null; // Fall back to truncation\n }\n}\n\nasync function generateSummary(llmProvider: ILLMProvider, prompt: string): Promise<string | null> {\n if (typeof llmProvider.chat !== 'function') return null;\n const raw = llmProvider.chat({ messages: [{ role: 'user', content: prompt }] });\n let resolved: unknown = raw;\n if (resolved != null && typeof (resolved as Promise<unknown>).then === 'function') {\n resolved = await (resolved as Promise<unknown>);\n }\n if (\n resolved != null &&\n typeof (resolved as AsyncIterable<unknown>)[Symbol.asyncIterator] === 'function'\n ) {\n let text = '';\n for await (const chunk of resolved as AsyncIterable<unknown>) {\n text += chunkToText(chunk);\n }\n return text || null;\n }\n if (typeof resolved === 'string') return resolved;\n return null;\n}\n\nfunction chunkToText(chunk: unknown): string {\n if (typeof chunk === 'string') return chunk;\n if (chunk != null && typeof chunk === 'object' && 'content' in chunk) {\n const content = (chunk as { content?: unknown }).content;\n return typeof content === 'string' ? content : JSON.stringify(content);\n }\n return JSON.stringify(chunk);\n}\n","import { getBuiltinAgentToolLoopSource } from '../../loops/agent-tool-loop/builtinLoopSources.js';\nimport { type AgentLoopScriptReference, loadAgentLoopScript } from '../scriptLoader.js';\nimport type { AgentLoopScriptPolicy } from '../types.js';\nimport type { AgentToolLoopScript } from './loop.js';\n\nexport type LoadAgentToolLoopScriptOptions = AgentLoopScriptPolicy;\n\nexport type AgentToolLoopScriptReference = AgentLoopScriptReference;\n\nexport async function loadAgentToolLoopScript(\n scriptReference: AgentToolLoopScriptReference,\n options: LoadAgentToolLoopScriptOptions = {},\n): Promise<AgentToolLoopScript> {\n return loadAgentLoopScript<AgentToolLoopScript>(scriptReference, {\n ...options,\n getBuiltinScriptSource: getBuiltinAgentToolLoopSource,\n scriptType: 'AgentToolLoop script',\n });\n}\n","import type { HookSlot, PromptConcatHooks, PromptConcatTool } from './types.js';\n\nconst defaultPluginRegistry = new Map<string, PromptConcatTool>();\n/**\n * 默认全局注册表。生产与常规定义工具共用此 Map。\n * 测试或沙箱可用 {@link runWithPluginRegistry} 替换为独立 Map,避免用例间泄漏。\n */\nexport const pluginRegistry = defaultPluginRegistry;\n\n/**\n * 当前活跃的插件注册表覆盖(用于测试隔离)。\n * 不使用 AsyncLocalStorage,改用模块级变量 + try/finally,避免对 node:async_hooks 的依赖。\n */\nlet activeOverride: Map<string, PromptConcatTool> | null = null;\n\nexport function getActivePluginRegistry(): Map<string, PromptConcatTool> {\n return activeOverride ?? defaultPluginRegistry;\n}\n\nexport function runWithPluginRegistry<T>(\n registry: Map<string, PromptConcatTool>,\n function_: () => T,\n): T {\n const previous = activeOverride;\n activeOverride = registry;\n try {\n return function_();\n } finally {\n activeOverride = previous;\n }\n}\n\n/** Lightweight hook slot:tapAsync 注册,promise 串行执行(对齐 TidGi tapable AsyncSeriesHook) */\nfunction createHookSlot(): HookSlot & {\n handlers: Array<(context: any, callback: () => void) => void>;\n} {\n const handlers: Array<(context: any, callback: () => void) => void> = [];\n return {\n handlers,\n tapAsync(_name: string, function_: (context: any, callback: () => void) => void) {\n handlers.push(function_);\n },\n async promise(context: unknown) {\n for (const function_ of handlers) {\n await new Promise<void>((resolve) => {\n function_(context, resolve);\n });\n }\n },\n };\n}\n\nexport function createAgentFrameworkHooks(): PromptConcatHooks {\n return {\n processPrompts: createHookSlot(),\n finalizePrompts: createHookSlot(),\n postProcess: createHookSlot(),\n userMessageReceived: createHookSlot(),\n agentStatusChanged: createHookSlot(),\n toolExecuted: createHookSlot(),\n responseUpdate: createHookSlot(),\n responseComplete: createHookSlot(),\n };\n}\n\nconst hookHandlers: {\n processPrompts?: Array<(context: any, callback: () => void) => void>;\n} = {};\n\nexport async function runProcessPromptsHooks<TContext>(\n _hooks: PromptConcatHooks,\n context: TContext,\n): Promise<TContext> {\n const slot = _hooks.processPrompts as {\n handlers?: Array<(context_: any, callback: () => void) => void>;\n };\n const fns = slot?.handlers ?? hookHandlers.processPrompts ?? [];\n for (const function_ of fns) {\n await new Promise<void>((resolve) => {\n function_(context, resolve);\n });\n }\n return context;\n}\n\nexport async function runResponseCompleteHooks(\n hooks: PromptConcatHooks,\n context: unknown,\n): Promise<void> {\n await hooks.responseComplete.promise(context);\n}\n\nexport async function runPostProcessHooks(\n hooks: PromptConcatHooks,\n context: unknown,\n): Promise<void> {\n await hooks.postProcess.promise(context);\n}\n\nexport async function runToolExecutedHooks(\n hooks: PromptConcatHooks,\n context: unknown,\n): Promise<void> {\n await hooks.toolExecuted.promise(context);\n}\n\n/**\n * TidGi `createHooksWithPlugins`:按 agentFrameworkConfig.plugins 把插件注册表里的工具挂到 hooks。\n */\n/** 从 Agent 上下文解析插件表:优先 `tools.getPromptPlugins()`,否则 ALS / 全局默认。 */\nexport function resolvePromptPluginMap(context: {\n tools?: { getPromptPlugins?: () => Map<string, PromptConcatTool> };\n}): Map<string, PromptConcatTool> {\n const fromTools = context.tools?.getPromptPlugins?.();\n if (fromTools) return fromTools;\n return getActivePluginRegistry();\n}\n\nexport async function createHooksWithPlugins(\n agentFrameworkConfig: {\n plugins?: Array<{ toolId: string; [key: string]: unknown }>;\n },\n options?: { pluginRegistry?: Map<string, PromptConcatTool> },\n): Promise<{\n hooks: PromptConcatHooks;\n pluginConfigs: Array<{ toolId: string; [key: string]: unknown }>;\n}> {\n const reg = options?.pluginRegistry ?? getActivePluginRegistry();\n const hooks = createAgentFrameworkHooks();\n if (agentFrameworkConfig.plugins) {\n for (const pluginConfig of agentFrameworkConfig.plugins) {\n const { toolId } = pluginConfig;\n const plugin = reg.get(toolId);\n if (plugin) {\n plugin(hooks);\n }\n }\n }\n return {\n hooks,\n pluginConfigs: agentFrameworkConfig.plugins ?? [],\n };\n}\n","/**\n * 从 TidGi-Desktop `responsePatternUtility.ts` 迁移:解析 LLM 输出中的 XML 风格 tool 调用。\n * 仅做数据解析,不执行任何代码。\n */\nimport JSON5 from 'json5';\n\nconst MAX_FALLBACK_INPUT_LENGTH = 1000;\n\nexport type ToolCallingMatch =\n | { found: false }\n | {\n found: true;\n toolId: string;\n parameters: Record<string, unknown>;\n originalText: string;\n };\n\ninterface ToolPattern {\n name: string;\n pattern: RegExp;\n extractToolId: (match: RegExpExecArray) => string;\n extractParams: (match: RegExpExecArray) => string;\n extractOriginalText: (match: RegExpExecArray) => string;\n}\n\nfunction parseToolParameters(parametersText: string): Record<string, unknown> {\n if (!parametersText || !parametersText.trim()) {\n return {};\n }\n\n const trimmedText = parametersText.trim();\n\n try {\n return JSON.parse(trimmedText) as Record<string, unknown>;\n } catch {\n /* try JSON5 */\n }\n\n try {\n return JSON5.parse(trimmedText);\n } catch {\n /* fall through */\n }\n\n return { input: trimmedText.substring(0, MAX_FALLBACK_INPUT_LENGTH) };\n}\n\nfunction extractFunctionCallsParameters(text: string): Record<string, unknown> {\n const parameters: Record<string, unknown> = {};\n const parameterRegex = /<parameter\\s+name=\"([^\"]+)\"[^>]*>([^<]*)<\\/parameter>/g;\n let m: RegExpExecArray | null;\n while ((m = parameterRegex.exec(text)) !== null) {\n parameters[m[1]] = m[2].trim();\n }\n return parameters;\n}\n\nconst toolPatterns: ToolPattern[] = [\n {\n name: 'tool_use',\n pattern: /<tool_use\\s+name=\"([^\"]+)\"[^>]*>(.*?)<\\/tool_use>/gis,\n extractToolId: (match) => match[1],\n extractParams: (match) => match[2],\n extractOriginalText: (match) => match[0],\n },\n {\n name: 'function_call',\n pattern: /<function_call\\s+name=\"([^\"]+)\"[^>]*>(.*?)<\\/function_call>/gis,\n extractToolId: (match) => match[1],\n extractParams: (match) => match[2],\n extractOriginalText: (match) => match[0],\n },\n {\n name: 'function_calls_invoke',\n pattern: /<invoke\\s+name=\"([^\"]+)\"[^>]*>(.*?)<\\/invoke>/gis,\n extractToolId: (match) => match[1],\n extractParams: (match) => JSON.stringify(extractFunctionCallsParameters(match[2])),\n extractOriginalText: (match) => match[0],\n },\n];\n\nexport function matchToolCalling(responseText: string): ToolCallingMatch {\n try {\n for (const toolPattern of toolPatterns) {\n toolPattern.pattern.lastIndex = 0;\n\n const match = toolPattern.pattern.exec(responseText);\n if (match) {\n const toolId = toolPattern.extractToolId(match);\n const parametersText = toolPattern.extractParams(match);\n const originalText = toolPattern.extractOriginalText(match);\n\n return {\n found: true,\n toolId,\n parameters: parseToolParameters(parametersText),\n originalText,\n };\n }\n }\n\n return { found: false };\n } catch {\n return { found: false };\n }\n}\n\nexport function matchAllToolCallings(responseText: string): {\n calls: Array<ToolCallingMatch & { found: true }>;\n parallel: boolean;\n} {\n const calls: Array<ToolCallingMatch & { found: true }> = [];\n const parallel = /<parallel_tool_calls>/i.test(responseText);\n\n try {\n for (const toolPattern of toolPatterns) {\n toolPattern.pattern.lastIndex = 0;\n let match: RegExpExecArray | null;\n while ((match = toolPattern.pattern.exec(responseText)) !== null) {\n calls.push({\n found: true,\n toolId: toolPattern.extractToolId(match),\n parameters: parseToolParameters(toolPattern.extractParams(match)),\n originalText: toolPattern.extractOriginalText(match),\n });\n }\n }\n } catch {\n /* ignore */\n }\n\n return { calls, parallel };\n}\n","import type { IAgentStorage } from '../types.js';\n\n/**\n * 下一条消息的 Lamport 时钟:取会话内已有消息的最大 lamportClock + 1。\n */\nexport async function nextLamportClockForConversation(\n storage: IAgentStorage,\n conversationId: string,\n): Promise<number> {\n if (typeof storage.getMaxLamportClockForConversation === 'function') {\n const max = await storage.getMaxLamportClockForConversation(conversationId);\n return max + 1;\n }\n const msgs = await storage.getMessages(conversationId, { mode: 'full-content' });\n let max = 0;\n for (const m of msgs) {\n if (typeof m.lamportClock === 'number' && m.lamportClock > max) {\n max = m.lamportClock;\n }\n }\n return max + 1;\n}\n","/**\n * Hook registry for managing lifecycle hook handlers.\n * Hooks execute in registration order (first registered, first executed).\n *\n * Converted from module-level singletons to an instance class for test isolation\n * and multi-runtime support. Backward-compatible function exports delegate to a\n * default global instance.\n */\n\nimport type { HookContext, HookHandler, HookResult, HookType } from './types.js';\n\n/** Type matching the hook handler maps. */\ntype HookHandlerMap = Map<string, HookHandler>;\n\n/**\n * Instance-level hook registry. Each instance maintains its own handler state.\n */\nexport class HookRegistry {\n private readonly hookRegistry = new Map<HookType, HookHandlerMap>();\n private readonly hookOrder: Map<HookType, HookHandler[]> = new Map();\n\n /**\n * Register a hook handler for a specific lifecycle event.\n */\n registerHook(type: HookType, handler: HookHandler, name?: string): void {\n const key = name ?? `hook:${Date.now().toString(36)}:${Math.random().toString(36).slice(2, 8)}`;\n const handlers = this.hookOrder.get(type) ?? [];\n handlers.push(handler);\n this.hookOrder.set(type, handlers);\n\n const map = this.hookRegistry.get(type) ?? new Map<string, HookHandler>();\n map.set(key, handler);\n this.hookRegistry.set(type, map);\n }\n\n /**\n * Unregister a specific hook handler by name.\n */\n unregisterHook(type: HookType, name: string): boolean {\n const map = this.hookRegistry.get(type);\n if (!map) return false;\n const deleted = map.delete(name);\n if (deleted) {\n this.hookOrder.set(type, Array.from(map.values()));\n }\n return deleted;\n }\n\n /**\n * Execute all registered hooks for a given type in registration order.\n */\n async executeHooks(\n type: HookType,\n context: HookContext,\n data: Record<string, unknown>,\n ): Promise<HookResult> {\n const handlers = this.hookOrder.get(type);\n if (!handlers || handlers.length === 0) {\n return { allowed: true };\n }\n\n let currentData = data;\n let mergedModified: Record<string, unknown> | undefined;\n let permissionAction: HookResult['permissionAction'];\n for (const handler of handlers) {\n try {\n const result = await handler(context, currentData);\n if (result.modified) {\n mergedModified = { ...(mergedModified ?? {}), ...result.modified };\n currentData = { ...currentData, ...result.modified };\n }\n if (result.permissionAction && result.permissionAction !== 'allow') {\n permissionAction = result.permissionAction;\n }\n if (!result.allowed) {\n return {\n ...result,\n modified: mergedModified ?? result.modified,\n permissionAction: permissionAction ?? result.permissionAction,\n };\n }\n } catch (error) {\n return {\n allowed: false,\n reason: error instanceof Error ? error.message : 'Hook execution failed',\n modified: mergedModified,\n permissionAction,\n };\n }\n }\n\n const finalResult: HookResult = { allowed: true };\n if (mergedModified) finalResult.modified = mergedModified;\n if (permissionAction) finalResult.permissionAction = permissionAction;\n return finalResult;\n }\n\n /**\n * Check if any hooks are registered for a given type.\n */\n hasHooks(type: HookType): boolean {\n const map = this.hookRegistry.get(type);\n return map != null && map.size > 0;\n }\n\n /**\n * Remove all registered hooks of all types.\n */\n clearHooks(): void {\n this.hookRegistry.clear();\n this.hookOrder.clear();\n }\n\n /**\n * List all hook types that have at least one registered handler.\n */\n listRegisteredHookTypes(): HookType[] {\n const types: HookType[] = [];\n for (const [type, map] of this.hookRegistry) {\n if (map.size > 0) {\n types.push(type);\n }\n }\n return types;\n }\n\n /**\n * Get the count of registered handlers for a hook type.\n */\n getHookCount(type: HookType): number {\n const map = this.hookRegistry.get(type);\n return map?.size ?? 0;\n }\n}\n\n// ─── Default global instance + backward-compatible function exports ───\n\nconst defaultHookRegistry = new HookRegistry();\n\nexport function getDefaultHookRegistry(): HookRegistry {\n return defaultHookRegistry;\n}\n\nexport function registerHook(type: HookType, handler: HookHandler, name?: string): void {\n defaultHookRegistry.registerHook(type, handler, name);\n}\n\nexport function unregisterHook(type: HookType, name: string): boolean {\n return defaultHookRegistry.unregisterHook(type, name);\n}\n\nexport async function executeHooks(\n type: HookType,\n context: HookContext,\n data: Record<string, unknown>,\n): Promise<HookResult> {\n return defaultHookRegistry.executeHooks(type, context, data);\n}\n\nexport function hasHooks(type: HookType): boolean {\n return defaultHookRegistry.hasHooks(type);\n}\n\nexport function clearHooks(): void {\n defaultHookRegistry.clearHooks();\n}\n\nexport function listRegisteredHookTypes(): HookType[] {\n return defaultHookRegistry.listRegisteredHookTypes();\n}\n\n/**\n * Get the count of registered handlers for a hook type.\n */\nexport function getHookCount(type: HookType): number {\n return defaultHookRegistry.getHookCount(type);\n}\n","import type { ChatMessage } from '../conversation/index.js';\n\nimport { createAgentFrameworkHooks, resolvePromptPluginMap, runProcessPromptsHooks } from '../tools/pluginRegistry.js';\nimport type { AgentFrameworkContext } from '../types.js';\nimport type { AgentPromptDescription, PromptNode, PromptPluginConfig } from './types.js';\n\n/** 将 prompt 节点 `id` 映射到 agentFrameworkConfig.prompts 树中的索引路径(供 UI / schema 注解)。 */\nexport function collectPromptSourcePaths(\n prompts: PromptNode[],\n basePath = 'agentFrameworkConfig.prompts',\n): Record<string, string> {\n const out: Record<string, string> = {};\n function walk(nodes: PromptNode[], prefix: string): void {\n nodes.forEach((n, index) => {\n const p = `${prefix}.${index}`;\n if (n.id) {\n out[n.id] = p;\n }\n if (n.children?.length) {\n walk(n.children, `${p}.children`);\n }\n });\n }\n walk(prompts, basePath);\n return out;\n}\n\nconst logger = {\n debug: (..._arguments: unknown[]) => {},\n info: (..._arguments: unknown[]) => {},\n warn: (..._arguments: unknown[]) => {},\n error: (..._arguments: unknown[]) => {},\n};\n\nexport interface PromptConcatContext {\n messages: ChatMessage[];\n}\n\n/** 扁平化后的 LLM 消息(不依赖 peer `ai` 包导出,避免 d.ts 与 SDK 主版本不一致) */\nexport type PromptFlatModelMessage = {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: unknown;\n};\n\nexport function findPromptById(\n prompts: PromptNode[],\n id: string,\n): { prompt: PromptNode; parent: PromptNode[]; index: number } | undefined {\n for (let index = 0; index < prompts.length; index++) {\n const prompt = prompts[index];\n if (prompt.id === id) {\n return { prompt, parent: prompts, index };\n }\n if (prompt.children) {\n const found = findPromptById(prompt.children, id);\n if (found) return found;\n }\n }\n return undefined;\n}\n\nexport function flattenPrompts(prompts: PromptNode[]): PromptFlatModelMessage[] {\n const result: PromptFlatModelMessage[] = [];\n\n function processPrompt(prompt: PromptNode): string {\n let text = prompt.text ?? '';\n if (prompt.children) {\n for (const child of prompt.children) {\n if (!child.role) {\n text += processPrompt(child);\n }\n }\n }\n return text;\n }\n\n function collectRolePrompts(nodes: PromptNode[]): void {\n for (const prompt of nodes) {\n if (prompt.enabled === false) continue;\n\n const content = processPrompt(prompt);\n if (content.trim() || prompt.role) {\n result.push({\n role: prompt.role ?? 'system',\n content: content.trim(),\n });\n }\n\n if (prompt.children) {\n collectRolePrompts(prompt.children);\n }\n }\n }\n\n collectRolePrompts(prompts);\n return result;\n}\n\nexport interface PromptConcatPluginPreview {\n id: string;\n toolId?: string;\n caption?: string;\n}\n\nexport interface PromptConcatStreamState {\n processedPrompts: PromptNode[];\n flatPrompts: PromptFlatModelMessage[];\n step: 'flatten' | 'complete' | 'plugin' | 'finalize';\n isComplete: boolean;\n /** prompt 节点 id → JSON 路径(如 agentFrameworkConfig.prompts.0) */\n sourcePaths?: Record<string, string>;\n /** Desktop UI: plugin currently being processed. */\n currentPlugin?: PromptConcatPluginPreview;\n /** Desktop UI: progress value between 0 and 1. */\n progress?: number;\n}\n\nexport interface PromptConcatOptions {\n readAttachmentFile?: (path: string) => Promise<Uint8Array | Buffer>;\n}\n\nexport async function* promptConcatStream(\n agentConfig: Pick<AgentPromptDescription, 'agentFrameworkConfig'>,\n messages: ChatMessage[],\n agentFrameworkContext: AgentFrameworkContext,\n options?: PromptConcatOptions,\n): AsyncGenerator<PromptConcatStreamState, PromptConcatStreamState, unknown> {\n const frameworkConfig = agentConfig.agentFrameworkConfig;\n const promptConfigs: PromptNode[] = frameworkConfig?.prompts ?? [];\n const plugins: PromptPluginConfig[] = frameworkConfig?.plugins ?? [];\n\n const hooks = createAgentFrameworkHooks();\n const pluginMap = resolvePromptPluginMap(agentFrameworkContext);\n for (const plugin of plugins) {\n const entry = pluginMap.get(plugin.toolId);\n if (entry) entry(hooks);\n }\n\n // Run processPrompts hooks once per plugin so each handler sees its own toolConfig.\n // Desktop defineTool handlers check toolConfig.toolId and skip non-matching plugins.\n let processedContext = { prompts: promptConfigs };\n for (let index = 0; index < plugins.length; index++) {\n const plugin = plugins[index];\n processedContext = await runProcessPromptsHooks(hooks, {\n prompts: processedContext.prompts,\n messages,\n toolConfig: plugin as never,\n pluginIndex: index,\n agentFrameworkContext,\n });\n }\n\n const processed = processedContext.prompts;\n const flat = flattenPrompts(processed);\n\n // 如果最后一条消息是 user,把其内容追加到 prompts\n const last = messages[messages.length - 1];\n if (last && last.role === 'user') {\n const content = last.content;\n const fileMeta = (last as ChatMessage & { metadata?: { file?: { path?: string } } }).metadata\n ?.file;\n if (fileMeta?.path && options?.readAttachmentFile) {\n try {\n const buf = await options.readAttachmentFile(fileMeta.path);\n flat.push({\n role: 'user',\n content: [\n { type: 'image', image: buf },\n { type: 'text', text: content },\n ],\n });\n } catch (error) {\n logger.error('failed to read attached file', { error, path: fileMeta.path });\n }\n } else if (fileMeta?.path && !options?.readAttachmentFile) {\n flat.push({\n role: 'user',\n content: `[attached path: ${fileMeta.path}]\\n${content}`,\n });\n } else {\n flat.push({ role: 'user', content });\n }\n }\n\n const state: PromptConcatStreamState = {\n processedPrompts: processed,\n flatPrompts: flat,\n step: 'complete',\n isComplete: true,\n sourcePaths: collectPromptSourcePaths(processed),\n };\n\n yield state;\n return state;\n}\n","import type { DetailReference } from '../conversation/index.js';\n\n/**\n * Tools may attach this key to their return object so `agentToolLoop` persists\n * `summary` + optional `detailRef` instead of `JSON.stringify` of the whole payload (plan §5.2.1).\n */\nexport const MEMELOOP_STRUCTURED_TOOL_KEY = '__memeloopToolResult' as const;\n\n/** Truncate tool summary for persisted `ChatMessage` / LLM context (plan §5.2.1). */\nexport function truncateToolSummary(s: string, max = 2000): string {\n if (s.length <= max) return s;\n return `${s.slice(0, max - 3)}...`;\n}\n\nexport interface MemeloopStructuredToolPayload {\n /** Short text for the tool message body (≤2000 chars recommended). */\n summary: string;\n detailRef?: DetailReference;\n /**\n * When set, `agentToolLoop` pauses after persisting this tool row until `waitForTerminalSession` resolves\n * (terminal `await` mode, plan §16.4.1).\n */\n awaitSessionId?: string;\n}\n\nexport function extractMemeloopStructuredToolPayload(\n raw: unknown,\n): MemeloopStructuredToolPayload | null {\n if (raw === null || typeof raw !== 'object') return null;\n const o = raw as Record<string, unknown>;\n const payload = o[MEMELOOP_STRUCTURED_TOOL_KEY];\n if (payload === null || typeof payload !== 'object') return null;\n const p = payload as Record<string, unknown>;\n if (typeof p.summary !== 'string' || p.summary.length === 0) return null;\n const awaitSessionId = typeof p.awaitSessionId === 'string' && p.awaitSessionId.length > 0\n ? p.awaitSessionId\n : undefined;\n return {\n summary: p.summary,\n detailRef: p.detailRef as MemeloopStructuredToolPayload['detailRef'],\n awaitSessionId,\n };\n}\n","import type { MergedPermissions, PermissionAction, PermissionSet } from './types.js';\n\n/**\n * Test whether a tool name matches a wildcard pattern.\n *\n * Supported patterns:\n * - `*` → matches everything\n * - `file.*` → matches any tool starting with `file.`\n * - `shell(*)` → matches tools like `shell(rm)`, `shell(ls)` (literal parens)\n * - exact name → matches only that exact tool name\n *\n * Patterns are converted to anchored regexes internally.\n */\nexport function matchPattern(toolName: string, pattern: string): boolean {\n // Exact match short-circuit\n if (pattern === toolName) return true;\n if (pattern === '*') return true;\n\n // Escape all regex special characters, then convert escaped * back to wildcard .*\n const escaped = pattern\n .replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&')\n .replace(/\\\\\\*/g, '.*');\n\n return new RegExp(`^${escaped}$`).test(toolName);\n}\n\n/**\n * Merge multiple permission sets from lowest to highest priority.\n *\n * Sets are processed in order; later rules override earlier ones for the same tool pattern.\n * Within a single set, rules are processed in order (last wins).\n *\n * @param sets - Ordered from lowest to highest priority (e.g. default → agent → user → session)\n * @returns Flattened `MergedPermissions` with all unique patterns per action.\n */\nexport function mergePermissionSets(sets: PermissionSet[]): MergedPermissions {\n // Map from action to a Map of pattern → action (deduplicated by pattern, last wins)\n const merged = new Map<PermissionAction, Map<string, PermissionAction>>();\n merged.set('allow', new Map());\n merged.set('deny', new Map());\n merged.set('ask', new Map());\n\n for (const set of sets) {\n for (const rule of set.rules) {\n // Remove this pattern from any OTHER action maps (to avoid contradictions)\n for (const [action, map] of merged) {\n if (action !== rule.action) {\n map.delete(rule.toolPattern);\n }\n }\n // Set pattern in its action map\n merged.get(rule.action)!.set(rule.toolPattern, rule.action);\n }\n }\n\n return {\n allow: [...merged.get('allow')!.keys()],\n deny: [...merged.get('deny')!.keys()],\n ask: [...merged.get('ask')!.keys()],\n };\n}\n\n/**\n * Check what action applies to a given tool name under merged permissions.\n *\n * Precedence: exact patterns always beat wildcards.\n * Within same specificity: deny > ask > allow.\n */\nexport function checkPermission(\n toolName: string,\n merged: MergedPermissions,\n): PermissionAction {\n const isWildcard = (p: string) => p.includes('*');\n\n // Exact patterns first: deny > ask > allow\n for (const pattern of merged.deny) {\n if (!isWildcard(pattern) && matchPattern(toolName, pattern)) return 'deny';\n }\n for (const pattern of merged.ask) {\n if (!isWildcard(pattern) && matchPattern(toolName, pattern)) return 'ask';\n }\n for (const pattern of merged.allow) {\n if (!isWildcard(pattern) && matchPattern(toolName, pattern)) return 'allow';\n }\n\n // Wildcard patterns: deny > ask > allow\n for (const pattern of merged.deny) {\n if (isWildcard(pattern) && matchPattern(toolName, pattern)) return 'deny';\n }\n for (const pattern of merged.ask) {\n if (isWildcard(pattern) && matchPattern(toolName, pattern)) return 'ask';\n }\n for (const pattern of merged.allow) {\n if (isWildcard(pattern) && matchPattern(toolName, pattern)) return 'allow';\n }\n\n // Fallback: when no rules are configured at all, allow everything (backward compat).\n // When rules exist but none match, deny (secure default).\n const hasAnyRules = merged.allow.length > 0 || merged.deny.length > 0 || merged.ask.length > 0;\n return hasAnyRules ? 'deny' : 'allow';\n}\n","import type { PermissionSet } from './types.js';\n\nexport interface PermissionSqlStatement {\n get(...arguments_: unknown[]): unknown;\n run(...arguments_: unknown[]): unknown;\n}\n\nexport interface PermissionSqlDatabase {\n prepare(sql: string): PermissionSqlStatement;\n}\n\nconst TABLE_NAME = 'permissions';\nconst STORAGE_KEY = 'user';\n\n/**\n * Load user-level permission set from SQLite.\n *\n * The `permissions` table stores JSON blobs keyed by `source`.\n * Returns an empty set if no persisted rules exist.\n */\nexport function loadUserPermissions(database: PermissionSqlDatabase): PermissionSet {\n try {\n const row = database\n .prepare(`SELECT rulesJson FROM ${TABLE_NAME} WHERE source = ? LIMIT 1`)\n .get(STORAGE_KEY) as { rulesJson: string } | undefined;\n\n if (row?.rulesJson) {\n return JSON.parse(row.rulesJson) as PermissionSet;\n }\n } catch {\n /* Table may not exist yet; return empty */\n }\n\n return { rules: [], source: 'user' };\n}\n\n/**\n * Persist user-level permission set to SQLite.\n *\n * Uses INSERT OR REPLACE so first-time saves work without explicit table detection.\n */\nexport function saveUserPermissions(database: PermissionSqlDatabase, set: PermissionSet): void {\n database.prepare(\n `INSERT OR REPLACE INTO ${TABLE_NAME} (source, rulesJson, updatedAt)\n VALUES (?, ?, ?)`,\n ).run(set.source, JSON.stringify(set), Date.now());\n}\n\n/** SQL statement to create the permissions table during migration. */\nexport const PERMISSIONS_TABLE_DDL = `\n CREATE TABLE IF NOT EXISTS ${TABLE_NAME} (\n source TEXT PRIMARY KEY,\n rulesJson TEXT NOT NULL,\n updatedAt INTEGER NOT NULL\n );\n`;\n","/**\n * TidGi `approval.ts` 逐行迁移(pending 队列 + UI 监听)。\n */\nimport type { ApprovalDecision, ToolApprovalConfig, ToolApprovalRequest } from './types.js';\n\nconst pendingApprovals = new Map<\n string,\n {\n request: ToolApprovalRequest;\n resolve: (decision: 'allow' | 'deny') => void;\n }\n>();\n\nconst approvalListeners = new Set<(request: ToolApprovalRequest) => void>();\n\nexport function onApprovalRequest(listener: (request: ToolApprovalRequest) => void): () => void {\n approvalListeners.add(listener);\n return () => {\n approvalListeners.delete(listener);\n };\n}\n\nexport function evaluateApproval(\n approval: ToolApprovalConfig | undefined,\n toolName: string,\n parameters: Record<string, unknown>,\n): ApprovalDecision {\n if (!approval || approval.mode === 'auto') {\n return 'allow';\n }\n\n const callContent = JSON.stringify({ tool: toolName, parameters });\n\n if (approval.denyPatterns?.length) {\n for (const pattern of approval.denyPatterns) {\n try {\n if (new RegExp(pattern, 'i').test(callContent)) {\n return 'deny';\n }\n } catch {\n /* invalid regex */\n }\n }\n }\n\n if (approval.allowPatterns?.length) {\n for (const pattern of approval.allowPatterns) {\n try {\n if (new RegExp(pattern, 'i').test(callContent)) {\n return 'allow';\n }\n } catch {\n /* invalid regex */\n }\n }\n }\n\n return 'pending';\n}\n\nexport function requestApproval(request: ToolApprovalRequest, timeoutMs: number = 60_000): Promise<'allow' | 'deny'> {\n return new Promise<'allow' | 'deny'>((resolve) => {\n pendingApprovals.set(request.approvalId, { request, resolve });\n\n for (const listener of approvalListeners) {\n try {\n listener(request);\n } catch {\n /* ignore listener errors */\n }\n }\n\n if (timeoutMs > 0) {\n setTimeout(() => {\n if (pendingApprovals.has(request.approvalId)) {\n pendingApprovals.delete(request.approvalId);\n resolve('deny');\n }\n }, timeoutMs);\n }\n });\n}\n\nexport function resolveApproval(approvalId: string, decision: 'allow' | 'deny'): void {\n const pending = pendingApprovals.get(approvalId);\n if (pending) {\n pendingApprovals.delete(approvalId);\n pending.resolve(decision);\n }\n}\n\nexport function getPendingApprovals(): ToolApprovalRequest[] {\n return [...pendingApprovals.values()].map((p) => p.request);\n}\n\nexport function cancelPendingApprovals(agentId: string): void {\n for (const [id, pending] of pendingApprovals) {\n if (pending.request.agentId === agentId) {\n pendingApprovals.delete(id);\n pending.resolve('deny');\n }\n }\n}\n","/**\n * TidGi `responseConcat.ts` 迁移:postProcess 钩子链 + responses 合并。\n */\nimport type { ChatMessage } from '../conversation/index.js';\nimport { createAgentFrameworkHooks, resolvePromptPluginMap, runPostProcessHooks } from '../tools/pluginRegistry.js';\nimport type { AgentResponse, DefineToolAgentFrameworkContext, FrameworkPluginToolConfig } from '../tools/types.js';\nimport type { YieldNextRoundTarget } from '../tools/types.js';\nimport type { ToolCallingMatch } from './responsePatternUtility.js';\nimport type { IPrompt } from './types.js';\n\nfunction cloneResponses(responses: AgentResponse[]): AgentResponse[] {\n return structuredClone(responses);\n}\n\nexport async function responseConcat(\n agentFrameworkConfig: { response?: AgentResponse[]; plugins?: FrameworkPluginToolConfig[] },\n llmResponse: string,\n agentFrameworkContext: DefineToolAgentFrameworkContext,\n messages: ChatMessage[],\n): Promise<{\n processedResponse: string;\n yieldNextRoundTo?: YieldNextRoundTarget;\n toolCallInfo?: ToolCallingMatch;\n}> {\n const responses: AgentResponse[] = Array.isArray(agentFrameworkConfig?.response)\n ? cloneResponses(agentFrameworkConfig.response)\n : [];\n const toolConfigs = (\n Array.isArray(agentFrameworkConfig.plugins) ? agentFrameworkConfig.plugins : []\n ).filter((t) => t.enabled !== false);\n\n const hooks = createAgentFrameworkHooks();\n const pluginMap = resolvePromptPluginMap(agentFrameworkContext);\n for (const tool of toolConfigs) {\n const builtInTool = pluginMap.get(tool.toolId);\n if (builtInTool) {\n builtInTool(hooks);\n }\n }\n\n let yieldNextRoundTo: YieldNextRoundTarget | undefined;\n let toolCallInfo: ToolCallingMatch | undefined;\n\n for (const tool of toolConfigs) {\n const responseContext = {\n agentFrameworkContext,\n messages,\n prompts: [] as IPrompt[],\n toolConfig: tool,\n llmResponse,\n responses,\n metadata: {},\n actions: {} as { yieldNextRoundTo?: YieldNextRoundTarget; toolCalling?: ToolCallingMatch },\n };\n\n await runPostProcessHooks(hooks, responseContext);\n\n if (responseContext.actions?.yieldNextRoundTo) {\n yieldNextRoundTo = responseContext.actions.yieldNextRoundTo;\n if (responseContext.actions.toolCalling) {\n toolCallInfo = responseContext.actions.toolCalling;\n }\n }\n }\n\n const processedResponse = flattenResponses(responses);\n\n return {\n processedResponse: processedResponse || llmResponse,\n yieldNextRoundTo,\n toolCallInfo,\n };\n}\n\nfunction flattenResponses(responses: AgentResponse[]): string {\n if (responses.length === 0) {\n return '';\n }\n return responses\n .filter((response) => response.enabled !== false)\n .map((response) => response.text || '')\n .join('\\n\\n')\n .trim();\n}\n","import type { ChatMessage } from '../../conversation/index.js';\nimport { nextLamportClockForConversation } from '../../storage/nextLamport.js';\nimport type { AgentFrameworkContext } from '../../types.js';\nimport { executeHooks, hasHooks } from '../hooks/registry.js';\nimport { autoCompact as autoCompactMessages, shouldCompact } from './compaction.js';\n\nimport type { AgentLoopStep } from '../types.js';\n\ntype ContextCompactionModified = {\n history?: unknown;\n skipDefault?: unknown;\n compacted?: unknown;\n droppedCount?: unknown;\n summaryText?: unknown;\n persistSummaryMessage?: unknown;\n};\n\ntype AutoCompactResult = {\n messages: ChatMessage[];\n compacted: boolean;\n droppedCount: number;\n summaryText: string;\n};\n\ntype AutoCompactFunction = (\n messages: ChatMessage[],\n options: {\n recentTurnsToKeep: number;\n maxTokens: number;\n llmProvider: unknown;\n },\n) => Promise<AutoCompactResult>;\n\nfunction compactHistory(\n history: ChatMessage[],\n options: AgentFrameworkContext['agentToolLoop'],\n): ChatMessage[] {\n const maxMessages = options?.contextCompaction?.maxMessages ?? 0;\n if (maxMessages <= 0 || history.length <= maxMessages) return history;\n const dropped = history.length - maxMessages;\n const tail = history.slice(-maxMessages);\n const summaryMessage: ChatMessage = {\n ...tail[0],\n messageId: `${tail[0]?.conversationId ?? 'unknown'}:summary:${Date.now().toString(36)}`,\n role: 'assistant',\n content: `[context-summary] ${dropped} earlier messages were compacted.`,\n };\n if (options?.contextCompaction?.replayLastUserMessage === false) return tail;\n const lastUser = [...history].reverse().find((message) => message.role === 'user');\n if (!lastUser) return [summaryMessage, ...tail];\n if (tail.some((message) => message.messageId === lastUser.messageId)) return tail;\n return [summaryMessage, lastUser, ...tail];\n}\n\nfunction asChatMessages(value: unknown): ChatMessage[] | undefined {\n if (!Array.isArray(value)) return undefined;\n if (!value.every((message) => message != null && typeof message === 'object')) return undefined;\n return value as ChatMessage[];\n}\n\nfunction buildCompactedStep(\n conversationId: string,\n iteration: number,\n droppedCount: unknown,\n summaryText: unknown,\n): AgentLoopStep {\n return {\n type: 'thinking',\n data: {\n status: 'compacted',\n conversationId,\n droppedCount: typeof droppedCount === 'number' ? droppedCount : 0,\n summaryText: typeof summaryText === 'string' ? summaryText : '',\n iteration,\n },\n };\n}\n\nasync function persistSummaryMessage(\n context: AgentFrameworkContext,\n conversationId: string,\n summaryMessage: ChatMessage | undefined,\n): Promise<void> {\n if (!summaryMessage) return;\n const lamportSummary = await nextLamportClockForConversation(context.storage, conversationId);\n await context.storage.appendMessage({\n ...summaryMessage,\n lamportClock: lamportSummary,\n });\n}\n\nasync function maybeApplyContextCompactionHook(options: {\n context: AgentFrameworkContext;\n conversationId: string;\n iteration: number;\n history: ChatMessage[];\n agentToolLoopOptions: AgentFrameworkContext['agentToolLoop'];\n}): Promise<{ handled: boolean; history: ChatMessage[]; steps: AgentLoopStep[] }> {\n const { context, conversationId, iteration, history, agentToolLoopOptions } = options;\n if (!hasHooks('ContextCompaction')) {\n return { handled: false, history, steps: [] };\n }\n\n const hookResult = await executeHooks('ContextCompaction', context, {\n conversationId,\n iteration,\n history,\n autoCompact: agentToolLoopOptions?.autoCompact,\n contextCompaction: agentToolLoopOptions?.contextCompaction,\n });\n const modified = hookResult.modified as ContextCompactionModified | undefined;\n const modifiedHistory = asChatMessages(modified?.history);\n const nextHistory = modifiedHistory ?? history;\n const skipDefault = !hookResult.allowed || modifiedHistory != null || modified?.skipDefault === true;\n if (!skipDefault) {\n return { handled: false, history: nextHistory, steps: [] };\n }\n\n const steps = modified?.compacted === true\n ? [buildCompactedStep(conversationId, iteration, modified.droppedCount, modified.summaryText)]\n : [];\n if (modified?.persistSummaryMessage === true) {\n await persistSummaryMessage(context, conversationId, nextHistory[0]);\n }\n\n return { handled: true, history: nextHistory, steps };\n}\n\nasync function applyBuiltInAutoCompact(options: {\n context: AgentFrameworkContext;\n conversationId: string;\n iteration: number;\n history: ChatMessage[];\n agentToolLoopOptions: AgentFrameworkContext['agentToolLoop'];\n}): Promise<{ history: ChatMessage[]; steps: AgentLoopStep[] }> {\n const { context, conversationId, iteration, agentToolLoopOptions } = options;\n let history = options.history;\n const autoCompactOptions = agentToolLoopOptions?.autoCompact;\n if (!autoCompactOptions) {\n return { history, steps: [] };\n }\n\n const threshold = autoCompactOptions.threshold ?? 50;\n if (!shouldCompact(history, threshold)) {\n return { history, steps: [] };\n }\n\n try {\n const result = await (autoCompactMessages as unknown as AutoCompactFunction)(history, {\n recentTurnsToKeep: autoCompactOptions.recentTurnsToKeep ?? 4,\n maxTokens: autoCompactOptions.maxTokens ?? 0,\n llmProvider: context.llmProvider,\n });\n if (!result.compacted) {\n return { history, steps: [] };\n }\n\n history = result.messages;\n await persistSummaryMessage(context, conversationId, result.messages[0]);\n return {\n history,\n steps: [\n buildCompactedStep(conversationId, iteration, result.droppedCount, result.summaryText),\n ],\n };\n } catch (error) {\n if (context.logger?.warn) {\n context.logger.warn('[agentToolLoop] auto-compact failed:', error);\n } else {\n console.warn('[agentToolLoop] auto-compact failed:', error);\n }\n return { history, steps: [] };\n }\n}\n\nexport async function prepareIterationHistory(options: {\n context: AgentFrameworkContext;\n conversationId: string;\n iteration: number;\n rawHistory: ChatMessage[];\n agentToolLoopOptions: AgentFrameworkContext['agentToolLoop'];\n}): Promise<{ history: ChatMessage[]; steps: AgentLoopStep[] }> {\n const { agentToolLoopOptions } = options;\n const hookResult = await maybeApplyContextCompactionHook({\n ...options,\n history: options.rawHistory,\n });\n if (hookResult.handled) {\n return hookResult;\n }\n\n const autoCompactResult = await applyBuiltInAutoCompact({\n ...options,\n history: hookResult.history,\n });\n return {\n history: compactHistory(autoCompactResult.history, agentToolLoopOptions),\n steps: autoCompactResult.steps,\n };\n}\n","type LegacyLlmContext = {\n llmProvider: {\n chat?: unknown;\n };\n};\n\ntype LegacyChatFunction = (request: unknown) => unknown;\n\nfunction isAsyncIterable(value: unknown): value is AsyncIterable<unknown> {\n return (\n value != null && typeof (value as AsyncIterable<unknown>)[Symbol.asyncIterator] === 'function'\n );\n}\n\nexport function chunkToText(chunk: unknown): string {\n if (typeof chunk === 'string') return chunk;\n if (chunk != null && typeof chunk === 'object' && 'content' in chunk) {\n const content = (chunk as { content?: unknown }).content;\n return typeof content === 'string' ? content : JSON.stringify(content);\n }\n return JSON.stringify(chunk);\n}\n\nexport async function* streamLlm(\n context: LegacyLlmContext,\n request: unknown,\n): AsyncGenerator<unknown, void, unknown> {\n const chatFunction = context.llmProvider.chat;\n\n if (typeof chatFunction !== 'function') {\n throw new Error(\n \"LLM provider does not support legacy chat() method. Use AI SDK's streamText instead.\",\n );\n }\n const raw = (chatFunction as LegacyChatFunction)(request);\n let resolved: unknown = raw;\n if (resolved != null && typeof (resolved as Promise<unknown>).then === 'function') {\n resolved = await (resolved as Promise<unknown>);\n }\n if (isAsyncIterable(resolved)) {\n for await (const chunk of resolved) {\n yield chunk;\n }\n return;\n }\n yield resolved;\n}\n","import type { ChatMessage } from '../conversation/index.js';\n\nexport function normalizeRoleForLlm(role: string): 'user' | 'assistant' | 'system' | 'tool' {\n if (role === 'assistant' || role === 'system' || role === 'tool') return role;\n return 'user';\n}\n\n/**\n * 丢弃早于 `now - maxAgeMs` 的历史消息(按 `ChatMessage.timestamp`,毫秒)。\n * `maxAgeMs <= 0` 时不裁剪。\n */\nexport function filterOldMessagesByDuration(\n messages: ChatMessage[],\n maxAgeMs: number,\n now: number = Date.now(),\n): ChatMessage[] {\n if (maxAgeMs <= 0) return messages;\n const cutoff = now - maxAgeMs;\n return messages.filter((m) => typeof m.timestamp === 'number' && m.timestamp >= cutoff);\n}\n\nexport function getFinalPromptResult(parts: string[]): string {\n return parts.filter(Boolean).join('\\n\\n');\n}\n","import type { AgentDefinition } from '../../agent/types.js';\nimport type { ChatMessage } from '../../conversation/index.js';\nimport { promptConcatStream } from '../../promptUtilities/promptConcat.js';\nimport type { PromptNode, PromptPluginConfig } from '../../promptUtilities/types.js';\nimport { filterOldMessagesByDuration } from '../../promptUtilities/utilities.js';\nimport type { AgentFrameworkContext } from '../../types.js';\n\nexport type LlmRequestMessage = {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: unknown;\n};\n\nfunction chatMessageToModelMessage(message: ChatMessage): LlmRequestMessage {\n const role: LlmRequestMessage['role'] = message.role === 'agent' || message.role === 'error'\n ? 'assistant'\n : message.role === 'tool'\n ? 'tool'\n : message.role === 'user'\n ? 'user'\n : 'assistant';\n return {\n role,\n content: message.content,\n };\n}\n\nexport async function resolveAgentDefinitionModel(\n context: AgentFrameworkContext,\n definitionId: string,\n): Promise<AgentDefinition | null> {\n if (context.resolveAgentDefinition) {\n return context.resolveAgentDefinition(definitionId);\n }\n return context.storage.getAgentDefinition(definitionId);\n}\n\nexport async function inferDefinitionId(\n storage: AgentFrameworkContext['storage'],\n conversationId: string,\n): Promise<string> {\n try {\n const meta = await storage.getConversationMeta(conversationId);\n if (meta?.definitionId) return meta.definitionId;\n } catch {\n /* optional on old mocks */\n }\n const parts = conversationId.split(':');\n if (parts.length >= 2) {\n return parts.slice(0, -1).join(':');\n }\n return conversationId;\n}\n\nexport async function buildLlmMessages(\n context: AgentFrameworkContext,\n conversationId: string,\n history: ChatMessage[],\n): Promise<LlmRequestMessage[]> {\n const definitionId = await inferDefinitionId(context.storage, conversationId);\n const definition = await resolveAgentDefinitionModel(context, definitionId);\n const fw = definition?.agentFrameworkConfig as\n | { prompts?: unknown[]; plugins?: unknown[] }\n | undefined;\n const maxHistoryAgeMs = context.agentToolLoop?.maxHistoryAgeMs ?? 0;\n const historyForPrompt = maxHistoryAgeMs > 0 ? filterOldMessagesByDuration(history, maxHistoryAgeMs) : history;\n\n if (fw?.prompts && Array.isArray(fw.prompts) && fw.prompts.length > 0) {\n const readAttachmentFile = context.agentToolLoop?.readAttachmentFile;\n const gen = promptConcatStream(\n {\n agentFrameworkConfig: {\n prompts: fw.prompts as PromptNode[],\n plugins: (fw.plugins ?? []) as PromptPluginConfig[],\n response: [],\n },\n },\n historyForPrompt,\n context,\n readAttachmentFile ? { readAttachmentFile } : undefined,\n );\n let lastFlat: LlmRequestMessage[] = [];\n for await (const state of gen) {\n lastFlat = state.flatPrompts as LlmRequestMessage[];\n }\n const withoutTrailingUser = lastFlat.length > 0 && lastFlat[lastFlat.length - 1]?.role === 'user'\n ? lastFlat.slice(0, -1)\n : lastFlat;\n return [...withoutTrailingUser, ...historyForPrompt.map(chatMessageToModelMessage)];\n }\n\n const systemText = typeof definition?.systemPrompt === 'string' ? definition.systemPrompt.trim() : '';\n if (systemText.length > 0) {\n return [\n { role: 'system', content: systemText },\n ...historyForPrompt.map(chatMessageToModelMessage),\n ];\n }\n\n return historyForPrompt.map(chatMessageToModelMessage);\n}\n","export function formatToolResultMessage(\n toolName: string,\n parameters: Record<string, unknown>,\n body: string,\n isError: boolean,\n): string {\n return `<functions_result>\nTool: ${toolName}\nParameters: ${JSON.stringify(parameters)}\n${isError ? 'Error' : 'Result'}: ${body}\n</functions_result>`;\n}\n","import type { DetailReference } from '../../conversation/index.js';\nimport { nextLamportClockForConversation } from '../../storage/nextLamport.js';\nimport { extractMemeloopStructuredToolPayload, truncateToolSummary } from '../../tools/structuredToolResult.js';\nimport type { AgentFrameworkContext } from '../../types.js';\nimport { executeHooks, hasHooks } from '../hooks/registry.js';\n\nimport type { AgentLoopStep } from '../types.js';\nimport { formatToolResultMessage } from './toolResultMessage.js';\nimport type { PendingToolCall } from './toolUseGate.js';\n\ntype ToolRunRow = {\n text: string;\n isError: boolean;\n detailRef?: DetailReference;\n awaitSessionId?: string;\n};\n\ntype CompletedToolCall = ToolRunRow & { call: PendingToolCall };\n\nasync function executeRegistryTool(\n context: AgentFrameworkContext,\n toolId: string,\n parameters: Record<string, unknown>,\n): Promise<ToolRunRow> {\n const normalizedId = toolId.includes('-')\n ? toolId.replace(/-([a-z])/g, (_m, c: string) => c.toUpperCase())\n : toolId;\n const impl = (context.tools.getTool(toolId) ?? context.tools.getTool(normalizedId)) as\n | ((arguments_: Record<string, unknown>) => unknown)\n | undefined;\n\n if (typeof impl !== 'function') {\n return {\n text: `No tool registered for \"${toolId}\".`,\n isError: true,\n };\n }\n\n try {\n const raw = await impl(parameters);\n if (raw != null && typeof raw === 'object') {\n const o = raw as { error?: string; result?: unknown };\n if (typeof o.error === 'string' && o.error.length > 0) {\n return { text: o.error, isError: true };\n }\n if ('result' in o) {\n return {\n text: typeof o.result === 'string' ? o.result : JSON.stringify(o.result),\n isError: false,\n };\n }\n const structured = extractMemeloopStructuredToolPayload(raw);\n if (structured) {\n return {\n text: structured.summary,\n isError: false,\n detailRef: structured.detailRef,\n awaitSessionId: structured.awaitSessionId,\n };\n }\n }\n return { text: typeof raw === 'string' ? raw : JSON.stringify(raw), isError: false };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n if (context.logger?.warn) {\n context.logger.warn('[agentToolLoop] tool execution error', toolId, message);\n } else {\n console.warn('[agentToolLoop] tool execution error', toolId, message);\n }\n return { text: message, isError: true };\n }\n}\n\nasync function executeWithGuards(\n context: AgentFrameworkContext,\n options: AgentFrameworkContext['agentToolLoop'],\n conversationId: string,\n recentToolCalls: string[],\n call: PendingToolCall,\n): Promise<ToolRunRow> {\n const signature = `${call.toolId}:${JSON.stringify(call.parameters)}`;\n recentToolCalls.push(signature);\n const threshold = Math.max(2, options?.doomLoopThreshold ?? 3);\n const last = recentToolCalls.slice(-threshold);\n if (last.length === threshold && last.every((x) => x === signature)) {\n return { text: 'Blocked by doom-loop guard', isError: true };\n }\n\n const row = await executeRegistryTool(context, call.toolId, call.parameters);\n\n if (hasHooks('PostToolUse')) {\n await executeHooks('PostToolUse', context, {\n toolId: call.toolId,\n parameters: call.parameters,\n result: row.text,\n isError: row.isError,\n conversationId,\n });\n }\n\n return row;\n}\n\nasync function persistToolResult(\n context: AgentFrameworkContext,\n conversationId: string,\n call: PendingToolCall,\n row: ToolRunRow,\n): Promise<void> {\n const lamportTool = await nextLamportClockForConversation(context.storage, conversationId);\n await context.storage.appendMessage({\n messageId: `${conversationId}:t:${call.toolId}:${Date.now().toString(36)}`,\n conversationId,\n originNodeId: 'local',\n timestamp: Date.now(),\n lamportClock: lamportTool,\n role: 'tool',\n content: formatToolResultMessage(call.toolId, call.parameters, row.text, row.isError),\n detailRef: row.detailRef,\n });\n}\n\nasync function persistTerminalAwaitCompletion(\n context: AgentFrameworkContext,\n options: AgentFrameworkContext['agentToolLoop'],\n conversationId: string,\n call: PendingToolCall,\n row: ToolRunRow,\n): Promise<void> {\n const sid = row.awaitSessionId;\n const wait = options?.waitForTerminalSession;\n if (!sid || !wait || row.isError) return;\n const done = await wait(sid);\n const lamportTool = await nextLamportClockForConversation(context.storage, conversationId);\n const body = truncateToolSummary(\n `[terminal.await done] session=${sid}\\nexitCode: ${done.exitCode ?? 'null'}\\n---\\n${done.truncatedOutput}`,\n );\n await context.storage.appendMessage({\n messageId: `${conversationId}:t:${call.toolId}:await:${Date.now().toString(36)}`,\n conversationId,\n originNodeId: 'local',\n timestamp: Date.now(),\n lamportClock: lamportTool,\n role: 'tool',\n content: formatToolResultMessage(call.toolId, call.parameters, body, false),\n detailRef: row.detailRef\n ? { ...row.detailRef, exitCode: done.exitCode ?? row.detailRef.exitCode }\n : undefined,\n });\n}\n\nfunction toolStep(row: CompletedToolCall, parallel: boolean): AgentLoopStep {\n return {\n type: 'tool',\n data: {\n toolId: row.call.toolId,\n parameters: row.call.parameters,\n parallel,\n result: row.text,\n isError: row.isError,\n },\n };\n}\n\nexport async function* runRegistryToolCalls(options: {\n context: AgentFrameworkContext;\n agentToolLoopOptions: AgentFrameworkContext['agentToolLoop'];\n conversationId: string;\n calls: PendingToolCall[];\n parallel: boolean;\n recentToolCalls: string[];\n}): AsyncGenerator<AgentLoopStep, void, unknown> {\n const { context, agentToolLoopOptions, conversationId, calls, parallel, recentToolCalls } = options;\n\n if (parallel) {\n const results = await Promise.all(\n calls.map(\n async (call): Promise<CompletedToolCall> => ({\n call,\n ...(await executeWithGuards(\n context,\n agentToolLoopOptions,\n conversationId,\n recentToolCalls,\n call,\n )),\n }),\n ),\n );\n for (const row of results) {\n yield toolStep(row, true);\n }\n for (const row of results) {\n await persistToolResult(context, conversationId, row.call, row);\n }\n for (const row of results) {\n await persistTerminalAwaitCompletion(\n context,\n agentToolLoopOptions,\n conversationId,\n row.call,\n row,\n );\n }\n return;\n }\n\n for (const call of calls) {\n const row = await executeWithGuards(\n context,\n agentToolLoopOptions,\n conversationId,\n recentToolCalls,\n call,\n );\n yield toolStep({ call, ...row }, false);\n await persistToolResult(context, conversationId, call, row);\n await persistTerminalAwaitCompletion(context, agentToolLoopOptions, conversationId, call, row);\n }\n}\n","import type { MergedPermissions, PermissionAction, PermissionSet } from '../../permission/index.js';\nimport { checkPermission, mergePermissionSets } from '../../permission/index.js';\nimport type { ToolCallingMatch } from '../../promptUtilities/responsePatternUtility.js';\nimport { nextLamportClockForConversation } from '../../storage/nextLamport.js';\nimport { requestApproval } from '../../tools/approval.js';\nimport type { AgentFrameworkContext } from '../../types.js';\nimport { executeHooks, hasHooks } from '../hooks/registry.js';\nimport type { HookHandler, HookResult, PreToolUseData } from '../hooks/types.js';\n\nimport type { AgentLoopStep } from '../types.js';\nimport { formatToolResultMessage } from './toolResultMessage.js';\n\nexport type PendingToolCall = ToolCallingMatch & { found: true };\n\n/**\n * Build layered permission sets from context options.\n *\n * Layers (lowest to highest priority):\n * 1. default - `toolPermissions.default` (e.g. \"allow\")\n * 2. agent - `toolPermissions.perAgent[definitionId]`\n * 3. user - persisted in SQLite (loaded via permission storage)\n * 4. session - `toolPermissions.rules` (global rules)\n */\nexport function buildLayeredPermissions(\n options: AgentFrameworkContext['agentToolLoop'],\n definitionId: string,\n userSet?: PermissionSet,\n): MergedPermissions {\n const global = options?.toolPermissions;\n const sets: PermissionSet[] = [];\n\n if (global?.default) {\n sets.push({\n source: 'default',\n rules: [{ toolPattern: '*', action: global.default }],\n });\n }\n\n const scoped = global?.perAgent?.[definitionId];\n if (scoped) {\n if (scoped.default) {\n sets.push({\n source: `agent:${definitionId}:default`,\n rules: [{ toolPattern: '*', action: scoped.default }],\n });\n }\n if (scoped.rules && scoped.rules.length > 0) {\n sets.push({\n source: `agent:${definitionId}`,\n rules: scoped.rules.map((r) => ({ toolPattern: r.pattern, action: r.action })),\n });\n }\n }\n\n if (userSet && userSet.rules.length > 0) {\n sets.push(userSet);\n }\n\n if (global?.rules && global.rules.length > 0) {\n sets.push({\n source: 'session',\n rules: global.rules.map((r) => ({ toolPattern: r.pattern, action: r.action })),\n });\n }\n\n if (!sets.some((s) => s.rules.some((r) => r.toolPattern === '*'))) {\n sets.unshift({\n source: 'implied-default',\n rules: [{ toolPattern: '*', action: 'allow' }],\n });\n }\n\n return mergePermissionSets(sets);\n}\n\nexport function createPermissionPreToolUseHook(\n options: AgentFrameworkContext['agentToolLoop'],\n definitionId: string,\n userSet?: PermissionSet,\n): HookHandler {\n const mergedPermissions = buildLayeredPermissions(options, definitionId, userSet);\n return async (_context, data) => {\n const toolId = typeof data.toolId === 'string' ? data.toolId : '';\n const action = checkPermission(toolId, mergedPermissions);\n if (action === 'allow') {\n return { allowed: true, permissionAction: 'allow' };\n }\n return {\n allowed: true,\n permissionAction: action,\n reason: action === 'deny' ? 'Denied by tool permission' : undefined,\n };\n };\n}\n\nfunction applyModifiedCall(\n call: PendingToolCall,\n modified?: Record<string, unknown>,\n): PendingToolCall {\n if (!modified) return call;\n const toolId = typeof modified.toolId === 'string' ? modified.toolId : call.toolId;\n const parameters = modified.parameters != null && typeof modified.parameters === 'object'\n ? (modified.parameters as Record<string, unknown>)\n : call.parameters;\n return { ...call, toolId, parameters };\n}\n\nfunction normalizePreToolUseResult(result: HookResult): {\n action: PermissionAction;\n reason?: string;\n} {\n if (!result.allowed) {\n return { action: 'deny', reason: result.reason ?? 'Blocked by PreToolUse hook' };\n }\n if (result.permissionAction === 'ask' || result.permissionAction === 'deny') {\n return { action: result.permissionAction, reason: result.reason };\n }\n return { action: 'allow', reason: result.reason };\n}\n\nasync function persistDeniedToolResult(\n context: AgentFrameworkContext,\n conversationId: string,\n call: PendingToolCall,\n errorText: string,\n): Promise<void> {\n const lamportTool = await nextLamportClockForConversation(context.storage, conversationId);\n await context.storage.appendMessage({\n messageId: `${conversationId}:t:${call.toolId}:${Date.now().toString(36)}`,\n conversationId,\n originNodeId: 'local',\n timestamp: Date.now(),\n lamportClock: lamportTool,\n role: 'tool',\n content: formatToolResultMessage(call.toolId, call.parameters, errorText, true),\n });\n}\n\nasync function* resolveAskAction(\n conversationId: string,\n call: PendingToolCall,\n): AsyncGenerator<AgentLoopStep, PermissionAction, unknown> {\n yield {\n type: 'permission_request' as const,\n data: { tool: call.toolId, args: call.parameters },\n };\n const decision = await requestApproval(\n {\n approvalId: `${conversationId}:${Date.now().toString(36)}:${call.toolId}`,\n agentId: conversationId,\n toolName: call.toolId,\n parameters: call.parameters,\n created: new Date(),\n },\n 60_000,\n );\n return decision === 'allow' ? 'allow' : 'deny';\n}\n\nasync function runPreToolUseHook(\n context: AgentFrameworkContext,\n data: PreToolUseData,\n): Promise<HookResult> {\n if (!hasHooks('PreToolUse')) return { allowed: true };\n return executeHooks('PreToolUse', context, data);\n}\n\nexport async function* gateToolCallsWithPreToolUse(\n context: AgentFrameworkContext,\n options: AgentFrameworkContext['agentToolLoop'],\n definitionId: string,\n conversationId: string,\n calls: PendingToolCall[],\n): AsyncGenerator<AgentLoopStep, PendingToolCall[], unknown> {\n const permissionHook = createPermissionPreToolUseHook(options, definitionId);\n const allowedCalls: PendingToolCall[] = [];\n\n for (const originalCall of calls) {\n let call = originalCall;\n const permissionResult = await permissionHook(context, {\n toolId: call.toolId,\n parameters: call.parameters,\n conversationId,\n });\n call = applyModifiedCall(call, permissionResult.modified);\n\n let { action, reason } = normalizePreToolUseResult(permissionResult);\n if (action === 'ask') {\n action = yield* resolveAskAction(conversationId, call);\n reason = action === 'deny' ? 'Tool approval denied or timed out' : reason;\n }\n if (action === 'deny') {\n const errorText = reason ?? 'Denied by tool permission';\n yield {\n type: 'tool' as const,\n data: {\n toolId: call.toolId,\n parameters: call.parameters,\n parallel: false,\n result: errorText,\n isError: true,\n },\n };\n await persistDeniedToolResult(context, conversationId, call, errorText);\n continue;\n }\n\n const hookResult = await runPreToolUseHook(context, {\n toolId: call.toolId,\n parameters: call.parameters,\n conversationId,\n });\n call = applyModifiedCall(call, hookResult.modified);\n ({ action, reason } = normalizePreToolUseResult(hookResult));\n if (action === 'ask') {\n action = yield* resolveAskAction(conversationId, call);\n reason = action === 'deny' ? 'Tool approval denied or timed out' : reason;\n }\n if (action === 'deny') {\n const errorText = reason ?? 'Blocked by PreToolUse hook';\n yield {\n type: 'tool' as const,\n data: {\n toolId: call.toolId,\n parameters: call.parameters,\n parallel: false,\n result: errorText,\n isError: true,\n },\n };\n await persistDeniedToolResult(context, conversationId, call, errorText);\n continue;\n }\n\n allowedCalls.push(call);\n }\n\n return allowedCalls;\n}\n","import type { ChatMessage } from '../../conversation/index.js';\n\nimport { responseConcat } from '../../promptUtilities/responseConcat.js';\nimport { matchAllToolCallings, type ToolCallingMatch } from '../../promptUtilities/responsePatternUtility.js';\nimport { nextLamportClockForConversation } from '../../storage/nextLamport.js';\nimport { createHooksWithPlugins, resolvePromptPluginMap, runResponseCompleteHooks } from '../../tools/pluginRegistry.js';\nimport type { DefineToolAgentFrameworkContext } from '../../tools/types.js';\nimport type { AgentFrameworkContext, AgentInstanceModel } from '../../types.js';\nimport { executeHooks, hasHooks } from '../hooks/registry.js';\nimport type { AgentStopData } from '../hooks/types.js';\nimport type { AgentLoopInput, AgentLoopStep } from '../types.js';\nimport type { AgentToolLoopIterationGenerator, AgentToolLoopState, AgentToolLoopTurnStartResult } from './contracts.js';\nimport { prepareIterationHistory } from './historyCompaction.js';\nimport { chunkToText, streamLlm } from './llmStream.js';\nimport { buildLlmMessages, inferDefinitionId, resolveAgentDefinitionModel } from './modelMessages.js';\nimport { runRegistryToolCalls } from './toolCallRunner.js';\nimport { gateToolCallsWithPreToolUse } from './toolUseGate.js';\n\nconst DEFAULT_MAX_ITERATIONS = 256;\n\nfunction toolCallHandledInAgentMessages(\n agentMessages: ChatMessage[],\n assistantContent: string,\n call: ToolCallingMatch & { found: true },\n): boolean {\n let assistantIndex = -1;\n for (let index = agentMessages.length - 1; index >= 0; index -= 1) {\n const message = agentMessages[index];\n if (message.role === 'assistant' && message.content === assistantContent) {\n assistantIndex = index;\n break;\n }\n }\n if (assistantIndex < 0) return false;\n const after = agentMessages.slice(assistantIndex + 1);\n return after.some(\n message =>\n message.role === 'tool' &&\n (message.metadata?.toolId === call.toolId ||\n (typeof message.content === 'string' && message.content.includes(`Tool: ${call.toolId}`))),\n );\n}\n\nfunction resolveMaxIterations(context: AgentFrameworkContext): number {\n const configured = context.agentToolLoop?.maxIterations;\n return configured != null && configured > 0 ? configured : DEFAULT_MAX_ITERATIONS;\n}\n\nexport function createAgentToolLoopState(context: AgentFrameworkContext): AgentToolLoopState {\n return {\n iteration: 0,\n maxIterations: resolveMaxIterations(context),\n recentToolCalls: [],\n agentStarted: false,\n agentStopped: false,\n };\n}\n\nfunction markAgentToolLoopStop(state: AgentToolLoopState, reason: AgentStopData['reason']): void {\n state.stopReason ??= reason;\n}\n\nfunction finishAgentToolLoopThinking(\n state: AgentToolLoopState,\n reason: AgentStopData['reason'],\n data: Record<string, unknown>,\n): AgentLoopStep {\n markAgentToolLoopStop(state, reason);\n return { type: 'thinking', data };\n}\n\nexport async function startAgentToolLoopTurn(\n context: AgentFrameworkContext,\n input: AgentLoopInput,\n state: AgentToolLoopState,\n): Promise<AgentToolLoopTurnStartResult> {\n const now = Date.now();\n const lamportClock = await nextLamportClockForConversation(\n context.storage,\n input.conversationId,\n );\n const hostUserMessage = input.userMessage;\n const userMessage = context.normalizeMessage?.({\n ...hostUserMessage,\n messageId: hostUserMessage?.messageId ?? `${input.conversationId}:${now.toString(36)}`,\n conversationId: input.conversationId,\n originNodeId: hostUserMessage?.originNodeId ?? 'local',\n timestamp: hostUserMessage?.timestamp ?? now,\n lamportClock: hostUserMessage?.lamportClock ?? lamportClock,\n role: 'user',\n content: hostUserMessage?.content ?? input.message,\n }) ?? {\n ...hostUserMessage,\n messageId: hostUserMessage?.messageId ?? `${input.conversationId}:${now.toString(36)}`,\n conversationId: input.conversationId,\n originNodeId: hostUserMessage?.originNodeId ?? 'local',\n timestamp: hostUserMessage?.timestamp ?? now,\n lamportClock: hostUserMessage?.lamportClock ?? lamportClock,\n role: 'user',\n content: hostUserMessage?.content ?? input.message,\n };\n\n if (input.resumeSession && input.resumeSession.length > 0) {\n await context.storage.insertMessagesIfAbsent(input.resumeSession);\n }\n\n await context.storage.appendMessage(userMessage);\n\n if (hasHooks('UserPromptSubmit')) {\n const hookResult = await executeHooks('UserPromptSubmit', context, {\n message: input.message,\n conversationId: input.conversationId,\n });\n if (!hookResult.allowed) {\n return {\n action: 'stop',\n step: {\n type: 'thinking',\n data: {\n status: 'blocked',\n conversationId: input.conversationId,\n reason: hookResult.reason ?? 'Blocked by UserPromptSubmit hook',\n },\n },\n };\n }\n }\n\n const initialDefinitionId = await inferDefinitionId(context.storage, input.conversationId);\n if (hasHooks('AgentStart')) {\n const hookResult = await executeHooks('AgentStart', context, {\n conversationId: input.conversationId,\n definitionId: initialDefinitionId,\n });\n if (!hookResult.allowed) {\n return {\n action: 'stop',\n step: {\n type: 'thinking',\n data: {\n status: 'blocked',\n conversationId: input.conversationId,\n reason: hookResult.reason ?? 'Blocked by AgentStart hook',\n },\n },\n };\n }\n }\n state.agentStarted = true;\n return { action: 'continue' };\n}\n\nexport async function* runAgentToolLoopIteration(\n context: AgentFrameworkContext,\n input: AgentLoopInput,\n state: AgentToolLoopState,\n): AgentToolLoopIterationGenerator {\n const options = context.agentToolLoop ?? {};\n const enableToolLoop = options.enableToolLoop !== false;\n const fallbackRegistry = options.fallbackRegistryTools !== false;\n const checkpointOptions = options.sessionCheckpoint;\n\n if (state.iteration >= state.maxIterations) {\n yield finishAgentToolLoopThinking(state, 'max-iterations', {\n status: 'max-iterations',\n conversationId: input.conversationId,\n maxIterations: state.maxIterations,\n });\n return { action: 'stop', reason: 'max-iterations' };\n }\n\n state.iteration += 1;\n const iteration = state.iteration;\n\n if (options.isCancelled?.(input.conversationId)) {\n yield finishAgentToolLoopThinking(state, 'cancelled', {\n status: 'cancelled',\n conversationId: input.conversationId,\n });\n return { action: 'stop', reason: 'cancelled' };\n }\n\n const rawHistory = await context.storage.getMessages(input.conversationId, {\n mode: 'full-content',\n });\n\n const { history, steps: compactionSteps } = await prepareIterationHistory({\n context,\n conversationId: input.conversationId,\n iteration,\n rawHistory,\n agentToolLoopOptions: options,\n });\n for (const step of compactionSteps) {\n yield step;\n }\n\n const runtimeAgent = context.resolveAgentRuntimeView\n ? await context.resolveAgentRuntimeView(input.conversationId, history)\n : ({ id: input.conversationId, messages: history } as AgentInstanceModel);\n\n const hookContext: DefineToolAgentFrameworkContext = {\n ...context,\n agent: runtimeAgent,\n persistAgentMessage: async message => {\n await context.storage.appendMessage(message);\n },\n };\n\n yield {\n type: 'thinking',\n data: {\n status: 'calling-llm',\n conversationId: input.conversationId,\n messageCount: history.length,\n iteration,\n },\n };\n\n const messages = await buildLlmMessages(context, input.conversationId, history);\n const request = { conversationId: input.conversationId, messages };\n let assistantText = '';\n for await (const chunk of streamLlm(context, request)) {\n assistantText += chunkToText(chunk);\n yield { type: 'message', data: chunk };\n }\n\n const definitionId = await inferDefinitionId(context.storage, input.conversationId);\n const agentDefinition = await resolveAgentDefinitionModel(context, definitionId);\n const frameworkConfig = agentDefinition?.agentFrameworkConfig as\n | { prompts?: unknown[]; plugins?: unknown[]; response?: unknown[] }\n | undefined;\n const hasPlugins = Boolean(\n frameworkConfig?.plugins && Array.isArray(frameworkConfig.plugins) && frameworkConfig.plugins.length > 0,\n );\n\n const assistantMessage = context.normalizeMessage?.({\n messageId: `${input.conversationId}:a:${Date.now().toString(36)}`,\n conversationId: input.conversationId,\n originNodeId: 'local',\n timestamp: Date.now(),\n lamportClock: await nextLamportClockForConversation(\n context.storage,\n input.conversationId,\n ),\n role: 'assistant',\n content: assistantText,\n }) ?? {\n messageId: `${input.conversationId}:a:${Date.now().toString(36)}`,\n conversationId: input.conversationId,\n originNodeId: 'local',\n timestamp: Date.now(),\n lamportClock: await nextLamportClockForConversation(\n context.storage,\n input.conversationId,\n ),\n role: 'assistant',\n content: assistantText,\n };\n hookContext.agent.messages.push(assistantMessage);\n await hookContext.persistAgentMessage?.(assistantMessage);\n\n const { calls, parallel } = matchAllToolCallings(assistantText);\n\n if (hasPlugins && frameworkConfig) {\n const { hooks } = await createHooksWithPlugins(\n frameworkConfig as { plugins: Array<{ toolId: string }> },\n {\n pluginRegistry: resolvePromptPluginMap(context),\n },\n );\n const responseCompletePayload: {\n agentFrameworkContext: DefineToolAgentFrameworkContext;\n response: { status: 'done'; content: string };\n agentFrameworkConfig: {\n plugins?: import('../../tools/types.js').FrameworkPluginToolConfig[];\n };\n requestId: undefined;\n toolConfig: import('../../tools/types.js').FrameworkPluginToolConfig;\n actions?: { yieldNextRoundTo?: 'human' | 'self' };\n } = {\n agentFrameworkContext: hookContext,\n response: { status: 'done', content: assistantText },\n agentFrameworkConfig: frameworkConfig as {\n plugins?: import('../../tools/types.js').FrameworkPluginToolConfig[];\n },\n requestId: undefined,\n toolConfig: { id: '_memeloop', toolId: '_memeloop' },\n actions: {},\n };\n await runResponseCompleteHooks(hooks, responseCompletePayload);\n\n await context.storage.insertMessagesIfAbsent(hookContext.agent.messages);\n\n const postProcess = await responseConcat(\n frameworkConfig as {\n response?: import('../../tools/types.js').AgentResponse[];\n plugins?: import('../../tools/types.js').FrameworkPluginToolConfig[];\n },\n assistantText,\n hookContext,\n hookContext.agent.messages,\n );\n\n const yieldTarget = responseCompletePayload.actions?.yieldNextRoundTo ?? postProcess.yieldNextRoundTo;\n\n if (yieldTarget === 'human') {\n yield finishAgentToolLoopThinking(state, 'completed', {\n status: 'input-required',\n conversationId: input.conversationId,\n });\n return { action: 'stop', reason: 'completed' };\n }\n if (yieldTarget === 'self') {\n return { action: 'continue' };\n }\n }\n\n if (calls.length === 0) {\n markAgentToolLoopStop(state, 'completed');\n return { action: 'stop', reason: 'completed' };\n }\n\n if (!enableToolLoop) {\n markAgentToolLoopStop(state, 'completed');\n return { action: 'stop', reason: 'completed' };\n }\n\n const pending = calls.filter(\n call => !toolCallHandledInAgentMessages(hookContext.agent.messages, assistantText, call),\n );\n\n if (pending.length === 0) {\n if (hasPlugins && calls.length > 0) {\n return { action: 'continue' };\n }\n markAgentToolLoopStop(state, 'completed');\n return { action: 'stop', reason: 'completed' };\n }\n\n if (!fallbackRegistry && hasPlugins) {\n return { action: 'continue' };\n }\n\n const allowedCalls = yield* gateToolCallsWithPreToolUse(\n context,\n options,\n definitionId,\n input.conversationId,\n pending,\n );\n\n if (allowedCalls.length === 0) {\n return { action: 'continue' };\n }\n\n yield* runRegistryToolCalls({\n context,\n agentToolLoopOptions: options,\n conversationId: input.conversationId,\n calls: allowedCalls,\n parallel,\n recentToolCalls: state.recentToolCalls,\n });\n\n if (checkpointOptions?.enabled) {\n const checkpointStore = checkpointOptions.store;\n if (!checkpointStore) {\n if (context.logger?.warn) {\n context.logger.warn('[agentToolLoop] checkpoint enabled without a checkpoint store');\n } else {\n console.warn('[agentToolLoop] checkpoint enabled without a checkpoint store');\n }\n return { action: 'continue' };\n }\n try {\n const allMessages = await context.storage.getMessages(input.conversationId, {\n mode: 'full-content',\n });\n await checkpointStore.saveCheckpoint(input.conversationId, allMessages);\n } catch (error) {\n if (context.logger?.warn) {\n context.logger.warn('[agentToolLoop] checkpoint save failed:', error);\n } else {\n console.warn('[agentToolLoop] checkpoint save failed:', error);\n }\n }\n }\n\n return { action: 'continue' };\n}\n\nexport async function stopAgentToolLoopTurn(\n context: AgentFrameworkContext,\n input: AgentLoopInput,\n state: AgentToolLoopState,\n reason?: AgentStopData['reason'],\n): Promise<void> {\n if (reason) markAgentToolLoopStop(state, reason);\n if (state.agentStarted && !state.agentStopped && state.stopReason && hasHooks('AgentStop')) {\n state.agentStopped = true;\n await executeHooks('AgentStop', context, {\n conversationId: input.conversationId,\n reason: state.stopReason,\n });\n }\n}\n","import type { AgentLoopGenerator, AgentLoopInput, AgentLoopStep } from '../types.js';\nimport type { AgentToolLoopContext, AgentToolLoopScript, AgentToolLoopScriptContext } from './contracts.js';\nimport { loadAgentToolLoopScript } from './scriptLoader.js';\nimport { createAgentToolLoopState, runAgentToolLoopIteration, startAgentToolLoopTurn, stopAgentToolLoopTurn } from './turnPrimitives.js';\n\nfunction isAsyncIterable(value: unknown): value is AgentLoopGenerator {\n return Boolean(value && typeof value === 'object' && Symbol.asyncIterator in value);\n}\n\nfunction messageStep(message: string): AgentLoopStep {\n return { type: 'message', data: message };\n}\n\nasync function* drainEmittedSteps(steps: AgentLoopStep[]): AgentLoopGenerator {\n while (steps.length > 0) {\n const step = steps.shift();\n if (step) yield step;\n }\n}\n\nexport function asAgentToolLoopContext(rawContext: { [key: string]: unknown }): AgentToolLoopContext {\n return rawContext as unknown as AgentToolLoopContext;\n}\n\nexport async function resolveAgentToolLoopScript(context: AgentToolLoopContext): Promise<AgentToolLoopScript | undefined> {\n if (context.script) return context.script;\n const scriptReference = context.profile?.scriptReference ?? context.profile?.scriptRef ?? context.profile?.script;\n if (!scriptReference) return undefined;\n if (context.loadScript) return context.loadScript(scriptReference, context);\n return loadAgentToolLoopScript(scriptReference, context.scriptPolicy);\n}\n\nfunction createAgentToolLoopScriptContext(\n input: AgentLoopInput,\n context: AgentToolLoopContext,\n emittedSteps: AgentLoopStep[],\n): AgentToolLoopScriptContext {\n const emit = (step: AgentLoopStep): void => {\n emittedSteps.push(step);\n context.runtime?.emit?.(step);\n };\n return {\n input,\n context,\n profile: context.profile,\n createState: () => createAgentToolLoopState(context),\n startTurn: state => startAgentToolLoopTurn(context, input, state),\n runIteration: state => runAgentToolLoopIteration(context, input, state),\n stopTurn: (state, reason) => stopAgentToolLoopTurn(context, input, state, reason),\n emit,\n finish: message => {\n emit(typeof message === 'string' ? messageStep(message) : message);\n },\n isCancelled: () => context.runtime?.signal?.cancelled === true || context.agentToolLoop?.isCancelled?.(input.conversationId) === true,\n log: (event, data) => {\n context.runtime?.log?.(event, data);\n context.logger?.debug?.(event, data);\n },\n };\n}\n\nexport async function* runAgentToolLoopScript(\n script: AgentToolLoopScript,\n input: AgentLoopInput,\n context: AgentToolLoopContext,\n): AgentLoopGenerator {\n const emittedSteps: AgentLoopStep[] = [];\n const result = await script(createAgentToolLoopScriptContext(input, context, emittedSteps));\n\n yield* drainEmittedSteps(emittedSteps);\n if (isAsyncIterable(result)) {\n yield* result;\n yield* drainEmittedSteps(emittedSteps);\n } else if (typeof result === 'string') {\n yield messageStep(result);\n } else if (Array.isArray(result)) {\n yield* result;\n } else if (result) {\n yield result;\n }\n}\n","import type { AgentFrameworkContext } from '../../types.js';\nimport type { AgentLoopDefinition, AgentLoopGenerator, AgentLoopInput } from '../types.js';\nimport { asAgentToolLoopContext, resolveAgentToolLoopScript, runAgentToolLoopScript } from './scriptRunner.js';\nimport { createAgentToolLoopState, runAgentToolLoopIteration, startAgentToolLoopTurn, stopAgentToolLoopTurn } from './turnPrimitives.js';\n\nexport type {\n AgentToolLoopContext,\n AgentToolLoopIterationGenerator,\n AgentToolLoopIterationResult,\n AgentToolLoopScript,\n AgentToolLoopScriptContext,\n AgentToolLoopScriptReference,\n AgentToolLoopState,\n AgentToolLoopTurnStartResult,\n LoadAgentToolLoopScriptOptions,\n} from './contracts.js';\n\nexport function createAgentToolLoopRunner(\n context: AgentFrameworkContext,\n): (input: AgentLoopInput) => AgentLoopGenerator {\n return async function* agentToolLoopRunner(input): AgentLoopGenerator {\n const state = createAgentToolLoopState(context);\n try {\n const start = await startAgentToolLoopTurn(context, input, state);\n if (start.step) yield start.step;\n if (start.action === 'stop') return;\n\n while (true) {\n const result = yield* runAgentToolLoopIteration(context, input, state);\n if (result.action === 'stop') return;\n }\n } catch (error) {\n await stopAgentToolLoopTurn(context, input, state, 'error');\n throw error;\n } finally {\n await stopAgentToolLoopTurn(context, input, state);\n }\n };\n}\n\nexport function createAgentToolLoopDefinition(name = 'AgentToolLoop'): AgentLoopDefinition {\n return {\n id: 'agent-tool-loop',\n name,\n description: 'Agent/tool loop that alternates between LLM output and external tool execution.',\n createRunner: (rawContext) => {\n const context = asAgentToolLoopContext(rawContext);\n return async function* agentToolLoop(input) {\n const script = await resolveAgentToolLoopScript(context);\n if (script) {\n yield* runAgentToolLoopScript(script, input, context);\n return;\n }\n yield* createAgentToolLoopRunner(context)(input);\n };\n },\n };\n}\n","/**\n * AgentToolLoop runner — convenience API for driving a full loop turn.\n */\n\nimport type { AgentFrameworkContext, AgentInstanceState } from '../../types.js';\nimport type { AgentLoopGenerator, AgentLoopInput, AgentLoopStep } from '../types.js';\nimport { createAgentToolLoopRunner } from './loop.js';\n\nexport interface RunAgentToolLoopTurnCallbacks {\n onStep?: (step: AgentLoopStep) => void | Promise<void>;\n onProgress?: (\n status: string,\n data: Record<string, unknown>,\n step: AgentLoopStep,\n ) => void | Promise<void>;\n agentToolLoop?: (input: AgentLoopInput) => AgentLoopGenerator;\n}\n\nexport interface RunAgentToolLoopTurnResult {\n state: AgentInstanceState;\n stepCount: number;\n}\n\nexport function resolveAgentToolLoopTerminalState(\n step: AgentLoopStep,\n current: AgentInstanceState,\n): AgentInstanceState {\n if (step.type !== 'thinking') return current;\n const data = step.data as { status?: string };\n if (data.status === 'input-required') return 'input-required';\n if (data.status === 'cancelled') return 'canceled';\n if (data.status === 'max-iterations') return 'completed';\n if (data.status === 'blocked') return 'failed';\n if (data.status === 'calling-llm') return 'working';\n return current;\n}\n\nexport async function runAgentToolLoopTurn(\n context: AgentFrameworkContext,\n input: AgentLoopInput,\n callbacks: RunAgentToolLoopTurnCallbacks = {},\n): Promise<RunAgentToolLoopTurnResult> {\n const agentToolLoop = callbacks.agentToolLoop ?? createAgentToolLoopRunner(context);\n let terminalState: AgentInstanceState = 'completed';\n let stepCount = 0;\n\n for await (const step of agentToolLoop(input)) {\n stepCount += 1;\n terminalState = resolveAgentToolLoopTerminalState(step, terminalState);\n await callbacks.onStep?.(step);\n\n if (step.type === 'thinking' && step.data && typeof step.data === 'object') {\n const data = step.data as Record<string, unknown>;\n const status = data.status;\n if (typeof status === 'string') {\n await callbacks.onProgress?.(status, data, step);\n }\n }\n }\n\n return {\n state: terminalState === 'working' || terminalState === 'submitted' ? 'completed' : terminalState,\n stepCount,\n };\n}\n","/**\n * Agent loop registry.\n *\n * Discovers, registers, and resolves loop types, loop profiles, and loop plugins.\n * Core does NOT hard-import any loop implementation; all are registered by host or plugin.\n */\n\nimport type { AgentLoopDefinition, AgentLoopGenerator, AgentLoopInput, LoopPlugin, LoopProfile, LoopProfilePluginEntry } from './types.js';\n\ntype LoopPluginSelection = string | LoopProfilePluginEntry;\n\nfunction normalizePluginSelections(\n selected?: LoopPluginSelection[],\n): Map<string, LoopProfilePluginEntry> | undefined {\n if (!selected) return undefined;\n\n const result = new Map<string, LoopProfilePluginEntry>();\n for (const entry of selected) {\n if (typeof entry === 'string') {\n result.set(entry, { id: entry, enabled: true });\n continue;\n }\n if (entry.enabled === false) continue;\n result.set(entry.id, entry);\n }\n return result;\n}\n\n// ─── Loop Registry ─────────────────────────────────────────────────────\n\nclass LoopRegistryImpl {\n private readonly loops = new Map<string, AgentLoopDefinition>();\n private readonly profiles = new Map<string, LoopProfile>();\n private readonly plugins = new Map<string, LoopPlugin>();\n\n // ── Loop registration ──\n\n registerLoop(definition: AgentLoopDefinition): void {\n if (!definition.id) throw new Error('Loop definition must have an id');\n this.loops.set(definition.id, definition);\n }\n\n getLoop(id: string): AgentLoopDefinition | undefined {\n return this.loops.get(id);\n }\n\n listLoops(): AgentLoopDefinition[] {\n return Array.from(this.loops.values());\n }\n\n // ── Profile registration ──\n\n registerProfile(profile: LoopProfile): void {\n if (!profile.id) throw new Error('Loop profile must have an id');\n this.profiles.set(profile.id, profile);\n }\n\n getProfile(id: string): LoopProfile | undefined {\n return this.profiles.get(id);\n }\n\n listProfiles(): LoopProfile[] {\n return Array.from(this.profiles.values());\n }\n\n // ── Plugin registration ──\n\n registerPlugin(plugin: LoopPlugin): void {\n if (!plugin.id) throw new Error('Loop plugin must have an id');\n this.plugins.set(plugin.id, plugin);\n }\n\n getPlugin(id: string): LoopPlugin | undefined {\n return this.plugins.get(id);\n }\n\n listPlugins(): LoopPlugin[] {\n return Array.from(this.plugins.values());\n }\n\n installPluginsForLoop(\n loopId: string,\n target: { [key: string]: unknown },\n selected?: LoopPluginSelection[],\n ): void {\n const selectedEntries = normalizePluginSelections(selected);\n\n for (const plugin of this.plugins.values()) {\n const entry = selectedEntries?.get(plugin.id);\n if (selectedEntries && !entry) continue;\n if (plugin.targetLoopId && plugin.targetLoopId !== '*' && plugin.targetLoopId !== loopId) {\n continue;\n }\n if (plugin.install) {\n plugin.install(target, entry?.config);\n }\n }\n }\n\n installPluginsForProfile(profile: LoopProfile, target: { [key: string]: unknown }): void {\n this.installPluginsForLoop(profile.loopId ?? 'agent-tool-loop', target, profile.plugins ?? []);\n }\n\n createRunnerForProfile(\n profile: LoopProfile,\n context: { [key: string]: unknown } = {},\n ): ((input: AgentLoopInput) => AgentLoopGenerator) | null {\n const loopId = profile.loopId ?? 'agent-tool-loop';\n this.installPluginsForProfile(profile, context);\n return this.createRunner(loopId, { ...context, profile });\n }\n\n // ── Lifecycle ──\n\n createRunner(\n loopId: string,\n context: { [key: string]: unknown } = {},\n ): ((input: AgentLoopInput) => AgentLoopGenerator) | null {\n const definition = this.loops.get(loopId);\n if (!definition) return null;\n return definition.createRunner(context);\n }\n\n reset(): void {\n this.loops.clear();\n this.profiles.clear();\n this.plugins.clear();\n }\n}\n\n// ─── Global singleton ─────────────────────────────────────────────────\n\nlet defaultRegistry: LoopRegistryImpl | null = null;\n\nexport function getLoopRegistry(): LoopRegistryImpl {\n if (!defaultRegistry) {\n defaultRegistry = new LoopRegistryImpl();\n }\n return defaultRegistry;\n}\n\nexport function resetLoopRegistry(): void {\n if (defaultRegistry) {\n defaultRegistry.reset();\n }\n defaultRegistry = null;\n}\n\nexport type { LoopRegistryImpl };\n","/**\n * Built-in loop registrations — installed at startup so getLoopRegistry().createRunner('agent-tool-loop') works.\n *\n * This module allows hosts to skip manual registerLoop() for the built-in loop types.\n * Hosts can still override by calling registerLoop() with the same id after.\n */\n\nimport { createAgentAgentLoopDefinition, getAgentAgentLoopId } from '../agent-agent-loop/loop.js';\nimport { createAgentToolLoopDefinition } from '../agent-tool-loop/loop.js';\nimport { getLoopRegistry } from '../registry.js';\n\nexport const AGENT_TOOL_LOOP_ID = 'agent-tool-loop';\nexport const AGENT_AGENT_LOOP_ID = getAgentAgentLoopId();\n\n/**\n * Register the default built-in loops (agent-tool-loop and agent-agent-loop) with the loop registry.\n * Safe to call multiple times — skips already-registered loops.\n */\nexport function registerBuiltinLoops(): void {\n const registry = getLoopRegistry();\n\n if (!registry.getLoop(AGENT_TOOL_LOOP_ID)) {\n registry.registerLoop(createAgentToolLoopDefinition('AgentToolLoop'));\n }\n\n if (!registry.getLoop(AGENT_AGENT_LOOP_ID)) {\n registry.registerLoop(createAgentAgentLoopDefinition());\n }\n}\n","const toolSchemas = new Map<string, unknown>();\nconst toolMetadata = new Map<string, { displayName: string; description: string }>();\n\nexport function registerToolParameterSchema(\n toolId: string,\n schema: unknown,\n metadata?: { displayName: string; description: string },\n): void {\n toolSchemas.set(toolId, schema);\n if (metadata) {\n toolMetadata.set(toolId, metadata);\n }\n}\n\nexport function getToolParameterSchema(toolId: string): unknown {\n return toolSchemas.get(toolId);\n}\n\nexport function getToolMetadata(\n toolId: string,\n): { displayName: string; description: string } | undefined {\n return toolMetadata.get(toolId);\n}\n","type Pending = {\n resolve: (answer: string) => void;\n reject: (error: Error) => void;\n timer: ReturnType<typeof setTimeout>;\n};\n\nconst pending = new Map<string, Pending>();\n\nexport function resolveQuestionAnswer(questionId: string, answer: string): boolean {\n const p = pending.get(questionId);\n if (!p) return false;\n clearTimeout(p.timer);\n pending.delete(questionId);\n p.resolve(answer);\n return true;\n}\n\nexport function waitForQuestionAnswer(questionId: string, timeoutMs: number): Promise<string> {\n return new Promise((resolve, reject) => {\n const timer = setTimeout(() => {\n pending.delete(questionId);\n reject(new Error('askQuestion_timeout'));\n }, timeoutMs);\n pending.set(questionId, { resolve, reject, timer });\n });\n}\n","import { z } from 'zod';\n\nimport { waitForQuestionAnswer } from './questionWaitRegistry.js';\nimport type { BuiltinToolContext } from './types.js';\n\nexport const askQuestionConfigSchema = z.object({\n question: z.string().min(1),\n /**\n * Desktop / TidGi 的 LLM 工具参数里通常不会显式携带 conversationId,\n * 由宿主侧上下文负责关联;这里允许缺省,交给宿主回调侧做路由。\n */\n conversationId: z.string().min(1).optional(),\n timeoutMs: z.number().int().positive().max(3_600_000).optional(),\n inputType: z.enum(['single-select', 'multi-select', 'text']).optional(),\n options: z\n .array(\n z.object({\n label: z.string(),\n description: z.string().optional(),\n }),\n )\n .optional(),\n allowFreeform: z.boolean().optional().default(true),\n});\n\n/**\n * Must match `tool_use name=\"ask-question\"` extracted by responsePatternUtility.\n */\nexport const ASK_QUESTION_TOOL_ID = 'ask-question';\n\nexport async function askQuestionImpl(\n arguments_: Record<string, unknown>,\n context: BuiltinToolContext,\n): Promise<{ result: string } | { error: string }> {\n const parsed = askQuestionConfigSchema.safeParse(arguments_);\n if (!parsed.success) {\n return { error: 'invalid_askQuestion_args' };\n }\n const { question, conversationId, timeoutMs, inputType, options, allowFreeform } = parsed.data;\n const questionId = crypto.randomUUID();\n const timeout = timeoutMs ?? 300_000;\n context.notifyAskQuestion?.({\n questionId,\n question,\n conversationId,\n inputType,\n options,\n allowFreeform,\n });\n try {\n const answer = await waitForQuestionAnswer(questionId, timeout);\n return { result: answer };\n } catch (error) {\n return { error: error instanceof Error ? error.message : 'askQuestion_failed' };\n }\n}\n","/**\n * AskUserQuestion Tool — Pause agent execution and ask user for input.\n *\n * Uses the existing askQuestion pattern (notifyAskQuestion + waitForQuestionAnswer)\n * but provides a dedicated tool ID for explicit user question prompting.\n */\nimport { z } from 'zod';\n\nimport { waitForQuestionAnswer } from './questionWaitRegistry.js';\nimport type { BuiltinToolContext } from './types.js';\n\nexport const askUserQuestionConfigSchema = z.object({\n question: z.string().min(1).describe('The question to ask the user'),\n inputType: z\n .enum(['text', 'single-select', 'multi-select'])\n .optional()\n .default('text')\n .describe('Type of input expected: text, single-select, or multi-select'),\n options: z\n .array(\n z.object({\n label: z.string().min(1),\n description: z.string().optional(),\n }),\n )\n .optional()\n .describe('Options for single-select or multi-select input types'),\n allowFreeform: z\n .boolean()\n .optional()\n .default(true)\n .describe('Allow free-text input even for select types'),\n timeoutMs: z\n .number()\n .int()\n .positive()\n .max(3_600_000)\n .optional()\n .default(300_000)\n .describe('Timeout in milliseconds (default 5 minutes)'),\n});\n\nexport const ASK_USER_QUESTION_TOOL_ID = 'askUserQuestion';\n\nexport async function askUserQuestionImpl(\n arguments_: Record<string, unknown>,\n context: BuiltinToolContext,\n): Promise<{ result: string } | { error: string }> {\n const parsed = askUserQuestionConfigSchema.safeParse(arguments_);\n if (!parsed.success) {\n return { error: `invalid_askUserQuestion_args: ${parsed.error.message}` };\n }\n\n const { question, inputType, options, allowFreeform, timeoutMs } = parsed.data;\n const questionId = crypto.randomUUID();\n const conversationId = context.agent?.id ?? context.activeToolConversationId;\n\n context.notifyAskQuestion?.({\n questionId,\n question,\n conversationId,\n inputType,\n options,\n allowFreeform,\n });\n\n try {\n const answer = await waitForQuestionAnswer(questionId, timeoutMs);\n return { result: answer };\n } catch (error) {\n const message = error instanceof Error ? error.message : 'askUserQuestion_failed';\n return { error: message };\n }\n}\n","import type { BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'mcpClient';\n\nexport const mcpClientConfigSchema = {\n type: 'object',\n properties: {\n nodeId: { type: 'string', description: 'Target node ID' },\n serverName: { type: 'string', description: 'MCP server name on that node' },\n toolName: { type: 'string', description: 'Tool to invoke' },\n args: { type: 'object', description: 'Tool arguments' },\n },\n required: ['nodeId', 'serverName', 'toolName'],\n} as const;\n\nexport const mcpClientImpl: BuiltinToolImpl = async (arguments_, context) => {\n const nodeId = arguments_.nodeId as string | undefined;\n const serverName = arguments_.serverName as string | undefined;\n const toolName = arguments_.toolName as string | undefined;\n const toolArguments = (arguments_.args as Record<string, unknown>) ?? {};\n\n if (!nodeId || !serverName || !toolName) {\n return {\n error: 'mcpClient requires nodeId, serverName, and toolName',\n };\n }\n\n if (!context.mcpCallRemote) {\n return {\n error: 'MCP proxy not configured (no mcpCallRemote in context). Connect to nodes that expose MCP.',\n };\n }\n\n try {\n const result = await context.mcpCallRemote(nodeId, serverName, toolName, toolArguments);\n return { result };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { error: `MCP call failed: ${message}` };\n }\n};\n\nexport function getMcpClientToolId(): string {\n return TOOL_ID;\n}\n","import type { BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'mcpForward';\n\nexport const mcpForwardConfigSchema = {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['list', 'listTools'],\n description: \"Action: 'list' returns nodes with MCP servers, 'listTools' returns all available MCP tools across nodes\",\n },\n },\n} as const;\n\ninterface McpServerInfo {\n name: string;\n}\n\ninterface McpToolInfo {\n nodeId: string;\n serverName: string;\n name: string;\n description?: string;\n}\n\n/**\n * MCP forwarding tool: discover MCP servers and tools on connected nodes.\n * - action=list: returns nodes with their MCP servers\n * - action=listTools: returns all available MCP tools across all nodes\n */\nexport const mcpForwardImpl: BuiltinToolImpl = async (arguments_, context) => {\n const action = (arguments_.action as string | undefined) ?? 'list';\n\n if (!context.getPeers) {\n return { error: 'Peer list not configured (no getPeers).' };\n }\n\n if (!context.sendRpcToNode) {\n return { error: 'Remote node RPC not configured (no sendRpcToNode).' };\n }\n\n const peers = await context.getPeers();\n const online = peers.filter((p) => p.reachability.state === 'online');\n\n if (action === 'list') {\n // List devices with their MCP servers\n const result: Array<{ nodeId: string; name: string; mcpServers: McpServerInfo[] }> = [];\n\n for (const node of online) {\n try {\n const response = (await context.sendRpcToNode(\n node.peerId,\n 'memeloop.mcp.listServers',\n {},\n )) as {\n servers?: McpServerInfo[];\n };\n const servers = Array.isArray(response?.servers) ? response.servers : [];\n if (servers.length > 0) {\n result.push({\n nodeId: node.peerId,\n name: node.displayName,\n mcpServers: servers,\n });\n }\n } catch {\n // Skip devices that don't support MCP or fail to respond\n }\n }\n\n return { nodes: result };\n }\n\n if (action === 'listTools') {\n // List all MCP tools across all devices\n const allTools: McpToolInfo[] = [];\n\n for (const node of online) {\n try {\n const response = (await context.sendRpcToNode(\n node.peerId,\n 'memeloop.mcp.listTools',\n {},\n )) as {\n tools?: Array<{ serverName: string; name: string; description?: string }>;\n };\n const tools = Array.isArray(response?.tools) ? response.tools : [];\n for (const tool of tools) {\n allTools.push({\n nodeId: node.peerId,\n serverName: tool.serverName,\n name: tool.name,\n description: tool.description,\n });\n }\n } catch {\n // Skip devices that don't support MCP or fail to respond\n }\n }\n\n return { tools: allTools };\n }\n\n return { error: `Unknown action: ${action}` };\n};\n\nexport function getMcpForwardToolId(): string {\n return TOOL_ID;\n}\n","import { MEMELOOP_STRUCTURED_TOOL_KEY, truncateToolSummary } from '../structuredToolResult.js';\nimport type { BuiltinToolContext, BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'remoteAgent';\nconst REMOTE_LOG_POLL_INTERVAL_MS = 500;\nconst REMOTE_LOG_IDLE_POLLS = 2;\n\ntype RemoteConversationMessage = {\n messageId?: string;\n role?: string;\n content?: unknown;\n};\n\nfunction messageContentToText(content: unknown): string {\n if (typeof content === 'string') return content;\n if (content == null) return '';\n try {\n return JSON.stringify(content);\n } catch {\n return Object.prototype.toString.call(content);\n }\n}\n\nfunction getRemoteStreamChunkContent(chunk: unknown): unknown {\n if (chunk != null && typeof chunk === 'object' && 'content' in chunk) {\n return Reflect.get(chunk, 'content');\n }\n\n return undefined;\n}\n\nfunction summarizeRemoteMessages(messages: RemoteConversationMessage[]): string {\n const relevant = messages.filter((message) => message.role && message.role !== 'user');\n if (relevant.length === 0) {\n return '(task dispatched; waiting for remote output)';\n }\n const joined = relevant\n .map((message) => {\n const role = typeof message.role === 'string' ? message.role : 'message';\n const content = messageContentToText(message.content).trim();\n return content.length > 0 ? `[${role}] ${content}` : '';\n })\n .filter((line) => line.length > 0)\n .join('\\n');\n return joined.trim() || '(task dispatched; remote messages had no readable content)';\n}\n\nasync function collectRemoteConversationSummary(\n sendRpc: NonNullable<BuiltinToolContext['sendRpcToNode']>,\n nodeId: string,\n conversationId: string,\n timeoutMs: number,\n): Promise<string> {\n const startedAt = Date.now();\n const knownMessageIds = new Set<string>();\n const collectedMessages: RemoteConversationMessage[] = [];\n let idlePolls = 0;\n\n while (Date.now() - startedAt < timeoutMs) {\n const response = (await sendRpc(nodeId, 'memeloop.chat.pullAgentRunLog', {\n conversationId,\n knownMessageIds: [...knownMessageIds],\n })) as { messages?: RemoteConversationMessage[] };\n const newMessages = Array.isArray(response?.messages) ? response.messages : [];\n\n if (newMessages.length > 0) {\n idlePolls = 0;\n for (const message of newMessages) {\n if (typeof message.messageId === 'string' && message.messageId.length > 0) {\n knownMessageIds.add(message.messageId);\n }\n collectedMessages.push(message);\n }\n } else if (collectedMessages.some((message) => message.role && message.role !== 'user')) {\n idlePolls += 1;\n if (idlePolls >= REMOTE_LOG_IDLE_POLLS) {\n break;\n }\n }\n\n await new Promise((resolve) => setTimeout(resolve, REMOTE_LOG_POLL_INTERVAL_MS));\n }\n\n return summarizeRemoteMessages(collectedMessages);\n}\n\nexport const remoteAgentConfigSchema = {\n type: 'object',\n properties: {\n nodeId: { type: 'string', description: 'Target node ID to run the agent-run on' },\n definitionId: { type: 'string', description: 'Agent definition ID on that node' },\n message: { type: 'string', description: 'Task message for the remote agent' },\n },\n required: ['nodeId', 'definitionId', 'message'],\n} as const;\n\n/** List nodes and their definitions (for tool description / agent choice). No args. */\nexport const remoteAgentListImpl: BuiltinToolImpl = async (_arguments, context) => {\n const getPeers = context.getPeers ? async () => context.getPeers?.() : undefined;\n const sendRpc = context.sendRpcToNode\n ? async (nodeId: string, method: string, parameters: unknown) => context.sendRpcToNode?.(nodeId, method, parameters)\n : undefined;\n\n if (!getPeers) {\n return { nodes: [], error: 'Peer list not configured (no getPeers).' };\n }\n\n const peers = (await getPeers()) ?? [];\n const online = peers.filter((p) => p.reachability?.state === 'online');\n const result: { nodeId: string; name: string; definitions?: unknown[] }[] = [];\n\n for (const node of online) {\n const entry: { nodeId: string; name: string; definitions?: unknown[] } = {\n nodeId: node.peerId,\n name: node.displayName,\n };\n if (sendRpc) {\n try {\n const response = (await sendRpc(\n node.peerId,\n 'memeloop.agent.getDefinitions',\n {},\n )) as { definitions?: unknown[] };\n entry.definitions = Array.isArray(response?.definitions) ? response.definitions : [];\n } catch {\n entry.definitions = [];\n }\n }\n result.push(entry);\n }\n\n return { nodes: result };\n};\n\nexport const remoteAgentImpl: BuiltinToolImpl = async (arguments_, context) => {\n const nodeId = arguments_.nodeId as string | undefined;\n const definitionId = arguments_.definitionId as string | undefined;\n const message = arguments_.message as string | undefined;\n\n if (!nodeId || !definitionId || typeof message !== 'string') {\n return remoteAgentListImpl(arguments_, context);\n }\n\n const sendRpc = context.sendRpcToNode\n ? async (nodeId: string, method: string, parameters: unknown) => context.sendRpcToNode?.(nodeId, method, parameters)\n : undefined;\n if (!sendRpc) {\n return {\n error: 'Remote node RPC not configured (no sendRpcToNode). Connect to peer nodes first.',\n };\n }\n\n try {\n const createResult = (await sendRpc(nodeId, 'memeloop.agent.create', {\n definitionId,\n })) as { conversationId?: string };\n const conversationId = createResult?.conversationId;\n if (!conversationId) {\n return { error: 'Remote agent.create did not return conversationId', raw: createResult };\n }\n\n await sendRpc(nodeId, 'memeloop.agent.send', {\n conversationId,\n message,\n });\n\n const subscribeStream = (\n context as BuiltinToolContext & {\n subscribeRemoteStream?: (\n nodeId: string,\n conversationId: string,\n onChunk: (chunk: unknown) => void,\n ) => () => void;\n }\n ).subscribeRemoteStream;\n const streamWaitMs = context.remoteAgentStreamTimeoutMs ?? 30_000;\n const chunks: string[] = [];\n if (subscribeStream) {\n await new Promise<void>((resolve) => {\n const unsub = subscribeStream(nodeId, conversationId, (chunk) => {\n if (typeof chunk === 'string') chunks.push(chunk);\n else {\n const chunkContent = getRemoteStreamChunkContent(chunk);\n if (chunkContent !== undefined) {\n chunks.push(messageContentToText(chunkContent));\n }\n }\n });\n setTimeout(() => {\n unsub();\n resolve();\n }, streamWaitMs);\n });\n }\n\n const fullSummary = chunks.length > 0\n ? chunks.join('').trim()\n : await collectRemoteConversationSummary(sendRpc, nodeId, conversationId, streamWaitMs);\n const shortSummary = truncateToolSummary(fullSummary);\n return {\n summary: fullSummary,\n remoteNodeId: nodeId,\n remoteConversationId: conversationId,\n definitionId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run',\n conversationId,\n nodeId,\n },\n },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : messageContentToText(error);\n return { error: `remoteAgent failed: ${message}` };\n }\n};\n\nexport function getRemoteAgentToolId(): string {\n return TOOL_ID;\n}\n","import { MEMELOOP_STRUCTURED_TOOL_KEY, truncateToolSummary } from '../structuredToolResult.js';\nimport type { BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'spawnAgent';\n\nexport const spawnAgentConfigSchema = {\n type: 'object',\n properties: {\n definitionId: { type: 'string', description: 'Agent definition ID to use for the agent-run' },\n message: { type: 'string', description: 'User message / task for the agent-run' },\n },\n required: ['definitionId', 'message'],\n} as const;\n\nexport const spawnAgentImpl: BuiltinToolImpl = async (arguments_, context) => {\n const definitionId = arguments_.definitionId as string | undefined;\n const message = arguments_.message as string | undefined;\n\n if (!definitionId || typeof message !== 'string') {\n return { error: 'spawnAgent requires definitionId and message' };\n }\n\n if (!context.runLocalAgent) {\n return {\n error: 'Local agent runner not configured (no runLocalAgent in context).',\n };\n }\n\n const conversationId = `spawn:${definitionId}:${Date.now().toString(36)}`;\n const chunks: string[] = [];\n\n try {\n for await (const step of context.runLocalAgent({ conversationId, message })) {\n if (step.type === 'message' && typeof step.data === 'string') {\n chunks.push(step.data);\n }\n if (\n step.type === 'message' &&\n step.data != null &&\n typeof step.data === 'object' &&\n 'content' in step.data\n ) {\n const c = (step.data as { content?: string }).content;\n if (typeof c === 'string') chunks.push(c);\n }\n }\n const fullSummary = chunks.join('').trim() || '(no text output)';\n const shortSummary = truncateToolSummary(fullSummary);\n const nodeId = context.localNodeId?.trim() || 'local';\n return {\n summary: fullSummary,\n conversationId,\n definitionId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run',\n conversationId,\n nodeId,\n },\n },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { error: `spawnAgent failed: ${message}`, conversationId };\n }\n};\n\nexport function getSpawnAgentToolId(): string {\n return TOOL_ID;\n}\n","import type { AgentDefinition as ProtocolAgentDefinition } from './types.js';\n\n/**\n * Extended agent definition used by the agent profile registry.\n * Wraps the protocol-level AgentDefinition with additional runtime metadata.\n */\nexport interface AgentProfile {\n /** Unique ID for this agent (matches protocol id convention like \"memeloop:build\") */\n id: string;\n /** Display name */\n name: string;\n /** Agent type / role */\n type: AgentProfileType;\n /** System prompt / instructions for the agent */\n prompt: string;\n /** Tool permission rules (mutually exclusive with permissive defaults) */\n permissions: ToolPermissionRules;\n /** Optional model override (provider/model string) */\n model?: string;\n /** Underlying protocol-compatible definition for framework integration */\n protocolDef: ProtocolAgentDefinition;\n}\n\nexport type AgentProfileType = 'build' | 'plan' | 'explore' | 'oracle' | 'librarian';\n\nexport interface ToolPermissionRules {\n /** Default action for tools not matching any rule */\n default: 'allow' | 'ask' | 'deny';\n /** Per-tool or wildcard rules */\n rules: Array<{ pattern: string; action: 'allow' | 'ask' | 'deny' }>;\n}\n\nfunction makeBuiltinDefinition(\n id: string,\n name: string,\n type: AgentProfileType,\n prompt: string,\n permissions: ToolPermissionRules,\n model?: string,\n): AgentProfile {\n const systemPrompt = prompt;\n const tools: string[] = []; // runtime tools; permissions govern access\n return {\n id,\n name,\n type,\n prompt,\n permissions,\n model,\n protocolDef: {\n id,\n name,\n description: prompt.slice(0, 200),\n systemPrompt,\n tools,\n version: '1.0.0',\n modelConfig: model\n ? {\n provider: model.split('/')[0] ?? 'memeloop',\n model: model.split('/').slice(1).join('/') || model,\n }\n : undefined,\n },\n };\n}\n\n/**\n * Build agent: full access, default model.\n * Primary agent for executing tasks, writing code, running commands.\n */\nexport const buildAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:build',\n 'Build Agent',\n 'build',\n \"You are a build agent capable of executing tasks, writing and editing files, running commands, and making changes. Use tools to accomplish the user's goals efficiently.\",\n { default: 'allow', rules: [] },\n);\n\n/**\n * Plan agent: read-only, denies file edits and terminal execution.\n * Used for high-level planning and task decomposition.\n */\nexport const planAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:plan',\n 'Plan Agent',\n 'plan',\n 'You are a planning agent. Your role is to analyze requirements, decompose tasks, and create structured plans. You CANNOT write files or execute terminal commands. Only use read and search tools.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n ],\n },\n);\n\n/**\n * Explore agent: read + search tools only.\n * Fast search and codebase exploration without modification.\n */\nexport const exploreAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:explore',\n 'Explore Agent',\n 'explore',\n 'You are an exploration agent specialized in fast codebase search and discovery. You have read and search tools. Do NOT modify files or run terminal commands. Focus on finding relevant code, files, and patterns.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n { pattern: 'lsp.*', action: 'allow' },\n ],\n },\n);\n\n/**\n * Oracle agent: read-only, for architecture consultation and code review.\n */\nexport const oracleAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:oracle',\n 'Oracle Agent',\n 'oracle',\n 'You are an oracle agent specialized in architecture analysis, code review, and constraint verification. You have read access only. Review code, identify issues, and provide expert architectural guidance.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n { pattern: 'lsp.*', action: 'allow' },\n ],\n },\n);\n\n/**\n * Librarian agent: read + web search tools only.\n * External documentation lookup and context gathering.\n */\nexport const librarianAgent: AgentProfile = makeBuiltinDefinition(\n 'memeloop:librarian',\n 'Librarian Agent',\n 'librarian',\n 'You are a librarian agent specialized in external documentation lookup, web search, and context gathering. Use web search tools to find relevant documentation, APIs, and examples. Do NOT modify files or run terminal commands.',\n {\n default: 'deny',\n rules: [\n { pattern: 'file.read', action: 'allow' },\n { pattern: 'file.search', action: 'allow' },\n { pattern: 'file.list', action: 'allow' },\n { pattern: 'web.*', action: 'allow' },\n { pattern: 'grep.search', action: 'allow' },\n { pattern: 'glob.*', action: 'allow' },\n ],\n },\n);\n\n/** Built-in agent profiles used by the task delegation tool. */\nexport const BUILTIN_AGENT_PROFILES: AgentProfile[] = [\n buildAgent,\n planAgent,\n exploreAgent,\n oracleAgent,\n librarianAgent,\n];\n","import type { AgentProfile, AgentProfileType } from './agentProfiles.js';\nimport { BUILTIN_AGENT_PROFILES } from './agentProfiles.js';\n\n/**\n * Registry for agent profiles used by task delegation.\n * Pre-seeded with built-in profiles (build, plan, explore, oracle, librarian).\n */\nexport class AgentProfileRegistry {\n private readonly profiles = new Map<string, AgentProfile>();\n\n constructor() {\n this.seedDefaults();\n }\n\n /** Seed the registry with built-in agent profiles. */\n private seedDefaults(): void {\n for (const profile of BUILTIN_AGENT_PROFILES) {\n this.profiles.set(profile.id, profile);\n }\n }\n\n /**\n * Register a new agent profile or override an existing one.\n * Throws if the profile is invalid.\n */\n registerAgentProfile(profile: AgentProfile): void {\n if (!profile.id || typeof profile.id !== 'string' || profile.id.trim().length === 0) {\n throw new Error('Agent profile must have a non-empty id');\n }\n if (!profile.name || typeof profile.name !== 'string') {\n throw new Error('Agent profile must have a name');\n }\n if (!profile.type || typeof profile.type !== 'string') {\n throw new Error('Agent profile must have a type');\n }\n if (!profile.prompt || typeof profile.prompt !== 'string') {\n throw new Error('Agent profile must have a prompt');\n }\n if (!profile.permissions || typeof profile.permissions.default !== 'string') {\n throw new Error('Agent profile must have valid permissions');\n }\n this.profiles.set(profile.id, profile);\n }\n\n /**\n * Get an agent profile by ID.\n * Returns undefined if not found.\n */\n getAgentProfile(id: string): AgentProfile | undefined {\n return this.profiles.get(id);\n }\n\n /**\n * List all registered agent profiles.\n */\n listAgentProfiles(): AgentProfile[] {\n return Array.from(this.profiles.values());\n }\n\n /**\n * List agent profiles filtered by type.\n */\n listAgentProfilesByType(type: AgentProfileType): AgentProfile[] {\n return this.listAgentProfiles().filter((profile) => profile.type === type);\n }\n\n /**\n * Remove an agent profile by ID.\n */\n unregisterAgentProfile(id: string): boolean {\n return this.profiles.delete(id);\n }\n\n /**\n * Reset the registry to only built-in defaults.\n */\n reset(): void {\n this.profiles.clear();\n this.seedDefaults();\n }\n}\n\n/** Shared singleton instance for convenience. */\nlet defaultRegistry: AgentProfileRegistry | null = null;\n\nexport function getAgentProfileRegistry(): AgentProfileRegistry {\n if (!defaultRegistry) {\n defaultRegistry = new AgentProfileRegistry();\n }\n return defaultRegistry;\n}\n\nexport function resetAgentProfileRegistry(): void {\n if (defaultRegistry) {\n defaultRegistry.reset();\n }\n defaultRegistry = null;\n}\n","import { getAgentProfileRegistry } from '../../agent/agentProfileRegistry.js';\nimport { MEMELOOP_STRUCTURED_TOOL_KEY, truncateToolSummary } from '../structuredToolResult.js';\nimport type { BuiltinToolImpl } from './types.js';\n\nconst TOOL_ID = 'task';\n\nexport const taskToolConfigSchema = {\n type: 'object',\n properties: {\n agent: {\n type: 'string',\n description: \"Agent ID to delegate to (e.g. 'memeloop:build', 'memeloop:explore')\",\n },\n prompt: {\n type: 'string',\n description: 'Task prompt / instructions for the delegated agent',\n },\n background: {\n type: 'boolean',\n description: 'If true, runs asynchronously and returns a task ID immediately',\n },\n },\n required: ['agent', 'prompt'],\n} as const;\n\n/**\n * Check if we're already nested too deep in agent-runs.\n * The conversationId format for agent-runs is `agentId:timestamp`.\n * We check the current conversation for nesting depth heuristics.\n */\nfunction isTooDeeplyNested(context: { activeToolConversationId?: string }): boolean {\n const cid = context.activeToolConversationId;\n if (!cid) return false;\n // Count how many colons indicate nesting depth\n const depth = cid.split(':').length - 1;\n // Allow up to 2 levels of nesting (agent:sub:timestamp = 2 colons)\n return depth > 2;\n}\n\n/**\n * Set up per-agent tool permissions on the framework context so that\n * the AgentToolLoop's resolveToolPermission picks up the agent's restrictions.\n */\nfunction applyAgentPermissions(\n context: { agentToolLoop?: { toolPermissions?: Record<string, unknown> } },\n agentId: string,\n defaultAction: 'allow' | 'ask' | 'deny',\n rules: Array<{ pattern: string; action: 'allow' | 'ask' | 'deny' }>,\n): void {\n const tp = context.agentToolLoop ?? (context.agentToolLoop = {});\n const tperm = (tp.toolPermissions ?? (tp.toolPermissions = {})) as {\n perAgent?: Record<\n string,\n { default?: string; rules?: Array<{ pattern: string; action: string }> }\n >;\n };\n const perAgent = tperm.perAgent ?? (tperm.perAgent = {});\n perAgent[agentId] = { default: defaultAction, rules };\n}\n\nexport const taskToolImpl: BuiltinToolImpl = async (arguments_, context) => {\n const agentId = arguments_.agent as string | undefined;\n const prompt = arguments_.prompt as string | undefined;\n const background = arguments_.background as boolean | undefined;\n\n if (!agentId || typeof prompt !== 'string' || prompt.trim().length === 0) {\n return { error: \"task requires 'agent' (string) and 'prompt' (non-empty string)\" };\n }\n\n if (isTooDeeplyNested(context)) {\n return {\n error: 'Maximum agent nesting depth exceeded. Cannot delegate further.',\n };\n }\n\n const registry = getAgentProfileRegistry();\n const agentProfile = registry.getAgentProfile(agentId);\n if (!agentProfile) {\n const available = registry\n .listAgentProfiles()\n .map((a) => a.id)\n .join(', ');\n return {\n error: `Agent \"${agentId}\" not found in registry. Available: [${available}]`,\n };\n }\n\n // Apply agent-specific tool permission rules\n applyAgentPermissions(\n context as { agentToolLoop?: { toolPermissions?: Record<string, unknown> } },\n agentProfile.id,\n agentProfile.permissions.default,\n agentProfile.permissions.rules,\n );\n\n const timestamp = Date.now().toString(36);\n const conversationId = `${agentProfile.id}:${timestamp}`;\n\n const runLocal = context.runLocalAgent?.bind(context);\n if (!runLocal) {\n return {\n error: 'Local agent runner not configured (no runLocalAgent in context).',\n };\n }\n\n // Helper to collect text from generator steps\n async function collectOutput(\n gen: AsyncIterable<{ type: string; data?: unknown }>,\n ): Promise<{ text: string; conversationId: string }> {\n const chunks: string[] = [];\n for await (const step of gen) {\n if (step.type === 'message') {\n if (typeof step.data === 'string') {\n chunks.push(step.data);\n } else if (step.data != null && typeof step.data === 'object' && 'content' in step.data) {\n const c = (step.data as { content?: string }).content;\n if (typeof c === 'string') chunks.push(c);\n }\n }\n }\n return { text: chunks.join('').trim() || '(no text output)', conversationId };\n }\n\n if (background) {\n // Fire-and-forget: collect output asynchronously without awaiting\n const gen = runLocal({ conversationId, message: prompt });\n void collectOutput(gen).catch(() => {\n /* background errors are non-fatal */\n });\n\n const nodeId = context.localNodeId?.trim() || 'local';\n return {\n summary: `Background task \"${agentId}\" launched. Task ID: ${conversationId}`,\n conversationId,\n agentId,\n taskId: conversationId,\n background: true,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: `[bg-task] ${agentId}: ${conversationId}`,\n detailRef: {\n type: 'agent-run' as const,\n conversationId,\n nodeId,\n },\n },\n };\n }\n\n // Synchronous: run inline and return result\n try {\n const gen = runLocal({ conversationId, message: prompt });\n const { text, conversationId: cid } = await collectOutput(gen);\n\n const shortSummary = truncateToolSummary(text);\n const nodeId = context.localNodeId?.trim() || 'local';\n return {\n result: text,\n conversationId: cid,\n agentId,\n [MEMELOOP_STRUCTURED_TOOL_KEY]: {\n summary: shortSummary,\n detailRef: {\n type: 'agent-run' as const,\n conversationId: cid,\n nodeId,\n },\n },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return {\n error: `Task execution failed: ${message}`,\n conversationId,\n agentId,\n };\n }\n};\n\nexport function getTaskToolId(): string {\n return TOOL_ID;\n}\n","/**\n * TodoWrite Tool — Manage structured todo lists stored in conversation context.\n *\n * Supports operations: create, update, complete, list, remove.\n * Todo state is stored in-memory per conversation, keyed by conversationId.\n */\nimport { z } from 'zod';\n\nimport type { BuiltinToolContext } from './types.js';\n\nexport const todoWriteConfigSchema = z.object({\n action: z\n .enum(['create', 'update', 'complete', 'list', 'remove'])\n .describe('Action: create, update, complete, list, or remove'),\n id: z.string().min(1).optional().describe('Todo item ID (required for update/complete/remove)'),\n content: z.string().min(1).optional().describe('Todo item content (required for create/update)'),\n status: z\n .enum(['pending', 'in_progress', 'completed', 'cancelled'])\n .optional()\n .describe(\"Status (defaults to 'pending' for create)\"),\n priority: z\n .enum(['high', 'medium', 'low'])\n .optional()\n .default('medium')\n .describe('Priority level'),\n});\n\nexport const TODO_WRITE_TOOL_ID = 'todoWrite';\n\ninterface TodoItem {\n id: string;\n content: string;\n status: 'pending' | 'in_progress' | 'completed' | 'cancelled';\n priority: 'high' | 'medium' | 'low';\n createdAt: number;\n updatedAt: number;\n}\n\n/**\n * In-memory per-conversation todo store.\n * In production this could be backed by IAgentStorage for persistence.\n */\nconst conversationTodos = new Map<string, Map<string, TodoItem>>();\n\n/** Exported for test cleanup. */\nexport function __clearTodoStore(): void {\n conversationTodos.clear();\n}\n\nfunction getConversationTodos(\n conversationId: string,\n): Map<string, TodoItem> {\n let todos = conversationTodos.get(conversationId);\n if (!todos) {\n todos = new Map<string, TodoItem>();\n conversationTodos.set(conversationId, todos);\n }\n return todos;\n}\n\nfunction formatTodoList(todos: Map<string, TodoItem>): string {\n if (todos.size === 0) {\n return '(No todos)';\n }\n\n const statusOrder: Record<string, number> = {\n in_progress: 0,\n pending: 1,\n completed: 2,\n cancelled: 3,\n };\n\n const sorted = [...todos.values()].sort(\n (a, b) =>\n (statusOrder[a.status] ?? 99) - (statusOrder[b.status] ?? 99) ||\n b.updatedAt - a.updatedAt,\n );\n\n const statusIcons: Record<string, string> = {\n pending: '○',\n in_progress: '◉',\n completed: '✓',\n cancelled: '✗',\n };\n\n return sorted\n .map(\n (t) => `${statusIcons[t.status] ?? '?'} [${t.priority}] ${t.content} (id: ${t.id})`,\n )\n .join('\\n');\n}\n\nfunction getConversationId(context: BuiltinToolContext): string {\n return context.agent?.id ?? context.activeToolConversationId ?? 'default';\n}\n\nexport async function todoWriteImpl(\n arguments_: Record<string, unknown>,\n context: BuiltinToolContext,\n): Promise<{ result: string } | { error: string }> {\n const parsed = todoWriteConfigSchema.safeParse(arguments_);\n if (!parsed.success) {\n return { error: `invalid_todoWrite_args: ${parsed.error.message}` };\n }\n\n const { action, id, content, status, priority } = parsed.data;\n const conversationId = getConversationId(context);\n const todos = getConversationTodos(conversationId);\n const now = Date.now();\n\n switch (action) {\n case 'create': {\n if (!content) {\n return { error: 'content is required for create action' };\n }\n const newId = id ?? crypto.randomUUID();\n if (todos.has(newId)) {\n return { error: `Todo with id '${newId}' already exists. Use update action.` };\n }\n const item: TodoItem = {\n id: newId,\n content,\n status: status ?? 'pending',\n priority,\n createdAt: now,\n updatedAt: now,\n };\n todos.set(newId, item);\n return {\n result: `Todo created: [${item.priority}] ${item.content} (id: ${item.id})\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'update': {\n if (!id) {\n return { error: 'id is required for update action' };\n }\n const existing = todos.get(id);\n if (!existing) {\n return { error: `Todo with id '${id}' not found` };\n }\n if (content !== undefined) existing.content = content;\n if (status !== undefined) existing.status = status;\n existing.priority = priority ?? existing.priority;\n existing.updatedAt = now;\n return {\n result: `Todo updated: [${existing.priority}] ${existing.content} (id: ${existing.id}, status: ${existing.status})\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'complete': {\n if (!id) {\n return { error: 'id is required for complete action' };\n }\n const existing = todos.get(id);\n if (!existing) {\n return { error: `Todo with id '${id}' not found` };\n }\n existing.status = 'completed';\n existing.updatedAt = now;\n return {\n result: `Todo completed: [${existing.priority}] ${existing.content} (id: ${existing.id})\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'remove': {\n if (!id) {\n // Remove all completed/cancelled todos\n let removed = 0;\n for (const [key, item] of todos) {\n if (item.status === 'completed' || item.status === 'cancelled') {\n todos.delete(key);\n removed++;\n }\n }\n return {\n result: `Removed ${removed} completed/cancelled todo(s)\\n\\n${formatTodoList(todos)}`,\n };\n }\n const removed = todos.delete(id);\n return {\n result: removed\n ? `Todo removed: ${id}\\n\\n${formatTodoList(todos)}`\n : `Todo with id '${id}' not found\\n\\n${formatTodoList(todos)}`,\n };\n }\n\n case 'list':\n default: {\n return {\n result: `Todo list (${todos.size} items):\\n\\n${formatTodoList(todos)}`,\n };\n }\n }\n}\n","/**\n * Builtin tool plugins — registers core tools as LoopPlugin entries.\n *\n * Each tool is a separate LoopPlugin that can be overridden by user/host plugins\n * with the same id. The plugin.install callback calls the tool registry to\n * register the tool implementation.\n *\n * These are registered in the loop registry at startup and loaded by\n * `registerBuiltinTools` via plugin discovery.\n */\n\nimport { registerToolParameterSchema } from '../../tools/schemaRegistry.js';\nimport type { IToolRegistry } from '../../types.js';\nimport { getLoopRegistry } from '../registry.js';\nimport type { LoopPlugin } from '../types.js';\n\n// ─── Import tool implementations ─────────────────────────────────────\n\nimport { ASK_QUESTION_TOOL_ID, askQuestionConfigSchema, askQuestionImpl } from '../../tools/builtins/askQuestion.js';\nimport { ASK_USER_QUESTION_TOOL_ID, askUserQuestionConfigSchema, askUserQuestionImpl } from '../../tools/builtins/askUserQuestion.js';\nimport { getMcpClientToolId, mcpClientConfigSchema, mcpClientImpl } from '../../tools/builtins/mcpClient.js';\nimport { getMcpForwardToolId, mcpForwardConfigSchema, mcpForwardImpl } from '../../tools/builtins/mcpForward.js';\nimport { getRemoteAgentToolId, remoteAgentConfigSchema, remoteAgentImpl } from '../../tools/builtins/remoteAgent.js';\nimport { getSpawnAgentToolId, spawnAgentConfigSchema, spawnAgentImpl } from '../../tools/builtins/spawnAgent.js';\nimport { getTaskToolId, taskToolConfigSchema, taskToolImpl } from '../../tools/builtins/task.js';\nimport { TODO_WRITE_TOOL_ID, todoWriteConfigSchema, todoWriteImpl } from '../../tools/builtins/todoWrite.js';\nimport type { BuiltinToolContext, BuiltinToolImpl } from '../../tools/builtins/types.js';\n\n// ─── Plugin id constants ───────────────────────────────────────────\n\nexport const PLUGIN_MCP_CLIENT = 'builtin:mcp-client';\nexport const PLUGIN_MCP_FORWARD = 'builtin:mcp-forward';\nexport const PLUGIN_SPAWN_AGENT = 'builtin:spawn-agent';\nexport const PLUGIN_REMOTE_AGENT = 'builtin:remote-agent';\nexport const PLUGIN_ASK_QUESTION = 'builtin:ask-question';\nexport const PLUGIN_TODO_WRITE = 'builtin:todo-write';\nexport const PLUGIN_ASK_USER_QUESTION = 'builtin:ask-user-question';\nexport const PLUGIN_TASK = 'builtin:task';\n\nexport const BUILTIN_TOOL_PLUGIN_IDS = [\n PLUGIN_MCP_CLIENT,\n PLUGIN_MCP_FORWARD,\n PLUGIN_SPAWN_AGENT,\n PLUGIN_REMOTE_AGENT,\n PLUGIN_ASK_QUESTION,\n PLUGIN_TODO_WRITE,\n PLUGIN_ASK_USER_QUESTION,\n PLUGIN_TASK,\n] as const;\n\ninterface BuiltinToolPluginOptions {\n id: string;\n toolId: string;\n schema: unknown;\n metadata: { displayName: string; description: string };\n implementation: BuiltinToolImpl;\n}\n\nfunction getToolRegistry(context: { [key: string]: unknown }): IToolRegistry | undefined {\n return context.toolRegistry as IToolRegistry | undefined;\n}\n\nfunction createBuiltinToolPlugin(options: BuiltinToolPluginOptions): LoopPlugin {\n return {\n id: options.id,\n targetLoopId: '*',\n install: (context) => {\n const registry = getToolRegistry(context);\n if (!registry) return;\n\n const builtinContext = context as unknown as BuiltinToolContext;\n registry.registerTool(options.toolId, (arguments_: Record<string, unknown>) => options.implementation(arguments_, builtinContext));\n registerToolParameterSchema(options.toolId, options.schema, options.metadata);\n },\n };\n}\n\nconst builtinToolPlugins: LoopPlugin[] = [\n createBuiltinToolPlugin({\n id: PLUGIN_MCP_CLIENT,\n toolId: getMcpClientToolId(),\n schema: mcpClientConfigSchema,\n metadata: {\n displayName: 'MCP Client',\n description: 'Call a tool on a remote MCP server (transparent proxy). Requires nodeId, serverName, toolName, and optional args.',\n },\n implementation: mcpClientImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_MCP_FORWARD,\n toolId: getMcpForwardToolId(),\n schema: mcpForwardConfigSchema,\n metadata: {\n displayName: 'MCP Forward',\n description: \"Discover MCP servers and tools on connected nodes. Use action='list' for nodes with servers, action='listTools' for all available tools.\",\n },\n implementation: mcpForwardImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_SPAWN_AGENT,\n toolId: getSpawnAgentToolId(),\n schema: spawnAgentConfigSchema,\n metadata: {\n displayName: 'Spawn Agent',\n description: 'Run a local agent-agent-loop with the given definition and message. Returns summary.',\n },\n implementation: spawnAgentImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_REMOTE_AGENT,\n toolId: getRemoteAgentToolId(),\n schema: remoteAgentConfigSchema,\n metadata: {\n displayName: 'Remote Agent',\n description: 'Create and run a agent-agent-loop on a remote node. Requires nodeId, definitionId, message. List nodes with no args.',\n },\n implementation: remoteAgentImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_ASK_QUESTION,\n toolId: ASK_QUESTION_TOOL_ID,\n schema: askQuestionConfigSchema,\n metadata: {\n displayName: 'Ask Question',\n description: 'Block until the user answers (via memeloop.agent.resolveQuestion RPC). Args: question, conversationId, optional timeoutMs.',\n },\n implementation: askQuestionImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_TODO_WRITE,\n toolId: TODO_WRITE_TOOL_ID,\n schema: todoWriteConfigSchema,\n metadata: {\n displayName: 'Todo Write',\n description: 'Manage structured todo lists: create, update, complete, list, remove. Todos scoped per conversation.',\n },\n implementation: todoWriteImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_ASK_USER_QUESTION,\n toolId: ASK_USER_QUESTION_TOOL_ID,\n schema: askUserQuestionConfigSchema,\n metadata: {\n displayName: 'Ask User Question',\n description: 'Pause agent and ask user a question. Supports text, single-select, and multi-select input types. Blocks until answered.',\n },\n implementation: askUserQuestionImpl,\n }),\n createBuiltinToolPlugin({\n id: PLUGIN_TASK,\n toolId: getTaskToolId(),\n schema: taskToolConfigSchema,\n metadata: {\n displayName: 'Task Delegation',\n description: 'Delegate a task to a specialized agent-agent-loop (build, plan, explore, oracle, librarian). Supports sync (default) and background modes.',\n },\n implementation: taskToolImpl,\n }),\n];\n\nexport function getBuiltinToolPlugins(): LoopPlugin[] {\n return builtinToolPlugins;\n}\n\n/** Register all builtin tool plugins with the loop registry. */\nexport function registerBuiltinToolPlugins(): void {\n const loopRegistry = getLoopRegistry();\n\n for (const plugin of builtinToolPlugins) {\n if (loopRegistry.getPlugin(plugin.id)) continue;\n loopRegistry.registerPlugin(plugin);\n }\n}\n","/**\n * Token counting and auto-compaction trigger.\n * Tracks token usage per conversation and triggers compaction when approaching limits.\n *\n * Based on: Claude Code autoCompact + OpenCode autoCompact@95%\n */\n\n/** Rough token estimation: ~4 chars per token (conservative) */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 3.5);\n}\n\n/** Estimate token count for a messages array */\nexport function estimateMessagesTokens(messages: Array<{ content: unknown }>): number {\n let total = 0;\n for (const message of messages) {\n const content = typeof message.content === 'string' ? message.content : JSON.stringify(message.content ?? '');\n total += estimateTokens(content);\n }\n return total;\n}\n\nexport interface TokenTrackerConfig {\n /** Maximum context window in tokens (default: 200000) */\n contextWindow?: number;\n /** Trigger compaction when usage exceeds this fraction (default: 0.90) */\n compactionThreshold?: number;\n /** Buffer tokens reserved for output (default: 16000) */\n outputBuffer?: number;\n}\n\nexport interface TokenUsage {\n promptTokens: number;\n completionTokens: number;\n totalTokens: number;\n contextWindow: number;\n usagePercent: number;\n shouldCompact: boolean;\n}\n\n/**\n * Tracks token usage and decides when to trigger auto-compaction.\n */\nexport class TokenTracker {\n private promptTokens = 0;\n private completionTokens = 0;\n private readonly contextWindow: number;\n private readonly compactionThreshold: number;\n private readonly outputBuffer: number;\n private compacting = false;\n private consecutiveCompactionFailures = 0;\n private maxConsecutiveFailures = 3;\n\n constructor(config?: TokenTrackerConfig) {\n this.contextWindow = config?.contextWindow ?? 200_000;\n this.compactionThreshold = config?.compactionThreshold ?? 0.9;\n this.outputBuffer = config?.outputBuffer ?? 16_000;\n }\n\n /** Record token usage from an LLM response */\n recordUsage(promptTokens: number, completionTokens: number): void {\n this.promptTokens += promptTokens;\n this.completionTokens += completionTokens;\n }\n\n /** Manually set the prompt token count (e.g., from estimation) */\n setPromptTokens(tokens: number): void {\n this.promptTokens = tokens;\n }\n\n /** Get current usage */\n getUsage(): TokenUsage {\n const total = this.promptTokens + this.completionTokens;\n const effectiveWindow = this.contextWindow - this.outputBuffer;\n const usagePercent = total / effectiveWindow;\n return {\n promptTokens: this.promptTokens,\n completionTokens: this.completionTokens,\n totalTokens: total,\n contextWindow: this.contextWindow,\n usagePercent: Math.min(usagePercent, 1.0),\n shouldCompact: usagePercent >= this.compactionThreshold && !this.compacting,\n };\n }\n\n /** Check if auto-compaction should be triggered */\n shouldTriggerCompaction(): boolean {\n if (this.consecutiveCompactionFailures >= this.maxConsecutiveFailures) return false;\n return this.getUsage().shouldCompact;\n }\n\n /** Mark that compaction is starting */\n markCompactionStart(): void {\n this.compacting = true;\n }\n\n /** Mark that compaction succeeded — reset token counts */\n markCompactionSuccess(estimatedPostTokens: number): void {\n this.compacting = false;\n this.promptTokens = estimatedPostTokens;\n this.completionTokens = 0;\n this.consecutiveCompactionFailures = 0;\n }\n\n /** Mark that compaction failed */\n markCompactionFailure(): void {\n this.compacting = false;\n this.consecutiveCompactionFailures++;\n }\n\n /** Reset all counters */\n reset(): void {\n this.promptTokens = 0;\n this.completionTokens = 0;\n this.compacting = false;\n this.consecutiveCompactionFailures = 0;\n }\n\n /** Get a human-readable summary */\n formatUsage(): string {\n const usage = this.getUsage();\n const promptK = (usage.promptTokens / 1000).toFixed(1);\n const windowK = (usage.contextWindow / 1000).toFixed(0);\n const pct = (usage.usagePercent * 100).toFixed(1);\n return `${promptK}K/${windowK}K tokens (${pct}%)`;\n }\n}\n\n/** Interface for a compaction engine that can summarize conversation history */\nexport interface CompactionEngine {\n compact(\n messages: Array<{ role: string; content: unknown }>,\n conversationId: string,\n ): Promise<void>;\n}\n\n/**\n * Auto-compaction hook — call this after each LLM response.\n * Triggers compaction when token usage exceeds threshold.\n *\n * @returns true if compaction was triggered\n */\nexport async function maybeAutoCompact(\n tracker: TokenTracker,\n compactionEngine: CompactionEngine,\n messages: Array<{ role: string; content: unknown }>,\n conversationId: string,\n): Promise<boolean> {\n if (!tracker.shouldTriggerCompaction()) return false;\n\n tracker.markCompactionStart();\n try {\n await compactionEngine.compact(messages, conversationId);\n const estimatedPost = estimateTokens('Summary of previous conversation context.');\n tracker.markCompactionSuccess(estimatedPost);\n return true;\n } catch {\n tracker.markCompactionFailure();\n return false;\n }\n}\n","// Generated by scripts/generate-profile-sources.mjs. Edit src/loopProfiles/*.json instead.\n\n/** Builtin Loop Profile JSON sources, embedded at build time. */\nexport const builtinProfileSources: Readonly<Record<string, string>> = {\n 'code-assistant': [\n '{',\n ' \"id\": \"memeloop:code-assistant\",',\n ' \"name\": \"代码助手\",',\n ' \"description\": \"专注于代码编写、重构和调试的助手。\",',\n ' \"loopId\": \"agent-tool-loop\",',\n ' \"systemPrompt\": \"You are a senior software engineer helping the user write and refactor code.\",',\n ' \"tools\": [',\n ' \"workspacesList\",',\n ' \"wikiSearch\",',\n ' \"wikiOperation\",',\n ' \"modelContextProtocol\",',\n ' \"spawnAgent\",',\n ' \"askQuestion\",',\n ' \"getErrors\",',\n ' \"webFetch\"',\n ' ],',\n ' \"plugins\": [',\n ' { \"id\": \"builtin:mcp-client\" },',\n ' { \"id\": \"builtin:mcp-forward\" },',\n ' { \"id\": \"builtin:spawn-agent\" },',\n ' { \"id\": \"builtin:ask-question\" }',\n ' ],',\n ' \"agentTools\": [',\n ' {',\n ' \"toolId\": \"workspacesList\",',\n ' \"parameters\": {',\n ' \"workspacesListParam\": { \"targetId\": \"builtin-system\", \"position\": \"after\" }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"wikiSearch\",',\n ' \"parameters\": {',\n ' \"wikiSearchParam\": {',\n ' \"sourceType\": \"wiki\",',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"wikiOperation\",',\n ' \"parameters\": {',\n ' \"wikiOperationParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"modelContextProtocol\",',\n ' \"parameters\": {',\n ' \"modelContextProtocolParam\": {',\n ' \"serverUrl\": \"http://127.0.0.1:38385/mcp\",',\n ' \"timeoutSecond\": 30,',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"spawnAgent\",',\n ' \"parameters\": {',\n ' \"spawnAgentParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 2,',\n ' \"defaultTimeoutMs\": 120000',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"askQuestion\",',\n ' \"parameters\": {',\n ' \"askQuestionParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" }',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"getErrors\",',\n ' \"parameters\": {',\n ' \"getErrorsParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" }',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"webFetch\",',\n ' \"parameters\": {',\n ' \"webFetchParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' }',\n ' ],',\n ' \"agentFrameworkConfig\": {',\n ' \"prompts\": [',\n ' {',\n ' \"id\": \"builtin-system\",',\n ' \"role\": \"system\",',\n ' \"text\": \"You are a senior software engineer helping the user write and refactor code. Prefer small, safe edits; use file.read and file.search before changing code; use terminal.execute for build/tests when appropriate.\"',\n ' }',\n ' ],',\n ' \"plugins\": [{ \"toolId\": \"fullReplacement\" }],',\n ' \"response\": []',\n ' },',\n ' \"modelConfig\": {',\n ' \"provider\": \"memeloop\",',\n ' \"model\": \"claude-opus-4.6\",',\n ' \"temperature\": 0.2,',\n ' \"maxTokens\": 4096',\n ' },',\n ' \"version\": \"1.0.0\"',\n '}',\n '',\n ].join('\\n'),\n 'frontend-ui-ux': [\n '{',\n ' \"id\": \"memeloop:frontend-ui-ux\",',\n ' \"name\": \"Frontend UI/UX\",',\n ' \"description\": \"Designer-turned-developer who crafts stunning UI/UX even without design mockups.\",',\n ' \"loopId\": \"agent-tool-loop\",',\n ' \"systemPrompt\": \"You are a designer-turned-developer who crafts stunning UI/UX even without design mockups.\\\\n\\\\nWhen working on frontend tasks:\\\\n- Prioritize visual polish and user experience above all else\\\\n- Use consistent spacing, typography, and color schemes\\\\n- Apply modern design patterns: rounded corners, subtle shadows, smooth transitions\\\\n- Ensure responsive design across mobile, tablet, and desktop breakpoints\\\\n- Prefer accessible patterns: semantic HTML, ARIA labels, keyboard navigation\\\\n- Optimize for perceived performance: skeleton loaders, optimistic updates, progressive enhancement\\\\n- Use component composition over monolithic layouts\\\\n- Match the existing design system when extending an existing UI\",',\n ' \"tools\": [',\n ' \"workspacesList\",',\n ' \"wikiSearch\",',\n ' \"wikiOperation\",',\n ' \"modelContextProtocol\",',\n ' \"spawnAgent\",',\n ' \"askQuestion\",',\n ' \"webFetch\"',\n ' ],',\n ' \"plugins\": [',\n ' { \"id\": \"builtin:mcp-client\" },',\n ' { \"id\": \"builtin:mcp-forward\" },',\n ' { \"id\": \"builtin:spawn-agent\" },',\n ' { \"id\": \"builtin:ask-question\" }',\n ' ],',\n ' \"agentTools\": [',\n ' {',\n ' \"toolId\": \"workspacesList\",',\n ' \"parameters\": {',\n ' \"workspacesListParam\": { \"targetId\": \"builtin-system\", \"position\": \"after\" }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"wikiSearch\",',\n ' \"parameters\": {',\n ' \"wikiSearchParam\": {',\n ' \"sourceType\": \"wiki\",',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"wikiOperation\",',\n ' \"parameters\": {',\n ' \"wikiOperationParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"modelContextProtocol\",',\n ' \"parameters\": {',\n ' \"modelContextProtocolParam\": {',\n ' \"serverUrl\": \"http://127.0.0.1:38385/mcp\",',\n ' \"timeoutSecond\": 30,',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"spawnAgent\",',\n ' \"parameters\": {',\n ' \"spawnAgentParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 2,',\n ' \"defaultTimeoutMs\": 120000',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"askQuestion\",',\n ' \"parameters\": {',\n ' \"askQuestionParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" }',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"webFetch\",',\n ' \"parameters\": {',\n ' \"webFetchParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' }',\n ' ],',\n ' \"agentFrameworkConfig\": {',\n ' \"prompts\": [',\n ' {',\n ' \"id\": \"builtin-system\",',\n ' \"role\": \"system\",',\n ' \"text\": \"You are a designer-turned-developer who crafts stunning UI/UX even without design mockups.\\\\n\\\\nWhen working on frontend tasks:\\\\n- Prioritize visual polish and user experience above all else\\\\n- Use consistent spacing, typography, and color schemes\\\\n- Apply modern design patterns: rounded corners, subtle shadows, smooth transitions\\\\n- Ensure responsive design across mobile, tablet, and desktop breakpoints\\\\n- Prefer accessible patterns: semantic HTML, ARIA labels, keyboard navigation\\\\n- Optimize for perceived performance: skeleton loaders, optimistic updates, progressive enhancement\\\\n- Use component composition over monolithic layouts\\\\n- Match the existing design system when extending an existing UI\"',\n ' }',\n ' ],',\n ' \"plugins\": [],',\n ' \"response\": []',\n ' },',\n ' \"modelConfig\": {',\n ' \"provider\": \"memeloop\",',\n ' \"model\": \"claude-opus-4.6\",',\n ' \"temperature\": 0.3,',\n ' \"maxTokens\": 4096',\n ' },',\n ' \"version\": \"1.0.0\"',\n '}',\n '',\n ].join('\\n'),\n 'general-assistant': [\n '{',\n ' \"id\": \"memeloop:general-assistant\",',\n ' \"name\": \"通用助手\",',\n ' \"description\": \"通用自然语言助理,用于日常问答和简单任务。\",',\n ' \"loopId\": \"agent-tool-loop\",',\n ' \"systemPrompt\": \"You are a helpful general-purpose assistant. When you need to use a tool, output ONLY the tool call in this exact XML format:\\\\n<tool_use name=\\\\\"TOOL_NAME\\\\\">{\\\\\"param\\\\\":\\\\\"value\\\\\"}</tool_use>\\\\nNever wrap tool calls in markdown code blocks or add explanatory text before/after the tool call in the same message. After receiving the tool result, continue responding normally.\",',\n ' \"tools\": [',\n ' \"workspacesList\",',\n ' \"wikiSearch\",',\n ' \"wikiOperation\",',\n ' \"modelContextProtocol\",',\n ' \"spawnAgent\",',\n ' \"askQuestion\"',\n ' ],',\n ' \"plugins\": [',\n ' { \"id\": \"builtin:mcp-client\" },',\n ' { \"id\": \"builtin:mcp-forward\" },',\n ' { \"id\": \"builtin:spawn-agent\" },',\n ' { \"id\": \"builtin:ask-question\" }',\n ' ],',\n ' \"agentTools\": [',\n ' {',\n ' \"toolId\": \"workspacesList\",',\n ' \"parameters\": {',\n ' \"workspacesListParam\": { \"targetId\": \"builtin-system\", \"position\": \"after\" }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"wikiSearch\",',\n ' \"parameters\": {',\n ' \"wikiSearchParam\": {',\n ' \"sourceType\": \"wiki\",',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"wikiOperation\",',\n ' \"parameters\": {',\n ' \"wikiOperationParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"modelContextProtocol\",',\n ' \"parameters\": {',\n ' \"modelContextProtocolParam\": {',\n ' \"serverUrl\": \"http://127.0.0.1:38385/mcp\",',\n ' \"timeoutSecond\": 30,',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"spawnAgent\",',\n ' \"parameters\": {',\n ' \"spawnAgentParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 2,',\n ' \"defaultTimeoutMs\": 120000',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"askQuestion\",',\n ' \"parameters\": {',\n ' \"askQuestionParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" }',\n ' }',\n ' }',\n ' }',\n ' ],',\n ' \"agentFrameworkConfig\": {',\n ' \"prompts\": [',\n ' {',\n ' \"id\": \"builtin-system\",',\n ' \"role\": \"system\",',\n ' \"text\": \"You are a helpful general-purpose assistant. When you need to use a tool, output ONLY the tool call in this exact XML format:\\\\n<tool_use name=\\\\\"TOOL_NAME\\\\\">{\\\\\"param\\\\\":\\\\\"value\\\\\"}</tool_use>\\\\nNever wrap tool calls in markdown code blocks or add explanatory text before/after the tool call in the same message. After receiving the tool result, continue responding normally.\"',\n ' }',\n ' ],',\n ' \"plugins\": [{ \"toolId\": \"fullReplacement\" }],',\n ' \"response\": []',\n ' },',\n ' \"modelConfig\": {',\n ' \"provider\": \"memeloop\",',\n ' \"model\": \"claude-opus-4.6\",',\n ' \"temperature\": 0.5,',\n ' \"maxTokens\": 4096',\n ' },',\n ' \"version\": \"1.0.0\"',\n '}',\n '',\n ].join('\\n'),\n 'git-master': [\n '{',\n ' \"id\": \"memeloop:git-master\",',\n ' \"name\": \"Git Master\",',\n ' \"description\": \"Expert git workflow management with safety-first approach.\",',\n ' \"loopId\": \"agent-tool-loop\",',\n ' \"systemPrompt\": \"You are an expert in git workflow management. Follow these rules:\\\\n\\\\nGit Safety Protocol:\\\\n- NEVER update the git config\\\\n- NEVER run destructive/irreversible git commands (push --force, hard reset, etc.) unless the user explicitly requests them\\\\n- NEVER skip hooks (--no-verify, --no-gpg-sign, etc.) unless the user explicitly requests it\\\\n- NEVER force push to main/master; warn the user if they request it\\\\n- Avoid git commit --amend. ONLY use --amend when ALL conditions are met:\\\\n (1) User explicitly requested amend, OR the commit succeeded and pre-commit hooks auto-modified files that need including\\\\n (2) HEAD commit was created by you in this conversation\\\\n (3) Commit has NOT been pushed to remote\\\\n- If commit FAILED or was REJECTED by hook, NEVER amend — fix the issue and create a NEW commit\\\\n- If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)\\\\n\\\\nCommitting:\\\\n- NEVER commit changes unless the user explicitly asks\\\\n- Run: git status, git diff, git log (recent commits)\\\\n- Analyze all staged changes and draft a concise commit message\\\\n- Summarize nature of changes: add/update/fix/refactor/test/docs\\\\n- Do NOT commit files that likely contain secrets\\\\n\\\\nPull Requests:\\\\n- Check branch status, divergence from base, full commit history\\\\n- Create PR with descriptive title and summary body\\\\n- Return the PR URL when done\",',\n ' \"tools\": [\"workspacesList\", \"git\", \"askQuestion\"],',\n ' \"plugins\": [{ \"id\": \"builtin:ask-question\" }],',\n ' \"agentTools\": [',\n ' {',\n ' \"toolId\": \"workspacesList\",',\n ' \"parameters\": {',\n ' \"workspacesListParam\": { \"targetId\": \"builtin-system\", \"position\": \"after\" }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"git\",',\n ' \"parameters\": {',\n ' \"gitParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" }',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"askQuestion\",',\n ' \"parameters\": {',\n ' \"askQuestionParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" }',\n ' }',\n ' }',\n ' }',\n ' ],',\n ' \"agentFrameworkConfig\": {',\n ' \"prompts\": [',\n ' {',\n ' \"id\": \"builtin-system\",',\n ' \"role\": \"system\",',\n ' \"text\": \"You are an expert in git workflow management. Follow these rules:\\\\n\\\\nGit Safety Protocol:\\\\n- NEVER update the git config\\\\n- NEVER run destructive/irreversible git commands (push --force, hard reset, etc.) unless the user explicitly requests them\\\\n- NEVER skip hooks (--no-verify, --no-gpg-sign, etc.) unless the user explicitly requests it\\\\n- NEVER force push to main/master; warn the user if they request it\\\\n- Avoid git commit --amend. ONLY use --amend when ALL conditions are met:\\\\n (1) User explicitly requested amend, OR the commit succeeded and pre-commit hooks auto-modified files that need including\\\\n (2) HEAD commit was created by you in this conversation\\\\n (3) Commit has NOT been pushed to remote\\\\n- If commit FAILED or was REJECTED by hook, NEVER amend — fix the issue and create a NEW commit\\\\n- If you already pushed to remote, NEVER amend unless user explicitly requests it (requires force push)\\\\n\\\\nCommitting:\\\\n- NEVER commit changes unless the user explicitly asks\\\\n- Run: git status, git diff, git log (recent commits)\\\\n- Analyze all staged changes and draft a concise commit message\\\\n- Summarize nature of changes: add/update/fix/refactor/test/docs\\\\n- Do NOT commit files that likely contain secrets\\\\n\\\\nPull Requests:\\\\n- Check branch status, divergence from base, full commit history\\\\n- Create PR with descriptive title and summary body\\\\n- Return the PR URL when done\"',\n ' }',\n ' ],',\n ' \"plugins\": [],',\n ' \"response\": []',\n ' },',\n ' \"modelConfig\": {',\n ' \"provider\": \"memeloop\",',\n ' \"model\": \"claude-opus-4.6\",',\n ' \"temperature\": 0.2,',\n ' \"maxTokens\": 4096',\n ' },',\n ' \"version\": \"1.0.0\"',\n '}',\n '',\n ].join('\\n'),\n 'playwright': [\n '{',\n ' \"id\": \"memeloop:playwright\",',\n ' \"name\": \"Playwright\",',\n ' \"description\": \"Browser automation via Playwright for verification, browsing, information gathering, web scraping, testing, and screenshots.\",',\n ' \"loopId\": \"agent-tool-loop\",',\n ' \"systemPrompt\": \"You have access to Playwright for browser automation. Use it for:\\\\n\\\\nBrowser Automation:\\\\n- Navigate to URLs and verify page content\\\\n- Fill forms, click buttons, and interact with page elements\\\\n- Take screenshots of specific elements or full pages\\\\n- Extract data from web pages (scraping)\\\\n- Test web application functionality end-to-end\\\\n- Automate browser workflows\\\\n- Log into websites and maintain sessions\\\\n\\\\nBest Practices:\\\\n- Use specific selectors (data-testid, id, or unique CSS selectors) over fragile XPath\\\\n- Wait for elements to be visible before interacting\\\\n- Handle page navigation and loading states explicitly\\\\n- Take screenshots at key steps for debugging\\\\n- Clean up browser resources when done\\\\n- Handle timeouts and error states gracefully\\\\n\\\\nAvailable Playwright MCP Tools:\\\\n- browser_navigate: Navigate to a URL\\\\n- browser_click: Click an element\\\\n- browser_type: Type into an input field\\\\n- browser_snapshot: Take accessibility snapshot of page\\\\n- browser_take_screenshot: Capture screenshot\\\\n- browser_fill_form: Fill multiple form fields at once\\\\n- browser_evaluate: Execute JavaScript in page context\\\\n- browser_select_option: Select from dropdown\\\\n- browser_drag: Drag and drop elements\\\\n- browser_hover: Hover over an element\\\\n- browser_press_key: Press a keyboard key\\\\n- browser_handle_dialog: Handle browser dialogs (alert/confirm/prompt)\\\\n- browser_close: Close the browser\",',\n ' \"tools\": [\"modelContextProtocol\", \"askQuestion\"],',\n ' \"plugins\": [',\n ' { \"id\": \"builtin:mcp-client\" },',\n ' { \"id\": \"builtin:mcp-forward\" },',\n ' { \"id\": \"builtin:ask-question\" }',\n ' ],',\n ' \"agentTools\": [',\n ' {',\n ' \"toolId\": \"modelContextProtocol\",',\n ' \"parameters\": {',\n ' \"modelContextProtocolParam\": {',\n ' \"serverUrl\": \"http://127.0.0.1:38385/mcp\",',\n ' \"timeoutSecond\": 30,',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' },',\n ' {',\n ' \"toolId\": \"askQuestion\",',\n ' \"parameters\": {',\n ' \"askQuestionParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" }',\n ' }',\n ' }',\n ' }',\n ' ],',\n ' \"agentFrameworkConfig\": {',\n ' \"prompts\": [',\n ' {',\n ' \"id\": \"builtin-system\",',\n ' \"role\": \"system\",',\n ' \"text\": \"You have access to Playwright for browser automation. Use it for:\\\\n\\\\nBrowser Automation:\\\\n- Navigate to URLs and verify page content\\\\n- Fill forms, click buttons, and interact with page elements\\\\n- Take screenshots of specific elements or full pages\\\\n- Extract data from web pages (scraping)\\\\n- Test web application functionality end-to-end\\\\n- Automate browser workflows\\\\n- Log into websites and maintain sessions\\\\n\\\\nBest Practices:\\\\n- Use specific selectors (data-testid, id, or unique CSS selectors) over fragile XPath\\\\n- Wait for elements to be visible before interacting\\\\n- Handle page navigation and loading states explicitly\\\\n- Take screenshots at key steps for debugging\\\\n- Clean up browser resources when done\\\\n- Handle timeouts and error states gracefully\\\\n\\\\nAvailable Playwright MCP Tools:\\\\n- browser_navigate: Navigate to a URL\\\\n- browser_click: Click an element\\\\n- browser_type: Type into an input field\\\\n- browser_snapshot: Take accessibility snapshot of page\\\\n- browser_take_screenshot: Capture screenshot\\\\n- browser_fill_form: Fill multiple form fields at once\\\\n- browser_evaluate: Execute JavaScript in page context\\\\n- browser_select_option: Select from dropdown\\\\n- browser_drag: Drag and drop elements\\\\n- browser_hover: Hover over an element\\\\n- browser_press_key: Press a keyboard key\\\\n- browser_handle_dialog: Handle browser dialogs (alert/confirm/prompt)\\\\n- browser_close: Close the browser\"',\n ' }',\n ' ],',\n ' \"plugins\": [],',\n ' \"response\": []',\n ' },',\n ' \"modelConfig\": {',\n ' \"provider\": \"memeloop\",',\n ' \"model\": \"claude-opus-4.6\",',\n ' \"temperature\": 0.3,',\n ' \"maxTokens\": 4096',\n ' },',\n ' \"version\": \"1.0.0\"',\n '}',\n '',\n ].join('\\n'),\n};\n\n","/**\n * Built-in Loop Profiles.\n *\n * Each profile defines which agent loop to run, which .mjs script to load,\n * which prompts, plugins, and hook plugins to enable.\n *\n * Replaces the old `src/prompt/loadBuiltins.ts`.\n */\n\nimport { getLoopRegistry } from '../loopAPI/registry.js';\nimport type { LoopProfile } from '../loopAPI/types.js';\nimport { builtinProfileSources } from './builtinProfileSources.js';\n\nfunction loadProfile(name: string): LoopProfile {\n const source = builtinProfileSources[name];\n if (!source) {\n throw new Error(`Builtin profile not found: ${name}`);\n }\n return JSON.parse(source) as LoopProfile;\n}\n\n/** Get all built-in Loop Profiles. */\nexport function getBuiltinLoopProfiles(): LoopProfile[] {\n return [\n loadProfile('general-assistant'),\n loadProfile('code-assistant'),\n loadProfile('frontend-ui-ux'),\n loadProfile('git-master'),\n loadProfile('playwright'),\n ];\n}\n\n/** Get a built-in Loop Profile by id. */\nexport function getBuiltinLoopProfile(id: string): LoopProfile | undefined {\n return getBuiltinLoopProfiles().find((p) => p.id === id);\n}\n\n/** Register bundled profiles with the global loop registry. */\nexport function registerBuiltinLoopProfiles(): void {\n const registry = getLoopRegistry();\n for (const profile of getBuiltinLoopProfiles()) {\n registry.registerProfile(profile);\n }\n}\n","import { getActivePluginRegistry } from '../tools/pluginRegistry.js';\nimport type { PromptConcatHooks, PromptConcatTool } from '../tools/types.js';\n\nimport type { PromptNode } from './types.js';\n\nexport const FULL_REPLACEMENT_PLUGIN_TOOL_ID = 'fullReplacement';\nexport const DYNAMIC_POSITION_PLUGIN_TOOL_ID = 'dynamicPosition';\n\nfunction registerFullReplacement(reg: Map<string, PromptConcatTool>): void {\n if (reg.has(FULL_REPLACEMENT_PLUGIN_TOOL_ID)) return;\n reg.set(FULL_REPLACEMENT_PLUGIN_TOOL_ID, (hooks: PromptConcatHooks) => {\n hooks.processPrompts.tapAsync(\n 'fullReplacementLite',\n (context: { messages: unknown[] }, callback) => {\n const msgs = context.messages;\n if (!Array.isArray(msgs)) {\n callback();\n return;\n }\n const maxChars = Number(process.env.MEMELOOP_FULL_REPLACEMENT_MAX_CHARS ?? 48_000);\n if (!Number.isFinite(maxChars) || maxChars <= 0) {\n callback();\n return;\n }\n let total = 0;\n const kept: unknown[] = [];\n for (let index = msgs.length - 1; index >= 0; index--) {\n const m = msgs[index] as { content?: unknown };\n const c = typeof m?.content === 'string'\n ? m.content\n : m?.content != null\n ? JSON.stringify(m.content)\n : '';\n total += c.length;\n if (total > maxChars) break;\n kept.push(m);\n }\n kept.reverse();\n context.messages = kept;\n callback();\n },\n );\n });\n}\n\n/**\n * TidGi `dynamicPosition` 极简版:根级 `prompt` 若带 `dynamicPosition: \"deferToEnd\"`,\n * 在用户轮次 ≥2 时将该节点移到同级列表末尾(多轮后再强调尾部 system/user 块)。\n */\nfunction registerDynamicPosition(reg: Map<string, PromptConcatTool>): void {\n if (reg.has(DYNAMIC_POSITION_PLUGIN_TOOL_ID)) return;\n reg.set(DYNAMIC_POSITION_PLUGIN_TOOL_ID, (hooks: PromptConcatHooks) => {\n hooks.processPrompts.tapAsync(\n 'dynamicPositionLite',\n (context: { messages: unknown[]; prompts?: PromptNode[] }, callback) => {\n const prompts = context.prompts;\n const messages = context.messages;\n if (!Array.isArray(prompts) || prompts.length < 2 || !Array.isArray(messages)) {\n callback();\n return;\n }\n const userTurns = messages.filter((m) => (m as { role?: string })?.role === 'user').length;\n if (userTurns < 2) {\n callback();\n return;\n }\n const deferred: PromptNode[] = [];\n const rest: PromptNode[] = [];\n for (const n of prompts) {\n if (n?.dynamicPosition === 'deferToEnd') deferred.push(n);\n else rest.push(n);\n }\n if (deferred.length === 0) {\n callback();\n return;\n }\n context.prompts = [...rest, ...deferred] as typeof context.prompts;\n callback();\n },\n );\n });\n}\n\n/**\n * 注册内置 prompt 插件(fullReplacement、dynamicPosition)。\n * @param target 若传入(如节点 `ToolRegistry` 上的 Map),只写入该表;否则写入活动注册表(全局或 ALS)。\n */\nexport function registerBuiltinPromptPlugins(target?: Map<string, PromptConcatTool>): void {\n const reg = target ?? getActivePluginRegistry();\n registerFullReplacement(reg);\n registerDynamicPosition(reg);\n}\n","import type { ChatMessage } from './conversation/index.js';\nimport type { ConversationMeta } from './sync/protocol.js';\n\nimport { registerBuiltinLoops } from './loopAPI/plugins/builtinLoopsPlugin.js';\nimport { registerBuiltinToolPlugins } from './loopAPI/plugins/builtinToolsPlugin.js';\nimport { getLoopRegistry } from './loopAPI/registry.js';\nimport type { AgentLoopGenerator, AgentLoopInput, AgentLoopRuntime, LoopProfile } from './loopAPI/types.js';\nimport { getBuiltinLoopProfile } from './loopProfiles/loadBuiltins.js';\nimport { registerBuiltinPromptPlugins } from './promptUtilities/builtinPromptPlugins.js';\nimport { nextLamportClockForConversation } from './storage/nextLamport.js';\nimport type { AgentFrameworkContext } from './types.js';\n\nexport interface CreateAgentOptions {\n definitionId: string;\n initialMessage?: string;\n}\n\nexport interface SendMessageOptions {\n conversationId: string;\n message: string;\n definitionId?: string;\n userMessage?: AgentLoopInput['userMessage'];\n resumeSession?: ChatMessage[];\n}\n\nexport interface MemeLoopRuntime {\n createAgent(options: CreateAgentOptions): Promise<{ conversationId: string }>;\n sendMessage(options: SendMessageOptions): Promise<void>;\n cancelAgent(conversationId: string): Promise<void>;\n subscribeToUpdates(conversationId: string, listener: (update: unknown) => void): () => void;\n}\n\nexport interface CreateAgentLoopRunnerOptions {\n definitionId: string;\n conversationId?: string;\n}\n\nasync function drainAgentLoop(\n gen: AgentLoopGenerator,\n conversationId: string,\n notify: (conversationId: string, update: unknown) => void,\n): Promise<void> {\n try {\n for await (const step of gen) {\n notify(conversationId, { type: 'agent-step', step });\n }\n notify(conversationId, { type: 'agent-done' });\n } catch (error) {\n notify(conversationId, {\n type: 'agent-error',\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nfunction inferDefinitionIdFromConversationId(conversationId: string): string {\n const parts = conversationId.split(':');\n if (parts.length >= 2) return parts.slice(0, -1).join(':');\n return conversationId;\n}\n\nasync function resolveDefinitionId(\n context: AgentFrameworkContext,\n conversationId: string,\n): Promise<string> {\n try {\n const meta = await context.storage.getConversationMeta(conversationId);\n if (meta?.definitionId) return meta.definitionId;\n } catch {\n /* optional for old storage adapters */\n }\n return inferDefinitionIdFromConversationId(conversationId);\n}\n\nasync function resolveLoopProfile(\n context: AgentFrameworkContext,\n definitionId: string,\n): Promise<LoopProfile | null> {\n const definition = (context.resolveAgentDefinition ? await context.resolveAgentDefinition(definitionId) : null) ??\n (await context.storage.getAgentDefinition(definitionId)) ??\n getBuiltinLoopProfile(definitionId) ??\n null;\n if (!definition) return null;\n return definition as unknown as LoopProfile;\n}\n\nasync function createProfileRunner(\n context: AgentFrameworkContext,\n definitionId: string,\n runtime?: Partial<AgentLoopRuntime>,\n): Promise<((input: AgentLoopInput) => AgentLoopGenerator) | null> {\n const profile = await resolveLoopProfile(context, definitionId);\n if (!profile) return null;\n\n registerBuiltinLoops();\n registerBuiltinToolPlugins();\n registerBuiltinPromptPlugins(context.tools.getPromptPlugins?.());\n\n const runnerContext = {\n ...context,\n runtime,\n scriptPolicy: context.loopScriptPolicy,\n toolRegistry: context.tools,\n } as { [key: string]: unknown };\n return getLoopRegistry().createRunnerForProfile(profile, runnerContext);\n}\n\nfunction createScriptRuntime(\n context: AgentFrameworkContext,\n cancellation: Set<string>,\n scriptState: Map<string, unknown>,\n conversationId: string,\n parentConversationId?: string,\n): Partial<AgentLoopRuntime> {\n const stateKey = (key: string): string => `${conversationId}:${key}`;\n return {\n runChildAgent: async function*(input) {\n const childRuntime = createScriptRuntime(\n context,\n cancellation,\n scriptState,\n input.conversationId,\n conversationId,\n );\n const run = await createProfileRunner(context, input.profileId, childRuntime);\n if (!run) {\n yield {\n type: 'message',\n data: `Child agent profile not found: ${input.profileId}`,\n };\n return;\n }\n yield* run({ conversationId: input.conversationId, message: input.prompt });\n },\n log: (event, data) => context.logger?.debug?.(event, data),\n emit: () => undefined,\n signal: {\n get cancelled() {\n return cancellation.has(conversationId) || (parentConversationId ? cancellation.has(parentConversationId) : false);\n },\n },\n state: {\n get: async <T>(key: string) => scriptState.get(stateKey(key)) as T | undefined,\n set: async (key, value) => {\n scriptState.set(stateKey(key), value);\n },\n update: async (key, updater) => {\n const fullKey = stateKey(key);\n scriptState.set(fullKey, updater(scriptState.get(fullKey)));\n },\n },\n checkpoint: async (key, result) => {\n scriptState.set(stateKey(`checkpoint:${key}`), result);\n },\n };\n}\n\nexport async function createAgentLoopRunner(\n context: AgentFrameworkContext,\n options: CreateAgentLoopRunnerOptions,\n): Promise<((input: AgentLoopInput) => AgentLoopGenerator) | null> {\n const cancellation = context.conversationCancellation ?? new Set<string>();\n context.conversationCancellation ??= cancellation;\n const scriptState = new Map<string, unknown>();\n const conversationId = options.conversationId ?? options.definitionId;\n return createProfileRunner(\n context,\n options.definitionId,\n createScriptRuntime(context, cancellation, scriptState, conversationId),\n );\n}\n\nexport function createMemeLoopRuntime(context: AgentFrameworkContext): MemeLoopRuntime {\n const listeners = new Map<string, Set<(update: unknown) => void>>();\n const cancellation = context.conversationCancellation ?? new Set<string>();\n const scriptState = new Map<string, unknown>();\n context.conversationCancellation ??= cancellation;\n\n function notify(conversationId: string, update: unknown) {\n const set = listeners.get(conversationId);\n if (!set) return;\n for (const listener of set) {\n listener(update);\n }\n }\n\n async function runAgentLoop(input: AgentLoopInput, definitionId: string): Promise<boolean> {\n const run = context.runAgentToolLoop ?? await createProfileRunner(\n context,\n definitionId,\n createScriptRuntime(context, cancellation, scriptState, input.conversationId),\n );\n if (!run) return false;\n void drainAgentLoop(run(input), input.conversationId, notify);\n return true;\n }\n\n async function* runChildAgent(input: Parameters<NonNullable<AgentFrameworkContext['runChildAgent']>>[0]): AgentLoopGenerator {\n const run = await createProfileRunner(\n context,\n input.profileId,\n createScriptRuntime(context, cancellation, scriptState, input.conversationId),\n );\n if (!run) {\n yield {\n type: 'message',\n data: `Child agent profile not found: ${input.profileId}`,\n };\n return;\n }\n yield* run({ conversationId: input.conversationId, message: input.prompt });\n }\n\n context.runChildAgent ??= runChildAgent;\n\n return {\n async createAgent(options) {\n const now = Date.now();\n const conversationId = `${options.definitionId}:${now.toString(36)}`;\n cancellation?.delete(conversationId);\n\n const meta: ConversationMeta = {\n conversationId,\n title: options.definitionId,\n lastMessagePreview: context.runAgentToolLoop ? '' : options.initialMessage ?? '',\n lastMessageTimestamp: now,\n messageCount: context.runAgentToolLoop || !options.initialMessage ? 0 : 1,\n originNodeId: 'local',\n definitionId: options.definitionId,\n isUserInitiated: true,\n };\n await context.storage.upsertConversationMetadata(meta);\n\n if (options.initialMessage) {\n const started = await runAgentLoop(\n { conversationId, message: options.initialMessage },\n options.definitionId,\n );\n if (started) {\n notify(conversationId, { type: 'created', conversationId });\n return { conversationId };\n }\n }\n\n if (options.initialMessage) {\n const message: ChatMessage = {\n messageId: `${conversationId}:m1`,\n conversationId,\n originNodeId: meta.originNodeId,\n timestamp: now,\n lamportClock: 1,\n role: 'user',\n content: options.initialMessage,\n };\n await context.storage.appendMessage(message);\n }\n\n notify(conversationId, { type: 'created', conversationId });\n return { conversationId };\n },\n async sendMessage(options) {\n cancellation?.delete(options.conversationId);\n const definitionId = options.definitionId ?? await resolveDefinitionId(context, options.conversationId);\n const started = await runAgentLoop(\n {\n conversationId: options.conversationId,\n message: options.message,\n userMessage: options.userMessage,\n resumeSession: options.resumeSession,\n },\n definitionId,\n );\n if (started) {\n notify(options.conversationId, { type: 'message-queued' });\n return;\n }\n\n if (options.resumeSession && options.resumeSession.length > 0) {\n await context.storage.insertMessagesIfAbsent(options.resumeSession);\n }\n\n const now = Date.now();\n const lamportClock = await nextLamportClockForConversation(\n context.storage,\n options.conversationId,\n );\n const hostUserMessage = options.userMessage;\n const message: ChatMessage = {\n ...hostUserMessage,\n messageId: hostUserMessage?.messageId ?? `${options.conversationId}:${now.toString(36)}`,\n conversationId: options.conversationId,\n originNodeId: hostUserMessage?.originNodeId ?? 'local',\n timestamp: hostUserMessage?.timestamp ?? now,\n lamportClock: hostUserMessage?.lamportClock ?? lamportClock,\n role: 'user',\n content: hostUserMessage?.content ?? options.message,\n };\n await context.storage.appendMessage(message);\n notify(options.conversationId, { type: 'message-queued' });\n },\n async cancelAgent(conversationId) {\n cancellation?.add(conversationId);\n notify(conversationId, { type: 'cancelled' });\n },\n subscribeToUpdates(conversationId, listener) {\n const set = listeners.get(conversationId) ?? new Set();\n set.add(listener);\n listeners.set(conversationId, set);\n return () => {\n const current = listeners.get(conversationId);\n if (!current) return;\n current.delete(listener);\n if (current.size === 0) {\n listeners.delete(conversationId);\n }\n };\n },\n };\n}\n","/**\n * Task category system for routing tasks to appropriate agent configurations.\n * Each category maps to a model, temperature, and description for delegation decisions.\n */\n\nexport type TaskCategory =\n | 'visual-engineering'\n | 'ultrabrain'\n | 'artistry'\n | 'quick'\n | 'unspecified-low'\n | 'unspecified-high'\n | 'writing';\n\nexport interface CategoryConfig {\n /** Model identifier (e.g., \"default\", \"gpt-4o\", \"claude-opus\") */\n model: string;\n /** LLM temperature (0.0 = deterministic, 1.0 = creative) */\n temperature: number;\n /** Human-readable description of the category's purpose */\n description: string;\n}\n\nconst CATEGORY_CONFIGS: Record<TaskCategory, CategoryConfig> = {\n 'visual-engineering': {\n model: 'default',\n temperature: 0.3,\n description: 'UI/UX visual engineering tasks requiring precise rendering and layout',\n },\n ultrabrain: {\n model: 'default',\n temperature: 0.1,\n description: 'Deep logical reasoning, architecture decisions, and complex problem-solving',\n },\n artistry: {\n model: 'default',\n temperature: 0.8,\n description: 'Creative writing, design, and artistic generation tasks',\n },\n quick: {\n model: 'default',\n temperature: 0.2,\n description: 'Fast, straightforward tasks with minimal deliberation needed',\n },\n 'unspecified-low': {\n model: 'default',\n temperature: 0.5,\n description: 'Unclassified tasks of moderate complexity and effort',\n },\n 'unspecified-high': {\n model: 'default',\n temperature: 0.4,\n description: 'Unclassified tasks requiring substantial effort across multiple systems',\n },\n writing: {\n model: 'default',\n temperature: 0.7,\n description: 'Documentation, prose, technical writing, and content generation',\n },\n};\n\n/**\n * Get the configuration for a task category.\n * @throws {Error} if the category is unknown\n */\nexport function getCategoryConfig(category: TaskCategory): CategoryConfig {\n const config = CATEGORY_CONFIGS[category];\n if (!config) {\n throw new Error(`Unknown task category: ${category}`);\n }\n return { ...config };\n}\n\n/**\n * Type guard: check if a string is a valid TaskCategory.\n */\nexport function isTaskCategory(value: string): value is TaskCategory {\n return value in CATEGORY_CONFIGS;\n}\n\n/** All registered category identifiers (read-only). */\nexport const ALL_CATEGORIES = Object.keys(CATEGORY_CONFIGS) as TaskCategory[];\n\n/**\n * Resolve a category string (or fallback to \"unspecified-low\").\n * Never throws; always returns a valid config.\n */\nexport function resolveCategory(category: string): CategoryConfig {\n if (isTaskCategory(category)) {\n return getCategoryConfig(category);\n }\n return getCategoryConfig('unspecified-low');\n}\n","/**\n * AI SDK-based LLM provider — wraps @ai-sdk/openai for any OpenAI-compatible API.\n *\n * Zero custom HTTP/SSE code. Streaming, tool calls, and error handling\n * are delegated to the Vercel AI SDK (`ai` + `@ai-sdk/openai`).\n */\n\nimport { createOpenAI } from '@ai-sdk/openai';\nimport type { LanguageModelV1 } from 'ai';\nimport { generateText, streamText } from 'ai';\n\nimport type { ILLMProvider } from '../types.js';\n\n// ─── Config ────────────────────────────────────────────────────────────\n\nexport interface FetchLLMProviderConfig {\n /** Display name, e.g. \"cloud-proxy\" or \"openai\". */\n name: string;\n /** Base URL of the OpenAI-compatible API (e.g. \"https://api.openai.com/v1\"). */\n baseUrl: string;\n /** Bearer token. Omit for unauthenticated endpoints. */\n apiKey?: string;\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────────\n\nfunction normalizeBaseUrl(raw: string): string {\n const trimmed = raw.trim().replace(/\\/+$/, '');\n if (!trimmed) throw new Error('Provider baseUrl is required');\n // Strip /chat/completions suffix if present — AI SDK appends its own paths\n return trimmed.replace(/\\/chat\\/completions$/i, '');\n}\n\n// ─── Factory ───────────────────────────────────────────────────────────\n\n/**\n * Create an `ILLMProvider` backed by the Vercel AI SDK.\n *\n * - `provider.model` — the `LanguageModelV1` instance (usable with `generateText` / `streamText`)\n * - `provider.chat(request)` — streams text deltas via `streamText`, falls back to `generateText` for non-streaming\n *\n * @example\n * ```ts\n * const provider = createFetchLLMProvider({\n * name: 'cloud-proxy',\n * baseUrl: 'https://cloud.example.com/v1',\n * apiKey: 'sk-...',\n * });\n * ```\n */\nexport function createFetchLLMProvider(config: FetchLLMProviderConfig): ILLMProvider {\n const baseURL = normalizeBaseUrl(config.baseUrl);\n\n const sdk = createOpenAI({\n baseURL,\n apiKey: config.apiKey,\n });\n\n return {\n name: config.name,\n model: sdk as unknown as LanguageModelV1,\n async chat(request: unknown) {\n const body = (typeof request === 'object' && request !== null ? request : {}) as {\n messages?: Array<{ role: string; content: string }>;\n model?: string;\n stream?: boolean;\n max_tokens?: number;\n temperature?: number;\n };\n\n const messages = (body.messages ?? []).map((msg) => ({\n role: msg.role as 'system' | 'user' | 'assistant',\n content: msg.content,\n }));\n\n const model = sdk(body.model ?? 'gpt-4o-mini');\n\n if (body.stream !== false) {\n const result = streamText({ model, messages });\n return (async function*() {\n for await (const chunk of result.textStream) {\n yield chunk;\n }\n })();\n }\n\n const result = await generateText({ model, messages });\n return result.text;\n },\n };\n}\n","import type { ILLMProvider } from '../types.js';\n\nexport interface ProviderConfig {\n name: string;\n baseUrl?: string;\n apiKey?: string;\n}\n\nexport interface RegisteredProvider {\n provider: ILLMProvider;\n config: ProviderConfig;\n}\n\nexport class ProviderRegistry {\n private providers = new Map<string, RegisteredProvider>();\n\n register(provider: ILLMProvider, config?: Omit<ProviderConfig, 'name'>): void {\n this.providers.set(provider.name, {\n provider,\n config: {\n name: provider.name,\n baseUrl: config?.baseUrl,\n apiKey: config?.apiKey,\n },\n });\n }\n\n unregister(name: string): void {\n this.providers.delete(name);\n }\n\n get(name: string): ILLMProvider | undefined {\n return this.providers.get(name)?.provider;\n }\n\n getConfig(name: string): ProviderConfig | undefined {\n return this.providers.get(name)?.config;\n }\n\n upsertConfig(config: ProviderConfig): void {\n const existing = this.providers.get(config.name);\n if (!existing) {\n throw new Error(`Provider not found: ${config.name}`);\n }\n this.providers.set(config.name, {\n provider: existing.provider,\n config: {\n name: config.name,\n baseUrl: config.baseUrl,\n apiKey: config.apiKey,\n },\n });\n }\n\n list(): string[] {\n return Array.from(this.providers.keys()).sort();\n }\n\n listConfigs(): ProviderConfig[] {\n return this.list().map((name) => {\n const config = this.providers.get(name)?.config;\n if (!config) {\n throw new Error(`Provider config missing: ${name}`);\n }\n return { ...config };\n });\n }\n\n resolve(modelId: string): { provider: ILLMProvider; providerName: string; modelName?: string } {\n const [providerName, ...rest] = modelId.split('/');\n const registered = this.providers.get(providerName);\n if (!registered) {\n throw new Error(`Provider not found: ${providerName}`);\n }\n return {\n provider: registered.provider,\n providerName,\n modelName: rest.length > 0 ? rest.join('/') : undefined,\n };\n }\n}\n","/**\n * Domain factories for creating canonical ChatMessage and AgentInstance objects.\n *\n * These factories ensure that every host (Desktop, Mobile, CLI, Cloud)\n * constructs messages and instances with the same required fields,\n * default values, and clock behavior.\n *\n * Hosts that need a different originNodeId, message ID scheme, or lamport\n * clock source should pass those values explicitly rather than creating\n * their own factory.\n */\nimport type { AgentDefinition } from '../agent/types.js';\nimport type { AgentFrameworkConfig } from '../promptUtilities/types.js';\nimport type { AgentInstance, AgentInstanceLatestStatus } from '../types.js';\nimport type { ChatMessage, ChatRole } from './types.js';\n\n/**\n * Create a canonical ChatMessage with required defaults.\n *\n * @param input.messageId - Unique message identifier. Use nanoid or equivalent.\n * @param input.conversationId - The conversation/agent-instance this message belongs to.\n * @param input.role - Message role (user, assistant, tool, agent, error).\n * @param input.content - Message text content.\n * @param input.originNodeId - Node that originated this message. Core default is \"unknown\";\n * hosts should pass their own identifier (e.g. \"tidgi-desktop\", \"memeloop-cli\").\n * @param input.contentType - MIME type override (default \"text/plain\").\n * @param input.metadata - Optional metadata map.\n * @param input.duration - Processing duration in ms.\n * @param input.lamportClock - Lamport clock value. Defaults to `Date.now()`.\n * @param input.toolCalls - Tool calls associated with assistant messages.\n * @param input.reasoning_content - Reasoning/thinking content.\n * @param input.hidden - Whether the message is hidden from the UI.\n * @param input.detailRef - Reference to large tool output stored elsewhere.\n */\nexport function createChatMessage(input: {\n messageId: string;\n conversationId: string;\n role: ChatRole;\n content: string;\n originNodeId?: string;\n contentType?: string;\n metadata?: Record<string, unknown>;\n duration?: number | null;\n lamportClock?: number;\n toolCalls?: ChatMessage['toolCalls'];\n reasoning_content?: string;\n hidden?: boolean;\n attachments?: ChatMessage['attachments'];\n detailRef?: ChatMessage['detailRef'];\n}): ChatMessage {\n const now = Date.now();\n return {\n messageId: input.messageId,\n conversationId: input.conversationId,\n originNodeId: input.originNodeId ?? 'unknown',\n timestamp: now,\n lamportClock: input.lamportClock ?? now,\n role: input.role,\n content: input.content,\n contentType: input.contentType ?? 'text/plain',\n metadata: input.metadata,\n duration: input.duration,\n toolCalls: input.toolCalls,\n reasoning_content: input.reasoning_content,\n hidden: input.hidden,\n attachments: input.attachments,\n detailRef: input.detailRef,\n };\n}\n\n/**\n * Default status applied to newly created agent instances.\n */\nconst DEFAULT_INSTANCE_STATUS: AgentInstanceLatestStatus = {\n state: 'completed',\n modified: new Date(),\n};\n\n/**\n * Create an AgentInstance from an AgentDefinition.\n *\n * The returned instance has an empty message list, a default \"completed\"\n * status, and copies all definition-level fields as instance defaults.\n *\n * @param definition - The AgentDefinition to base the instance on.\n * @param overrides - Optional overrides for instance-specific fields:\n * - `id`: Instance ID (default: nanoid-equivalent, must be provided by host)\n * - `name`: Display name (default: definition.name)\n * - `status`: Initial status\n * - `volatile`: Whether the instance is ephemeral\n * - `closed`: Whether closed on creation\n * - `isDelegatedAgentRun`, `parentAgentRunId`: Delegated agent relationship\n * - `agentFrameworkConfig`: Per-instance framework config override\n */\nexport function createAgentInstanceFromDefinition(\n definition: AgentDefinition,\n overrides: {\n id: string;\n name?: string;\n status?: AgentInstanceLatestStatus;\n volatile?: boolean;\n closed?: boolean;\n isDelegatedAgentRun?: boolean;\n parentAgentRunId?: string;\n agentFrameworkConfig?: AgentFrameworkConfig;\n },\n): AgentInstance {\n const now = new Date();\n return {\n ...definition,\n id: overrides.id,\n agentDefId: definition.id,\n name: overrides.name ?? definition.name,\n status: overrides.status ?? DEFAULT_INSTANCE_STATUS,\n messages: [],\n created: now,\n modified: now,\n closed: overrides.closed ?? false,\n volatile: overrides.volatile ?? false,\n isDelegatedAgentRun: overrides.isDelegatedAgentRun,\n parentAgentRunId: overrides.parentAgentRunId,\n agentFrameworkConfig: overrides.agentFrameworkConfig,\n };\n}\n","import type { HookType } from '../loopAPI/hooks/types.js';\nimport type { LoadedPlugin, PluginManifest, PluginModule } from './types.js';\n\nconst loadedPlugins = new Map<string, LoadedPlugin>();\n\nconst hookTypes = new Set<string>([\n 'PreToolUse',\n 'PostToolUse',\n 'UserPromptSubmit',\n 'ContextCompaction',\n 'AgentStart',\n 'AgentStop',\n]);\n\nfunction isHookType(value: unknown): value is HookType {\n return typeof value === 'string' && hookTypes.has(value);\n}\n\nexport function validatePluginManifest(object: unknown): PluginManifest | null {\n if (!object || typeof object !== 'object') return null;\n const manifest = object as Record<string, unknown>;\n if (\n typeof manifest.name !== 'string' ||\n manifest.name.trim().length === 0 ||\n typeof manifest.version !== 'string' ||\n manifest.version.trim().length === 0\n ) {\n return null;\n }\n return {\n name: manifest.name.trim(),\n version: manifest.version.trim(),\n description: typeof manifest.description === 'string' ? manifest.description : '',\n exports: validateExports(manifest.exports),\n author: typeof manifest.author === 'string' ? manifest.author : undefined,\n minMemeloopVersion: typeof manifest.minMemeloopVersion === 'string' ? manifest.minMemeloopVersion : undefined,\n };\n}\n\nfunction validateExports(object: unknown): PluginManifest['exports'] {\n if (!object || typeof object !== 'object') return undefined;\n const exportsRecord = object as Record<string, unknown>;\n return {\n tools: Array.isArray(exportsRecord.tools)\n ? exportsRecord.tools.filter((tool): tool is string => typeof tool === 'string')\n : undefined,\n hooks: Array.isArray(exportsRecord.hooks) ? exportsRecord.hooks.filter(isHookType) : undefined,\n };\n}\n\nexport interface LoadPluginModuleOptions {\n manifest: PluginManifest;\n module: PluginModule;\n api?: unknown;\n source?: string;\n}\n\nexport async function loadPluginModule(\n options: LoadPluginModuleOptions,\n): Promise<LoadedPlugin | null> {\n const { manifest, module, api, source = '' } = options;\n const validManifest = validatePluginManifest(manifest);\n if (!validManifest) return null;\n\n if (loadedPlugins.has(validManifest.name)) {\n return loadedPlugins.get(validManifest.name) ?? null;\n }\n\n if (!module || typeof module.activate !== 'function') {\n return null;\n }\n\n const cleanup = await module.activate(api as never);\n const loaded: LoadedPlugin = {\n manifest: validManifest,\n source,\n module,\n cleanup: typeof cleanup === 'function' ? cleanup : undefined,\n loadedAt: new Date(),\n };\n\n loadedPlugins.set(validManifest.name, loaded);\n return loaded;\n}\n\nexport async function loadPluginModules(\n plugins: LoadPluginModuleOptions[],\n): Promise<LoadedPlugin[]> {\n const loaded: LoadedPlugin[] = [];\n for (const plugin of plugins) {\n const result = await loadPluginModule(plugin);\n if (result) loaded.push(result);\n }\n return loaded;\n}\n\nexport function unloadPlugin(name: string): boolean {\n const loaded = loadedPlugins.get(name);\n if (!loaded) return false;\n\n try {\n loaded.cleanup?.();\n } catch (error) {\n console.warn(`[plugin] Error during cleanup of \"${name}\":`, error);\n }\n\n loadedPlugins.delete(name);\n return true;\n}\n\nexport function listPlugins(): LoadedPlugin[] {\n return Array.from(loadedPlugins.values());\n}\n\nexport function getLoadedPlugin(name: string): LoadedPlugin | undefined {\n return loadedPlugins.get(name);\n}\n\nexport function isPluginLoaded(name: string): boolean {\n return loadedPlugins.has(name);\n}\n\nexport function unloadAllPlugins(): void {\n for (const name of loadedPlugins.keys()) {\n unloadPlugin(name);\n }\n}\n","/**\n * Plugin registry: bridges plugin exports to memeloop's tool and hook registries.\n *\n * Provides a `createPluginAPI()` factory that plugins call during `activate()`\n * to register their tools and hooks with the host runtime.\n *\n * Converted from module-level singletons to an instance class for test isolation\n * and multi-runtime support.\n */\n\nimport { registerHook } from '../loopAPI/hooks/registry.js';\nimport type { HookHandler, HookType } from '../loopAPI/hooks/types.js';\nimport { registerToolParameterSchema } from '../tools/schemaRegistry.js';\nimport type { PluginAPI } from './types.js';\n\n/** Plugin API factory options. */\nexport interface PluginAPIOptions {\n toolRegistry?: {\n registerTool(id: string, impl: unknown): void;\n };\n logger?: PluginAPI['logger'];\n}\n\n/**\n * Track which tools/plugins belong to each plugin so we can clean up on unload.\n */\ninterface PluginRegistration {\n pluginName: string;\n tools: string[];\n hooks: Array<{ type: HookType; name: string }>;\n}\n\n/**\n * Instance-level plugin registration manager.\n */\nexport class PluginRegistryManager {\n private readonly pluginRegistrations = new Map<string, PluginRegistration>();\n\n private ensureRegistration(pluginName: string): PluginRegistration {\n const existing = this.pluginRegistrations.get(pluginName);\n if (existing) return existing;\n const reg: PluginRegistration = {\n pluginName,\n tools: [],\n hooks: [],\n };\n this.pluginRegistrations.set(pluginName, reg);\n return reg;\n }\n\n /**\n * Create a PluginAPI instance that plugins use to register their capabilities.\n */\n createPluginAPI(options: PluginAPIOptions = {}): PluginAPI {\n const toolRegistry = options.toolRegistry;\n const logger = options.logger ?? {\n debug: (...arguments_: unknown[]) => {\n console.debug('[plugin]', ...arguments_);\n },\n info: (...arguments_: unknown[]) => {\n console.info('[plugin]', ...arguments_);\n },\n warn: (...arguments_: unknown[]) => {\n console.warn('[plugin]', ...arguments_);\n },\n error: (...arguments_: unknown[]) => {\n console.error('[plugin]', ...arguments_);\n },\n };\n\n return {\n logger,\n\n registerTool(toolId: string, impl: (...arguments_: unknown[]) => unknown, schema?: unknown) {\n toolRegistry?.registerTool(toolId, impl);\n if (schema) {\n registerToolParameterSchema(toolId, schema as object, {\n displayName: toolId,\n description: `Plugin tool: ${toolId}`,\n });\n }\n },\n\n registerHook(type: HookType, handler: HookHandler, name?: string) {\n const hookName = name ?? `plugin-hook:${type}:${Date.now().toString(36)}`;\n registerHook(type, handler, hookName);\n },\n };\n }\n\n registerPluginTools(\n pluginName: string,\n tools: Array<readonly [string, (...arguments_: unknown[]) => unknown, unknown?]>,\n ): void {\n const reg = this.ensureRegistration(pluginName);\n for (const [toolId, , schema] of tools) {\n if (schema) {\n registerToolParameterSchema(toolId, schema as object, {\n displayName: toolId,\n description: `Plugin tool: ${toolId}`,\n });\n }\n reg.tools.push(toolId);\n }\n }\n\n registerPluginHooks(\n pluginName: string,\n hooks: Array<readonly [HookType, HookHandler, string?]>,\n ): void {\n const reg = this.ensureRegistration(pluginName);\n for (const [type, handler, name] of hooks) {\n const hookName = name ?? `plugin-hook:${pluginName}:${type}:${reg.hooks.length}`;\n registerHook(type, handler, hookName);\n reg.hooks.push({ type, name: hookName });\n }\n }\n\n getPluginRegistrations(pluginName: string): PluginRegistration | undefined {\n return this.pluginRegistrations.get(pluginName);\n }\n\n clearPluginRegistrations(): void {\n this.pluginRegistrations.clear();\n }\n}\n\n// ─── Default global instance + backward-compatible function exports ───\n\nconst defaultPluginRegistryManager = new PluginRegistryManager();\n\nexport function getDefaultPluginRegistryManager(): PluginRegistryManager {\n return defaultPluginRegistryManager;\n}\n\nexport function createPluginAPI(options: PluginAPIOptions = {}): PluginAPI {\n return defaultPluginRegistryManager.createPluginAPI(options);\n}\n\nexport function registerPluginTools(\n pluginName: string,\n tools: Array<readonly [string, (...arguments_: unknown[]) => unknown, unknown?]>,\n): void {\n defaultPluginRegistryManager.registerPluginTools(pluginName, tools);\n}\n\nexport function registerPluginHooks(\n pluginName: string,\n hooks: Array<readonly [HookType, HookHandler, string?]>,\n): void {\n defaultPluginRegistryManager.registerPluginHooks(pluginName, hooks);\n}\n\nexport function getPluginRegistrations(pluginName: string): PluginRegistration | undefined {\n return defaultPluginRegistryManager.getPluginRegistrations(pluginName);\n}\n\nexport function clearPluginRegistrations(): void {\n defaultPluginRegistryManager.clearPluginRegistrations();\n}\n"],"mappings":";AAEO,IAAM,oCAAoC;AAE1C,IAAM,kDAAkD;AAExD,IAAM,+BAAiE;AAAA,EAC5E,CAAC,iCAAiC,GAAG;AAAA,IACnC;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;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AO,KAAK,OAAO,aAAa,GAAG;AAAA,EAC/C;AACF;;;AC3HO,IAAM,wBAA0D;AAAA,EACrE,kBAAkB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AAAA,EACX,kBAAkB;AAAA,IAChB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AAAA,EACX,qBAAqB;AAAA,IACnB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AAAA,EACX,cAAc;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AAAA,EACX,cAAc;AAAA,IACZ;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF,EAAE,KAAK,IAAI;AACb;;;ACvaA,SAAS,YAAY,MAA2B;AAC9C,QAAM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B,IAAI,UAAU;AAAA,EAChD;AAAA,EAEA,2BAAiC;AAC/B,SAAK,oBAAoB,MAAM;AAAA,EACjC;AACF;AAIA,IAAM,+BAA+B,IAAI,sBAAsB;AAMxD,SAAS,gBAAgB,UAA4B,CAAC,GAAc;AACzE,SAAO,6BAA6B,gBAAgB,OAAO;AAC7D;AAEO,SAAS,oBACd,YACA,OACM;AACN,+BAA6B,oBAAoB,YAAY,KAAK;AACpE;AAEO,SAAS,oBACd,YACA,OACM;AACN,+BAA6B,oBAAoB,YAAY,KAAK;AACpE;AAEO,SAAS,uBAAuB,YAAoD;AACzF,SAAO,6BAA6B,uBAAuB,UAAU;AACvE;AAEO,SAAS,2BAAiC;AAC/C,+BAA6B,yBAAyB;AACxD;","names":["max","pending","isAsyncIterable","chunkToText","chunkToText","pending","isAsyncIterable","messageStep","drainEmittedSteps","z","z","TOOL_ID","TOOL_ID","nodeId","message","TOOL_ID","message","defaultRegistry","TOOL_ID","z","removed","result","logger"]}
|