memeloop 0.1.1 → 0.1.3
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/THIRD_PARTY_NOTICES.md +29 -0
- package/dist/{chunk-MAJWHAKR.js → chunk-5JEV7632.js} +2 -2
- package/dist/{chunk-KFS2EJT6.js → chunk-K5KZJNDP.js} +2 -2
- package/dist/{chunk-T7FSXWFR.js → chunk-LGUGYRR4.js} +4 -4
- package/dist/{chunk-T7FSXWFR.js.map → chunk-LGUGYRR4.js.map} +1 -1
- package/dist/{chunk-2C6BJZI3.js → chunk-P6L3444O.js} +3 -3
- package/dist/index.cjs +3 -3
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +5 -5
- package/dist/loop-api.cjs +3 -3
- package/dist/loop-api.cjs.map +1 -1
- package/dist/loop-api.js +4 -4
- package/dist/mobile.cjs +3 -3
- package/dist/mobile.cjs.map +1 -1
- package/dist/mobile.js +2 -2
- package/dist/model-catalog.cjs +246 -0
- package/dist/model-catalog.cjs.map +1 -0
- package/dist/model-catalog.d.cts +57 -0
- package/dist/model-catalog.d.ts +57 -0
- package/dist/model-catalog.js +213 -0
- package/dist/model-catalog.js.map +1 -0
- package/dist/{runtime-PGWR6FIV.js → runtime-UONPTAYK.js} +3 -3
- package/package.json +9 -2
- /package/dist/{chunk-MAJWHAKR.js.map → chunk-5JEV7632.js.map} +0 -0
- /package/dist/{chunk-KFS2EJT6.js.map → chunk-K5KZJNDP.js.map} +0 -0
- /package/dist/{chunk-2C6BJZI3.js.map → chunk-P6L3444O.js.map} +0 -0
- /package/dist/{runtime-PGWR6FIV.js.map → runtime-UONPTAYK.js.map} +0 -0
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/permission/engine.ts","../src/orchestration/security/admission.ts","../src/orchestration/drivers/unknownEffect.ts","../src/tools/pluginRegistry.ts","../src/promptUtilities/responsePatternUtility.ts","../src/storage/nextLamport.ts","../src/loopAPI/hooks/registry.ts","../src/loopAPI/agent-tool-loop/compaction.ts","../src/promptUtilities/promptConcat.ts","../src/tools/structuredToolResult.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/toolResultMessage.ts","../src/loopAPI/agent-tool-loop/modelMessages.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/directRunner.ts","../src/loopAPI/registry.ts","../src/loopProfiles/builtinProfileSources.ts","../src/loopProfiles/loadBuiltins.ts"],"sourcesContent":["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 { matchPattern } from '../../permission/engine.js';\nimport type { PermissionAction } from '../../permission/types.js';\n\nimport type { NodeTrustClass, SecurityProfileResource, ToolAdmissionAction, ToolAdmissionPolicy, ToolAdmissionRule, ToolOperationResource } from '../resources.js';\n\nexport type { NodeTrustClass, ToolAdmissionAction, ToolAdmissionPolicy, ToolAdmissionRule } from '../resources.js';\n\nexport interface ToolAdmissionDecision {\n action: ToolAdmissionAction;\n source: 'rule' | 'default';\n reason?: string;\n matchedRule?: ToolAdmissionRule;\n}\n\n/**\n * Default trusted admission posture per node trust class. Trusted nodes keep\n * the historical allow-by-default posture; restricted and quarantine nodes\n * deny everything unless an explicit rule allows it.\n */\nexport function defaultAdmissionPolicyForTrustClass(trustClass: NodeTrustClass): ToolAdmissionPolicy {\n switch (trustClass) {\n case 'restricted':\n case 'quarantine':\n return { defaultAction: 'deny', rules: [] };\n default:\n return { defaultAction: 'allow', rules: [] };\n }\n}\n\n/**\n * Resolve the effective trusted admission policy for a workload from its\n * SecurityProfile and the node's trust class. Profile rules are evaluated\n * first (they can allow specific tools on restricted nodes); the trust-class\n * default applies after. For restricted/quarantine the resolved default is\n * forced to `deny` — a profile cannot override it.\n */\nexport function resolveAdmissionPolicy(\n profile: Pick<SecurityProfileResource, 'spec'> | undefined,\n trustClass: NodeTrustClass,\n): ToolAdmissionPolicy {\n const base = defaultAdmissionPolicyForTrustClass(trustClass);\n const overlay = profile?.spec.toolAdmission;\n if (!overlay) return base;\n const defaultAction = trustClass === 'trusted' ? overlay.defaultAction ?? base.defaultAction : 'deny';\n return {\n defaultAction,\n rules: [...(overlay.rules ?? []), ...(base.rules ?? [])],\n };\n}\n\n/**\n * Model-facing implied permission default for a trust class. Used by the\n * AgentToolLoop permission gate when no explicit wildcard rule exists.\n */\nexport function defaultPermissionActionForTrustClass(trustClass: NodeTrustClass | undefined): PermissionAction {\n return trustClass === 'restricted' || trustClass === 'quarantine' ? 'deny' : 'allow';\n}\n\nexport function evaluateToolAdmission(\n policy: ToolAdmissionPolicy,\n operation: Pick<ToolOperationResource, 'spec'>,\n): ToolAdmissionDecision {\n const toolName = operation.spec.toolRef.name;\n const effect = operation.spec.effect;\n for (const rule of policy.rules ?? []) {\n if (!matchPattern(toolName, rule.toolPattern)) continue;\n if (rule.effects && !rule.effects.includes(effect)) continue;\n return {\n action: rule.action,\n source: 'rule',\n reason: rule.reason,\n matchedRule: rule,\n };\n }\n return { action: policy.defaultAction, source: 'default' };\n}\n","import type { OrchestrationCondition } from '../client.js';\nimport type { ToolOperationResource, ToolOperationStatus } from '../resources.js';\n\n/**\n * Condition type raised on a ToolOperation whose executor crashed or\n * disconnected after a side effect may have occurred. While this condition is\n * `True`, controllers must follow the recorded reconciliation decision instead\n * of blindly repeating the operation.\n */\nexport const TOOL_OPERATION_CONDITION_EFFECT_UNKNOWN = 'EffectUnknown';\n\n/**\n * Evidence gathered by driver/controller inspection after an executor crash or\n * disconnect. Evidence is produced by the trusted side (driver checkpoints,\n * verifier probes, artifact records), never by the possibly-failed executor's\n * own claim alone.\n */\nexport interface UnknownEffectEvidence {\n /**\n * The executor produced a result before the disconnect and only the\n * completion acknowledgement was lost. The caller is responsible for\n * attaching the observed result when applying the decision.\n */\n resultObserved?: boolean;\n /** Reference to independent verification evidence (artifact, verifier run). */\n evidenceRef?: string;\n /** ISO timestamp of the observed disconnect/crash. */\n disconnectedAt?: string;\n}\n\nexport type UnknownEffectAction = 'retry' | 'succeeded' | 'verification-required' | 'manual-intervention';\n\nexport interface UnknownEffectDecision {\n action: UnknownEffectAction;\n reason: string;\n}\n\nconst DEFAULT_MAX_ATTEMPTS = 3;\n\nfunction attemptsOf(operation: ToolOperationResource): number {\n return operation.status?.attempts ?? 0;\n}\n\nfunction maxAttemptsOf(operation: ToolOperationResource): number {\n return operation.spec.retry?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n}\n\n/**\n * Decide how to reconcile an operation whose effect is unknown. The decision\n * never blindly repeats destructive work:\n *\n * 1. An observed result means only the ack was lost → `succeeded`.\n * 2. `read` effects have no side effects → `retry` (within attempt budget).\n * 3. `retry.nonRetryable` operations are never repeated → `manual-intervention`.\n * 4. Operations with an `idempotencyKey` dedupe at the executor/store, so a\n * repeated delivery is safe → `retry` (within attempt budget).\n * 5. Everything else requires independent verification before any retry →\n * `verification-required`.\n */\nexport function reconcileUnknownEffect(\n operation: ToolOperationResource,\n evidence: UnknownEffectEvidence,\n): UnknownEffectDecision {\n if (evidence.resultObserved) {\n return { action: 'succeeded', reason: 'result was observed before the disconnect; only the ack was lost' };\n }\n\n if (operation.spec.retry?.nonRetryable) {\n return { action: 'manual-intervention', reason: 'operation is marked nonRetryable and its effect is unknown' };\n }\n\n const attempts = attemptsOf(operation);\n const maxAttempts = maxAttemptsOf(operation);\n const withinBudget = attempts < maxAttempts;\n\n if (operation.spec.effect === 'read') {\n if (withinBudget) {\n return { action: 'retry', reason: `read effect has no side effects (attempt ${attempts + 1}/${maxAttempts})` };\n }\n return { action: 'verification-required', reason: `read retry budget exhausted (${attempts}/${maxAttempts})` };\n }\n\n if (operation.spec.idempotencyKey) {\n if (withinBudget) {\n return {\n action: 'retry',\n reason: `idempotencyKey deduplicates repeated delivery (attempt ${attempts + 1}/${maxAttempts})`,\n };\n }\n return {\n action: 'verification-required',\n reason: `idempotent retry budget exhausted (${attempts}/${maxAttempts}); verify before further attempts`,\n };\n }\n\n return {\n action: 'verification-required',\n reason: `effect '${operation.spec.effect}' without idempotencyKey must be verified before any retry`,\n };\n}\n\nfunction effectUnknownCondition(decision: UnknownEffectDecision, at: string): OrchestrationCondition {\n return {\n type: TOOL_OPERATION_CONDITION_EFFECT_UNKNOWN,\n status: 'True',\n reason: decision.action,\n message: decision.reason,\n lastTransitionTime: at,\n };\n}\n\n/**\n * Apply a reconciliation decision to an operation, producing the next status:\n *\n * - `retry` → back to `Pending` (requeue) with the EffectUnknown condition.\n * - `succeeded` → `Completed` (caller attaches the observed result separately).\n * - `verification-required` / `manual-intervention` → stays `Running` with the\n * EffectUnknown condition; the operation is not repeated until a verifier or\n * operator clears the condition.\n */\nexport function applyUnknownEffectDecision(\n operation: ToolOperationResource,\n decision: UnknownEffectDecision,\n at: string = new Date().toISOString(),\n): ToolOperationResource {\n const conditions = [\n ...(operation.status?.conditions ?? []).filter((c) => c.type !== TOOL_OPERATION_CONDITION_EFFECT_UNKNOWN),\n effectUnknownCondition(decision, at),\n ];\n\n const base: ToolOperationStatus = {\n ...operation.status,\n conditions,\n };\n\n if (decision.action === 'retry') {\n return { ...operation, status: { ...base, phase: 'Pending' } };\n }\n if (decision.action === 'succeeded') {\n return {\n ...operation,\n status: { ...base, phase: 'Completed', completedAt: at },\n };\n }\n return { ...operation, status: { ...base, phase: 'Running' } };\n}\n","import type { HookSlot, PromptConcatHooks, PromptConcatTool, TapAsyncHandler } 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: TapAsyncHandler[];\n} {\n const handlers: TapAsyncHandler[] = [];\n return {\n handlers,\n tapAsync(_name, function_) {\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?: TapAsyncHandler[];\n} = {};\n\nexport async function runProcessPromptsHooks<TContext>(\n _hooks: PromptConcatHooks,\n context: TContext,\n): Promise<TContext> {\n const slot = _hooks.processPrompts as {\n handlers?: TapAsyncHandler[];\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;\nexport const TOOL_PARAMETER_PARSE_ERROR_KEY = '__memeloopToolParameterParseError';\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 {\n [TOOL_PARAMETER_PARSE_ERROR_KEY]: `Invalid tool arguments JSON. Return one valid JSON object inside the tool tag. Received: ${\n trimmedText.substring(0, MAX_FALLBACK_INPUT_LENGTH)\n }`,\n };\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 { ConversationEventStore } from './ports.js';\n\n/**\n * 下一条消息的 Lamport 时钟:取会话内已有消息的最大 lamportClock + 1。\n * Depends only on the narrow ConversationEventStore port (plan 24.41).\n */\nexport async function nextLamportClockForConversation(\n storage: ConversationEventStore,\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';\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 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>;\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","/**\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","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 { AgentDefinition } from '../../agent/types.js';\nimport { type ChatMessage, getChatMessageParts, isToolResultPart } 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';\nimport { formatToolResultMessage } from './toolResultMessage.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\n if (role === 'tool') {\n const toolResults = getChatMessageParts(message).filter(isToolResultPart);\n if (toolResults.length > 0) {\n return {\n role,\n content: toolResults.map((part) =>\n formatToolResultMessage(\n part.toolName,\n (part.parameters && typeof part.parameters === 'object' ? part.parameters : {}) as Record<string, unknown>,\n part.result,\n part.isError === true,\n )\n ).join('\\n\\n'),\n };\n }\n }\n\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","import { createChatMessage, type DetailReference } from '../../conversation/index.js';\nimport type { AgentOrchestrationClient, OrchestrationResourceReference } from '../../orchestration/client.js';\nimport { reconcileUnknownEffect } from '../../orchestration/drivers/unknownEffect.js';\nimport { OrchestrationError } from '../../orchestration/errors.js';\nimport { createToolOperationManifest, TOOL_OPERATION_API_VERSION, TOOL_OPERATION_KIND, type ToolOperationResource } from '../../orchestration/resources.js';\nimport { TOOL_PARAMETER_PARSE_ERROR_KEY } from '../../promptUtilities/responsePatternUtility.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 type { PendingToolCall } from './toolUseGate.js';\n\ntype ToolRunRow = {\n text: string;\n isError: boolean;\n payload?: unknown;\n detailRef?: DetailReference;\n awaitSessionId?: string;\n};\n\ntype CompletedToolCall = ToolRunRow & { call: PendingToolCall };\n\nconst TOOL_OPERATION_DEFAULT_TIMEOUT_MS = 60_000;\nconst TOOL_OPERATION_POLL_INTERVAL_MS = 250;\n\nlet toolOperationCounter = 0;\nlet toolResultMessageCounter = 0;\n\nfunction isTerminalToolOperationPhase(phase: string | undefined): boolean {\n return phase === 'Completed' || phase === 'Failed' || phase === 'Cancelled';\n}\n\n/** Deterministic stringify (sorted object keys) for stable idempotency keys. */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'undefined';\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n const entries = Object.entries(value as Record<string, unknown>)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`);\n return `{${entries.join(',')}}`;\n}\n\n/** Browser-safe FNV-1a hash for idempotency keys (not a security primitive). */\nfunction fnv1aHex(input: string): string {\n let hash = 0x81_1c_9d_c5;\n for (let index = 0; index < input.length; index += 1) {\n hash = Math.imul(hash ^ input.charCodeAt(index), 0x01_00_01_93) >>> 0;\n }\n return hash.toString(16).padStart(8, '0');\n}\n\nfunction isTransientGetError(error: unknown): boolean {\n return (\n error instanceof OrchestrationError &&\n (error.code === 'UNAVAILABLE' || error.code === 'TIMEOUT' || error.code === 'INTERNAL')\n );\n}\n\n/**\n * Poll a ToolOperation until terminal. Transient `get` failures are treated\n * as possible unknown-effect situations: reconciliation decides whether to\n * keep waiting (`retry`) or stop and surface the required intervention,\n * never blindly repeating the operation.\n */\nasync function waitForToolOperationTerminal(\n client: AgentOrchestrationClient,\n reference: OrchestrationResourceReference,\n timeoutMs: number,\n applied?: ToolOperationResource,\n): Promise<ToolOperationResource> {\n const deadline = Date.now() + timeoutMs;\n let last: ToolOperationResource | null = applied ?? null;\n while (Date.now() < deadline) {\n let resource: Awaited<ReturnType<AgentOrchestrationClient['get']>> | undefined;\n try {\n resource = await client.get(reference);\n } catch (error) {\n if (!isTransientGetError(error)) throw error;\n const basis = last ?? applied;\n if (!basis) throw error;\n const decision = reconcileUnknownEffect(basis, { resultObserved: false });\n if (decision.action === 'retry') {\n // The operation itself is safe to keep awaiting; do not re-apply.\n } else {\n throw new Error(\n `ToolOperation ${reference.name ?? '<unknown>'} effect unknown after transport failure: ` +\n `${decision.action} — ${decision.reason}`,\n );\n }\n }\n if (resource) {\n last = resource as unknown as ToolOperationResource;\n if (isTerminalToolOperationPhase(last.status?.phase)) {\n return last;\n }\n }\n await new Promise<void>((resolve) => {\n setTimeout(resolve, TOOL_OPERATION_POLL_INTERVAL_MS);\n });\n }\n if (last) {\n return last;\n }\n throw new Error(`ToolOperation ${reference.name ?? '<unknown>'} was not observed before timeout`);\n}\n\nfunction toolOperationRow(resource: ToolOperationResource): ToolRunRow {\n const status = resource.status;\n if (status?.phase === 'Completed') {\n const value = status.result?.value;\n if (value != null && typeof value === 'object') {\n const structured = extractMemeloopStructuredToolPayload(value);\n if (structured) {\n return {\n text: structured.summary,\n isError: false,\n detailRef: structured.detailRef,\n awaitSessionId: structured.awaitSessionId,\n };\n }\n if ('error' in value && typeof value.error === 'string') {\n return { text: value.error, isError: true };\n }\n if ('result' in value && value.result != null) {\n return {\n text: typeof value.result === 'string' ? value.result : JSON.stringify(value.result),\n payload: typeof value.result === 'string' ? undefined : value.result,\n isError: false,\n };\n }\n }\n return { text: typeof value === 'string' ? value : JSON.stringify(value), isError: false };\n }\n if (status?.phase === 'Failed' || status?.phase === 'Cancelled') {\n return {\n text: status.result?.error?.message ?? `ToolOperation ${status.phase}`,\n isError: true,\n };\n }\n return {\n text: `ToolOperation did not reach a terminal phase (last phase: ${status?.phase ?? 'unknown'})`,\n isError: true,\n };\n}\n\nasync function executeToolOperation(\n context: AgentFrameworkContext,\n conversationId: string,\n call: PendingToolCall,\n occurrence: number,\n): Promise<ToolRunRow | null> {\n const client = context.orchestration;\n if (!client) return null;\n\n try {\n const caps = await client.getCapabilities();\n if (\n !caps.resourceKinds.includes(TOOL_OPERATION_KIND) ||\n !caps.operations.includes('apply') ||\n !caps.operations.includes('get')\n ) {\n return null;\n }\n } catch {\n return null;\n }\n\n const timeoutMs = context.agentToolLoop?.toolOperationTimeoutMs ?? TOOL_OPERATION_DEFAULT_TIMEOUT_MS;\n // Stable per logical call: controller retries re-deliver the same operation,\n // while a new identical call (next occurrence) produces a distinct key.\n const idempotencyKey = `${conversationId}:${\n fnv1aHex(stableStringify({\n toolId: call.toolId,\n parameters: call.parameters,\n }))\n }:${occurrence}`;\n\n toolOperationCounter += 1;\n const operation = createToolOperationManifest(\n `${call.toolId}-${Date.now().toString(36)}-${toolOperationCounter.toString(36)}`,\n {\n toolRef: { kind: 'BuiltinTool', name: call.toolId },\n effect: context.tools.getToolEffect?.(call.toolId) ?? 'execute',\n arguments: call.parameters,\n idempotencyKey,\n timeoutMs,\n policy: { auditLevel: 'metadata' },\n },\n );\n\n try {\n const applied = await client.apply(operation);\n if (applied.apiVersion !== TOOL_OPERATION_API_VERSION || applied.kind !== TOOL_OPERATION_KIND) {\n return { text: 'ToolOperation apply returned an unexpected resource kind', isError: true };\n }\n let resource = applied as unknown as ToolOperationResource;\n if (!isTerminalToolOperationPhase(resource.status?.phase)) {\n const reference: OrchestrationResourceReference = {\n apiVersion: applied.apiVersion,\n kind: applied.kind,\n name: applied.metadata.name,\n namespace: applied.metadata.namespace,\n };\n resource = await waitForToolOperationTerminal(client, reference, timeoutMs, resource);\n }\n return toolOperationRow(resource);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { text: `ToolOperation execution error: ${message}`, isError: true };\n }\n}\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 payload: typeof o.result === 'string' ? undefined : 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 parameterParseError = call.parameters[TOOL_PARAMETER_PARSE_ERROR_KEY];\n if (typeof parameterParseError === 'string') {\n return { text: parameterParseError, isError: true };\n }\n\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 // Occurrence of this exact call in the conversation; distinguishes a new\n // logical call from a controller retry of a previous one.\n const occurrence = recentToolCalls.filter((entry) => entry === signature).length;\n const row = (await executeToolOperation(context, conversationId, call, occurrence)) ??\n (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 toolResultMessageCounter += 1;\n const lamportTool = await nextLamportClockForConversation(context.storage, conversationId);\n await context.storage.appendMessage(createChatMessage({\n // Counter suffix keeps message identity unique for identical calls within\n // the same millisecond (parallel tools or fast consecutive rounds).\n messageId: `${conversationId}:t:${call.toolId}:${Date.now().toString(36)}:${toolResultMessageCounter.toString(36)}`,\n conversationId,\n originNodeId: 'local',\n lamportClock: lamportTool,\n role: 'tool',\n parts: [{\n type: 'tool-result',\n toolName: call.toolId,\n parameters: call.parameters,\n result: row.text,\n isError: row.isError,\n payload: row.payload,\n detailRef: row.detailRef,\n }],\n detailRef: row.detailRef,\n metadata: {\n isToolResult: true,\n isError: row.isError,\n toolId: call.toolId,\n toolParameters: call.parameters,\n },\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(createChatMessage({\n messageId: `${conversationId}:t:${call.toolId}:await:${Date.now().toString(36)}:${toolResultMessageCounter.toString(36)}`,\n conversationId,\n originNodeId: 'local',\n lamportClock: lamportTool,\n role: 'tool',\n parts: [{\n type: 'tool-result',\n toolName: call.toolId,\n parameters: call.parameters,\n result: body,\n detailRef: row.detailRef\n ? { ...row.detailRef, exitCode: done.exitCode ?? row.detailRef.exitCode }\n : undefined,\n }],\n detailRef: row.detailRef\n ? { ...row.detailRef, exitCode: done.exitCode ?? row.detailRef.exitCode }\n : undefined,\n metadata: {\n isToolResult: true,\n toolId: call.toolId,\n toolParameters: call.parameters,\n awaitSessionId: sid,\n },\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 { createChatMessage } from '../../conversation/index.js';\nimport { defaultPermissionActionForTrustClass } from '../../orchestration/security/admission.js';\nimport 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';\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 *\n * When no wildcard rule exists, an implied default is derived from the\n * host-bound trust class: restricted/quarantine workers deny by default,\n * trusted workers keep the historical allow default.\n */\nexport function buildLayeredPermissions(\n options: AgentFrameworkContext['agentToolLoop'],\n definitionId: string,\n userSet?: PermissionSet,\n): MergedPermissions {\n const globalPerms = options?.toolPermissions;\n const sets: PermissionSet[] = [];\n\n if (globalPerms?.default) {\n sets.push({\n source: 'default',\n rules: [{ toolPattern: '*', action: globalPerms.default }],\n });\n }\n\n const scoped = globalPerms?.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 (globalPerms?.rules && globalPerms.rules.length > 0) {\n sets.push({\n source: 'session',\n rules: globalPerms.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: defaultPermissionActionForTrustClass(options?.trustClass) }],\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(createChatMessage({\n messageId: `${conversationId}:t:${call.toolId}:${Date.now().toString(36)}`,\n conversationId,\n originNodeId: 'local',\n lamportClock: lamportTool,\n role: 'tool',\n parts: [{\n type: 'tool-result',\n toolName: call.toolId,\n parameters: call.parameters,\n result: errorText,\n isError: true,\n }],\n metadata: {\n isToolResult: true,\n isError: true,\n toolId: call.toolId,\n toolParameters: call.parameters,\n },\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, createChatMessage } 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\nfunction pluginToolCallSignature(calls: Array<ToolCallingMatch & { found: true }>): string {\n return calls.map(call => `${call.toolId}:${JSON.stringify(call.parameters)}`).join('|');\n}\n\nasync function blockRepeatedPluginToolCalls(\n context: AgentFrameworkContext,\n input: AgentLoopInput,\n state: AgentToolLoopState,\n calls: Array<ToolCallingMatch & { found: true }>,\n hookContext: DefineToolAgentFrameworkContext,\n): Promise<{ blocked: false } | { blocked: true; message: string }> {\n if (calls.length === 0) return { blocked: false };\n\n const signature = pluginToolCallSignature(calls);\n state.recentToolCalls.push(signature);\n const threshold = Math.max(2, context.agentToolLoop?.doomLoopThreshold ?? 3);\n const last = state.recentToolCalls.slice(-threshold);\n if (last.length !== threshold || !last.every(entry => entry === signature)) {\n return { blocked: false };\n }\n\n const message = `Blocked by doom-loop guard: the model repeated the same tool call ${threshold} times. ` +\n 'Change the arguments or approach before trying again.';\n const firstCall = calls[0];\n const lamportClock = await nextLamportClockForConversation(\n context.storage,\n input.conversationId,\n );\n const toolMessage = createChatMessage({\n messageId: `${input.conversationId}:t:doom-loop:${state.iteration}:${Date.now().toString(36)}`,\n conversationId: input.conversationId,\n originNodeId: 'local',\n lamportClock,\n role: 'tool',\n parts: [{\n type: 'tool-result',\n toolName: firstCall.toolId,\n parameters: firstCall.parameters,\n result: message,\n isError: true,\n }],\n metadata: {\n isToolResult: true,\n isError: true,\n toolId: firstCall.toolId,\n toolParameters: firstCall.parameters,\n doomLoopBlocked: true,\n },\n });\n hookContext.agent.messages.push(toolMessage);\n await context.storage.appendMessage(toolMessage);\n return { blocked: true, message };\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 // Prompt plugins may inspect the live agent (for example Desktop's\n // persistent goal/todo tool). Give prompt concatenation the same enriched\n // context used by response hooks instead of the host-only base context.\n const messages = await buildLlmMessages(hookContext, input.conversationId, history);\n const request = { conversationId: input.conversationId, messages };\n // Include the iteration so rounds started within the same millisecond keep\n // distinct message identity; otherwise a later round replaces an earlier\n // round's assistant message and duplicate-output detection misfires.\n const assistantMessageId = `${input.conversationId}:a:${iteration}:${Date.now().toString(36)}`;\n const assistantLamportClock = await nextLamportClockForConversation(\n context.storage,\n input.conversationId,\n );\n const buildAssistantMessage = (content: string) =>\n context.normalizeMessage?.({\n messageId: assistantMessageId,\n conversationId: input.conversationId,\n originNodeId: 'local',\n timestamp: Date.now(),\n lamportClock: assistantLamportClock,\n role: 'assistant',\n content,\n }) ?? {\n messageId: assistantMessageId,\n conversationId: input.conversationId,\n originNodeId: 'local',\n timestamp: Date.now(),\n lamportClock: assistantLamportClock,\n role: 'assistant' as const,\n content,\n };\n const updateAssistantView = (message: ChatMessage) => {\n const existingIndex = hookContext.agent.messages.findIndex(\n item => item.messageId === message.messageId,\n );\n if (existingIndex >= 0) {\n hookContext.agent.messages[existingIndex] = message;\n } else {\n hookContext.agent.messages.push(message);\n }\n };\n let assistantText = '';\n for await (const chunk of streamLlm(context, request)) {\n assistantText += chunkToText(chunk);\n // Conversation stores are append-only. Keep streaming partials in the\n // in-memory agent view/UI only; persist the immutable final message once.\n const transientAssistantMessage = buildAssistantMessage(assistantText);\n updateAssistantView(transientAssistantMessage);\n try {\n await context.onTransientMessage?.(transientAssistantMessage);\n } catch (error) {\n // A renderer/update subscriber must not turn a successful model stream\n // into a failed turn or prevent the immutable final message from being\n // persisted.\n context.logger?.warn?.('[agentToolLoop] transient message subscriber failed:', error);\n }\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 = buildAssistantMessage(assistantText);\n updateAssistantView(assistantMessage);\n await hookContext.persistAgentMessage?.(assistantMessage);\n\n const { calls, parallel } = matchAllToolCallings(assistantText);\n\n if (hasPlugins && frameworkConfig) {\n const doomLoop = await blockRepeatedPluginToolCalls(\n context,\n input,\n state,\n calls,\n hookContext,\n );\n if (doomLoop.blocked) {\n yield {\n type: 'tool',\n data: {\n toolId: calls[0].toolId,\n parameters: calls[0].parameters,\n parallel,\n result: doomLoop.message,\n isError: true,\n },\n };\n yield finishAgentToolLoopThinking(state, 'error', {\n status: 'blocked',\n conversationId: input.conversationId,\n reason: doomLoop.message,\n });\n return { action: 'stop', reason: 'error' };\n }\n\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 { AgentFrameworkContext } from '../../types.js';\nimport type { AgentLoopGenerator, AgentLoopInput } from '../types.js';\nimport { createAgentToolLoopState, runAgentToolLoopIteration, startAgentToolLoopTurn, stopAgentToolLoopTurn } from './turnPrimitives.js';\n\n/**\n * Direct agent/tool runner with no dynamic script-loader dependency.\n *\n * This is the portable path used by React Native. Hosts that need deployable\n * script references use `createAgentToolLoopDefinition` from the full entry.\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","/**\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","// 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 ' \"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\": \"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\": \"可靠的通用智能体,用于对话、Wiki 知识工作、目标推进和日常计算机操作。\",',\n ' \"loopId\": \"agent-tool-loop\",',\n ' \"systemPrompt\": \"You are MemeLoop, a reliable general-purpose agent for conversation, knowledge work, goal completion, and everyday computer tasks.\\\\n\\\\nOperating contract:\\\\n- Treat the user request as the active goal. For a task with three or more meaningful steps, use the planning tool actually listed in the tool instructions (for example manage-todo or todoWrite) to create a short plan, keep exactly one item in progress, and update it as work advances. Continue until the goal is achieved or genuinely blocked.\\\\n- Use tools for actions and for facts that must be read from the user\\'s environment. Never claim that an action succeeded without a successful tool result. Never invent search results, file contents, counts, or completion evidence.\\\\n- Use the exact tool name and parameter schema shown in the tool list. When calling a tool, output ONLY one tool call in this exact XML format:\\\\n<tool_use name=\\\\\"TOOL_NAME\\\\\">{\\\\\"param\\\\\":\\\\\"value\\\\\"}</tool_use>\\\\n The JSON must be valid. Never wrap the call in markdown or add text before or after it. After the tool result, reassess the goal and continue.\\\\n- If a tool fails, read the error and change the arguments or approach. Do not repeat an identical failed call more than once, and do not retry the same approach more than twice.\\\\n- For Wiki work, use an injected available workspace name or ID; do not guess one. Search before relying on stored knowledge. For wiki-search, exact-title filter syntax is [title[Exact Title]], tag syntax is [tag[Tag]], and semantic search uses searchType \\\\\"vector\\\\\" with query. A filter search uses searchType \\\\\"filter\\\\\" with filter. After a write, verify important content with a valid exact-title search. If verification fails, report that honestly.\\\\n- Save durable facts, decisions, plans, and user-requested memories to Wiki when useful. Do not store credentials or other sensitive data unless the user explicitly asks.\\\\n- For UI or computer actions, inspect the current state before acting, prefer reversible changes, verify the resulting state, and ask before destructive actions or consequential external communication.\\\\n- Do not ask for confirmation before an explicitly requested reversible action when the target is already known. Ask a concise question only when missing information materially changes the result. Otherwise make safe, explicit assumptions and proceed.\\\\n- In the final response, lead with the outcome, cite concrete verification, and state any remaining limitation briefly.\",',\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 ' { \"id\": \"builtin:todo-write\" }',\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\": \"todo\",',\n ' \"parameters\": {',\n ' \"todoParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"todoInjectionTargetId\": \"builtin-system\",',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' }',\n ' ],',\n ' \"agentFrameworkConfig\": {',\n ' \"prompts\": [',\n ' {',\n ' \"id\": \"builtin-system\",',\n ' \"role\": \"system\",',\n ' \"text\": \"You are MemeLoop, a reliable general-purpose agent for conversation, knowledge work, goal completion, and everyday computer tasks.\\\\n\\\\nOperating contract:\\\\n- Treat the user request as the active goal. For a task with three or more meaningful steps, use the planning tool actually listed in the tool instructions (for example manage-todo or todoWrite) to create a short plan, keep exactly one item in progress, and update it as work advances. Continue until the goal is achieved or genuinely blocked.\\\\n- Use tools for actions and for facts that must be read from the user\\'s environment. Never claim that an action succeeded without a successful tool result. Never invent search results, file contents, counts, or completion evidence.\\\\n- Use the exact tool name and parameter schema shown in the tool list. When calling a tool, output ONLY one tool call in this exact XML format:\\\\n<tool_use name=\\\\\"TOOL_NAME\\\\\">{\\\\\"param\\\\\":\\\\\"value\\\\\"}</tool_use>\\\\n The JSON must be valid. Never wrap the call in markdown or add text before or after it. After the tool result, reassess the goal and continue.\\\\n- If a tool fails, read the error and change the arguments or approach. Do not repeat an identical failed call more than once, and do not retry the same approach more than twice.\\\\n- For Wiki work, use an injected available workspace name or ID; do not guess one. Search before relying on stored knowledge. For wiki-search, exact-title filter syntax is [title[Exact Title]], tag syntax is [tag[Tag]], and semantic search uses searchType \\\\\"vector\\\\\" with query. A filter search uses searchType \\\\\"filter\\\\\" with filter. After a write, verify important content with a valid exact-title search. If verification fails, report that honestly.\\\\n- Save durable facts, decisions, plans, and user-requested memories to Wiki when useful. Do not store credentials or other sensitive data unless the user explicitly asks.\\\\n- For UI or computer actions, inspect the current state before acting, prefer reversible changes, verify the resulting state, and ask before destructive actions or consequential external communication.\\\\n- Do not ask for confirmation before an explicitly requested reversible action when the target is already known. Ask a concise question only when missing information materially changes the result. Otherwise make safe, explicit assumptions and proceed.\\\\n- In the final response, lead with the outcome, cite concrete verification, and state any remaining limitation briefly.\"',\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.1.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 * 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"],"mappings":";;;;;;;;;;;;;;;AAaO,SAAS,aAAa,UAAkB,SAA0B;AAEvE,MAAI,YAAY,SAAU,QAAO;AACjC,MAAI,YAAY,IAAK,QAAO;AAG5B,QAAM,UAAU,QACb,QAAQ,uBAAuB,MAAM,EACrC,QAAQ,SAAS,IAAI;AAExB,SAAO,IAAI,OAAO,IAAI,OAAO,GAAG,EAAE,KAAK,QAAQ;AACjD;AAWO,SAAS,oBAAoB,MAA0C;AAE5E,QAAM,SAAS,oBAAI,IAAqD;AACxE,SAAO,IAAI,SAAS,oBAAI,IAAI,CAAC;AAC7B,SAAO,IAAI,QAAQ,oBAAI,IAAI,CAAC;AAC5B,SAAO,IAAI,OAAO,oBAAI,IAAI,CAAC;AAE3B,aAAW,OAAO,MAAM;AACtB,eAAW,QAAQ,IAAI,OAAO;AAE5B,iBAAW,CAAC,QAAQ,GAAG,KAAK,QAAQ;AAClC,YAAI,WAAW,KAAK,QAAQ;AAC1B,cAAI,OAAO,KAAK,WAAW;AAAA,QAC7B;AAAA,MACF;AAEA,aAAO,IAAI,KAAK,MAAM,E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AAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,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,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,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,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;;;AC7ZA,SAAS,YAAY,MAA2B;AAC9C,QAAM,SAAS,sBAAsB,IAAI;AACzC,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,8BAA8B,IAAI,EAAE;AAAA,EACtD;AACA,SAAO,KAAK,MAAM,MAAM;AAC1B;AAGO,SAAS,yBAAwC;AACtD,SAAO;AAAA,IACL,YAAY,mBAAmB;AAAA,IAC/B,YAAY,gBAAgB;AAAA,IAC5B,YAAY,gBAAgB;AAAA,IAC5B,YAAY,YAAY;AAAA,IACxB,YAAY,YAAY;AAAA,EAC1B;AACF;AAGO,SAAS,sBAAsB,IAAqC;AACzE,SAAO,uBAAuB,EAAE,KAAK,CAAC,MAAM,EAAE,OAAO,EAAE;AACzD;AAGO,SAAS,8BAAoC;AAClD,QAAM,WAAW,gBAAgB;AACjC,aAAW,WAAW,uBAAuB,GAAG;AAC9C,aAAS,gBAAgB,OAAO;AAAA,EAClC;AACF;","names":["max","chunkToText","chunkToText"]}
|
|
1
|
+
{"version":3,"sources":["../src/permission/engine.ts","../src/orchestration/security/admission.ts","../src/orchestration/drivers/unknownEffect.ts","../src/tools/pluginRegistry.ts","../src/promptUtilities/responsePatternUtility.ts","../src/storage/nextLamport.ts","../src/loopAPI/hooks/registry.ts","../src/loopAPI/agent-tool-loop/compaction.ts","../src/promptUtilities/promptConcat.ts","../src/tools/structuredToolResult.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/toolResultMessage.ts","../src/loopAPI/agent-tool-loop/modelMessages.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/directRunner.ts","../src/loopAPI/registry.ts","../src/loopProfiles/builtinProfileSources.ts","../src/loopProfiles/loadBuiltins.ts"],"sourcesContent":["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 { matchPattern } from '../../permission/engine.js';\nimport type { PermissionAction } from '../../permission/types.js';\n\nimport type { NodeTrustClass, SecurityProfileResource, ToolAdmissionAction, ToolAdmissionPolicy, ToolAdmissionRule, ToolOperationResource } from '../resources.js';\n\nexport type { NodeTrustClass, ToolAdmissionAction, ToolAdmissionPolicy, ToolAdmissionRule } from '../resources.js';\n\nexport interface ToolAdmissionDecision {\n action: ToolAdmissionAction;\n source: 'rule' | 'default';\n reason?: string;\n matchedRule?: ToolAdmissionRule;\n}\n\n/**\n * Default trusted admission posture per node trust class. Trusted nodes keep\n * the historical allow-by-default posture; restricted and quarantine nodes\n * deny everything unless an explicit rule allows it.\n */\nexport function defaultAdmissionPolicyForTrustClass(trustClass: NodeTrustClass): ToolAdmissionPolicy {\n switch (trustClass) {\n case 'restricted':\n case 'quarantine':\n return { defaultAction: 'deny', rules: [] };\n default:\n return { defaultAction: 'allow', rules: [] };\n }\n}\n\n/**\n * Resolve the effective trusted admission policy for a workload from its\n * SecurityProfile and the node's trust class. Profile rules are evaluated\n * first (they can allow specific tools on restricted nodes); the trust-class\n * default applies after. For restricted/quarantine the resolved default is\n * forced to `deny` — a profile cannot override it.\n */\nexport function resolveAdmissionPolicy(\n profile: Pick<SecurityProfileResource, 'spec'> | undefined,\n trustClass: NodeTrustClass,\n): ToolAdmissionPolicy {\n const base = defaultAdmissionPolicyForTrustClass(trustClass);\n const overlay = profile?.spec.toolAdmission;\n if (!overlay) return base;\n const defaultAction = trustClass === 'trusted' ? overlay.defaultAction ?? base.defaultAction : 'deny';\n return {\n defaultAction,\n rules: [...(overlay.rules ?? []), ...(base.rules ?? [])],\n };\n}\n\n/**\n * Model-facing implied permission default for a trust class. Used by the\n * AgentToolLoop permission gate when no explicit wildcard rule exists.\n */\nexport function defaultPermissionActionForTrustClass(trustClass: NodeTrustClass | undefined): PermissionAction {\n return trustClass === 'restricted' || trustClass === 'quarantine' ? 'deny' : 'allow';\n}\n\nexport function evaluateToolAdmission(\n policy: ToolAdmissionPolicy,\n operation: Pick<ToolOperationResource, 'spec'>,\n): ToolAdmissionDecision {\n const toolName = operation.spec.toolRef.name;\n const effect = operation.spec.effect;\n for (const rule of policy.rules ?? []) {\n if (!matchPattern(toolName, rule.toolPattern)) continue;\n if (rule.effects && !rule.effects.includes(effect)) continue;\n return {\n action: rule.action,\n source: 'rule',\n reason: rule.reason,\n matchedRule: rule,\n };\n }\n return { action: policy.defaultAction, source: 'default' };\n}\n","import type { OrchestrationCondition } from '../client.js';\nimport type { ToolOperationResource, ToolOperationStatus } from '../resources.js';\n\n/**\n * Condition type raised on a ToolOperation whose executor crashed or\n * disconnected after a side effect may have occurred. While this condition is\n * `True`, controllers must follow the recorded reconciliation decision instead\n * of blindly repeating the operation.\n */\nexport const TOOL_OPERATION_CONDITION_EFFECT_UNKNOWN = 'EffectUnknown';\n\n/**\n * Evidence gathered by driver/controller inspection after an executor crash or\n * disconnect. Evidence is produced by the trusted side (driver checkpoints,\n * verifier probes, artifact records), never by the possibly-failed executor's\n * own claim alone.\n */\nexport interface UnknownEffectEvidence {\n /**\n * The executor produced a result before the disconnect and only the\n * completion acknowledgement was lost. The caller is responsible for\n * attaching the observed result when applying the decision.\n */\n resultObserved?: boolean;\n /** Reference to independent verification evidence (artifact, verifier run). */\n evidenceRef?: string;\n /** ISO timestamp of the observed disconnect/crash. */\n disconnectedAt?: string;\n}\n\nexport type UnknownEffectAction = 'retry' | 'succeeded' | 'verification-required' | 'manual-intervention';\n\nexport interface UnknownEffectDecision {\n action: UnknownEffectAction;\n reason: string;\n}\n\nconst DEFAULT_MAX_ATTEMPTS = 3;\n\nfunction attemptsOf(operation: ToolOperationResource): number {\n return operation.status?.attempts ?? 0;\n}\n\nfunction maxAttemptsOf(operation: ToolOperationResource): number {\n return operation.spec.retry?.maxAttempts ?? DEFAULT_MAX_ATTEMPTS;\n}\n\n/**\n * Decide how to reconcile an operation whose effect is unknown. The decision\n * never blindly repeats destructive work:\n *\n * 1. An observed result means only the ack was lost → `succeeded`.\n * 2. `read` effects have no side effects → `retry` (within attempt budget).\n * 3. `retry.nonRetryable` operations are never repeated → `manual-intervention`.\n * 4. Operations with an `idempotencyKey` dedupe at the executor/store, so a\n * repeated delivery is safe → `retry` (within attempt budget).\n * 5. Everything else requires independent verification before any retry →\n * `verification-required`.\n */\nexport function reconcileUnknownEffect(\n operation: ToolOperationResource,\n evidence: UnknownEffectEvidence,\n): UnknownEffectDecision {\n if (evidence.resultObserved) {\n return { action: 'succeeded', reason: 'result was observed before the disconnect; only the ack was lost' };\n }\n\n if (operation.spec.retry?.nonRetryable) {\n return { action: 'manual-intervention', reason: 'operation is marked nonRetryable and its effect is unknown' };\n }\n\n const attempts = attemptsOf(operation);\n const maxAttempts = maxAttemptsOf(operation);\n const withinBudget = attempts < maxAttempts;\n\n if (operation.spec.effect === 'read') {\n if (withinBudget) {\n return { action: 'retry', reason: `read effect has no side effects (attempt ${attempts + 1}/${maxAttempts})` };\n }\n return { action: 'verification-required', reason: `read retry budget exhausted (${attempts}/${maxAttempts})` };\n }\n\n if (operation.spec.idempotencyKey) {\n if (withinBudget) {\n return {\n action: 'retry',\n reason: `idempotencyKey deduplicates repeated delivery (attempt ${attempts + 1}/${maxAttempts})`,\n };\n }\n return {\n action: 'verification-required',\n reason: `idempotent retry budget exhausted (${attempts}/${maxAttempts}); verify before further attempts`,\n };\n }\n\n return {\n action: 'verification-required',\n reason: `effect '${operation.spec.effect}' without idempotencyKey must be verified before any retry`,\n };\n}\n\nfunction effectUnknownCondition(decision: UnknownEffectDecision, at: string): OrchestrationCondition {\n return {\n type: TOOL_OPERATION_CONDITION_EFFECT_UNKNOWN,\n status: 'True',\n reason: decision.action,\n message: decision.reason,\n lastTransitionTime: at,\n };\n}\n\n/**\n * Apply a reconciliation decision to an operation, producing the next status:\n *\n * - `retry` → back to `Pending` (requeue) with the EffectUnknown condition.\n * - `succeeded` → `Completed` (caller attaches the observed result separately).\n * - `verification-required` / `manual-intervention` → stays `Running` with the\n * EffectUnknown condition; the operation is not repeated until a verifier or\n * operator clears the condition.\n */\nexport function applyUnknownEffectDecision(\n operation: ToolOperationResource,\n decision: UnknownEffectDecision,\n at: string = new Date().toISOString(),\n): ToolOperationResource {\n const conditions = [\n ...(operation.status?.conditions ?? []).filter((c) => c.type !== TOOL_OPERATION_CONDITION_EFFECT_UNKNOWN),\n effectUnknownCondition(decision, at),\n ];\n\n const base: ToolOperationStatus = {\n ...operation.status,\n conditions,\n };\n\n if (decision.action === 'retry') {\n return { ...operation, status: { ...base, phase: 'Pending' } };\n }\n if (decision.action === 'succeeded') {\n return {\n ...operation,\n status: { ...base, phase: 'Completed', completedAt: at },\n };\n }\n return { ...operation, status: { ...base, phase: 'Running' } };\n}\n","import type { HookSlot, PromptConcatHooks, PromptConcatTool, TapAsyncHandler } 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: TapAsyncHandler[];\n} {\n const handlers: TapAsyncHandler[] = [];\n return {\n handlers,\n tapAsync(_name, function_) {\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?: TapAsyncHandler[];\n} = {};\n\nexport async function runProcessPromptsHooks<TContext>(\n _hooks: PromptConcatHooks,\n context: TContext,\n): Promise<TContext> {\n const slot = _hooks.processPrompts as {\n handlers?: TapAsyncHandler[];\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;\nexport const TOOL_PARAMETER_PARSE_ERROR_KEY = '__memeloopToolParameterParseError';\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 {\n [TOOL_PARAMETER_PARSE_ERROR_KEY]: `Invalid tool arguments JSON. Return one valid JSON object inside the tool tag. Received: ${\n trimmedText.substring(0, MAX_FALLBACK_INPUT_LENGTH)\n }`,\n };\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 { ConversationEventStore } from './ports.js';\n\n/**\n * 下一条消息的 Lamport 时钟:取会话内已有消息的最大 lamportClock + 1。\n * Depends only on the narrow ConversationEventStore port (plan 24.41).\n */\nexport async function nextLamportClockForConversation(\n storage: ConversationEventStore,\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';\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 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>;\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","/**\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","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 { AgentDefinition } from '../../agent/types.js';\nimport { type ChatMessage, getChatMessageParts, isToolResultPart } 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';\nimport { formatToolResultMessage } from './toolResultMessage.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\n if (role === 'tool') {\n const toolResults = getChatMessageParts(message).filter(isToolResultPart);\n if (toolResults.length > 0) {\n return {\n role,\n content: toolResults.map((part) =>\n formatToolResultMessage(\n part.toolName,\n (part.parameters && typeof part.parameters === 'object' ? part.parameters : {}) as Record<string, unknown>,\n part.result,\n part.isError === true,\n )\n ).join('\\n\\n'),\n };\n }\n }\n\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","import { createChatMessage, type DetailReference } from '../../conversation/index.js';\nimport type { AgentOrchestrationClient, OrchestrationResourceReference } from '../../orchestration/client.js';\nimport { reconcileUnknownEffect } from '../../orchestration/drivers/unknownEffect.js';\nimport { OrchestrationError } from '../../orchestration/errors.js';\nimport { createToolOperationManifest, TOOL_OPERATION_API_VERSION, TOOL_OPERATION_KIND, type ToolOperationResource } from '../../orchestration/resources.js';\nimport { TOOL_PARAMETER_PARSE_ERROR_KEY } from '../../promptUtilities/responsePatternUtility.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 type { PendingToolCall } from './toolUseGate.js';\n\ntype ToolRunRow = {\n text: string;\n isError: boolean;\n payload?: unknown;\n detailRef?: DetailReference;\n awaitSessionId?: string;\n};\n\ntype CompletedToolCall = ToolRunRow & { call: PendingToolCall };\n\nconst TOOL_OPERATION_DEFAULT_TIMEOUT_MS = 60_000;\nconst TOOL_OPERATION_POLL_INTERVAL_MS = 250;\n\nlet toolOperationCounter = 0;\nlet toolResultMessageCounter = 0;\n\nfunction isTerminalToolOperationPhase(phase: string | undefined): boolean {\n return phase === 'Completed' || phase === 'Failed' || phase === 'Cancelled';\n}\n\n/** Deterministic stringify (sorted object keys) for stable idempotency keys. */\nfunction stableStringify(value: unknown): string {\n if (value === null || typeof value !== 'object') return JSON.stringify(value) ?? 'undefined';\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`;\n const entries = Object.entries(value as Record<string, unknown>)\n .sort(([a], [b]) => a.localeCompare(b))\n .map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`);\n return `{${entries.join(',')}}`;\n}\n\n/** Browser-safe FNV-1a hash for idempotency keys (not a security primitive). */\nfunction fnv1aHex(input: string): string {\n let hash = 0x81_1c_9d_c5;\n for (let index = 0; index < input.length; index += 1) {\n hash = Math.imul(hash ^ input.charCodeAt(index), 0x01_00_01_93) >>> 0;\n }\n return hash.toString(16).padStart(8, '0');\n}\n\nfunction isTransientGetError(error: unknown): boolean {\n return (\n error instanceof OrchestrationError &&\n (error.code === 'UNAVAILABLE' || error.code === 'TIMEOUT' || error.code === 'INTERNAL')\n );\n}\n\n/**\n * Poll a ToolOperation until terminal. Transient `get` failures are treated\n * as possible unknown-effect situations: reconciliation decides whether to\n * keep waiting (`retry`) or stop and surface the required intervention,\n * never blindly repeating the operation.\n */\nasync function waitForToolOperationTerminal(\n client: AgentOrchestrationClient,\n reference: OrchestrationResourceReference,\n timeoutMs: number,\n applied?: ToolOperationResource,\n): Promise<ToolOperationResource> {\n const deadline = Date.now() + timeoutMs;\n let last: ToolOperationResource | null = applied ?? null;\n while (Date.now() < deadline) {\n let resource: Awaited<ReturnType<AgentOrchestrationClient['get']>> | undefined;\n try {\n resource = await client.get(reference);\n } catch (error) {\n if (!isTransientGetError(error)) throw error;\n const basis = last ?? applied;\n if (!basis) throw error;\n const decision = reconcileUnknownEffect(basis, { resultObserved: false });\n if (decision.action === 'retry') {\n // The operation itself is safe to keep awaiting; do not re-apply.\n } else {\n throw new Error(\n `ToolOperation ${reference.name ?? '<unknown>'} effect unknown after transport failure: ` +\n `${decision.action} — ${decision.reason}`,\n );\n }\n }\n if (resource) {\n last = resource as unknown as ToolOperationResource;\n if (isTerminalToolOperationPhase(last.status?.phase)) {\n return last;\n }\n }\n await new Promise<void>((resolve) => {\n setTimeout(resolve, TOOL_OPERATION_POLL_INTERVAL_MS);\n });\n }\n if (last) {\n return last;\n }\n throw new Error(`ToolOperation ${reference.name ?? '<unknown>'} was not observed before timeout`);\n}\n\nfunction toolOperationRow(resource: ToolOperationResource): ToolRunRow {\n const status = resource.status;\n if (status?.phase === 'Completed') {\n const value = status.result?.value;\n if (value != null && typeof value === 'object') {\n const structured = extractMemeloopStructuredToolPayload(value);\n if (structured) {\n return {\n text: structured.summary,\n isError: false,\n detailRef: structured.detailRef,\n awaitSessionId: structured.awaitSessionId,\n };\n }\n if ('error' in value && typeof value.error === 'string') {\n return { text: value.error, isError: true };\n }\n if ('result' in value && value.result != null) {\n return {\n text: typeof value.result === 'string' ? value.result : JSON.stringify(value.result),\n payload: typeof value.result === 'string' ? undefined : value.result,\n isError: false,\n };\n }\n }\n return { text: typeof value === 'string' ? value : JSON.stringify(value), isError: false };\n }\n if (status?.phase === 'Failed' || status?.phase === 'Cancelled') {\n return {\n text: status.result?.error?.message ?? `ToolOperation ${status.phase}`,\n isError: true,\n };\n }\n return {\n text: `ToolOperation did not reach a terminal phase (last phase: ${status?.phase ?? 'unknown'})`,\n isError: true,\n };\n}\n\nasync function executeToolOperation(\n context: AgentFrameworkContext,\n conversationId: string,\n call: PendingToolCall,\n occurrence: number,\n): Promise<ToolRunRow | null> {\n const client = context.orchestration;\n if (!client) return null;\n\n try {\n const caps = await client.getCapabilities();\n if (\n !caps.resourceKinds.includes(TOOL_OPERATION_KIND) ||\n !caps.operations.includes('apply') ||\n !caps.operations.includes('get')\n ) {\n return null;\n }\n } catch {\n return null;\n }\n\n const timeoutMs = context.agentToolLoop?.toolOperationTimeoutMs ?? TOOL_OPERATION_DEFAULT_TIMEOUT_MS;\n // Stable per logical call: controller retries re-deliver the same operation,\n // while a new identical call (next occurrence) produces a distinct key.\n const idempotencyKey = `${conversationId}:${\n fnv1aHex(stableStringify({\n toolId: call.toolId,\n parameters: call.parameters,\n }))\n }:${occurrence}`;\n\n toolOperationCounter += 1;\n const operation = createToolOperationManifest(\n `${call.toolId}-${Date.now().toString(36)}-${toolOperationCounter.toString(36)}`,\n {\n toolRef: { kind: 'BuiltinTool', name: call.toolId },\n effect: context.tools.getToolEffect?.(call.toolId) ?? 'execute',\n arguments: call.parameters,\n idempotencyKey,\n timeoutMs,\n policy: { auditLevel: 'metadata' },\n },\n );\n\n try {\n const applied = await client.apply(operation);\n if (applied.apiVersion !== TOOL_OPERATION_API_VERSION || applied.kind !== TOOL_OPERATION_KIND) {\n return { text: 'ToolOperation apply returned an unexpected resource kind', isError: true };\n }\n let resource = applied as unknown as ToolOperationResource;\n if (!isTerminalToolOperationPhase(resource.status?.phase)) {\n const reference: OrchestrationResourceReference = {\n apiVersion: applied.apiVersion,\n kind: applied.kind,\n name: applied.metadata.name,\n namespace: applied.metadata.namespace,\n };\n resource = await waitForToolOperationTerminal(client, reference, timeoutMs, resource);\n }\n return toolOperationRow(resource);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n return { text: `ToolOperation execution error: ${message}`, isError: true };\n }\n}\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 payload: typeof o.result === 'string' ? undefined : 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 parameterParseError = call.parameters[TOOL_PARAMETER_PARSE_ERROR_KEY];\n if (typeof parameterParseError === 'string') {\n return { text: parameterParseError, isError: true };\n }\n\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 // Occurrence of this exact call in the conversation; distinguishes a new\n // logical call from a controller retry of a previous one.\n const occurrence = recentToolCalls.filter((entry) => entry === signature).length;\n const row = (await executeToolOperation(context, conversationId, call, occurrence)) ??\n (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 toolResultMessageCounter += 1;\n const lamportTool = await nextLamportClockForConversation(context.storage, conversationId);\n await context.storage.appendMessage(createChatMessage({\n // Counter suffix keeps message identity unique for identical calls within\n // the same millisecond (parallel tools or fast consecutive rounds).\n messageId: `${conversationId}:t:${call.toolId}:${Date.now().toString(36)}:${toolResultMessageCounter.toString(36)}`,\n conversationId,\n originNodeId: 'local',\n lamportClock: lamportTool,\n role: 'tool',\n parts: [{\n type: 'tool-result',\n toolName: call.toolId,\n parameters: call.parameters,\n result: row.text,\n isError: row.isError,\n payload: row.payload,\n detailRef: row.detailRef,\n }],\n detailRef: row.detailRef,\n metadata: {\n isToolResult: true,\n isError: row.isError,\n toolId: call.toolId,\n toolParameters: call.parameters,\n },\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(createChatMessage({\n messageId: `${conversationId}:t:${call.toolId}:await:${Date.now().toString(36)}:${toolResultMessageCounter.toString(36)}`,\n conversationId,\n originNodeId: 'local',\n lamportClock: lamportTool,\n role: 'tool',\n parts: [{\n type: 'tool-result',\n toolName: call.toolId,\n parameters: call.parameters,\n result: body,\n detailRef: row.detailRef\n ? { ...row.detailRef, exitCode: done.exitCode ?? row.detailRef.exitCode }\n : undefined,\n }],\n detailRef: row.detailRef\n ? { ...row.detailRef, exitCode: done.exitCode ?? row.detailRef.exitCode }\n : undefined,\n metadata: {\n isToolResult: true,\n toolId: call.toolId,\n toolParameters: call.parameters,\n awaitSessionId: sid,\n },\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 { createChatMessage } from '../../conversation/index.js';\nimport { defaultPermissionActionForTrustClass } from '../../orchestration/security/admission.js';\nimport 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';\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 *\n * When no wildcard rule exists, an implied default is derived from the\n * host-bound trust class: restricted/quarantine workers deny by default,\n * trusted workers keep the historical allow default.\n */\nexport function buildLayeredPermissions(\n options: AgentFrameworkContext['agentToolLoop'],\n definitionId: string,\n userSet?: PermissionSet,\n): MergedPermissions {\n const globalPerms = options?.toolPermissions;\n const sets: PermissionSet[] = [];\n\n if (globalPerms?.default) {\n sets.push({\n source: 'default',\n rules: [{ toolPattern: '*', action: globalPerms.default }],\n });\n }\n\n const scoped = globalPerms?.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 (globalPerms?.rules && globalPerms.rules.length > 0) {\n sets.push({\n source: 'session',\n rules: globalPerms.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: defaultPermissionActionForTrustClass(options?.trustClass) }],\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(createChatMessage({\n messageId: `${conversationId}:t:${call.toolId}:${Date.now().toString(36)}`,\n conversationId,\n originNodeId: 'local',\n lamportClock: lamportTool,\n role: 'tool',\n parts: [{\n type: 'tool-result',\n toolName: call.toolId,\n parameters: call.parameters,\n result: errorText,\n isError: true,\n }],\n metadata: {\n isToolResult: true,\n isError: true,\n toolId: call.toolId,\n toolParameters: call.parameters,\n },\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, createChatMessage } 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\nfunction pluginToolCallSignature(calls: Array<ToolCallingMatch & { found: true }>): string {\n return calls.map(call => `${call.toolId}:${JSON.stringify(call.parameters)}`).join('|');\n}\n\nasync function blockRepeatedPluginToolCalls(\n context: AgentFrameworkContext,\n input: AgentLoopInput,\n state: AgentToolLoopState,\n calls: Array<ToolCallingMatch & { found: true }>,\n hookContext: DefineToolAgentFrameworkContext,\n): Promise<{ blocked: false } | { blocked: true; message: string }> {\n if (calls.length === 0) return { blocked: false };\n\n const signature = pluginToolCallSignature(calls);\n state.recentToolCalls.push(signature);\n const threshold = Math.max(2, context.agentToolLoop?.doomLoopThreshold ?? 3);\n const last = state.recentToolCalls.slice(-threshold);\n if (last.length !== threshold || !last.every(entry => entry === signature)) {\n return { blocked: false };\n }\n\n const message = `Blocked by doom-loop guard: the model repeated the same tool call ${threshold} times. ` +\n 'Change the arguments or approach before trying again.';\n const firstCall = calls[0];\n const lamportClock = await nextLamportClockForConversation(\n context.storage,\n input.conversationId,\n );\n const toolMessage = createChatMessage({\n messageId: `${input.conversationId}:t:doom-loop:${state.iteration}:${Date.now().toString(36)}`,\n conversationId: input.conversationId,\n originNodeId: 'local',\n lamportClock,\n role: 'tool',\n parts: [{\n type: 'tool-result',\n toolName: firstCall.toolId,\n parameters: firstCall.parameters,\n result: message,\n isError: true,\n }],\n metadata: {\n isToolResult: true,\n isError: true,\n toolId: firstCall.toolId,\n toolParameters: firstCall.parameters,\n doomLoopBlocked: true,\n },\n });\n hookContext.agent.messages.push(toolMessage);\n await context.storage.appendMessage(toolMessage);\n return { blocked: true, message };\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 // Prompt plugins may inspect the live agent (for example Desktop's\n // persistent goal/todo tool). Give prompt concatenation the same enriched\n // context used by response hooks instead of the host-only base context.\n const messages = await buildLlmMessages(hookContext, input.conversationId, history);\n const request = { conversationId: input.conversationId, messages };\n // Include the iteration so rounds started within the same millisecond keep\n // distinct message identity; otherwise a later round replaces an earlier\n // round's assistant message and duplicate-output detection misfires.\n const assistantMessageId = `${input.conversationId}:a:${iteration}:${Date.now().toString(36)}`;\n const assistantLamportClock = await nextLamportClockForConversation(\n context.storage,\n input.conversationId,\n );\n const buildAssistantMessage = (content: string) =>\n context.normalizeMessage?.({\n messageId: assistantMessageId,\n conversationId: input.conversationId,\n originNodeId: 'local',\n timestamp: Date.now(),\n lamportClock: assistantLamportClock,\n role: 'assistant',\n content,\n }) ?? {\n messageId: assistantMessageId,\n conversationId: input.conversationId,\n originNodeId: 'local',\n timestamp: Date.now(),\n lamportClock: assistantLamportClock,\n role: 'assistant' as const,\n content,\n };\n const updateAssistantView = (message: ChatMessage) => {\n const existingIndex = hookContext.agent.messages.findIndex(\n item => item.messageId === message.messageId,\n );\n if (existingIndex >= 0) {\n hookContext.agent.messages[existingIndex] = message;\n } else {\n hookContext.agent.messages.push(message);\n }\n };\n let assistantText = '';\n for await (const chunk of streamLlm(context, request)) {\n assistantText += chunkToText(chunk);\n // Conversation stores are append-only. Keep streaming partials in the\n // in-memory agent view/UI only; persist the immutable final message once.\n const transientAssistantMessage = buildAssistantMessage(assistantText);\n updateAssistantView(transientAssistantMessage);\n try {\n await context.onTransientMessage?.(transientAssistantMessage);\n } catch (error) {\n // A renderer/update subscriber must not turn a successful model stream\n // into a failed turn or prevent the immutable final message from being\n // persisted.\n context.logger?.warn?.('[agentToolLoop] transient message subscriber failed:', error);\n }\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 = buildAssistantMessage(assistantText);\n updateAssistantView(assistantMessage);\n await hookContext.persistAgentMessage?.(assistantMessage);\n\n const { calls, parallel } = matchAllToolCallings(assistantText);\n\n if (hasPlugins && frameworkConfig) {\n const doomLoop = await blockRepeatedPluginToolCalls(\n context,\n input,\n state,\n calls,\n hookContext,\n );\n if (doomLoop.blocked) {\n yield {\n type: 'tool',\n data: {\n toolId: calls[0].toolId,\n parameters: calls[0].parameters,\n parallel,\n result: doomLoop.message,\n isError: true,\n },\n };\n yield finishAgentToolLoopThinking(state, 'error', {\n status: 'blocked',\n conversationId: input.conversationId,\n reason: doomLoop.message,\n });\n return { action: 'stop', reason: 'error' };\n }\n\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 { AgentFrameworkContext } from '../../types.js';\nimport type { AgentLoopGenerator, AgentLoopInput } from '../types.js';\nimport { createAgentToolLoopState, runAgentToolLoopIteration, startAgentToolLoopTurn, stopAgentToolLoopTurn } from './turnPrimitives.js';\n\n/**\n * Direct agent/tool runner with no dynamic script-loader dependency.\n *\n * This is the portable path used by React Native. Hosts that need deployable\n * script references use `createAgentToolLoopDefinition` from the full entry.\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","/**\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","// 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 ' \"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\": \"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\": \"可靠的通用智能体,用于对话、Wiki 知识工作、目标推进和日常计算机操作。\",',\n ' \"loopId\": \"agent-tool-loop\",',\n ' \"systemPrompt\": \"You are MemeLoop, a reliable general-purpose agent for conversation, knowledge work, goal completion, and everyday computer tasks.\\\\n\\\\nOperating contract:\\\\n- Treat the user request as the active goal. For a task with three or more meaningful steps, use an enabled planning tool listed in the injected tool instructions to create a short plan, keep exactly one item in progress, and update it as work advances. Continue until the goal is achieved or genuinely blocked.\\\\n- Use tools for actions and for facts that must be read from the user\\'s environment. Never claim that an action succeeded without a successful tool result. Never invent search results, file contents, counts, or completion evidence.\\\\n- Use the exact tool name and parameter schema shown in the tool list. When calling a tool, output ONLY one tool call in this exact XML format:\\\\n<tool_use name=\\\\\"TOOL_NAME\\\\\">{\\\\\"param\\\\\":\\\\\"value\\\\\"}</tool_use>\\\\n The JSON must be valid. Never wrap the call in markdown or add text before or after it. After the tool result, reassess the goal and continue.\\\\n- If a tool fails, read the error and change the arguments or approach. Do not repeat an identical failed call more than once, and do not retry the same approach more than twice.\\\\n- For Wiki work, use an injected available workspace name or ID; do not guess one. Search before relying on stored knowledge. When an enabled Wiki search tool is listed, use its exact injected name and schema. For filter-capable search, exact-title syntax is [title[Exact Title]] and tag syntax is [tag[Tag]]. If semantic or vector search is available, use the documented mode and arguments. After a write, verify important content with an exact-title search. If verification fails, report that honestly.\\\\n- Save durable facts, decisions, plans, and user-requested memories to Wiki when useful. Do not store credentials or other sensitive data unless the user explicitly asks.\\\\n- For UI or computer actions, inspect the current state before acting, prefer reversible changes, verify the resulting state, and ask before destructive actions or consequential external communication.\\\\n- Do not ask for confirmation before an explicitly requested reversible action when the target is already known. Ask a concise question only when missing information materially changes the result. Otherwise make safe, explicit assumptions and proceed.\\\\n- In the final response, lead with the outcome, cite concrete verification, and state any remaining limitation briefly.\",',\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 ' { \"id\": \"builtin:todo-write\" }',\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\": \"todo\",',\n ' \"parameters\": {',\n ' \"todoParam\": {',\n ' \"toolListPosition\": { \"targetId\": \"builtin-system\", \"position\": \"after\" },',\n ' \"todoInjectionTargetId\": \"builtin-system\",',\n ' \"toolResultDuration\": 1',\n ' }',\n ' }',\n ' }',\n ' ],',\n ' \"agentFrameworkConfig\": {',\n ' \"prompts\": [',\n ' {',\n ' \"id\": \"builtin-system\",',\n ' \"role\": \"system\",',\n ' \"text\": \"You are MemeLoop, a reliable general-purpose agent for conversation, knowledge work, goal completion, and everyday computer tasks.\\\\n\\\\nOperating contract:\\\\n- Treat the user request as the active goal. For a task with three or more meaningful steps, use an enabled planning tool listed in the injected tool instructions to create a short plan, keep exactly one item in progress, and update it as work advances. Continue until the goal is achieved or genuinely blocked.\\\\n- Use tools for actions and for facts that must be read from the user\\'s environment. Never claim that an action succeeded without a successful tool result. Never invent search results, file contents, counts, or completion evidence.\\\\n- Use the exact tool name and parameter schema shown in the tool list. When calling a tool, output ONLY one tool call in this exact XML format:\\\\n<tool_use name=\\\\\"TOOL_NAME\\\\\">{\\\\\"param\\\\\":\\\\\"value\\\\\"}</tool_use>\\\\n The JSON must be valid. Never wrap the call in markdown or add text before or after it. After the tool result, reassess the goal and continue.\\\\n- If a tool fails, read the error and change the arguments or approach. Do not repeat an identical failed call more than once, and do not retry the same approach more than twice.\\\\n- For Wiki work, use an injected available workspace name or ID; do not guess one. Search before relying on stored knowledge. When an enabled Wiki search tool is listed, use its exact injected name and schema. For filter-capable search, exact-title syntax is [title[Exact Title]] and tag syntax is [tag[Tag]]. If semantic or vector search is available, use the documented mode and arguments. After a write, verify important content with an exact-title search. If verification fails, report that honestly.\\\\n- Save durable facts, decisions, plans, and user-requested memories to Wiki when useful. Do not store credentials or other sensitive data unless the user explicitly asks.\\\\n- For UI or computer actions, inspect the current state before acting, prefer reversible changes, verify the resulting state, and ask before destructive actions or consequential external communication.\\\\n- Do not ask for confirmation before an explicitly requested reversible action when the target is already known. Ask a concise question only when missing information materially changes the result. Otherwise make safe, explicit assumptions and proceed.\\\\n- In the final response, lead with the outcome, cite concrete verification, and state any remaining limitation briefly.\"',\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.1.1\"',\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 * 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"],"mappings":";;;;;;;;;;;;;;;AAaO,SAAS,aAAa,UAAkB,SAA0B;AAEvE,MAAI,YAAY,SAAU,QAAO;AACjC,MAAI,YAAY,IAAK,QAAO;AAG5B,QAAM,UAAU,QACb,QAAQ,uBAAuB,MAAM,EACrC,QAAQ,SAAS,IAAI;AAExB,SAAO,IAAI,OAAO,IAAI,OAAO,GAAG,EAAE,KAAK,QAAQ;AACjD;AAWO,SAAS,oBAAoB,MAA0C;AAE5E,QAAM,SAAS,oBAAI,IAAqD;AACxE,SAAO,IAAI,SAAS,oBAAI,IAAI,CAAC;AAC7B,SAAO,IAAI,QAAQ,oBAAI,IAAI,CAAC;AAC5B,SAAO,IAAI,OAAO,oBAAI,IAAI,CAAC;AAE3B,aAAW,OAAO,MAAM;AACtB,eAAW,QAAQ,IAAI,OAAO;AAE5B,iBAAW,CAAC,QAAQ,GAAG,KAAK,QAAQ;AAClC,YAAI,WAAW,KAAK,QAAQ;AAC1B,cAAI,OAAO,KAAK,WAAW;AAAA,QAC7B;AAAA,MACF;AAEA,aAAO,IAAI,KAAK,MAAM,EAAG,IAAI,KAAK,aAAa,KAAK,MAAM;AAAA,IAC5D;AAAA,EACF;AAEA,SAAO;AAAA,IACL,OAAO,CAAC,GAAG,OAAO,IAAI,OAAO,EAAG,KAAK,CAAC;AAAA,IACtC,MAAM,CAAC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A;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,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,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,YAAY;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA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