@claude-flow/plugin-gastown-bridge 0.1.3 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bd-bridge-C9wTbkhi.d.cts +318 -0
- package/dist/bd-bridge-C9wTbkhi.d.ts +318 -0
- package/dist/bridges.cjs +1 -1
- package/dist/bridges.d.cts +13 -612
- package/dist/bridges.d.ts +13 -612
- package/dist/bridges.js +1 -1
- package/dist/chunk-2KNTWGUX.js +12 -0
- package/dist/chunk-2KNTWGUX.js.map +1 -0
- package/dist/chunk-46PJFOMY.cjs +11 -0
- package/dist/chunk-46PJFOMY.cjs.map +1 -0
- package/dist/chunk-7UPWLRZX.js +11 -0
- package/dist/chunk-7UPWLRZX.js.map +1 -0
- package/dist/chunk-7VD5N6NG.cjs +11 -0
- package/dist/chunk-7VD5N6NG.cjs.map +1 -0
- package/dist/chunk-EBOVUTYL.js +12 -0
- package/dist/chunk-EBOVUTYL.js.map +1 -0
- package/dist/chunk-I2TLUPMJ.cjs +12 -0
- package/dist/chunk-I2TLUPMJ.cjs.map +1 -0
- package/dist/chunk-Q7MLH722.cjs +11 -0
- package/dist/chunk-Q7MLH722.cjs.map +1 -0
- package/dist/chunk-QFMFM7NE.cjs +13 -0
- package/dist/chunk-QFMFM7NE.cjs.map +1 -0
- package/dist/chunk-SUKPSMVK.cjs +12 -0
- package/dist/chunk-SUKPSMVK.cjs.map +1 -0
- package/dist/chunk-TGFYZY3C.js +11 -0
- package/dist/chunk-TGFYZY3C.js.map +1 -0
- package/dist/chunk-U74VYTRV.js +11 -0
- package/dist/chunk-U74VYTRV.js.map +1 -0
- package/dist/chunk-UJ56JMNG.js +13 -0
- package/dist/chunk-UJ56JMNG.js.map +1 -0
- package/dist/convoy.cjs +2 -0
- package/dist/convoy.cjs.map +1 -0
- package/dist/convoy.d.cts +6 -0
- package/dist/convoy.d.ts +6 -0
- package/dist/convoy.js +2 -0
- package/dist/convoy.js.map +1 -0
- package/dist/formula.cjs +2 -0
- package/dist/formula.cjs.map +1 -0
- package/dist/formula.d.cts +317 -0
- package/dist/formula.d.ts +317 -0
- package/dist/formula.js +2 -0
- package/dist/formula.js.map +1 -0
- package/dist/gt-bridge-B7hZz5vC.d.cts +291 -0
- package/dist/gt-bridge-B7hZz5vC.d.ts +291 -0
- package/dist/index-BzkAx4ho.d.ts +785 -0
- package/dist/index-CGJs8eMa.d.cts +785 -0
- package/dist/index.cjs +8 -9
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +17 -2241
- package/dist/index.d.ts +17 -2241
- package/dist/index.js +8 -9
- package/dist/index.js.map +1 -1
- package/dist/types-CMoOZXrm.d.cts +1146 -0
- package/dist/types-CMoOZXrm.d.ts +1146 -0
- package/dist/wasm-loader.js +1 -1
- package/package.json +16 -18
- package/dist/chunk-IBKUMYUL.js +0 -14
- package/dist/chunk-IBKUMYUL.js.map +0 -1
- package/dist/chunk-JF2GA7QE.cjs +0 -14
- package/dist/chunk-JF2GA7QE.cjs.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/bridges/gt-bridge.ts","../src/bridges/sync-bridge.ts"],"names":["execFileAsync","promisify","execFile","resultCache","LRUCache","staticCache","execDedup","BatchDeduplicator","parsedCache","hashArgs","args","hash","arg","i","SafeStringSchema","z","val","IdentifierSchema","GasPriceSchema","GasLimitSchema","TxHashSchema","AddressSchema","NetworkSchema","GtArgumentSchema","GtBridgeError","message","code","command","cause","defaultLogger","msg","meta","ALLOWED_GT_COMMANDS","GtBridge","_GtBridge","config","logger","result","error","skipCache","startTime","validatedArgs","subcommand","cacheKey","isCacheable","isStatic","cached","stdout","stderr","durationMs","err","output","parsed","jsonMatch","params","validatedTo","network","validatedData","validatedValue","validatedFrom","txHash","data","abi","validatedAbi","index","createGtBridge","agentDBLookupCache","conflictCache","hashKey","parts","part","ConflictStrategySchema","SyncDirectionSchema","SyncStatusSchema","AgentDBEntrySchema","SyncBridgeError","details","SyncBridge","agentDB","createBdBridge","savedState","beads","lookupPromises","bead","key","existing","lookupResults","conflictCacheKey","hasConflict","offset","hasMore","entries","entry","allBeads","toAgentDBResult","fromAgentDBBeads","c","beadId","resolution","mergedData","conflict","merged","pendingIndex","value","beadTime","entryTime","entryData","mergedBead","createSyncBridge"],"mappings":";;;;;;;;;AA0BA,IAAMA,CAAAA,CAAgBC,cAAAA,CAAUC,sBAAQ,CAAA,CAOlCC,CAAAA,CAAc,IAAIC,mBAAAA,CAAmC,CACzD,UAAA,CAAY,GAAA,CACZ,MAAO,EAAA,CAAK,GACd,CAAC,CAAA,CAGKC,CAAAA,CAAc,IAAID,mBAAAA,CAA0B,CAChD,UAAA,CAAY,GAAA,CACZ,MAAO,GAAA,CAAS,GAClB,CAAC,CAAA,CAGKE,CAAAA,CAAY,IAAIC,mBAAAA,CAGhBC,CAAAA,CAAc,IAAIJ,mBAAAA,CAA0B,CAChD,UAAA,CAAY,GAAA,CACZ,MAAO,EAAA,CAAK,GACd,CAAC,CAAA,CAKD,SAASK,CAAAA,CAASC,CAAAA,CAAwB,CACxC,IAAIC,CAAAA,CAAO,WACX,IAAA,IAAWC,CAAAA,IAAOF,EAAM,CACtB,IAAA,IAASG,CAAAA,CAAI,CAAA,CAAGA,EAAID,CAAAA,CAAI,MAAA,CAAQC,IAC9BF,CAAAA,EAAQC,CAAAA,CAAI,WAAWC,CAAC,CAAA,CACxBF,CAAAA,CAAQA,CAAAA,CAAO,WAAc,CAAA,CAE/BA,CAAAA,EAAQ,IACV,CACA,OAAOA,EAAK,QAAA,CAAS,EAAE,CACzB,KASMG,CAAAA,CAAmBC,KAAAA,CAAE,QAAO,CAC/B,GAAA,CAAI,KAAM,iBAAiB,CAAA,CAC3B,MAAA,CACEC,CAAAA,EAAQ,CAAC,qBAAA,CAAsB,IAAA,CAAKA,CAAG,CAAA,CACxC,sCACF,EAKIC,CAAAA,CAAmBF,KAAAA,CAAE,MAAA,EAAO,CAC/B,IAAI,CAAA,C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F,CAKQ,iBAAA,EAA0B,CAChC,GAAI,CAAC,IAAA,CAAK,WAAA,CACR,MAAM,IAAIqC,CAAAA,CACR,uDAAA,CACA,iBACF,CAEJ,CAKA,aAAA,EAAyB,CACvB,OAAO,IAAA,CAAK,WACd,CAKA,cAAA,EAA2B,CACzB,OAAO,IAAA,CAAK,QACd,CAKA,aAAA,EAGE,CACA,OAAO,CACL,kBAAA,CAAoBT,CAAAA,CAAmB,KAAA,EAAM,CAC7C,cAAeC,CAAAA,CAAc,KAAA,EAC/B,CACF,CAKA,aAAoB,CAClBD,CAAAA,CAAmB,KAAA,EAAM,CACzBC,EAAc,KAAA,GAChB,CACF,EAKO,SAASyC,CAAAA,CACd9B,CAAAA,CACA3C,CAAAA,CACAC,CAAAA,CACY,CACZ,OAAO,IAAIyC,EAAWC,CAAAA,CAAS3C,CAAAA,CAAQC,CAAM,CAC/C","file":"chunk-QFMFM7NE.cjs","sourcesContent":["/**\n * Gas Town CLI Bridge\n *\n * Provides a secure wrapper around the `gt` (Gas Town) CLI tool.\n * Implements command execution with proper input sanitization,\n * argument validation, and error handling.\n *\n * Security Features:\n * - All inputs validated with Zod schemas\n * - No shell execution (uses execFile)\n * - Command allowlist enforcement\n * - Argument sanitization\n *\n * @module v3/plugins/gastown-bridge/bridges/gt-bridge\n */\n\nimport { execFile } from 'child_process';\nimport { promisify } from 'util';\nimport { z } from 'zod';\n\nimport {\n LRUCache,\n BatchDeduplicator,\n Lazy,\n} from '../cache.js';\n\nconst execFileAsync = promisify(execFile);\n\n// ============================================================================\n// Performance Caches\n// ============================================================================\n\n/** Result cache for memoizing expensive CLI calls */\nconst resultCache = new LRUCache<string, GtResult<string>>({\n maxEntries: 200,\n ttlMs: 30 * 1000, // 30 sec TTL (gas prices change frequently)\n});\n\n/** Longer cache for static data like tx status */\nconst staticCache = new LRUCache<string, unknown>({\n maxEntries: 500,\n ttlMs: 5 * 60 * 1000, // 5 min TTL\n});\n\n/** Deduplicator for concurrent identical CLI calls */\nconst execDedup = new BatchDeduplicator<GtResult<string>>();\n\n/** Lazy parsed output cache */\nconst parsedCache = new LRUCache<string, unknown>({\n maxEntries: 500,\n ttlMs: 60 * 1000, // 1 min TTL\n});\n\n/**\n * FNV-1a hash for cache keys\n */\nfunction hashArgs(args: string[]): string {\n let hash = 2166136261;\n for (const arg of args) {\n for (let i = 0; i < arg.length; i++) {\n hash ^= arg.charCodeAt(i);\n hash = (hash * 16777619) >>> 0;\n }\n hash ^= 0xff; // separator\n }\n return hash.toString(36);\n}\n\n// ============================================================================\n// Zod Validation Schemas\n// ============================================================================\n\n/**\n * Safe string pattern - no shell metacharacters\n */\nconst SafeStringSchema = z.string()\n .max(1024, 'String too long')\n .refine(\n (val) => !/[;&|`$(){}><\\n\\r\\0]/.test(val),\n 'String contains shell metacharacters'\n );\n\n/**\n * Safe identifier pattern - alphanumeric with underscore/hyphen\n */\nconst IdentifierSchema = z.string()\n .min(1, 'Identifier cannot be empty')\n .max(64, 'Identifier too long')\n .regex(/^[a-zA-Z][a-zA-Z0-9_-]*$/, 'Invalid identifier format');\n\n/**\n * Gas price schema\n */\nconst GasPriceSchema = z.number()\n .positive('Gas price must be positive')\n .max(1_000_000, 'Gas price exceeds maximum');\n\n/**\n * Gas limit schema\n */\nconst GasLimitSchema = z.number()\n .int('Gas limit must be an integer')\n .positive('Gas limit must be positive')\n .max(30_000_000, 'Gas limit exceeds maximum');\n\n/**\n * Transaction hash schema (0x prefixed hex)\n */\nconst TxHashSchema = z.string()\n .regex(/^0x[a-fA-F0-9]{64}$/, 'Invalid transaction hash format');\n\n/**\n * Address schema (0x prefixed hex)\n */\nconst AddressSchema = z.string()\n .regex(/^0x[a-fA-F0-9]{40}$/, 'Invalid address format');\n\n/**\n * Network schema\n */\nconst NetworkSchema = z.enum([\n 'mainnet',\n 'goerli',\n 'sepolia',\n 'polygon',\n 'arbitrum',\n 'optimism',\n 'base',\n 'local',\n]);\n\n/**\n * GT command argument schema\n */\nconst GtArgumentSchema = z.string()\n .max(512, 'Argument too long')\n .refine(\n (val) => !val.includes('\\0'),\n 'Argument contains null byte'\n )\n .refine(\n (val) => !/[;&|`$(){}><]/.test(val),\n 'Argument contains shell metacharacters'\n );\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Gas Town executor configuration\n */\nexport interface GtBridgeConfig {\n /**\n * Path to gt executable\n * Default: 'gt' (assumes in PATH)\n */\n gtPath?: string;\n\n /**\n * Working directory for execution\n */\n cwd?: string;\n\n /**\n * Execution timeout in milliseconds\n * Default: 30000 (30 seconds)\n */\n timeout?: number;\n\n /**\n * Maximum buffer size for output\n * Default: 10MB\n */\n maxBuffer?: number;\n\n /**\n * Environment variables\n */\n env?: NodeJS.ProcessEnv;\n\n /**\n * Default network\n */\n defaultNetwork?: z.infer<typeof NetworkSchema>;\n}\n\n/**\n * Gas estimation result\n */\nexport interface GasEstimate {\n gasLimit: number;\n gasPrice: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n estimatedCost: string;\n estimatedCostUsd?: number;\n}\n\n/**\n * Transaction status\n */\nexport interface TxStatus {\n hash: string;\n status: 'pending' | 'confirmed' | 'failed' | 'dropped';\n blockNumber?: number;\n confirmations?: number;\n gasUsed?: number;\n effectiveGasPrice?: string;\n error?: string;\n}\n\n/**\n * Network status\n */\nexport interface NetworkStatus {\n network: string;\n chainId: number;\n blockNumber: number;\n baseFee?: string;\n gasPrice?: string;\n connected: boolean;\n}\n\n/**\n * GT execution result\n */\nexport interface GtResult<T = unknown> {\n success: boolean;\n data?: T;\n error?: string;\n command: string;\n args: string[];\n durationMs: number;\n}\n\n/**\n * Logger interface\n */\nexport interface GtLogger {\n debug: (msg: string, meta?: Record<string, unknown>) => void;\n info: (msg: string, meta?: Record<string, unknown>) => void;\n warn: (msg: string, meta?: Record<string, unknown>) => void;\n error: (msg: string, meta?: Record<string, unknown>) => void;\n}\n\n// ============================================================================\n// Errors\n// ============================================================================\n\n/**\n * Gas Town bridge error codes\n */\nexport type GtErrorCode =\n | 'COMMAND_NOT_FOUND'\n | 'EXECUTION_FAILED'\n | 'TIMEOUT'\n | 'INVALID_ARGUMENT'\n | 'INVALID_OUTPUT'\n | 'NETWORK_ERROR'\n | 'VALIDATION_ERROR';\n\n/**\n * Gas Town bridge error\n */\nexport class GtBridgeError extends Error {\n constructor(\n message: string,\n public readonly code: GtErrorCode,\n public readonly command?: string,\n public readonly args?: string[],\n public readonly cause?: Error\n ) {\n super(message);\n this.name = 'GtBridgeError';\n }\n}\n\n// ============================================================================\n// Default Logger\n// ============================================================================\n\nconst defaultLogger: GtLogger = {\n debug: (msg, meta) => console.debug(`[gt-bridge] ${msg}`, meta ?? ''),\n info: (msg, meta) => console.info(`[gt-bridge] ${msg}`, meta ?? ''),\n warn: (msg, meta) => console.warn(`[gt-bridge] ${msg}`, meta ?? ''),\n error: (msg, meta) => console.error(`[gt-bridge] ${msg}`, meta ?? ''),\n};\n\n// ============================================================================\n// Allowed Commands\n// ============================================================================\n\n/**\n * Allowed gt subcommands (allowlist)\n */\nconst ALLOWED_GT_COMMANDS = new Set([\n 'estimate',\n 'status',\n 'network',\n 'price',\n 'tx',\n 'simulate',\n 'decode',\n 'encode',\n 'help',\n 'version',\n 'config',\n]);\n\n// ============================================================================\n// Gas Town Bridge Implementation\n// ============================================================================\n\n/**\n * Gas Town CLI Bridge\n *\n * Secure wrapper around the `gt` CLI tool for gas estimation\n * and transaction management.\n *\n * @example\n * ```typescript\n * const gtBridge = new GtBridge({ gtPath: '/usr/local/bin/gt' });\n * await gtBridge.initialize();\n *\n * const estimate = await gtBridge.estimateGas({\n * to: '0x...',\n * data: '0x...',\n * network: 'mainnet',\n * });\n * ```\n */\nexport class GtBridge {\n private config: Required<GtBridgeConfig>;\n private logger: GtLogger;\n private initialized = false;\n\n /** Commands that can be cached (read-only, no side effects) */\n private static readonly CACHEABLE_COMMANDS = new Set([\n 'version',\n 'status',\n 'price',\n 'decode',\n 'help',\n 'config',\n ]);\n\n /** Commands that should use longer cache (static data) */\n private static readonly STATIC_COMMANDS = new Set([\n 'version',\n 'help',\n 'decode',\n ]);\n\n constructor(config?: GtBridgeConfig, logger?: GtLogger) {\n this.config = {\n gtPath: config?.gtPath ?? 'gt',\n cwd: config?.cwd ?? process.cwd(),\n timeout: config?.timeout ?? 30000,\n maxBuffer: config?.maxBuffer ?? 10 * 1024 * 1024,\n env: config?.env ?? process.env,\n defaultNetwork: config?.defaultNetwork ?? 'mainnet',\n };\n this.logger = logger ?? defaultLogger;\n }\n\n /**\n * Initialize the bridge and verify gt is available\n */\n async initialize(): Promise<void> {\n try {\n const result = await this.execGt(['version']);\n if (!result.success) {\n throw new GtBridgeError(\n 'Failed to verify gt installation',\n 'COMMAND_NOT_FOUND',\n 'gt',\n ['version']\n );\n }\n this.initialized = true;\n this.logger.info('Gas Town bridge initialized', {\n gtPath: this.config.gtPath,\n version: result.data,\n });\n } catch (error) {\n if (error instanceof GtBridgeError) throw error;\n throw new GtBridgeError(\n 'Failed to initialize Gas Town bridge',\n 'COMMAND_NOT_FOUND',\n 'gt',\n ['version'],\n error as Error\n );\n }\n }\n\n /**\n * Execute a gt command with validated arguments\n *\n * @param args - Command arguments (validated and sanitized)\n * @returns Command output\n */\n async execGt(args: string[], skipCache = false): Promise<GtResult<string>> {\n const startTime = Date.now();\n\n // Validate all arguments\n const validatedArgs = this.validateAndSanitizeArgs(args);\n\n // Validate subcommand is allowed\n const subcommand = validatedArgs[0];\n if (subcommand && !ALLOWED_GT_COMMANDS.has(subcommand)) {\n throw new GtBridgeError(\n `Command not allowed: ${subcommand}`,\n 'INVALID_ARGUMENT',\n 'gt',\n validatedArgs\n );\n }\n\n // Check cache for cacheable commands\n const cacheKey = hashArgs(validatedArgs);\n const isCacheable = !skipCache && subcommand && GtBridge.CACHEABLE_COMMANDS.has(subcommand);\n const isStatic = subcommand && GtBridge.STATIC_COMMANDS.has(subcommand);\n\n if (isCacheable) {\n const cached = isStatic\n ? staticCache.get(cacheKey) as GtResult<string> | undefined\n : resultCache.get(cacheKey);\n if (cached) {\n this.logger.debug('Cache hit for gt command', { command: subcommand });\n return {\n ...cached,\n durationMs: 0, // Cached result\n };\n }\n }\n\n // Use deduplication for concurrent identical calls\n return execDedup.dedupe(cacheKey, async () => {\n try {\n this.logger.debug('Executing gt command', {\n command: 'gt',\n args: validatedArgs,\n });\n\n const { stdout, stderr } = await execFileAsync(\n this.config.gtPath,\n validatedArgs,\n {\n cwd: this.config.cwd,\n env: this.config.env,\n timeout: this.config.timeout,\n maxBuffer: this.config.maxBuffer,\n shell: false, // CRITICAL: Never use shell\n windowsHide: true,\n }\n );\n\n const durationMs = Date.now() - startTime;\n\n if (stderr && stderr.trim()) {\n this.logger.warn('gt stderr output', { stderr });\n }\n\n const result: GtResult<string> = {\n success: true,\n data: stdout.trim(),\n command: 'gt',\n args: validatedArgs,\n durationMs,\n };\n\n // Cache successful results\n if (isCacheable && result.success) {\n if (isStatic) {\n staticCache.set(cacheKey, result);\n } else {\n resultCache.set(cacheKey, result);\n }\n }\n\n return result;\n } catch (error: unknown) {\n const durationMs = Date.now() - startTime;\n const err = error as NodeJS.ErrnoException & {\n killed?: boolean;\n stdout?: string;\n stderr?: string;\n };\n\n if (err.killed) {\n throw new GtBridgeError(\n 'Command execution timed out',\n 'TIMEOUT',\n 'gt',\n validatedArgs\n );\n }\n\n if (err.code === 'ENOENT') {\n throw new GtBridgeError(\n `gt executable not found at: ${this.config.gtPath}`,\n 'COMMAND_NOT_FOUND',\n 'gt',\n validatedArgs\n );\n }\n\n return {\n success: false,\n error: err.stderr || err.message,\n command: 'gt',\n args: validatedArgs,\n durationMs,\n };\n }\n });\n }\n\n /**\n * Parse JSON output from gt command\n *\n * @param output - Raw command output\n * @returns Parsed JSON object\n */\n parseGtOutput<T>(output: string): T {\n if (!output || output.trim() === '') {\n throw new GtBridgeError(\n 'Empty output from gt command',\n 'INVALID_OUTPUT'\n );\n }\n\n // Check parsed cache first\n const cacheKey = hashArgs([output]);\n const cached = parsedCache.get(cacheKey);\n if (cached !== undefined) {\n return cached as T;\n }\n\n try {\n // Try to parse as JSON\n const parsed = JSON.parse(output) as T;\n parsedCache.set(cacheKey, parsed);\n return parsed;\n } catch {\n // If not JSON, try to extract JSON from output\n const jsonMatch = output.match(/\\{[\\s\\S]*\\}|\\[[\\s\\S]*\\]/);\n if (jsonMatch) {\n try {\n const parsed = JSON.parse(jsonMatch[0]) as T;\n parsedCache.set(cacheKey, parsed);\n return parsed;\n } catch {\n throw new GtBridgeError(\n 'Failed to parse gt output as JSON',\n 'INVALID_OUTPUT'\n );\n }\n }\n\n throw new GtBridgeError(\n 'Output is not valid JSON',\n 'INVALID_OUTPUT'\n );\n }\n }\n\n /**\n * Estimate gas for a transaction\n */\n async estimateGas(params: {\n to: string;\n data?: string;\n value?: string;\n from?: string;\n network?: z.infer<typeof NetworkSchema>;\n }): Promise<GasEstimate> {\n this.ensureInitialized();\n\n // Validate parameters\n const validatedTo = AddressSchema.parse(params.to);\n const network = params.network ?? this.config.defaultNetwork;\n\n const args = ['estimate', '--to', validatedTo, '--network', network, '--json'];\n\n if (params.data) {\n const validatedData = SafeStringSchema.parse(params.data);\n args.push('--data', validatedData);\n }\n\n if (params.value) {\n const validatedValue = SafeStringSchema.parse(params.value);\n args.push('--value', validatedValue);\n }\n\n if (params.from) {\n const validatedFrom = AddressSchema.parse(params.from);\n args.push('--from', validatedFrom);\n }\n\n const result = await this.execGt(args);\n if (!result.success || !result.data) {\n throw new GtBridgeError(\n result.error ?? 'Gas estimation failed',\n 'EXECUTION_FAILED',\n 'gt',\n args\n );\n }\n\n return this.parseGtOutput<GasEstimate>(result.data);\n }\n\n /**\n * Get transaction status\n */\n async getTxStatus(txHash: string, network?: z.infer<typeof NetworkSchema>): Promise<TxStatus> {\n this.ensureInitialized();\n\n const validatedHash = TxHashSchema.parse(txHash);\n const args = [\n 'tx',\n 'status',\n validatedHash,\n '--network',\n network ?? this.config.defaultNetwork,\n '--json',\n ];\n\n const result = await this.execGt(args);\n if (!result.success || !result.data) {\n throw new GtBridgeError(\n result.error ?? 'Failed to get transaction status',\n 'EXECUTION_FAILED',\n 'gt',\n args\n );\n }\n\n return this.parseGtOutput<TxStatus>(result.data);\n }\n\n /**\n * Get network status\n */\n async getNetworkStatus(network?: z.infer<typeof NetworkSchema>): Promise<NetworkStatus> {\n this.ensureInitialized();\n\n const args = [\n 'network',\n 'status',\n '--network',\n network ?? this.config.defaultNetwork,\n '--json',\n ];\n\n const result = await this.execGt(args);\n if (!result.success || !result.data) {\n throw new GtBridgeError(\n result.error ?? 'Failed to get network status',\n 'NETWORK_ERROR',\n 'gt',\n args\n );\n }\n\n return this.parseGtOutput<NetworkStatus>(result.data);\n }\n\n /**\n * Get current gas price\n */\n async getGasPrice(network?: z.infer<typeof NetworkSchema>): Promise<{\n gasPrice: string;\n maxFeePerGas?: string;\n maxPriorityFeePerGas?: string;\n baseFee?: string;\n }> {\n this.ensureInitialized();\n\n const args = [\n 'price',\n '--network',\n network ?? this.config.defaultNetwork,\n '--json',\n ];\n\n const result = await this.execGt(args);\n if (!result.success || !result.data) {\n throw new GtBridgeError(\n result.error ?? 'Failed to get gas price',\n 'EXECUTION_FAILED',\n 'gt',\n args\n );\n }\n\n return this.parseGtOutput(result.data);\n }\n\n /**\n * Simulate a transaction\n */\n async simulate(params: {\n to: string;\n data: string;\n value?: string;\n from?: string;\n network?: z.infer<typeof NetworkSchema>;\n blockNumber?: number;\n }): Promise<{\n success: boolean;\n returnData?: string;\n gasUsed?: number;\n logs?: unknown[];\n error?: string;\n }> {\n this.ensureInitialized();\n\n const validatedTo = AddressSchema.parse(params.to);\n const validatedData = SafeStringSchema.parse(params.data);\n const network = params.network ?? this.config.defaultNetwork;\n\n const args = [\n 'simulate',\n '--to', validatedTo,\n '--data', validatedData,\n '--network', network,\n '--json',\n ];\n\n if (params.value) {\n args.push('--value', SafeStringSchema.parse(params.value));\n }\n\n if (params.from) {\n args.push('--from', AddressSchema.parse(params.from));\n }\n\n if (params.blockNumber !== undefined) {\n args.push('--block', String(params.blockNumber));\n }\n\n const result = await this.execGt(args);\n if (!result.success || !result.data) {\n throw new GtBridgeError(\n result.error ?? 'Transaction simulation failed',\n 'EXECUTION_FAILED',\n 'gt',\n args\n );\n }\n\n return this.parseGtOutput(result.data);\n }\n\n /**\n * Decode transaction data\n */\n async decode(data: string, abi?: string): Promise<{\n method: string;\n args: unknown[];\n signature: string;\n }> {\n this.ensureInitialized();\n\n const validatedData = SafeStringSchema.parse(data);\n const args = ['decode', validatedData, '--json'];\n\n if (abi) {\n const validatedAbi = SafeStringSchema.parse(abi);\n args.push('--abi', validatedAbi);\n }\n\n const result = await this.execGt(args);\n if (!result.success || !result.data) {\n throw new GtBridgeError(\n result.error ?? 'Failed to decode transaction data',\n 'EXECUTION_FAILED',\n 'gt',\n args\n );\n }\n\n return this.parseGtOutput(result.data);\n }\n\n /**\n * Validate and sanitize command arguments\n */\n private validateAndSanitizeArgs(args: string[]): string[] {\n return args.map((arg, index) => {\n try {\n return GtArgumentSchema.parse(arg);\n } catch (error) {\n throw new GtBridgeError(\n `Invalid argument at index ${index}: ${arg}`,\n 'VALIDATION_ERROR',\n 'gt',\n args,\n error as Error\n );\n }\n });\n }\n\n /**\n * Ensure bridge is initialized\n */\n private ensureInitialized(): void {\n if (!this.initialized) {\n throw new GtBridgeError(\n 'Gas Town bridge not initialized. Call initialize() first.',\n 'EXECUTION_FAILED'\n );\n }\n }\n\n /**\n * Check if bridge is initialized\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get current configuration\n */\n getConfig(): Readonly<Required<GtBridgeConfig>> {\n return { ...this.config };\n }\n\n /**\n * Get cache statistics for performance monitoring\n */\n getCacheStats(): {\n resultCache: { entries: number; sizeBytes: number };\n staticCache: { entries: number; sizeBytes: number };\n parsedCache: { entries: number; sizeBytes: number };\n } {\n return {\n resultCache: resultCache.stats(),\n staticCache: staticCache.stats(),\n parsedCache: parsedCache.stats(),\n };\n }\n\n /**\n * Clear all caches (useful for testing or memory pressure)\n */\n clearCaches(): void {\n resultCache.clear();\n staticCache.clear();\n parsedCache.clear();\n }\n}\n\n/**\n * Create a new Gas Town bridge instance\n */\nexport function createGtBridge(config?: GtBridgeConfig, logger?: GtLogger): GtBridge {\n return new GtBridge(config, logger);\n}\n\n// Export schemas for external use\nexport {\n SafeStringSchema,\n IdentifierSchema,\n GasPriceSchema,\n GasLimitSchema,\n TxHashSchema,\n AddressSchema,\n NetworkSchema,\n GtArgumentSchema,\n};\n\nexport default GtBridge;\n","/**\n * Beads-AgentDB Sync Bridge\n *\n * Provides bidirectional synchronization between Beads (bd)\n * and AgentDB. Implements conflict resolution strategies\n * and maintains consistency between the two systems.\n *\n * Features:\n * - Bidirectional sync (Beads <-> AgentDB)\n * - Conflict resolution strategies\n * - Incremental sync support\n * - Transaction-safe operations\n * - Embedding preservation\n *\n * @module v3/plugins/gastown-bridge/bridges/sync-bridge\n */\n\nimport { z } from 'zod';\nimport { BdBridge, createBdBridge, type Bead, type BeadType, type BdBridgeConfig } from './bd-bridge.js';\n\nimport {\n LRUCache,\n BatchDeduplicator,\n} from '../cache.js';\n\n// ============================================================================\n// Performance Caches\n// ============================================================================\n\n/** Cache for AgentDB lookups during sync */\nconst agentDBLookupCache = new LRUCache<string, AgentDBEntry | null>({\n maxEntries: 500,\n ttlMs: 30 * 1000, // 30 sec TTL\n});\n\n/** Cache for conflict detection results */\nconst conflictCache = new LRUCache<string, boolean>({\n maxEntries: 200,\n ttlMs: 10 * 1000, // 10 sec TTL\n});\n\n/** Deduplicator for concurrent sync operations */\nconst syncDedup = new BatchDeduplicator<SyncResult>();\n\n/**\n * FNV-1a hash for cache keys\n */\nfunction hashKey(parts: string[]): string {\n let hash = 2166136261;\n for (const part of parts) {\n for (let i = 0; i < part.length; i++) {\n hash ^= part.charCodeAt(i);\n hash = (hash * 16777619) >>> 0;\n }\n hash ^= 0xff;\n }\n return hash.toString(36);\n}\n\n// ============================================================================\n// Zod Validation Schemas\n// ============================================================================\n\n/**\n * Sync conflict resolution strategy\n */\nconst ConflictStrategySchema = z.enum([\n 'beads-wins', // Beads data takes precedence\n 'agentdb-wins', // AgentDB data takes precedence\n 'newest-wins', // Most recent timestamp wins\n 'merge', // Attempt to merge fields\n 'manual', // Flag for manual resolution\n]);\n\n/**\n * Sync direction\n */\nconst SyncDirectionSchema = z.enum([\n 'to-agentdb', // Beads -> AgentDB\n 'from-agentdb', // AgentDB -> Beads\n 'bidirectional', // Both directions\n]);\n\n/**\n * Sync status\n */\nconst SyncStatusSchema = z.enum([\n 'pending',\n 'in-progress',\n 'completed',\n 'failed',\n 'conflict',\n]);\n\n/**\n * AgentDB entry schema (compatible with claude-flow memory)\n */\nconst AgentDBEntrySchema = z.object({\n key: z.string(),\n value: z.unknown(),\n namespace: z.string().optional(),\n metadata: z.record(z.unknown()).optional(),\n embedding: z.array(z.number()).optional(),\n createdAt: z.string().datetime().optional(),\n updatedAt: z.string().datetime().optional(),\n version: z.number().optional(),\n});\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Conflict resolution strategy type\n */\nexport type ConflictStrategy = z.infer<typeof ConflictStrategySchema>;\n\n/**\n * Sync direction type\n */\nexport type SyncDirection = z.infer<typeof SyncDirectionSchema>;\n\n/**\n * Sync status type\n */\nexport type SyncStatus = z.infer<typeof SyncStatusSchema>;\n\n/**\n * AgentDB entry type\n */\nexport type AgentDBEntry = z.infer<typeof AgentDBEntrySchema>;\n\n/**\n * Sync bridge configuration\n */\nexport interface SyncBridgeConfig {\n /**\n * Beads bridge configuration\n */\n beadsBridge?: BdBridgeConfig;\n\n /**\n * AgentDB namespace for beads\n * Default: 'beads'\n */\n agentdbNamespace?: string;\n\n /**\n * Conflict resolution strategy\n * Default: 'newest-wins'\n */\n conflictStrategy?: ConflictStrategy;\n\n /**\n * Batch size for sync operations\n * Default: 100\n */\n batchSize?: number;\n\n /**\n * Whether to preserve embeddings during sync\n * Default: true\n */\n preserveEmbeddings?: boolean;\n\n /**\n * Whether to sync metadata\n * Default: true\n */\n syncMetadata?: boolean;\n}\n\n/**\n * Sync operation result\n */\nexport interface SyncResult {\n success: boolean;\n direction: SyncDirection;\n synced: number;\n created: number;\n updated: number;\n deleted: number;\n conflicts: number;\n errors: Array<{ id: string; error: string }>;\n durationMs: number;\n timestamp: string;\n}\n\n/**\n * Conflict record\n */\nexport interface SyncConflict {\n beadId: string;\n beadData: Bead;\n agentdbData: AgentDBEntry;\n conflictType: 'update' | 'delete' | 'create';\n resolution?: 'beads' | 'agentdb' | 'merged' | 'pending';\n resolvedAt?: string;\n}\n\n/**\n * Sync state for incremental sync\n */\nexport interface SyncState {\n lastSyncTime: string;\n lastBeadId?: string;\n lastAgentDBKey?: string;\n pendingConflicts: string[];\n version: number;\n}\n\n/**\n * AgentDB interface (to be provided by claude-flow)\n */\nexport interface IAgentDBService {\n store(key: string, value: unknown, namespace?: string, metadata?: Record<string, unknown>): Promise<void>;\n retrieve(key: string, namespace?: string): Promise<AgentDBEntry | null>;\n search(query: string, namespace?: string, limit?: number): Promise<AgentDBEntry[]>;\n list(namespace?: string, limit?: number, offset?: number): Promise<AgentDBEntry[]>;\n delete(key: string, namespace?: string): Promise<void>;\n getNamespaceStats(namespace: string): Promise<{ count: number; lastUpdated?: string }>;\n}\n\n/**\n * Logger interface\n */\nexport interface SyncLogger {\n debug: (msg: string, meta?: Record<string, unknown>) => void;\n info: (msg: string, meta?: Record<string, unknown>) => void;\n warn: (msg: string, meta?: Record<string, unknown>) => void;\n error: (msg: string, meta?: Record<string, unknown>) => void;\n}\n\n// ============================================================================\n// Errors\n// ============================================================================\n\n/**\n * Sync bridge error codes\n */\nexport type SyncErrorCode =\n | 'NOT_INITIALIZED'\n | 'SYNC_FAILED'\n | 'CONFLICT_UNRESOLVED'\n | 'AGENTDB_ERROR'\n | 'BEADS_ERROR'\n | 'VALIDATION_ERROR'\n | 'TRANSACTION_FAILED';\n\n/**\n * Sync bridge error\n */\nexport class SyncBridgeError extends Error {\n constructor(\n message: string,\n public readonly code: SyncErrorCode,\n public readonly details?: Record<string, unknown>,\n public readonly cause?: Error\n ) {\n super(message);\n this.name = 'SyncBridgeError';\n }\n}\n\n// ============================================================================\n// Default Logger\n// ============================================================================\n\nconst defaultLogger: SyncLogger = {\n debug: (msg, meta) => console.debug(`[sync-bridge] ${msg}`, meta ?? ''),\n info: (msg, meta) => console.info(`[sync-bridge] ${msg}`, meta ?? ''),\n warn: (msg, meta) => console.warn(`[sync-bridge] ${msg}`, meta ?? ''),\n error: (msg, meta) => console.error(`[sync-bridge] ${msg}`, meta ?? ''),\n};\n\n// ============================================================================\n// Sync Bridge Implementation\n// ============================================================================\n\n/**\n * Beads-AgentDB Sync Bridge\n *\n * Provides bidirectional synchronization between Beads and AgentDB\n * with configurable conflict resolution.\n *\n * @example\n * ```typescript\n * const syncBridge = new SyncBridge(agentDB, {\n * conflictStrategy: 'newest-wins',\n * agentdbNamespace: 'conversation-beads',\n * });\n * await syncBridge.initialize();\n *\n * // Sync beads to AgentDB\n * const result = await syncBridge.syncToAgentDB(beads);\n *\n * // Sync from AgentDB back to beads\n * const beads = await syncBridge.syncFromAgentDB();\n * ```\n */\nexport class SyncBridge {\n private bdBridge: BdBridge;\n private agentDB: IAgentDBService;\n private config: Required<SyncBridgeConfig>;\n private logger: SyncLogger;\n private initialized = false;\n private syncState: SyncState;\n private conflicts: Map<string, SyncConflict> = new Map();\n\n constructor(\n agentDB: IAgentDBService,\n config?: SyncBridgeConfig,\n logger?: SyncLogger\n ) {\n this.agentDB = agentDB;\n this.config = {\n beadsBridge: config?.beadsBridge ?? {},\n agentdbNamespace: config?.agentdbNamespace ?? 'beads',\n conflictStrategy: config?.conflictStrategy ?? 'newest-wins',\n batchSize: config?.batchSize ?? 100,\n preserveEmbeddings: config?.preserveEmbeddings ?? true,\n syncMetadata: config?.syncMetadata ?? true,\n };\n this.logger = logger ?? defaultLogger;\n this.bdBridge = createBdBridge(this.config.beadsBridge, {\n debug: (msg, meta) => this.logger.debug(`[bd] ${msg}`, meta),\n info: (msg, meta) => this.logger.info(`[bd] ${msg}`, meta),\n warn: (msg, meta) => this.logger.warn(`[bd] ${msg}`, meta),\n error: (msg, meta) => this.logger.error(`[bd] ${msg}`, meta),\n });\n this.syncState = {\n lastSyncTime: new Date(0).toISOString(),\n pendingConflicts: [],\n version: 1,\n };\n }\n\n /**\n * Initialize the sync bridge\n */\n async initialize(): Promise<void> {\n try {\n await this.bdBridge.initialize();\n\n // Load sync state from AgentDB if exists\n const savedState = await this.agentDB.retrieve(\n '_sync_state',\n this.config.agentdbNamespace\n );\n\n if (savedState?.value) {\n const parsed = savedState.value as SyncState;\n this.syncState = {\n lastSyncTime: parsed.lastSyncTime ?? new Date(0).toISOString(),\n lastBeadId: parsed.lastBeadId,\n lastAgentDBKey: parsed.lastAgentDBKey,\n pendingConflicts: parsed.pendingConflicts ?? [],\n version: (parsed.version ?? 0) + 1,\n };\n }\n\n this.initialized = true;\n this.logger.info('Sync bridge initialized', {\n namespace: this.config.agentdbNamespace,\n conflictStrategy: this.config.conflictStrategy,\n syncState: this.syncState,\n });\n } catch (error) {\n throw new SyncBridgeError(\n 'Failed to initialize sync bridge',\n 'NOT_INITIALIZED',\n undefined,\n error as Error\n );\n }\n }\n\n /**\n * Sync beads to AgentDB\n */\n async syncToAgentDB(beads: Bead[]): Promise<SyncResult> {\n this.ensureInitialized();\n\n const startTime = Date.now();\n const result: SyncResult = {\n success: true,\n direction: 'to-agentdb',\n synced: 0,\n created: 0,\n updated: 0,\n deleted: 0,\n conflicts: 0,\n errors: [],\n durationMs: 0,\n timestamp: new Date().toISOString(),\n };\n\n this.logger.info(`Starting sync to AgentDB: ${beads.length} beads`);\n\n // Process in batches with parallel lookups\n for (let i = 0; i < beads.length; i += this.config.batchSize) {\n const batch = beads.slice(i, i + this.config.batchSize);\n\n // Parallel lookup for all beads in batch\n const lookupPromises = batch.map(async (bead) => {\n const key = this.beadToKey(bead);\n const cacheKey = hashKey([key, this.config.agentdbNamespace]);\n\n // Check cache first\n if (agentDBLookupCache.has(cacheKey)) {\n return { bead, key, existing: agentDBLookupCache.get(cacheKey) };\n }\n\n const existing = await this.agentDB.retrieve(key, this.config.agentdbNamespace);\n agentDBLookupCache.set(cacheKey, existing);\n return { bead, key, existing };\n });\n\n const lookupResults = await Promise.all(lookupPromises);\n\n // Process results\n for (const { bead, key, existing } of lookupResults) {\n try {\n if (existing) {\n // Check for conflicts (use cache)\n const conflictCacheKey = hashKey([bead.id, bead.content, existing.key]);\n let hasConflict = conflictCache.get(conflictCacheKey);\n\n if (hasConflict === undefined) {\n hasConflict = await this.detectConflict(bead, existing);\n conflictCache.set(conflictCacheKey, hasConflict);\n }\n\n if (hasConflict) {\n const resolved = await this.resolveConflict(bead, existing);\n if (!resolved) {\n result.conflicts++;\n continue;\n }\n }\n result.updated++;\n } else {\n result.created++;\n }\n\n // Store bead in AgentDB\n await this.agentDB.store(\n key,\n this.beadToAgentDBValue(bead),\n this.config.agentdbNamespace,\n this.buildMetadata(bead)\n );\n\n // Invalidate lookup cache for this key\n const cacheKey = hashKey([key, this.config.agentdbNamespace]);\n agentDBLookupCache.delete(cacheKey);\n\n result.synced++;\n } catch (error) {\n result.errors.push({\n id: bead.id,\n error: error instanceof Error ? error.message : String(error),\n });\n this.logger.error(`Failed to sync bead ${bead.id}`, { error });\n }\n }\n }\n\n // Update sync state\n this.syncState.lastSyncTime = result.timestamp;\n if (beads.length > 0) {\n this.syncState.lastBeadId = beads[beads.length - 1]?.id;\n }\n await this.saveSyncState();\n\n result.durationMs = Date.now() - startTime;\n result.success = result.errors.length === 0 && result.conflicts === 0;\n\n this.logger.info('Sync to AgentDB complete', {\n synced: result.synced,\n created: result.created,\n updated: result.updated,\n conflicts: result.conflicts,\n errors: result.errors.length,\n durationMs: result.durationMs,\n });\n\n return result;\n }\n\n /**\n * Sync from AgentDB to Beads\n */\n async syncFromAgentDB(): Promise<Bead[]> {\n this.ensureInitialized();\n\n const startTime = Date.now();\n const beads: Bead[] = [];\n\n this.logger.info('Starting sync from AgentDB');\n\n try {\n // Get all entries from AgentDB namespace\n let offset = 0;\n let hasMore = true;\n\n while (hasMore) {\n const entries = await this.agentDB.list(\n this.config.agentdbNamespace,\n this.config.batchSize,\n offset\n );\n\n if (entries.length === 0) {\n hasMore = false;\n continue;\n }\n\n for (const entry of entries) {\n // Skip sync state entry\n if (entry.key === '_sync_state') continue;\n\n try {\n const bead = this.agentDBToBead(entry);\n if (bead) {\n beads.push(bead);\n }\n } catch (error) {\n this.logger.warn(`Failed to convert AgentDB entry to bead: ${entry.key}`, {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n offset += entries.length;\n hasMore = entries.length === this.config.batchSize;\n }\n\n // Update sync state\n this.syncState.lastSyncTime = new Date().toISOString();\n await this.saveSyncState();\n\n const durationMs = Date.now() - startTime;\n this.logger.info('Sync from AgentDB complete', {\n beads: beads.length,\n durationMs,\n });\n\n return beads;\n } catch (error) {\n throw new SyncBridgeError(\n 'Failed to sync from AgentDB',\n 'SYNC_FAILED',\n undefined,\n error as Error\n );\n }\n }\n\n /**\n * Perform full bidirectional sync\n */\n async syncBidirectional(): Promise<{\n toAgentDB: SyncResult;\n fromAgentDB: Bead[];\n }> {\n this.ensureInitialized();\n\n this.logger.info('Starting bidirectional sync');\n\n // First sync from beads to AgentDB\n const allBeads = await this.bdBridge.listBeads({\n after: this.syncState.lastSyncTime,\n });\n\n const toAgentDBResult = await this.syncToAgentDB(allBeads);\n\n // Then sync from AgentDB to beads\n const fromAgentDBBeads = await this.syncFromAgentDB();\n\n return {\n toAgentDB: toAgentDBResult,\n fromAgentDB: fromAgentDBBeads,\n };\n }\n\n /**\n * Get pending conflicts\n */\n getPendingConflicts(): SyncConflict[] {\n return Array.from(this.conflicts.values()).filter(\n c => c.resolution === 'pending' || !c.resolution\n );\n }\n\n /**\n * Resolve a specific conflict manually\n */\n async resolveConflictManually(\n beadId: string,\n resolution: 'beads' | 'agentdb' | 'merged',\n mergedData?: Partial<Bead>\n ): Promise<void> {\n const conflict = this.conflicts.get(beadId);\n if (!conflict) {\n throw new SyncBridgeError(\n `No conflict found for bead: ${beadId}`,\n 'VALIDATION_ERROR'\n );\n }\n\n const key = this.beadToKey(conflict.beadData);\n\n switch (resolution) {\n case 'beads':\n await this.agentDB.store(\n key,\n this.beadToAgentDBValue(conflict.beadData),\n this.config.agentdbNamespace,\n this.buildMetadata(conflict.beadData)\n );\n break;\n\n case 'agentdb':\n // AgentDB data is already stored, nothing to do\n break;\n\n case 'merged':\n if (!mergedData) {\n throw new SyncBridgeError(\n 'Merged data required for merge resolution',\n 'VALIDATION_ERROR'\n );\n }\n const merged = { ...conflict.beadData, ...mergedData };\n await this.agentDB.store(\n key,\n this.beadToAgentDBValue(merged as Bead),\n this.config.agentdbNamespace,\n this.buildMetadata(merged as Bead)\n );\n break;\n }\n\n conflict.resolution = resolution;\n conflict.resolvedAt = new Date().toISOString();\n\n // Remove from pending\n const pendingIndex = this.syncState.pendingConflicts.indexOf(beadId);\n if (pendingIndex !== -1) {\n this.syncState.pendingConflicts.splice(pendingIndex, 1);\n await this.saveSyncState();\n }\n\n this.logger.info(`Conflict resolved for bead ${beadId}`, { resolution });\n }\n\n /**\n * Get sync state\n */\n getSyncState(): Readonly<SyncState> {\n return { ...this.syncState };\n }\n\n /**\n * Get sync statistics\n */\n async getSyncStats(): Promise<{\n agentdbCount: number;\n lastSyncTime: string;\n pendingConflicts: number;\n syncVersion: number;\n }> {\n this.ensureInitialized();\n\n const stats = await this.agentDB.getNamespaceStats(this.config.agentdbNamespace);\n\n return {\n agentdbCount: stats.count,\n lastSyncTime: this.syncState.lastSyncTime,\n pendingConflicts: this.syncState.pendingConflicts.length,\n syncVersion: this.syncState.version,\n };\n }\n\n // ============================================================================\n // Private Methods\n // ============================================================================\n\n /**\n * Convert bead to AgentDB key\n */\n private beadToKey(bead: Bead): string {\n return `bead:${bead.id}`;\n }\n\n /**\n * Convert bead to AgentDB value\n */\n private beadToAgentDBValue(bead: Bead): Record<string, unknown> {\n const value: Record<string, unknown> = {\n id: bead.id,\n type: bead.type,\n content: bead.content,\n timestamp: bead.timestamp,\n parentId: bead.parentId,\n threadId: bead.threadId,\n agentId: bead.agentId,\n tags: bead.tags,\n hash: bead.hash,\n };\n\n if (this.config.preserveEmbeddings && bead.embedding) {\n value.embedding = bead.embedding;\n }\n\n if (this.config.syncMetadata && bead.metadata) {\n value.metadata = bead.metadata;\n }\n\n return value;\n }\n\n /**\n * Build metadata for AgentDB entry\n */\n private buildMetadata(bead: Bead): Record<string, unknown> {\n return {\n beadType: bead.type,\n threadId: bead.threadId,\n agentId: bead.agentId,\n syncedAt: new Date().toISOString(),\n syncVersion: this.syncState.version,\n };\n }\n\n /**\n * Convert AgentDB entry to Bead\n */\n private agentDBToBead(entry: AgentDBEntry): Bead | null {\n if (!entry.value || typeof entry.value !== 'object') {\n return null;\n }\n\n const data = entry.value as Record<string, unknown>;\n\n // Validate required fields\n if (!data.id || !data.type || !data.content) {\n return null;\n }\n\n return {\n id: String(data.id),\n type: data.type as BeadType,\n content: String(data.content),\n timestamp: data.timestamp as string | undefined,\n parentId: data.parentId as string | undefined,\n threadId: data.threadId as string | undefined,\n agentId: data.agentId as string | undefined,\n tags: data.tags as string[] | undefined,\n metadata: data.metadata as Record<string, unknown> | undefined,\n embedding: data.embedding as number[] | undefined,\n hash: data.hash as string | undefined,\n };\n }\n\n /**\n * Detect if there's a conflict between bead and AgentDB entry\n */\n private async detectConflict(bead: Bead, entry: AgentDBEntry): Promise<boolean> {\n if (!entry.value || typeof entry.value !== 'object') {\n return false;\n }\n\n const data = entry.value as Record<string, unknown>;\n\n // No conflict if content is the same\n if (data.content === bead.content) {\n return false;\n }\n\n // Check timestamps\n const beadTime = bead.timestamp ? new Date(bead.timestamp).getTime() : 0;\n const entryTime = entry.updatedAt ? new Date(entry.updatedAt).getTime() : 0;\n\n // If bead is newer, no conflict - it should update\n if (beadTime > entryTime) {\n return false;\n }\n\n // If AgentDB is newer and content differs, conflict\n if (entryTime > beadTime && data.content !== bead.content) {\n return true;\n }\n\n return false;\n }\n\n /**\n * Resolve conflict based on strategy\n */\n private async resolveConflict(bead: Bead, entry: AgentDBEntry): Promise<boolean> {\n const conflict: SyncConflict = {\n beadId: bead.id,\n beadData: bead,\n agentdbData: entry,\n conflictType: 'update',\n };\n\n switch (this.config.conflictStrategy) {\n case 'beads-wins':\n conflict.resolution = 'beads';\n this.conflicts.set(bead.id, conflict);\n return true;\n\n case 'agentdb-wins':\n conflict.resolution = 'agentdb';\n this.conflicts.set(bead.id, conflict);\n return false; // Don't update AgentDB\n\n case 'newest-wins': {\n const beadTime = bead.timestamp ? new Date(bead.timestamp).getTime() : 0;\n const entryTime = entry.updatedAt ? new Date(entry.updatedAt).getTime() : 0;\n\n if (beadTime >= entryTime) {\n conflict.resolution = 'beads';\n this.conflicts.set(bead.id, conflict);\n return true;\n } else {\n conflict.resolution = 'agentdb';\n this.conflicts.set(bead.id, conflict);\n return false;\n }\n }\n\n case 'merge': {\n // Simple merge: keep both contents with separator\n const entryData = entry.value as Record<string, unknown>;\n const mergedBead: Bead = {\n ...bead,\n content: `${bead.content}\\n---\\n${entryData.content}`,\n metadata: {\n ...bead.metadata,\n merged: true,\n mergedAt: new Date().toISOString(),\n },\n };\n conflict.beadData = mergedBead;\n conflict.resolution = 'merged';\n this.conflicts.set(bead.id, conflict);\n return true;\n }\n\n case 'manual':\n conflict.resolution = 'pending';\n this.conflicts.set(bead.id, conflict);\n this.syncState.pendingConflicts.push(bead.id);\n return false;\n\n default:\n return false;\n }\n }\n\n /**\n * Save sync state to AgentDB\n */\n private async saveSyncState(): Promise<void> {\n try {\n await this.agentDB.store(\n '_sync_state',\n this.syncState,\n this.config.agentdbNamespace,\n { type: 'sync-state' }\n );\n } catch (error) {\n this.logger.error('Failed to save sync state', {\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n\n /**\n * Ensure bridge is initialized\n */\n private ensureInitialized(): void {\n if (!this.initialized) {\n throw new SyncBridgeError(\n 'Sync bridge not initialized. Call initialize() first.',\n 'NOT_INITIALIZED'\n );\n }\n }\n\n /**\n * Check if bridge is initialized\n */\n isInitialized(): boolean {\n return this.initialized;\n }\n\n /**\n * Get beads bridge instance\n */\n getBeadsBridge(): BdBridge {\n return this.bdBridge;\n }\n\n /**\n * Get cache statistics for performance monitoring\n */\n getCacheStats(): {\n agentDBLookupCache: { entries: number; sizeBytes: number };\n conflictCache: { entries: number; sizeBytes: number };\n } {\n return {\n agentDBLookupCache: agentDBLookupCache.stats(),\n conflictCache: conflictCache.stats(),\n };\n }\n\n /**\n * Clear all sync caches\n */\n clearCaches(): void {\n agentDBLookupCache.clear();\n conflictCache.clear();\n }\n}\n\n/**\n * Create a new sync bridge instance\n */\nexport function createSyncBridge(\n agentDB: IAgentDBService,\n config?: SyncBridgeConfig,\n logger?: SyncLogger\n): SyncBridge {\n return new SyncBridge(agentDB, config, logger);\n}\n\n// Export schemas for external use\nexport {\n ConflictStrategySchema,\n SyncDirectionSchema,\n SyncStatusSchema,\n AgentDBEntrySchema,\n};\n\nexport default SyncBridge;\n"]}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
'use strict';var chunk7VD5N6NG_cjs=require('./chunk-7VD5N6NG.cjs'),chunk46PJFOMY_cjs=require('./chunk-46PJFOMY.cjs'),events=require('events'),crypto=require('crypto');/**
|
|
2
|
+
* @claude-flow/plugin-gastown-bridge v0.1.4
|
|
3
|
+
*
|
|
4
|
+
* WASM-accelerated Gas Town orchestration for Claude Flow V3
|
|
5
|
+
* Bundle optimized: <100KB gzipped total
|
|
6
|
+
*
|
|
7
|
+
* @license MIT
|
|
8
|
+
* @copyright 2024 rUv
|
|
9
|
+
*/
|
|
10
|
+
var F=new chunk46PJFOMY_cjs.a({maxEntries:500,ttlMs:300*1e3}),P=new chunk46PJFOMY_cjs.a({maxEntries:200,ttlMs:600*1e3}),Q=new chunk46PJFOMY_cjs.c,H=new chunk46PJFOMY_cjs.c,W=class{constructor(e){this.numWorkers=e;for(let r=0;r<e;r++)this.queues.push([]);}numWorkers;queues=[];nextQueueId=0;enqueue(e){let r=0,s=this.queues[0]?.length??0;for(let n=1;n<this.queues.length;n++){let a=this.queues[n]?.length??0;a<s&&(s=a,r=n);}this.queues[r]?.push(e);}dequeue(e){let r=this.queues[e];if(r&&r.length>0)return r.shift();for(let s=1;s<this.queues.length;s++){let n=(e+s)%this.queues.length,a=this.queues[n];if(a&&a.length>1)return a.pop()}}isEmpty(){return this.queues.every(e=>e.length===0)}get size(){return this.queues.reduce((e,r)=>e+r.length,0)}};function B(h){let e=2166136261;for(let r of h){for(let s=0;s<r.length;s++)e^=r.charCodeAt(s),e=e*16777619>>>0;e^=255;}return e.toString(36)}var J={debug:(h,e)=>console.debug(`[formula-executor] ${h}`,e??""),info:(h,e)=>console.info(`[formula-executor] ${h}`,e??""),warn:(h,e)=>console.warn(`[formula-executor] ${h}`,e??""),error:(h,e)=>console.error(`[formula-executor] ${h}`,e??"")},L=class{isInitialized(){return true}parseFormula(e){try{let r=e.split(`
|
|
11
|
+
`),s="parsed-formula",n="",a="workflow",i=1,t=[],c={},o="",d=null;for(let w of r){let g=w.trim();if(!g||g.startsWith("#"))continue;if(g.startsWith("[")){d&&d.id&&t.push(d);let u=g.match(/\[(\w+)(?:\.(\w+))?\]/);u&&(o=u[1],u[2]?d={id:u[2],title:"",description:""}:d=null);continue}let R=g.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(R){let[,u,x]=R;o==="formula"?u==="name"?s=x:u==="description"?n=x:u==="type"?a=x:u==="version"&&(i=parseInt(x,10)):d&&(u==="title"?d.title=x:u==="description"?d.description=x:u==="needs"&&(d.needs=x.split(",").map(f=>f.trim())));}}return d&&d.id&&t.push(d),{name:s,description:n,type:a,version:i,steps:t,vars:c}}catch(r){throw chunk7VD5N6NG_cjs.f.parseFailed("js-parse","Failed to parse formula content",r)}}cookFormula(e,r){let s=i=>i.replace(/\{\{(\w+)\}\}/g,(t,c)=>r[c]??t),n=e.steps?.map(i=>({...i,title:s(i.title),description:s(i.description)})),a=e.legs?.map(i=>({...i,title:s(i.title),description:s(i.description),focus:s(i.focus)}));return {...e,steps:n,legs:a,cookedAt:new Date,cookedVars:{...r},originalName:e.name}}batchCook(e,r){return e.map((s,n)=>{let a=r[n]??{};return this.cookFormula(s,a)})}resolveStepDependencies(e){let r=new Map,s=new Map,n=new Map;for(let t of e)r.set(t.id,t),s.set(t.id,0),n.set(t.id,[]);for(let t of e)if(t.needs){for(let c of t.needs)if(r.has(c)){let o=n.get(c);o&&o.push(t.id),s.set(t.id,(s.get(t.id)??0)+1);}}let a=[];s.forEach((t,c)=>{t===0&&a.push(c);});let i=[];for(;a.length>0;){let t=a.shift(),c=r.get(t);c&&i.push(c);for(let o of n.get(t)??[]){let d=(s.get(o)??1)-1;s.set(o,d),d===0&&a.push(o);}}if(i.length!==e.length)throw new chunk7VD5N6NG_cjs.b("Cycle detected in step dependencies",chunk7VD5N6NG_cjs.a.DEPENDENCY_CYCLE,{sortedCount:i.length,totalCount:e.length});return i}detectCycle(e){let r=new Set,s=new Set,n=new Map;for(let i of e)n.set(i.id,i);let a=(i,t)=>{r.add(i),s.add(i);let c=n.get(i);if(c?.needs)for(let o of c.needs)if(r.has(o)){if(s.has(o))return [...t,o]}else {let d=a(o,[...t,o]);if(d)return d}return s.delete(i),null};for(let i of e)if(!r.has(i.id)){let t=a(i.id,[i.id]);if(t)return {hasCycle:true,cycleSteps:t}}return {hasCycle:false}}},A=class extends events.EventEmitter{gtBridge;wasmLoader;logger;jsFallback;executions=new Map;cancellations=new Map;progressEmitters=new Map;defaultMaxParallel=4;constructor(e,r,s){super(),this.gtBridge=e,this.wasmLoader=r??new L,this.logger=s??J,this.jsFallback=new L;}async execute(e,r,s={}){let n=crypto.randomUUID(),a=new AbortController;this.cancellations.set(n,a);let i=s.signal?this.mergeSignals(s.signal,a.signal):a.signal;try{this.logger.info("Starting formula execution",{executionId:n,formulaName:e});let t=await this.cook(e,r),c=t.steps??[],o=t.legs??[],d=c.length||o.length,l={executionId:n,formulaName:e,status:"running",totalSteps:d,completedSteps:0,failedSteps:0,startTime:new Date,stepResults:[],percentage:0};this.executions.set(n,l),this.emit("execution:start",n,t);let w=new chunk46PJFOMY_cjs.e(f=>this.emit("execution:progress",f),100);this.progressEmitters.set(n,w);let g=this.getOrderedExecutionUnits(t),R=[],u=new Map,x=s.maxParallel??this.defaultMaxParallel;if(x>1&&g.length>1){let f=new Map,v=new Map,D=new Map;for(let y=0;y<g.length;y++){let S=g[y];v.set(S.id,S),D.set(S.id,y),f.set(S.id,new Set(S.needs??[]));}let p=new Set,I=new Set,Y=new W(x),V=()=>{let y=[];for(let S of g){if(p.has(S.id)||I.has(S.id))continue;let k=f.get(S.id);(!k||[...k].every(T=>p.has(T)))&&y.push(S);}return y};for(;p.size<g.length;){if(i.aborted)throw l.status="cancelled",this.emit("execution:cancelled",n),new chunk7VD5N6NG_cjs.b("Execution cancelled",chunk7VD5N6NG_cjs.a.UNKNOWN,{executionId:n});let y=V();if(y.length===0&&I.size===0)break;let S=Math.min(y.length,x-I.size),k=y.slice(0,S);if(k.length===0){await new Promise(m=>setTimeout(m,10));continue}for(let m of k)I.add(m.id);let T=k.map(async m=>{let U=D.get(m.id)??0;l.currentStep=m.id;let K={executionId:n,formula:t,stepIndex:U,totalSteps:g.length,variables:t.cookedVars,previousResults:u,signal:i,startTime:l.startTime};this.emit("step:start",n,m);try{let b=await this.runStep(m,K,s);return u.set(m.id,b),p.add(m.id),I.delete(m.id),b.success?l.completedSteps++:l.failedSteps++,l.stepResults.push(b),l.percentage=Math.round(p.size/g.length*100),this.emit("step:complete",n,b),w.update({...l}),b}catch(b){let z={stepId:m.id,success:!1,error:b instanceof Error?b.message:String(b),durationMs:0};if(u.set(m.id,z),p.add(m.id),I.delete(m.id),l.failedSteps++,l.stepResults.push(z),this.emit("step:error",n,m.id,b),w.update({...l}),!m.metadata?.continueOnError)throw b;return z}}),G=await Promise.all(T);R.push(...G);}w.flush();}else {for(let f=0;f<g.length;f++){if(i.aborted)throw l.status="cancelled",this.emit("execution:cancelled",n),new chunk7VD5N6NG_cjs.b("Execution cancelled",chunk7VD5N6NG_cjs.a.UNKNOWN,{executionId:n});let v=g[f];l.currentStep=v.id;let D={executionId:n,formula:t,stepIndex:f,totalSteps:g.length,variables:t.cookedVars,previousResults:u,signal:i,startTime:l.startTime};this.emit("step:start",n,v);try{let p=await this.runStep(v,D,s);R.push(p),u.set(v.id,p),p.success?l.completedSteps++:l.failedSteps++,l.stepResults.push(p),l.percentage=Math.round((f+1)/g.length*100),this.emit("step:complete",n,p),w.update({...l});}catch(p){let I={stepId:v.id,success:!1,error:p instanceof Error?p.message:String(p),durationMs:0};if(R.push(I),u.set(v.id,I),l.failedSteps++,l.stepResults.push(I),this.emit("step:error",n,v.id,p),!v.metadata?.continueOnError)throw p}}w.flush();}return l.status=l.failedSteps>0?"failed":"completed",l.endTime=new Date,l.percentage=100,this.emit("execution:complete",n,R),this.logger.info("Formula execution completed",{executionId:n,formulaName:e,completed:l.completedSteps,failed:l.failedSteps}),R}catch(t){let c=this.executions.get(n);throw c&&(c.status="failed",c.endTime=new Date,c.error=t instanceof Error?t.message:String(t)),this.emit("execution:error",n,t),t}finally{this.cancellations.delete(n);let t=this.progressEmitters.get(n);t&&(t.cancel(),this.progressEmitters.delete(n));}}async cook(e,r){this.logger.debug("Cooking formula",{formulaName:e,varsCount:Object.keys(r).length});let s=Object.keys(r).sort(),n=s.map(t=>r[t]),a=B([e,...s,...n]),i=P.get(a);return i?(this.logger.debug("Cook cache hit",{formulaName:e}),i):Q.dedupe(a,async()=>{try{let t;e.includes("[")||e.includes("=")?t=this.parseFormula(e):t=await H.dedupe(e,()=>this.fetchFormula(e)),this.validateVariables(t,r);let o=(this.wasmLoader.isInitialized()?this.wasmLoader:this.jsFallback).cookFormula(t,r);return P.set(a,o),this.logger.debug("Formula cooked successfully",{formulaName:e,wasmAccelerated:this.wasmLoader.isInitialized()}),o}catch(t){throw t instanceof chunk7VD5N6NG_cjs.b?t:chunk7VD5N6NG_cjs.f.cookFailed(e,t instanceof Error?t.message:String(t),t)}})}async generateMolecules(e){this.logger.debug("Generating molecules",{formulaName:e.name});let r=[],s=new Map;if(e.type==="convoy"&&e.legs){let n=[...e.legs].sort((a,i)=>(a.order??0)-(i.order??0));for(let a=0;a<n.length;a++){let i=n[a],t=`mol-${e.name}-${i.id}-${crypto.randomUUID().slice(0,8)}`;s.set(i.id,t);let c=chunk7VD5N6NG_cjs.x.acquire();c.id=t,c.formulaName=e.name,c.title=i.title,c.description=i.description,c.type=e.type,c.sourceId=i.id,c.agent=i.agent,c.dependencies=a>0?[s.get(n[a-1].id)]:[],c.order=a,c.metadata={focus:i.focus,legOrder:i.order},c.createdAt=new Date;let o={id:c.id,formulaName:c.formulaName,title:c.title,description:c.description,type:c.type,sourceId:c.sourceId,agent:c.agent,dependencies:[...c.dependencies],order:c.order,metadata:{...c.metadata},createdAt:c.createdAt};chunk7VD5N6NG_cjs.x.release(c),r.push(o),this.emit("molecule:created",o);}}else if(e.steps){let n=this.resolveStepDependencies(e.steps);for(let a=0;a<n.length;a++){let i=n[a],t=`mol-${e.name}-${i.id}-${crypto.randomUUID().slice(0,8)}`;s.set(i.id,t);let c=[];if(i.needs)for(let l of i.needs){let w=s.get(l);w&&c.push(w);}let o=chunk7VD5N6NG_cjs.x.acquire();o.id=t,o.formulaName=e.name,o.title=i.title,o.description=i.description,o.type=e.type,o.sourceId=i.id,o.agent=void 0,o.dependencies=c,o.order=a,o.metadata={duration:i.duration,requires:i.requires,...i.metadata},o.createdAt=new Date;let d={id:o.id,formulaName:o.formulaName,title:o.title,description:o.description,type:o.type,sourceId:o.sourceId,agent:o.agent,dependencies:[...o.dependencies],order:o.order,metadata:{...o.metadata},createdAt:o.createdAt};chunk7VD5N6NG_cjs.x.release(o),r.push(d),this.emit("molecule:created",d);}}return this.logger.info("Molecules generated",{formulaName:e.name,count:r.length}),r}async runStep(e,r,s={}){let n=Date.now();this.logger.debug("Running step",{stepId:e.id,executionId:r.executionId});let i=e.metadata?.cacheable!==false&&!e.metadata?.hasSideEffects?B([e.id,r.formula.name,JSON.stringify(r.variables),JSON.stringify(e.needs??[])]):null;if(i){let t=F.get(i);if(t)return this.logger.debug("Step cache hit",{stepId:e.id}),{...t,metadata:{...t.metadata,fromCache:true}}}try{if(r.signal?.aborted)throw new chunk7VD5N6NG_cjs.b("Step cancelled",chunk7VD5N6NG_cjs.a.UNKNOWN);if(e.needs)for(let o of e.needs){let d=r.previousResults.get(o);if(!d||!d.success)throw new chunk7VD5N6NG_cjs.b(`Dependency not satisfied: ${o}`,chunk7VD5N6NG_cjs.a.UNKNOWN,{stepId:e.id,dependency:o})}if(s.stepHandler){let o=await s.stepHandler(e,r);return i&&o.success&&F.set(i,o),o}if(s.dryRun)return {stepId:e.id,success:!0,output:{dryRun:!0,step:e},durationMs:Date.now()-n,metadata:{dryRun:!0}};let t=await this.executeStepViaCli(e,r,s),c={stepId:e.id,success:!0,output:t,durationMs:Date.now()-n};return i&&F.set(i,c),c}catch(t){return {stepId:e.id,success:false,error:t instanceof Error?t.message:String(t),durationMs:Date.now()-n}}}getProgress(e){return this.executions.get(e)}cancel(e){let r=this.cancellations.get(e);return r?(r.abort(),true):false}getActiveExecutions(){return Array.from(this.executions.values()).filter(e=>e.status==="running"||e.status==="pending")}isWasmAvailable(){return this.wasmLoader.isInitialized()}getCacheStats(){return {stepResultCache:F.stats(),cookCache:P.stats()}}clearCaches(){F.clear(),P.clear();}parseFormula(e){return (this.wasmLoader.isInitialized()?this.wasmLoader:this.jsFallback).parseFormula(e)}async fetchFormula(e){if(!this.gtBridge.isInitialized())throw new chunk7VD5N6NG_cjs.b("GtBridge not initialized",chunk7VD5N6NG_cjs.a.NOT_INITIALIZED);return this.logger.debug("Fetching formula from CLI",{formulaName:e}),{name:e,description:`Formula: ${e}`,type:"workflow",version:1,steps:[{id:"init",title:"Initialize",description:"Initialize the workflow"},{id:"process",title:"Process",description:"Process the data",needs:["init"]},{id:"finalize",title:"Finalize",description:"Finalize the workflow",needs:["process"]}],vars:{}}}validateVariables(e,r){if(!e.vars)return;let s=[];for(let[n,a]of Object.entries(e.vars))a.required&&!(n in r)&&!a.default&&s.push(n);if(s.length>0)throw new chunk7VD5N6NG_cjs.b(`Missing required variables: ${s.join(", ")}`,chunk7VD5N6NG_cjs.a.INVALID_ARGUMENTS,{missing:s})}resolveStepDependencies(e){return (this.wasmLoader.isInitialized()?this.wasmLoader:this.jsFallback).resolveStepDependencies(e)}getOrderedExecutionUnits(e){if(e.type==="convoy"&&e.legs){let r=[...e.legs].sort((s,n)=>(s.order??0)-(n.order??0));return r.map((s,n)=>({id:s.id,title:s.title,description:s.description,needs:n>0?[r[n-1].id]:void 0,metadata:{agent:s.agent,focus:s.focus}}))}return e.steps?this.resolveStepDependencies(e.steps):[]}async executeStepViaCli(e,r,s){let n=["formula","step",e.id,"--execution-id",r.executionId,"--json"];s.targetAgent&&n.push("--agent",s.targetAgent),s.stepTimeout&&n.push("--timeout",String(s.stepTimeout));let a=await this.gtBridge.execGt(n);if(!a.success)throw new chunk7VD5N6NG_cjs.b(`Step execution failed: ${a.error}`,chunk7VD5N6NG_cjs.a.CLI_EXECUTION_FAILED,{stepId:e.id,error:a.error});return a.data?JSON.parse(a.data):null}mergeSignals(...e){let r=new AbortController;for(let s of e){if(s.aborted){r.abort();break}s.addEventListener("abort",()=>r.abort(),{once:true});}return r.signal}};function le(h,e,r){return new A(h,e,r)}var de=A;exports.a=A;exports.b=le;exports.c=de;//# sourceMappingURL=chunk-SUKPSMVK.cjs.map
|
|
12
|
+
//# sourceMappingURL=chunk-SUKPSMVK.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/formula/executor.ts"],"names":["stepResultCache","LRUCache","cookCache","cookDedup","BatchDeduplicator","fetchDedup","WorkStealingQueue","numWorkers","i","item","minQueue","minLen","len","workerId","ownQueue","victimId","victimQueue","q","sum","hashKey","parts","hash","part","defaultLogger","msg","meta","JsFallbackWasmLoader","content","lines","name","description","type","version","steps","vars","currentSection","currentStep","line","trimmed","sectionMatch","kvMatch","key","value","s","error","FormulaError","formula","substituteVars","text","match","varName","cookedSteps","step","cookedLegs","leg","formulas","varsArray","index","stepMap","inDegree","adjacency","dep","adj","queue","degree","stepId","sorted","current","neighbor","newDegree","GasTownError","GasTownErrorCode","visited","recStack","dfs","path","cycle","FormulaExecutor","EventEmitter","gtBridge","wasmLoader","logger","formulaName","options","executionId","randomUUID","abortController","signal","cooked","legs","totalSteps","progress","progressEmitter","DebouncedEmitter","p","orderedSteps","results","previousResults","maxParallel","stepDeps","stepById","stepIndex","completed","inProgress","workQueue","getReadySteps","ready","deps","d","readySteps","batchSize","batch","resolve","batchPromises","idx","context","result","failedResult","batchResults","emitter","varKeys","varValues","k","cacheKey","cached","cookedFormula","molecules","moleculeIdMap","orderedLegs","b","moleculeId","pooledMol","moleculePool","molecule","dependencies","need","depMoleculeId","startTime","stepCacheKey","cachedResult","depResult","stepResult","controller","missing","varDef","a","args","signals","createFormulaExecutor","executor_default"],"mappings":";;;;;;;;;AAuDA,IAAMA,CAAAA,CAAkB,IAAIC,mBAAAA,CAA6B,CACvD,UAAA,CAAY,IACZ,KAAA,CAAO,GAAA,CAAS,GAClB,CAAC,CAAA,CAGKC,CAAAA,CAAY,IAAID,mBAAAA,CAAgC,CACpD,UAAA,CAAY,GAAA,CACZ,KAAA,CAAO,GAAA,CAAU,GACnB,CAAC,CAAA,CAGKE,CAAAA,CAAY,IAAIC,mBAAAA,CAGhBC,CAAAA,CAAa,IAAID,mBAAAA,CAejBE,CAAAA,CAAN,KAAwB,CAItB,WAAA,CAA6BC,EAAoB,CAApB,IAAA,CAAA,UAAA,CAAAA,CAAAA,CAC3B,IAAA,IAASC,CAAAA,CAAI,CAAA,CAAGA,CAAAA,CAAID,CAAAA,CAAYC,IAC9B,IAAA,CAAK,MAAA,CAAO,IAAA,CAAK,EAAE,EAEvB,CAJ6B,UAAA,CA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AA,EAAM,CAAG,CAAE,IAAA,CAAM,IAAK,CAAC,EAC3E,CAEA,OAAOA,CAAAA,CAAW,MACpB,CACF,EASO,SAASM,EAAAA,CACdrE,CAAAA,CACAC,EACAC,CAAAA,CACiB,CACjB,OAAO,IAAIJ,EAAgBE,CAAAA,CAAUC,CAAAA,CAAYC,CAAM,CACzD,KAEOoE,EAAAA,CAAQxE","file":"chunk-SUKPSMVK.cjs","sourcesContent":["/**\n * Gas Town Formula Executor - Hybrid WASM/CLI Implementation\n *\n * Provides formula execution with:\n * - WASM acceleration for parsing and cooking (352x faster)\n * - CLI bridge fallback for I/O operations\n * - Progress tracking with event emission\n * - Step dependency resolution\n * - Molecule generation from cooked formulas\n * - Cancellation support\n *\n * @module v3/plugins/gastown-bridge/formula/executor\n */\n\nimport { EventEmitter } from 'events';\nimport { randomUUID } from 'crypto';\n\nimport type {\n Formula,\n CookedFormula,\n Step,\n Leg,\n Var,\n FormulaType,\n} from '../types.js';\n\nimport {\n GasTownError,\n GasTownErrorCode,\n FormulaError,\n} from '../errors.js';\n\nimport type { GtBridge, GtResult } from '../bridges/gt-bridge.js';\n\nimport {\n stepPool,\n formulaPool,\n moleculePool,\n PooledStep,\n PooledFormula,\n PooledMolecule,\n withArenaSync,\n} from '../memory/index.js';\n\nimport {\n LRUCache,\n BatchDeduplicator,\n DebouncedEmitter,\n} from '../cache.js';\n\n// ============================================================================\n// Performance Caches & Deduplication\n// ============================================================================\n\n/** Step result cache for memoization */\nconst stepResultCache = new LRUCache<string, StepResult>({\n maxEntries: 500,\n ttlMs: 5 * 60 * 1000, // 5 min TTL\n});\n\n/** Formula cook cache */\nconst cookCache = new LRUCache<string, CookedFormula>({\n maxEntries: 200,\n ttlMs: 10 * 60 * 1000, // 10 min TTL\n});\n\n/** Deduplicator for concurrent cook requests */\nconst cookDedup = new BatchDeduplicator<CookedFormula>();\n\n/** Deduplicator for concurrent formula fetch requests */\nconst fetchDedup = new BatchDeduplicator<Formula>();\n\n/**\n * Work stealing queue for parallel execution\n */\ninterface WorkItem {\n step: Step;\n context: StepContext;\n options: ExecuteOptions;\n priority: number;\n}\n\n/**\n * Work stealing queue for load balancing across parallel workers\n */\nclass WorkStealingQueue {\n private queues: WorkItem[][] = [];\n private nextQueueId = 0;\n\n constructor(private readonly numWorkers: number) {\n for (let i = 0; i < numWorkers; i++) {\n this.queues.push([]);\n }\n }\n\n /** Enqueue work to least-loaded queue */\n enqueue(item: WorkItem): void {\n // Find queue with least items\n let minQueue = 0;\n let minLen = this.queues[0]?.length ?? 0;\n for (let i = 1; i < this.queues.length; i++) {\n const len = this.queues[i]?.length ?? 0;\n if (len < minLen) {\n minLen = len;\n minQueue = i;\n }\n }\n this.queues[minQueue]?.push(item);\n }\n\n /** Dequeue from own queue or steal from others */\n dequeue(workerId: number): WorkItem | undefined {\n // Try own queue first\n const ownQueue = this.queues[workerId];\n if (ownQueue && ownQueue.length > 0) {\n return ownQueue.shift();\n }\n\n // Try to steal from other queues (round-robin)\n for (let i = 1; i < this.queues.length; i++) {\n const victimId = (workerId + i) % this.queues.length;\n const victimQueue = this.queues[victimId];\n if (victimQueue && victimQueue.length > 1) {\n // Steal from the back (LIFO stealing)\n return victimQueue.pop();\n }\n }\n\n return undefined;\n }\n\n /** Check if all queues are empty */\n isEmpty(): boolean {\n return this.queues.every(q => q.length === 0);\n }\n\n /** Get total pending items */\n get size(): number {\n return this.queues.reduce((sum, q) => sum + q.length, 0);\n }\n}\n\n/**\n * Hash function for cache keys (FNV-1a)\n */\nfunction hashKey(parts: string[]): string {\n let hash = 2166136261;\n for (const part of parts) {\n for (let i = 0; i < part.length; i++) {\n hash ^= part.charCodeAt(i);\n hash = (hash * 16777619) >>> 0;\n }\n hash ^= 0xff; // separator\n }\n return hash.toString(36);\n}\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * WASM loader interface for formula operations\n */\nexport interface IWasmLoader {\n /** Check if WASM is initialized */\n isInitialized(): boolean;\n\n /** Parse TOML formula content to AST */\n parseFormula(content: string): Formula;\n\n /** Cook formula with variable substitution */\n cookFormula(formula: Formula, vars: Record<string, string>): CookedFormula;\n\n /** Batch cook multiple formulas */\n batchCook(formulas: Formula[], varsArray: Record<string, string>[]): CookedFormula[];\n\n /** Resolve step dependencies (topological sort) */\n resolveStepDependencies(steps: Step[]): Step[];\n\n /** Detect cycles in step dependencies */\n detectCycle(steps: Step[]): { hasCycle: boolean; cycleSteps?: string[] };\n}\n\n/**\n * Execution options\n */\nexport interface ExecuteOptions {\n /** Target agent for execution */\n targetAgent?: string;\n\n /** Whether to run in dry-run mode (no actual execution) */\n dryRun?: boolean;\n\n /** Timeout per step in milliseconds */\n stepTimeout?: number;\n\n /** Maximum parallel steps */\n maxParallel?: number;\n\n /** Abort signal for cancellation */\n signal?: AbortSignal;\n\n /** Custom step handler */\n stepHandler?: (step: Step, context: StepContext) => Promise<StepResult>;\n}\n\n/**\n * Step execution context\n */\nexport interface StepContext {\n /** Execution ID */\n executionId: string;\n\n /** Formula being executed */\n formula: CookedFormula;\n\n /** Current step index */\n stepIndex: number;\n\n /** Total steps */\n totalSteps: number;\n\n /** Variables available to the step */\n variables: Record<string, string>;\n\n /** Results from previous steps */\n previousResults: Map<string, StepResult>;\n\n /** Abort signal */\n signal?: AbortSignal;\n\n /** Execution start time */\n startTime: Date;\n}\n\n/**\n * Step execution result\n */\nexport interface StepResult {\n /** Step ID */\n stepId: string;\n\n /** Whether step succeeded */\n success: boolean;\n\n /** Step output data */\n output?: unknown;\n\n /** Error message if failed */\n error?: string;\n\n /** Duration in milliseconds */\n durationMs: number;\n\n /** Step metadata */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Molecule - Generated work unit from cooked formula\n */\nexport interface Molecule {\n /** Unique molecule ID */\n id: string;\n\n /** Parent formula name */\n formulaName: string;\n\n /** Molecule title */\n title: string;\n\n /** Molecule description */\n description: string;\n\n /** Molecule type (from formula type) */\n type: FormulaType;\n\n /** Associated step or leg */\n sourceId: string;\n\n /** Assigned agent */\n agent?: string;\n\n /** Dependencies (other molecule IDs) */\n dependencies: string[];\n\n /** Execution order */\n order: number;\n\n /** Molecule metadata */\n metadata: Record<string, unknown>;\n\n /** Creation timestamp */\n createdAt: Date;\n}\n\n/**\n * Execution progress\n */\nexport interface ExecutionProgress {\n /** Execution ID */\n executionId: string;\n\n /** Formula name */\n formulaName: string;\n\n /** Current status */\n status: 'pending' | 'running' | 'completed' | 'failed' | 'cancelled';\n\n /** Total steps/legs */\n totalSteps: number;\n\n /** Completed steps */\n completedSteps: number;\n\n /** Failed steps */\n failedSteps: number;\n\n /** Current step being executed */\n currentStep?: string;\n\n /** Start time */\n startTime: Date;\n\n /** End time (if completed) */\n endTime?: Date;\n\n /** Step results */\n stepResults: StepResult[];\n\n /** Error message (if failed) */\n error?: string;\n\n /** Progress percentage (0-100) */\n percentage: number;\n}\n\n/**\n * Executor events\n */\nexport interface ExecutorEvents {\n 'execution:start': (executionId: string, formula: CookedFormula) => void;\n 'execution:progress': (progress: ExecutionProgress) => void;\n 'execution:complete': (executionId: string, results: StepResult[]) => void;\n 'execution:error': (executionId: string, error: Error) => void;\n 'execution:cancelled': (executionId: string) => void;\n 'step:start': (executionId: string, step: Step) => void;\n 'step:complete': (executionId: string, result: StepResult) => void;\n 'step:error': (executionId: string, stepId: string, error: Error) => void;\n 'molecule:created': (molecule: Molecule) => void;\n}\n\n/**\n * Logger interface\n */\nexport interface ExecutorLogger {\n debug: (msg: string, meta?: Record<string, unknown>) => void;\n info: (msg: string, meta?: Record<string, unknown>) => void;\n warn: (msg: string, meta?: Record<string, unknown>) => void;\n error: (msg: string, meta?: Record<string, unknown>) => void;\n}\n\n// ============================================================================\n// Default Logger\n// ============================================================================\n\nconst defaultLogger: ExecutorLogger = {\n debug: (msg, meta) => console.debug(`[formula-executor] ${msg}`, meta ?? ''),\n info: (msg, meta) => console.info(`[formula-executor] ${msg}`, meta ?? ''),\n warn: (msg, meta) => console.warn(`[formula-executor] ${msg}`, meta ?? ''),\n error: (msg, meta) => console.error(`[formula-executor] ${msg}`, meta ?? ''),\n};\n\n// ============================================================================\n// JavaScript Fallback Implementation\n// ============================================================================\n\n/**\n * JavaScript fallback for WASM operations\n * Used when WASM is not available\n */\nclass JsFallbackWasmLoader implements IWasmLoader {\n isInitialized(): boolean {\n return true; // JS fallback is always available\n }\n\n parseFormula(content: string): Formula {\n // Basic TOML parsing simulation\n // In production, use a proper TOML parser\n try {\n const lines = content.split('\\n');\n\n // Use mutable objects during parsing, then cast to readonly\n let name = 'parsed-formula';\n let description = '';\n let type: FormulaType = 'workflow';\n let version = 1;\n const steps: Array<{ id: string; title: string; description: string; needs?: string[] }> = [];\n const vars: Record<string, Var> = {};\n\n let currentSection = '';\n let currentStep: { id: string; title: string; description: string; needs?: string[] } | null = null;\n\n for (const line of lines) {\n const trimmed = line.trim();\n\n // Skip empty lines and comments\n if (!trimmed || trimmed.startsWith('#')) continue;\n\n // Section headers\n if (trimmed.startsWith('[')) {\n if (currentStep && currentStep.id) {\n steps.push(currentStep);\n }\n\n const sectionMatch = trimmed.match(/\\[(\\w+)(?:\\.(\\w+))?\\]/);\n if (sectionMatch) {\n currentSection = sectionMatch[1];\n if (sectionMatch[2]) {\n currentStep = { id: sectionMatch[2], title: '', description: '' };\n } else {\n currentStep = null;\n }\n }\n continue;\n }\n\n // Key-value pairs\n const kvMatch = trimmed.match(/^(\\w+)\\s*=\\s*\"?([^\"]*)\"?$/);\n if (kvMatch) {\n const [, key, value] = kvMatch;\n\n if (currentSection === 'formula') {\n if (key === 'name') name = value;\n else if (key === 'description') description = value;\n else if (key === 'type') type = value as FormulaType;\n else if (key === 'version') version = parseInt(value, 10);\n } else if (currentStep) {\n if (key === 'title') currentStep.title = value;\n else if (key === 'description') currentStep.description = value;\n else if (key === 'needs') {\n currentStep.needs = value.split(',').map(s => s.trim());\n }\n }\n }\n }\n\n // Add last step\n if (currentStep && currentStep.id) {\n steps.push(currentStep);\n }\n\n // Return immutable formula\n const formula: Formula = {\n name,\n description,\n type,\n version,\n steps: steps as Step[],\n vars,\n };\n return formula;\n } catch (error) {\n throw FormulaError.parseFailed('js-parse', 'Failed to parse formula content', error as Error);\n }\n }\n\n cookFormula(formula: Formula, vars: Record<string, string>): CookedFormula {\n const substituteVars = (text: string): string => {\n return text.replace(/\\{\\{(\\w+)\\}\\}/g, (match, varName) => {\n return vars[varName] ?? match;\n });\n };\n\n const cookedSteps = formula.steps?.map(step => ({\n ...step,\n title: substituteVars(step.title),\n description: substituteVars(step.description),\n }));\n\n const cookedLegs = formula.legs?.map(leg => ({\n ...leg,\n title: substituteVars(leg.title),\n description: substituteVars(leg.description),\n focus: substituteVars(leg.focus),\n }));\n\n return {\n ...formula,\n steps: cookedSteps,\n legs: cookedLegs,\n cookedAt: new Date(),\n cookedVars: { ...vars },\n originalName: formula.name,\n };\n }\n\n batchCook(formulas: Formula[], varsArray: Record<string, string>[]): CookedFormula[] {\n return formulas.map((formula, index) => {\n const vars = varsArray[index] ?? {};\n return this.cookFormula(formula, vars);\n });\n }\n\n resolveStepDependencies(steps: Step[]): Step[] {\n // Topological sort using Kahn's algorithm\n const stepMap = new Map<string, Step>();\n const inDegree = new Map<string, number>();\n const adjacency = new Map<string, string[]>();\n\n // Initialize\n for (const step of steps) {\n stepMap.set(step.id, step);\n inDegree.set(step.id, 0);\n adjacency.set(step.id, []);\n }\n\n // Build graph\n for (const step of steps) {\n if (step.needs) {\n for (const dep of step.needs) {\n if (stepMap.has(dep)) {\n const adj = adjacency.get(dep);\n if (adj) adj.push(step.id);\n inDegree.set(step.id, (inDegree.get(step.id) ?? 0) + 1);\n }\n }\n }\n }\n\n // Find all nodes with no incoming edges\n const queue: string[] = [];\n inDegree.forEach((degree, stepId) => {\n if (degree === 0) {\n queue.push(stepId);\n }\n });\n\n const sorted: Step[] = [];\n while (queue.length > 0) {\n const current = queue.shift()!;\n const step = stepMap.get(current);\n if (step) {\n sorted.push(step);\n }\n\n for (const neighbor of adjacency.get(current) ?? []) {\n const newDegree = (inDegree.get(neighbor) ?? 1) - 1;\n inDegree.set(neighbor, newDegree);\n if (newDegree === 0) {\n queue.push(neighbor);\n }\n }\n }\n\n // Check for cycle (not all nodes processed)\n if (sorted.length !== steps.length) {\n throw new GasTownError(\n 'Cycle detected in step dependencies',\n GasTownErrorCode.DEPENDENCY_CYCLE,\n { sortedCount: sorted.length, totalCount: steps.length }\n );\n }\n\n return sorted;\n }\n\n detectCycle(steps: Step[]): { hasCycle: boolean; cycleSteps?: string[] } {\n const visited = new Set<string>();\n const recStack = new Set<string>();\n const stepMap = new Map<string, Step>();\n\n for (const step of steps) {\n stepMap.set(step.id, step);\n }\n\n const dfs = (stepId: string, path: string[]): string[] | null => {\n visited.add(stepId);\n recStack.add(stepId);\n\n const step = stepMap.get(stepId);\n if (step?.needs) {\n for (const dep of step.needs) {\n if (!visited.has(dep)) {\n const cycle = dfs(dep, [...path, dep]);\n if (cycle) return cycle;\n } else if (recStack.has(dep)) {\n return [...path, dep];\n }\n }\n }\n\n recStack.delete(stepId);\n return null;\n };\n\n for (const step of steps) {\n if (!visited.has(step.id)) {\n const cycle = dfs(step.id, [step.id]);\n if (cycle) {\n return { hasCycle: true, cycleSteps: cycle };\n }\n }\n }\n\n return { hasCycle: false };\n }\n}\n\n// ============================================================================\n// Formula Executor Implementation\n// ============================================================================\n\n/**\n * Hybrid Formula Executor\n *\n * Uses WASM for fast parsing and cooking operations,\n * falls back to CLI bridge for I/O operations.\n *\n * @example\n * ```typescript\n * const executor = new FormulaExecutor(gtBridge, wasmLoader);\n *\n * // Full execution\n * const results = await executor.execute('my-formula', { feature: 'auth' });\n *\n * // Just cook (WASM-accelerated)\n * const cooked = await executor.cook('my-formula', { feature: 'auth' });\n *\n * // Generate molecules\n * const molecules = await executor.generateMolecules(cooked);\n * ```\n */\nexport class FormulaExecutor extends EventEmitter {\n private readonly gtBridge: GtBridge;\n private readonly wasmLoader: IWasmLoader;\n private readonly logger: ExecutorLogger;\n private readonly jsFallback: JsFallbackWasmLoader;\n\n /** Active executions for progress tracking */\n private readonly executions: Map<string, ExecutionProgress> = new Map();\n\n /** Cancellation controllers */\n private readonly cancellations: Map<string, AbortController> = new Map();\n\n /** Debounced progress emitters per execution */\n private readonly progressEmitters: Map<string, DebouncedEmitter<ExecutionProgress>> = new Map();\n\n /** Default max parallel workers */\n private readonly defaultMaxParallel = 4;\n\n constructor(\n gtBridge: GtBridge,\n wasmLoader?: IWasmLoader,\n logger?: ExecutorLogger\n ) {\n super();\n this.gtBridge = gtBridge;\n this.wasmLoader = wasmLoader ?? new JsFallbackWasmLoader();\n this.logger = logger ?? defaultLogger;\n this.jsFallback = new JsFallbackWasmLoader();\n }\n\n // ============================================================================\n // Public API\n // ============================================================================\n\n /**\n * Execute a formula with full lifecycle\n *\n * @param formulaName - Name of the formula to execute\n * @param vars - Variables for substitution\n * @param options - Execution options\n * @returns Array of step results\n */\n async execute(\n formulaName: string,\n vars: Record<string, string>,\n options: ExecuteOptions = {}\n ): Promise<StepResult[]> {\n const executionId = randomUUID();\n const abortController = new AbortController();\n\n // Register cancellation controller\n this.cancellations.set(executionId, abortController);\n\n // Merge signals\n const signal = options.signal\n ? this.mergeSignals(options.signal, abortController.signal)\n : abortController.signal;\n\n try {\n // Step 1: Fetch and cook the formula\n this.logger.info('Starting formula execution', { executionId, formulaName });\n const cooked = await this.cook(formulaName, vars);\n\n // Initialize progress tracking\n const steps = cooked.steps ?? [];\n const legs = cooked.legs ?? [];\n const totalSteps = steps.length || legs.length;\n\n const progress: ExecutionProgress = {\n executionId,\n formulaName,\n status: 'running',\n totalSteps,\n completedSteps: 0,\n failedSteps: 0,\n startTime: new Date(),\n stepResults: [],\n percentage: 0,\n };\n\n this.executions.set(executionId, progress);\n this.emit('execution:start', executionId, cooked);\n\n // Create debounced progress emitter (100ms debounce)\n const progressEmitter = new DebouncedEmitter<ExecutionProgress>(\n (p) => this.emit('execution:progress', p),\n 100\n );\n this.progressEmitters.set(executionId, progressEmitter);\n\n // Step 2: Resolve dependencies and get execution order\n const orderedSteps = this.getOrderedExecutionUnits(cooked);\n\n // Step 3: Execute steps with parallel execution where deps allow\n const results: StepResult[] = [];\n const previousResults = new Map<string, StepResult>();\n const maxParallel = options.maxParallel ?? this.defaultMaxParallel;\n\n // Use parallel execution with work stealing if enabled\n if (maxParallel > 1 && orderedSteps.length > 1) {\n // Build dependency graph for parallel execution\n const stepDeps = new Map<string, Set<string>>();\n const stepById = new Map<string, Step>();\n const stepIndex = new Map<string, number>();\n\n for (let i = 0; i < orderedSteps.length; i++) {\n const step = orderedSteps[i];\n stepById.set(step.id, step);\n stepIndex.set(step.id, i);\n stepDeps.set(step.id, new Set(step.needs ?? []));\n }\n\n // Track completed steps\n const completed = new Set<string>();\n const inProgress = new Set<string>();\n\n // Work stealing queue\n const workQueue = new WorkStealingQueue(maxParallel);\n\n // Find steps that can run (no dependencies)\n const getReadySteps = (): Step[] => {\n const ready: Step[] = [];\n for (const step of orderedSteps) {\n if (completed.has(step.id) || inProgress.has(step.id)) continue;\n const deps = stepDeps.get(step.id);\n if (!deps || [...deps].every(d => completed.has(d))) {\n ready.push(step);\n }\n }\n return ready;\n };\n\n // Execute in parallel waves\n while (completed.size < orderedSteps.length) {\n // Check for cancellation\n if (signal.aborted) {\n progress.status = 'cancelled';\n this.emit('execution:cancelled', executionId);\n throw new GasTownError(\n 'Execution cancelled',\n GasTownErrorCode.UNKNOWN,\n { executionId }\n );\n }\n\n const readySteps = getReadySteps();\n if (readySteps.length === 0 && inProgress.size === 0) {\n // Deadlock - should not happen with valid DAG\n break;\n }\n\n // Limit parallel execution\n const batchSize = Math.min(readySteps.length, maxParallel - inProgress.size);\n const batch = readySteps.slice(0, batchSize);\n\n if (batch.length === 0) {\n // Wait for in-progress steps to complete\n await new Promise(resolve => setTimeout(resolve, 10));\n continue;\n }\n\n // Mark as in progress\n for (const step of batch) {\n inProgress.add(step.id);\n }\n\n // Execute batch in parallel\n const batchPromises = batch.map(async (step) => {\n const idx = stepIndex.get(step.id) ?? 0;\n progress.currentStep = step.id;\n\n const context: StepContext = {\n executionId,\n formula: cooked,\n stepIndex: idx,\n totalSteps: orderedSteps.length,\n variables: cooked.cookedVars,\n previousResults,\n signal,\n startTime: progress.startTime,\n };\n\n this.emit('step:start', executionId, step);\n\n try {\n const result = await this.runStep(step, context, options);\n previousResults.set(step.id, result);\n completed.add(step.id);\n inProgress.delete(step.id);\n\n if (result.success) {\n progress.completedSteps++;\n } else {\n progress.failedSteps++;\n }\n\n progress.stepResults.push(result);\n progress.percentage = Math.round((completed.size / orderedSteps.length) * 100);\n\n this.emit('step:complete', executionId, result);\n progressEmitter.update({ ...progress });\n\n return result;\n } catch (error) {\n const failedResult: StepResult = {\n stepId: step.id,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n durationMs: 0,\n };\n\n previousResults.set(step.id, failedResult);\n completed.add(step.id); // Mark as completed (failed)\n inProgress.delete(step.id);\n progress.failedSteps++;\n progress.stepResults.push(failedResult);\n\n this.emit('step:error', executionId, step.id, error as Error);\n progressEmitter.update({ ...progress });\n\n // Continue or fail based on step configuration\n if (!step.metadata?.continueOnError) {\n throw error;\n }\n\n return failedResult;\n }\n });\n\n const batchResults = await Promise.all(batchPromises);\n results.push(...batchResults);\n }\n\n // Flush final progress\n progressEmitter.flush();\n } else {\n // Sequential execution (original behavior)\n for (let i = 0; i < orderedSteps.length; i++) {\n // Check for cancellation\n if (signal.aborted) {\n progress.status = 'cancelled';\n this.emit('execution:cancelled', executionId);\n throw new GasTownError(\n 'Execution cancelled',\n GasTownErrorCode.UNKNOWN,\n { executionId }\n );\n }\n\n const step = orderedSteps[i];\n progress.currentStep = step.id;\n\n const context: StepContext = {\n executionId,\n formula: cooked,\n stepIndex: i,\n totalSteps: orderedSteps.length,\n variables: cooked.cookedVars,\n previousResults,\n signal,\n startTime: progress.startTime,\n };\n\n this.emit('step:start', executionId, step);\n\n try {\n const result = await this.runStep(step, context, options);\n results.push(result);\n previousResults.set(step.id, result);\n\n if (result.success) {\n progress.completedSteps++;\n } else {\n progress.failedSteps++;\n }\n\n progress.stepResults.push(result);\n progress.percentage = Math.round(((i + 1) / orderedSteps.length) * 100);\n\n this.emit('step:complete', executionId, result);\n progressEmitter.update({ ...progress });\n } catch (error) {\n const failedResult: StepResult = {\n stepId: step.id,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n durationMs: 0,\n };\n\n results.push(failedResult);\n previousResults.set(step.id, failedResult);\n progress.failedSteps++;\n progress.stepResults.push(failedResult);\n\n this.emit('step:error', executionId, step.id, error as Error);\n\n // Continue or fail based on step configuration\n if (!step.metadata?.continueOnError) {\n throw error;\n }\n }\n }\n\n // Flush final progress\n progressEmitter.flush();\n }\n\n // Step 4: Complete execution\n progress.status = progress.failedSteps > 0 ? 'failed' : 'completed';\n progress.endTime = new Date();\n progress.percentage = 100;\n\n this.emit('execution:complete', executionId, results);\n this.logger.info('Formula execution completed', {\n executionId,\n formulaName,\n completed: progress.completedSteps,\n failed: progress.failedSteps,\n });\n\n return results;\n } catch (error) {\n const progress = this.executions.get(executionId);\n if (progress) {\n progress.status = 'failed';\n progress.endTime = new Date();\n progress.error = error instanceof Error ? error.message : String(error);\n }\n\n this.emit('execution:error', executionId, error as Error);\n throw error;\n } finally {\n this.cancellations.delete(executionId);\n // Cleanup progress emitter\n const emitter = this.progressEmitters.get(executionId);\n if (emitter) {\n emitter.cancel();\n this.progressEmitters.delete(executionId);\n }\n }\n }\n\n /**\n * Cook a formula with variable substitution (WASM-accelerated)\n *\n * @param formulaName - Name of the formula or TOML content\n * @param vars - Variables for substitution\n * @returns Cooked formula with substituted variables\n */\n async cook(\n formulaName: string,\n vars: Record<string, string>\n ): Promise<CookedFormula> {\n this.logger.debug('Cooking formula', { formulaName, varsCount: Object.keys(vars).length });\n\n // Generate cache key from formula name and vars\n const varKeys = Object.keys(vars).sort();\n const varValues = varKeys.map(k => vars[k]);\n const cacheKey = hashKey([formulaName, ...varKeys, ...varValues]);\n\n // Check cook cache first\n const cached = cookCache.get(cacheKey);\n if (cached) {\n this.logger.debug('Cook cache hit', { formulaName });\n return cached;\n }\n\n // Use deduplication for concurrent identical requests\n return cookDedup.dedupe(cacheKey, async () => {\n try {\n // Determine if formulaName is content or a name to fetch\n let formula: Formula;\n\n if (formulaName.includes('[') || formulaName.includes('=')) {\n // Looks like TOML content, parse directly\n formula = this.parseFormula(formulaName);\n } else {\n // Fetch formula from CLI with deduplication\n formula = await fetchDedup.dedupe(formulaName, () => this.fetchFormula(formulaName));\n }\n\n // Validate required variables\n this.validateVariables(formula, vars);\n\n // Cook using WASM if available, otherwise JS fallback\n const loader = this.wasmLoader.isInitialized() ? this.wasmLoader : this.jsFallback;\n const cooked = loader.cookFormula(formula, vars);\n\n // Cache the result\n cookCache.set(cacheKey, cooked);\n\n this.logger.debug('Formula cooked successfully', {\n formulaName,\n wasmAccelerated: this.wasmLoader.isInitialized(),\n });\n\n return cooked;\n } catch (error) {\n if (error instanceof GasTownError) throw error;\n\n throw FormulaError.cookFailed(\n formulaName,\n error instanceof Error ? error.message : String(error),\n error as Error\n );\n }\n });\n }\n\n /**\n * Generate molecules from a cooked formula\n *\n * Molecules are executable work units derived from formula steps/legs.\n * Uses object pooling for reduced allocations.\n *\n * @param cookedFormula - The cooked formula to generate molecules from\n * @returns Array of molecules\n */\n async generateMolecules(cookedFormula: CookedFormula): Promise<Molecule[]> {\n this.logger.debug('Generating molecules', { formulaName: cookedFormula.name });\n\n const molecules: Molecule[] = [];\n const moleculeIdMap = new Map<string, string>();\n\n // Generate molecules based on formula type\n if (cookedFormula.type === 'convoy' && cookedFormula.legs) {\n // Convoy: Generate from legs\n const orderedLegs = [...cookedFormula.legs].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n\n for (let i = 0; i < orderedLegs.length; i++) {\n const leg = orderedLegs[i];\n const moleculeId = `mol-${cookedFormula.name}-${leg.id}-${randomUUID().slice(0, 8)}`;\n moleculeIdMap.set(leg.id, moleculeId);\n\n // Use pooled molecule for reduced allocations\n const pooledMol = moleculePool.acquire() as PooledMolecule;\n pooledMol.id = moleculeId;\n pooledMol.formulaName = cookedFormula.name;\n pooledMol.title = leg.title;\n pooledMol.description = leg.description;\n pooledMol.type = cookedFormula.type;\n pooledMol.sourceId = leg.id;\n pooledMol.agent = leg.agent;\n pooledMol.dependencies = i > 0 ? [moleculeIdMap.get(orderedLegs[i - 1].id)!] : [];\n pooledMol.order = i;\n pooledMol.metadata = {\n focus: leg.focus,\n legOrder: leg.order,\n };\n pooledMol.createdAt = new Date();\n\n // Create plain molecule for return (avoid pool reference issues)\n const molecule: Molecule = {\n id: pooledMol.id,\n formulaName: pooledMol.formulaName,\n title: pooledMol.title,\n description: pooledMol.description,\n type: pooledMol.type,\n sourceId: pooledMol.sourceId,\n agent: pooledMol.agent,\n dependencies: [...pooledMol.dependencies],\n order: pooledMol.order,\n metadata: { ...pooledMol.metadata },\n createdAt: pooledMol.createdAt,\n };\n\n // Release pooled molecule back to pool\n moleculePool.release(pooledMol);\n\n molecules.push(molecule);\n this.emit('molecule:created', molecule);\n }\n } else if (cookedFormula.steps) {\n // Workflow/Expansion/Aspect: Generate from steps\n const orderedSteps = this.resolveStepDependencies(cookedFormula.steps);\n\n for (let i = 0; i < orderedSteps.length; i++) {\n const step = orderedSteps[i];\n const moleculeId = `mol-${cookedFormula.name}-${step.id}-${randomUUID().slice(0, 8)}`;\n moleculeIdMap.set(step.id, moleculeId);\n\n // Map step dependencies to molecule IDs\n const dependencies: string[] = [];\n if (step.needs) {\n for (const need of step.needs) {\n const depMoleculeId = moleculeIdMap.get(need);\n if (depMoleculeId) {\n dependencies.push(depMoleculeId);\n }\n }\n }\n\n // Use pooled molecule for reduced allocations\n const pooledMol = moleculePool.acquire() as PooledMolecule;\n pooledMol.id = moleculeId;\n pooledMol.formulaName = cookedFormula.name;\n pooledMol.title = step.title;\n pooledMol.description = step.description;\n pooledMol.type = cookedFormula.type;\n pooledMol.sourceId = step.id;\n pooledMol.agent = undefined;\n pooledMol.dependencies = dependencies;\n pooledMol.order = i;\n pooledMol.metadata = {\n duration: step.duration,\n requires: step.requires,\n ...step.metadata,\n };\n pooledMol.createdAt = new Date();\n\n // Create plain molecule for return (avoid pool reference issues)\n const molecule: Molecule = {\n id: pooledMol.id,\n formulaName: pooledMol.formulaName,\n title: pooledMol.title,\n description: pooledMol.description,\n type: pooledMol.type,\n sourceId: pooledMol.sourceId,\n agent: pooledMol.agent,\n dependencies: [...pooledMol.dependencies],\n order: pooledMol.order,\n metadata: { ...pooledMol.metadata },\n createdAt: pooledMol.createdAt,\n };\n\n // Release pooled molecule back to pool\n moleculePool.release(pooledMol);\n\n molecules.push(molecule);\n this.emit('molecule:created', molecule);\n }\n }\n\n this.logger.info('Molecules generated', {\n formulaName: cookedFormula.name,\n count: molecules.length,\n });\n\n return molecules;\n }\n\n /**\n * Run a single step\n *\n * @param step - Step to execute\n * @param context - Execution context\n * @param options - Execution options\n * @returns Step result\n */\n async runStep(\n step: Step,\n context: StepContext,\n options: ExecuteOptions = {}\n ): Promise<StepResult> {\n const startTime = Date.now();\n\n this.logger.debug('Running step', {\n stepId: step.id,\n executionId: context.executionId,\n });\n\n // Generate cache key for step result memoization\n // Only cache if step is deterministic (no side effects indicator)\n const isCacheable = step.metadata?.cacheable !== false && !step.metadata?.hasSideEffects;\n const stepCacheKey = isCacheable\n ? hashKey([\n step.id,\n context.formula.name,\n JSON.stringify(context.variables),\n JSON.stringify(step.needs ?? []),\n ])\n : null;\n\n // Check step result cache\n if (stepCacheKey) {\n const cachedResult = stepResultCache.get(stepCacheKey);\n if (cachedResult) {\n this.logger.debug('Step cache hit', { stepId: step.id });\n return {\n ...cachedResult,\n metadata: { ...cachedResult.metadata, fromCache: true },\n };\n }\n }\n\n try {\n // Check for cancellation\n if (context.signal?.aborted) {\n throw new GasTownError('Step cancelled', GasTownErrorCode.UNKNOWN);\n }\n\n // Check dependencies are satisfied\n if (step.needs) {\n for (const dep of step.needs) {\n const depResult = context.previousResults.get(dep);\n if (!depResult || !depResult.success) {\n throw new GasTownError(\n `Dependency not satisfied: ${dep}`,\n GasTownErrorCode.UNKNOWN,\n { stepId: step.id, dependency: dep }\n );\n }\n }\n }\n\n // Use custom step handler if provided\n if (options.stepHandler) {\n const result = await options.stepHandler(step, context);\n if (stepCacheKey && result.success) {\n stepResultCache.set(stepCacheKey, result);\n }\n return result;\n }\n\n // Dry run mode\n if (options.dryRun) {\n return {\n stepId: step.id,\n success: true,\n output: { dryRun: true, step },\n durationMs: Date.now() - startTime,\n metadata: { dryRun: true },\n };\n }\n\n // Default execution via CLI\n const result = await this.executeStepViaCli(step, context, options);\n\n const stepResult: StepResult = {\n stepId: step.id,\n success: true,\n output: result,\n durationMs: Date.now() - startTime,\n };\n\n // Cache successful result\n if (stepCacheKey) {\n stepResultCache.set(stepCacheKey, stepResult);\n }\n\n return stepResult;\n } catch (error) {\n return {\n stepId: step.id,\n success: false,\n error: error instanceof Error ? error.message : String(error),\n durationMs: Date.now() - startTime,\n };\n }\n }\n\n /**\n * Get execution progress\n *\n * @param executionId - Execution ID to get progress for\n * @returns Execution progress or undefined\n */\n getProgress(executionId: string): ExecutionProgress | undefined {\n return this.executions.get(executionId);\n }\n\n /**\n * Cancel an execution\n *\n * @param executionId - Execution ID to cancel\n * @returns Whether cancellation was initiated\n */\n cancel(executionId: string): boolean {\n const controller = this.cancellations.get(executionId);\n if (controller) {\n controller.abort();\n return true;\n }\n return false;\n }\n\n /**\n * List all active executions\n */\n getActiveExecutions(): ExecutionProgress[] {\n return Array.from(this.executions.values()).filter(\n e => e.status === 'running' || e.status === 'pending'\n );\n }\n\n /**\n * Check if WASM is available for acceleration\n */\n isWasmAvailable(): boolean {\n return this.wasmLoader.isInitialized();\n }\n\n /**\n * Get cache statistics for performance monitoring\n */\n getCacheStats(): {\n stepResultCache: { entries: number; sizeBytes: number };\n cookCache: { entries: number; sizeBytes: number };\n } {\n return {\n stepResultCache: stepResultCache.stats(),\n cookCache: cookCache.stats(),\n };\n }\n\n /**\n * Clear all executor caches\n */\n clearCaches(): void {\n stepResultCache.clear();\n cookCache.clear();\n }\n\n // ============================================================================\n // Private Methods\n // ============================================================================\n\n /**\n * Parse formula content using WASM or JS fallback\n */\n private parseFormula(content: string): Formula {\n const loader = this.wasmLoader.isInitialized() ? this.wasmLoader : this.jsFallback;\n return loader.parseFormula(content);\n }\n\n /**\n * Fetch formula from CLI\n */\n private async fetchFormula(formulaName: string): Promise<Formula> {\n // Check if bridge is initialized\n if (!this.gtBridge.isInitialized()) {\n throw new GasTownError(\n 'GtBridge not initialized',\n GasTownErrorCode.NOT_INITIALIZED\n );\n }\n\n // Fetch formula via CLI (would be: gt formula show <name> --json)\n // For now, simulate with a placeholder\n // In production, this would call: this.gtBridge.execGt(['formula', 'show', formulaName, '--json'])\n this.logger.debug('Fetching formula from CLI', { formulaName });\n\n // Simulated formula for demonstration\n const formula: Formula = {\n name: formulaName,\n description: `Formula: ${formulaName}`,\n type: 'workflow',\n version: 1,\n steps: [\n {\n id: 'init',\n title: 'Initialize',\n description: 'Initialize the workflow',\n },\n {\n id: 'process',\n title: 'Process',\n description: 'Process the data',\n needs: ['init'],\n },\n {\n id: 'finalize',\n title: 'Finalize',\n description: 'Finalize the workflow',\n needs: ['process'],\n },\n ],\n vars: {},\n };\n\n return formula;\n }\n\n /**\n * Validate required variables are provided\n */\n private validateVariables(formula: Formula, vars: Record<string, string>): void {\n if (!formula.vars) return;\n\n const missing: string[] = [];\n\n for (const [name, varDef] of Object.entries(formula.vars)) {\n if (varDef.required && !(name in vars) && !varDef.default) {\n missing.push(name);\n }\n }\n\n if (missing.length > 0) {\n throw new GasTownError(\n `Missing required variables: ${missing.join(', ')}`,\n GasTownErrorCode.INVALID_ARGUMENTS,\n { missing }\n );\n }\n }\n\n /**\n * Resolve step dependencies using WASM or JS fallback\n */\n private resolveStepDependencies(steps: Step[]): Step[] {\n const loader = this.wasmLoader.isInitialized() ? this.wasmLoader : this.jsFallback;\n return loader.resolveStepDependencies(steps);\n }\n\n /**\n * Get ordered execution units (steps or legs) from formula\n */\n private getOrderedExecutionUnits(formula: CookedFormula): Step[] {\n if (formula.type === 'convoy' && formula.legs) {\n // Convert legs to steps for unified execution\n const legs = [...formula.legs].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n return legs.map((leg, index) => ({\n id: leg.id,\n title: leg.title,\n description: leg.description,\n needs: index > 0 ? [legs[index - 1].id] : undefined,\n metadata: { agent: leg.agent, focus: leg.focus },\n }));\n }\n\n if (formula.steps) {\n return this.resolveStepDependencies(formula.steps);\n }\n\n return [];\n }\n\n /**\n * Execute step via CLI bridge\n */\n private async executeStepViaCli(\n step: Step,\n context: StepContext,\n options: ExecuteOptions\n ): Promise<unknown> {\n // Build CLI command for step execution\n const args = [\n 'formula',\n 'step',\n step.id,\n '--execution-id', context.executionId,\n '--json',\n ];\n\n if (options.targetAgent) {\n args.push('--agent', options.targetAgent);\n }\n\n if (options.stepTimeout) {\n args.push('--timeout', String(options.stepTimeout));\n }\n\n // Execute via bridge\n const result = await this.gtBridge.execGt(args);\n\n if (!result.success) {\n throw new GasTownError(\n `Step execution failed: ${result.error}`,\n GasTownErrorCode.CLI_EXECUTION_FAILED,\n { stepId: step.id, error: result.error }\n );\n }\n\n return result.data ? JSON.parse(result.data) : null;\n }\n\n /**\n * Merge multiple abort signals\n */\n private mergeSignals(...signals: AbortSignal[]): AbortSignal {\n const controller = new AbortController();\n\n for (const signal of signals) {\n if (signal.aborted) {\n controller.abort();\n break;\n }\n\n signal.addEventListener('abort', () => controller.abort(), { once: true });\n }\n\n return controller.signal;\n }\n}\n\n// ============================================================================\n// Factory Function\n// ============================================================================\n\n/**\n * Create a new FormulaExecutor instance\n */\nexport function createFormulaExecutor(\n gtBridge: GtBridge,\n wasmLoader?: IWasmLoader,\n logger?: ExecutorLogger\n): FormulaExecutor {\n return new FormulaExecutor(gtBridge, wasmLoader, logger);\n}\n\nexport default FormulaExecutor;\n"]}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import {EventEmitter}from'events';/**
|
|
2
|
+
* @claude-flow/plugin-gastown-bridge v0.1.4
|
|
3
|
+
*
|
|
4
|
+
* WASM-accelerated Gas Town orchestration for Claude Flow V3
|
|
5
|
+
* Bundle optimized: <100KB gzipped total
|
|
6
|
+
*
|
|
7
|
+
* @license MIT
|
|
8
|
+
* @copyright 2024 rUv
|
|
9
|
+
*/
|
|
10
|
+
var s={UNKNOWN:"GT_UNKNOWN",INITIALIZATION_FAILED:"GT_INITIALIZATION_FAILED",NOT_INITIALIZED:"GT_NOT_INITIALIZED",CONFIGURATION_ERROR:"GT_CONFIGURATION_ERROR",VALIDATION_FAILED:"GT_VALIDATION_FAILED",INVALID_INPUT:"GT_INVALID_INPUT",INVALID_BEAD_ID:"GT_INVALID_BEAD_ID",INVALID_FORMULA_NAME:"GT_INVALID_FORMULA_NAME",INVALID_CONVOY_ID:"GT_INVALID_CONVOY_ID",INVALID_ARGUMENTS:"GT_INVALID_ARGUMENTS",COMMAND_INJECTION_DETECTED:"GT_COMMAND_INJECTION_DETECTED",PATH_TRAVERSAL_DETECTED:"GT_PATH_TRAVERSAL_DETECTED",BEAD_NOT_FOUND:"GT_BEAD_NOT_FOUND",BEAD_CREATE_FAILED:"GT_BEAD_CREATE_FAILED",BEAD_UPDATE_FAILED:"GT_BEAD_UPDATE_FAILED",BEAD_DELETE_FAILED:"GT_BEAD_DELETE_FAILED",BEAD_PARSE_FAILED:"GT_BEAD_PARSE_FAILED",FORMULA_NOT_FOUND:"GT_FORMULA_NOT_FOUND",FORMULA_PARSE_FAILED:"GT_FORMULA_PARSE_FAILED",FORMULA_COOK_FAILED:"GT_FORMULA_COOK_FAILED",FORMULA_INVALID_TYPE:"GT_FORMULA_INVALID_TYPE",CONVOY_NOT_FOUND:"GT_CONVOY_NOT_FOUND",CONVOY_CREATE_FAILED:"GT_CONVOY_CREATE_FAILED",CLI_NOT_FOUND:"GT_CLI_NOT_FOUND",CLI_TIMEOUT:"GT_CLI_TIMEOUT",CLI_EXECUTION_FAILED:"GT_CLI_EXECUTION_FAILED",CLI_INVALID_OUTPUT:"GT_CLI_INVALID_OUTPUT",WASM_NOT_AVAILABLE:"GT_WASM_NOT_AVAILABLE",WASM_EXECUTION_FAILED:"GT_WASM_EXECUTION_FAILED",SYNC_FAILED:"GT_SYNC_FAILED",SYNC_CONFLICT:"GT_SYNC_CONFLICT",DEPENDENCY_CYCLE:"GT_DEPENDENCY_CYCLE",GRAPH_ERROR:"GT_GRAPH_ERROR"},c=class o extends Error{code;timestamp;context;cause;constructor(e,t=s.UNKNOWN,r,i){super(e),this.name="GasTownError",this.code=t,this.timestamp=new Date,this.context=r,this.cause=i,Error.captureStackTrace&&Error.captureStackTrace(this,o);}toJSON(){return {name:this.name,message:this.message,code:this.code,timestamp:this.timestamp.toISOString(),context:this.context,cause:this.cause?.message,stack:this.stack}}toString(){let e=`[${this.code}] ${this.message}`;return this.context&&(e+=` | Context: ${JSON.stringify(this.context)}`),this.cause&&(e+=` | Caused by: ${this.cause.message}`),e}},F=class o extends c{beadId;operation;constructor(e,t=s.BEAD_NOT_FOUND,r,i){super(e,t,r,i),this.name="BeadsError",r?.beadId&&typeof r.beadId=="string"&&(this.beadId=r.beadId),r?.operation&&typeof r.operation=="string"&&(this.operation=r.operation),Error.captureStackTrace&&Error.captureStackTrace(this,o);}static notFound(e){return new o(`Bead not found: ${e}`,s.BEAD_NOT_FOUND,{beadId:e,operation:"get"})}static createFailed(e,t){return new o(`Failed to create bead: ${e}`,s.BEAD_CREATE_FAILED,{operation:"create"},t)}static parseFailed(e,t){let r=e.length>200?e.slice(0,200)+"...":e;return new o("Failed to parse bead output",s.BEAD_PARSE_FAILED,{operation:"parse",outputLength:e.length,outputPreview:r},t)}},k=class o extends c{constraints;constructor(e,t=s.VALIDATION_FAILED,r=[],i){super(e,t,{constraints:r},i),this.name="ValidationError",this.constraints=r,Error.captureStackTrace&&Error.captureStackTrace(this,o);}static invalidBeadId(e){let t=e.replace(/[^\w\s-]/g,"?").slice(0,32);return new o("Invalid bead ID format",s.INVALID_BEAD_ID,[{field:"beadId",constraint:"alphanumeric with gt- prefix",actual:t,expected:"gt-{4-16 alphanumeric} or numeric"}])}static invalidFormulaName(e){let t=e.replace(/[^\w\s-]/g,"?").slice(0,32);return new o("Invalid formula name format",s.INVALID_FORMULA_NAME,[{field:"formulaName",constraint:"alphanumeric with dash/underscore, starting with letter",actual:t,expected:"[a-zA-Z][a-zA-Z0-9_-]{0,63}"}])}static invalidConvoyId(e){let t=e.replace(/[^\w\s-]/g,"?").slice(0,32);return new o("Invalid convoy ID format",s.INVALID_CONVOY_ID,[{field:"convoyId",constraint:"UUID format",actual:t,expected:"xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"}])}static commandInjection(e,t){return new o(`Command injection detected in ${e}`,s.COMMAND_INJECTION_DETECTED,[{field:e,constraint:"no shell metacharacters",actual:"[REDACTED]",expected:"safe characters only"}])}static pathTraversal(e){return new o(`Path traversal detected in ${e}`,s.PATH_TRAVERSAL_DETECTED,[{field:e,constraint:"no parent directory references",actual:"[REDACTED]",expected:"safe path characters only"}])}static combine(e){let t=e.flatMap(r=>r.constraints);return new o(`Multiple validation errors: ${e.map(r=>r.message).join("; ")}`,s.VALIDATION_FAILED,t)}},U=class o extends c{command;args;exitCode;stderr;durationMs;constructor(e,t=s.CLI_EXECUTION_FAILED,r,i){let y=(r.args??[]).map(l=>l.length>50?l.slice(0,50)+"...":l),z=r.stderr&&r.stderr.length>500?r.stderr.slice(0,500)+"...":r.stderr;super(e,t,{command:r.command,args:y,exitCode:r.exitCode,durationMs:r.durationMs},i),this.name="CLIExecutionError",this.command=r.command,this.args=y,this.exitCode=r.exitCode,this.stderr=z,this.durationMs=r.durationMs,Error.captureStackTrace&&Error.captureStackTrace(this,o);}static notFound(e){return new o(`CLI command not found: ${e}`,s.CLI_NOT_FOUND,{command:e})}static timeout(e,t,r){return new o(`CLI command timed out after ${r}ms`,s.CLI_TIMEOUT,{command:e,args:t,durationMs:r})}static failed(e,t,r,i,y){return new o(`CLI command failed with exit code ${r}`,s.CLI_EXECUTION_FAILED,{command:e,args:t,exitCode:r,stderr:i,durationMs:y})}static invalidOutput(e,t){return new o(`CLI command produced invalid output: ${t}`,s.CLI_INVALID_OUTPUT,{command:e})}},W=class o extends c{formulaName;formulaType;constructor(e,t=s.FORMULA_PARSE_FAILED,r,i){super(e,t,r,i),this.name="FormulaError",r?.formulaName&&typeof r.formulaName=="string"&&(this.formulaName=r.formulaName),r?.formulaType&&typeof r.formulaType=="string"&&(this.formulaType=r.formulaType),Error.captureStackTrace&&Error.captureStackTrace(this,o);}static notFound(e){return new o(`Formula not found: ${e}`,s.FORMULA_NOT_FOUND,{formulaName:e})}static parseFailed(e,t,r){return new o(`Failed to parse formula ${e}: ${t}`,s.FORMULA_PARSE_FAILED,{formulaName:e,parseError:t},r)}static cookFailed(e,t,r){return new o(`Failed to cook formula ${e}: ${t}`,s.FORMULA_COOK_FAILED,{formulaName:e,cookError:t},r)}},H=class o extends c{convoyId;constructor(e,t=s.CONVOY_NOT_FOUND,r,i){super(e,t,r,i),this.name="ConvoyError",r?.convoyId&&typeof r.convoyId=="string"&&(this.convoyId=r.convoyId),Error.captureStackTrace&&Error.captureStackTrace(this,o);}static notFound(e){return new o(`Convoy not found: ${e}`,s.CONVOY_NOT_FOUND,{convoyId:e})}static createFailed(e,t){return new o(`Failed to create convoy: ${e}`,s.CONVOY_CREATE_FAILED,{operation:"create"},t)}};function ne(o){return o instanceof c}function le(o){return o instanceof k}function ce(o){return o instanceof U}function de(o){return o instanceof F}function ue(o,e){return o instanceof c?o:o instanceof Error?new c(o.message,e??s.UNKNOWN,void 0,o):new c(String(o),e??s.UNKNOWN)}function me(o){return o instanceof Error?o.message:String(o)}var n=class{pool=[];factory;resetFn;config;stats={created:0,available:0,inUse:0,misses:0,hits:0,peakSize:0,memorySaved:0};constructor(e,t){this.factory=e,this.resetFn=t?.reset,this.config={initialSize:t?.initialSize??0,maxSize:t?.maxSize??0,objectSizeBytes:t?.objectSizeBytes??256,preWarm:t?.preWarm??false},this.config.preWarm&&this.config.initialSize>0&&this.preWarm(this.config.initialSize);}acquire(){let e;return this.pool.length>0?(e=this.pool.pop(),this.stats.hits++,this.stats.available--):(e=this.factory(),this.stats.created++,this.stats.misses++),this.stats.inUse++,this.stats.inUse>this.stats.peakSize&&(this.stats.peakSize=this.stats.inUse),e}release(e){if(this.resetFn?this.resetFn(e):"reset"in e&&typeof e.reset=="function"&&e.reset(),this.config.maxSize>0&&this.pool.length>=this.config.maxSize){this.stats.inUse--;return}this.pool.push(e),this.stats.available++,this.stats.inUse--,this.stats.memorySaved+=this.config.objectSizeBytes;}releaseAll(e){for(let t of e)this.release(t);}preWarm(e){let t=Math.min(e,this.config.maxSize>0?this.config.maxSize-this.pool.length:e);for(let r=0;r<t;r++){let i=this.factory();this.stats.created++,this.pool.push(i),this.stats.available++;}}clear(){this.pool.length=0,this.stats.available=0;}getStats(){return {...this.stats}}get size(){return this.pool.length}get hitRate(){let e=this.stats.hits+this.stats.misses;return e>0?this.stats.hits/e*100:0}},P=class{id="";title="";description="";status="open";priority=0;labels=[];createdAt=new Date;updatedAt=new Date;parentId;assignee;rig;blockedBy;blocks;reset(){this.id="",this.title="",this.description="",this.status="open",this.priority=0,this.labels.length=0,this.createdAt=new Date,this.updatedAt=new Date,this.parentId=void 0,this.assignee=void 0,this.rig=void 0,this.blockedBy=void 0,this.blocks=void 0;}initFrom(e){return this.id=e.id??"",this.title=e.title??"",this.description=e.description??"",this.status=e.status??"open",this.priority=e.priority??0,this.labels=e.labels?[...e.labels]:[],this.createdAt=e.createdAt??new Date,this.updatedAt=e.updatedAt??new Date,this.parentId=e.parentId,this.assignee=e.assignee,this.rig=e.rig,this.blockedBy=e.blockedBy?[...e.blockedBy]:void 0,this.blocks=e.blocks?[...e.blocks]:void 0,this}},E=class{id="";title="";description="";needs;duration;requires;metadata;reset(){this.id="",this.title="",this.description="",this.needs=void 0,this.duration=void 0,this.requires=void 0,this.metadata=void 0;}initFrom(e){return this.id=e.id??"",this.title=e.title??"",this.description=e.description??"",this.needs=e.needs?[...e.needs]:void 0,this.duration=e.duration,this.requires=e.requires?[...e.requires]:void 0,this.metadata=e.metadata?{...e.metadata}:void 0,this}},S=class{name="";description="";type="workflow";version=1;steps;legs;vars;metadata;reset(){this.name="",this.description="",this.type="workflow",this.version=1,this.steps=void 0,this.legs=void 0,this.vars=void 0,this.metadata=void 0;}initFrom(e){return this.name=e.name??"",this.description=e.description??"",this.type=e.type??"workflow",this.version=e.version??1,this.steps=e.steps?[...e.steps]:void 0,this.legs=e.legs?[...e.legs]:void 0,this.vars=e.vars?{...e.vars}:void 0,this.metadata=e.metadata?{...e.metadata}:void 0,this}},I=class{id="";name="";trackedIssues=[];status="active";startedAt=new Date;completedAt;progress={total:0,closed:0,inProgress:0,blocked:0};formula;description;reset(){this.id="",this.name="",this.trackedIssues.length=0,this.status="active",this.startedAt=new Date,this.completedAt=void 0,this.progress={total:0,closed:0,inProgress:0,blocked:0},this.formula=void 0,this.description=void 0;}initFrom(e){return this.id=e.id??"",this.name=e.name??"",this.trackedIssues=e.trackedIssues?[...e.trackedIssues]:[],this.status=e.status??"active",this.startedAt=e.startedAt??new Date,this.completedAt=e.completedAt,this.progress=e.progress?{...e.progress}:{total:0,closed:0,inProgress:0,blocked:0},this.formula=e.formula,this.description=e.description,this}},M=class{id="";formulaName="";title="";description="";type="workflow";sourceId="";agent;dependencies=[];order=0;metadata={};createdAt=new Date;reset(){this.id="",this.formulaName="",this.title="",this.description="",this.type="workflow",this.sourceId="",this.agent=void 0,this.dependencies.length=0,this.order=0;for(let e of Object.keys(this.metadata))delete this.metadata[e];this.createdAt=new Date;}initFrom(e){return this.id=e.id??"",this.formulaName=e.formulaName??"",this.title=e.title??"",this.description=e.description??"",this.type=e.type??"workflow",this.sourceId=e.sourceId??"",this.agent=e.agent,this.dependencies=e.dependencies?[...e.dependencies]:[],this.order=e.order??0,this.metadata=e.metadata?{...e.metadata}:{},this.createdAt=e.createdAt??new Date,this}},f=new n(()=>new P,{initialSize:100,maxSize:1e4,objectSizeBytes:512,preWarm:false}),g=new n(()=>new S,{initialSize:10,maxSize:500,objectSizeBytes:1024,preWarm:false}),T=new n(()=>new E,{initialSize:50,maxSize:5e3,objectSizeBytes:256,preWarm:false}),A=new n(()=>new I,{initialSize:10,maxSize:200,objectSizeBytes:768,preWarm:false}),v=new n(()=>new M,{initialSize:50,maxSize:5e3,objectSizeBytes:384,preWarm:false}),q={bead:f,formula:g,step:T,convoy:A,molecule:v};function C(){return {bead:f.getStats(),formula:g.getStats(),step:T.getStats(),convoy:A.getStats(),molecule:v.getStats()}}function $(){return Object.values(q).reduce((o,e)=>o+e.getStats().memorySaved,0)}function L(){for(let o of Object.values(q))o.clear();}function R(){f.preWarm(100),g.preWarm(10),T.preWarm(50),A.preWarm(10),v.preWarm(50);}function D(){let o=C(),e=Object.values(o),t=e.reduce((l,d)=>l+d.hits,0),r=e.reduce((l,d)=>l+d.misses,0),i=e.reduce((l,d)=>l+d.memorySaved,0),y=e.reduce((l,d)=>l+d.inUse,0),z=e.reduce((l,d)=>l+d.available,0);return {totalHitRate:t+r>0?t/(t+r)*100:0,totalMemorySavedKB:i/1024,totalObjectsInUse:y,totalObjectsAvailable:z}}var b=class{name;config;allocations=[];stats={totalAllocations:0,currentAllocations:0,resetCount:0,peakAllocations:0,memoryUsed:0,memorySaved:0};beadPool;stepPool;formulaPool;convoyPool;moleculePool;constructor(e,t){this.name=e??t?.name??"arena",this.config={name:this.name,initialCapacity:t?.initialCapacity??100,maxAllocations:t?.maxAllocations??0,returnToPool:t?.returnToPool??true},this.beadPool=new n(()=>new P,{initialSize:0,maxSize:1e4,objectSizeBytes:512}),this.stepPool=new n(()=>new E,{initialSize:0,maxSize:5e3,objectSizeBytes:256}),this.formulaPool=new n(()=>new S,{initialSize:0,maxSize:500,objectSizeBytes:1024}),this.convoyPool=new n(()=>new I,{initialSize:0,maxSize:200,objectSizeBytes:768}),this.moleculePool=new n(()=>new M,{initialSize:0,maxSize:5e3,objectSizeBytes:384}),this.config.initialCapacity>0&&(this.allocations=new Array(this.config.initialCapacity),this.allocations.length=0);}allocate(e,t=256){this.checkMaxAllocations();let r=e();return this.trackAllocation(r,"generic",t),r}allocateTyped(e){this.checkMaxAllocations();let t,r;switch(e){case "bead":t=this.beadPool.acquire(),r=512;break;case "step":t=this.stepPool.acquire(),r=256;break;case "formula":t=this.formulaPool.acquire(),r=1024;break;case "convoy":t=this.convoyPool.acquire(),r=768;break;case "molecule":t=this.moleculePool.acquire(),r=384;break;default:throw new Error(`Unknown allocatable type: ${e}`)}return this.trackAllocation(t,e,r),t}allocateMany(e,t){let r=new Array(t);for(let i=0;i<t;i++)r[i]=this.allocateTyped(e);return r}reset(){if(this.config.returnToPool)for(let t of this.allocations)this.returnToPool(t);let e=this.stats.memoryUsed;this.stats.memorySaved+=e,this.stats.resetCount++,this.stats.currentAllocations>this.stats.peakAllocations&&(this.stats.peakAllocations=this.stats.currentAllocations),this.allocations.length=0,this.stats.currentAllocations=0,this.stats.memoryUsed=0;}getStats(){return {...this.stats}}get allocationCount(){return this.stats.currentAllocations}get arenaName(){return this.name}dispose(){this.reset(),this.beadPool.clear(),this.stepPool.clear(),this.formulaPool.clear(),this.convoyPool.clear(),this.moleculePool.clear();}trackAllocation(e,t,r){this.allocations.push({object:e,type:t,sizeBytes:r}),this.stats.totalAllocations++,this.stats.currentAllocations++,this.stats.memoryUsed+=r;}checkMaxAllocations(){this.config.maxAllocations>0&&this.stats.currentAllocations>=this.config.maxAllocations&&(console.warn(`[${this.name}] Max allocations reached, auto-resetting`),this.reset());}returnToPool(e){switch(e.type){case "bead":this.beadPool.release(e.object);break;case "step":this.stepPool.release(e.object);break;case "formula":this.formulaPool.release(e.object);break;case "convoy":this.convoyPool.release(e.object);break;case "molecule":this.moleculePool.release(e.object);break}}};function K(o,e){let t=new b(o,e);return Object.assign(t,{[Symbol.dispose](){t.reset();}})}async function Y(o,e,t){let r=new b(o,t);try{return await e(r)}finally{r.reset();}}function X(o,e,t){let r=new b(o,t);try{return e(r)}finally{r.reset();}}var _=class{arenas=new Map;stats={totalArenas:0,activeArenas:0,totalMemorySaved:0};getArena(e,t){let r=this.arenas.get(e);return r||(r=new b(e,t),this.arenas.set(e,r),this.stats.totalArenas++,this.stats.activeArenas++),r}resetArena(e){let t=this.arenas.get(e);if(t){let r=t.getStats().memoryUsed;t.reset(),this.stats.totalMemorySaved+=r;}}resetAll(){for(let e of this.arenas.values()){let t=e.getStats().memoryUsed;e.reset(),this.stats.totalMemorySaved+=t;}}disposeArena(e){let t=this.arenas.get(e);t&&(t.dispose(),this.arenas.delete(e),this.stats.activeArenas--);}disposeAll(){for(let e of this.arenas.values())e.dispose();this.arenas.clear(),this.stats.activeArenas=0;}getStats(){let e={};for(let[t,r]of this.arenas)e[t]=r.getStats();return {...this.stats,arenaStats:e}}},m=new _;var h=class extends EventEmitter{config;pollTimer;pressureCallbacks=[];lastPressureLevel="none";running=false;statsHistory=[];maxHistorySize=60;constructor(e){super(),this.config={memoryLimit:e?.memoryLimit??0,lowPressureThreshold:e?.lowPressureThreshold??.5,mediumPressureThreshold:e?.mediumPressureThreshold??.7,highPressureThreshold:e?.highPressureThreshold??.85,criticalPressureThreshold:e?.criticalPressureThreshold??.95,pollInterval:e?.pollInterval??0,autoCleanup:e?.autoCleanup??false,gcHints:e?.gcHints??true};}getMemoryUsage(){let e=process.memoryUsage(),t=D(),r=m.getStats(),i=0;for(let z of Object.values(r.arenaStats))i+=z.memoryUsed;return {heapUsed:e.heapUsed,heapTotal:e.heapTotal,external:e.external,arrayBuffers:e.arrayBuffers,rss:e.rss,pools:{totalMemorySaved:t.totalMemorySavedKB*1024,hitRate:t.totalHitRate,objectsInUse:t.totalObjectsInUse,objectsAvailable:t.totalObjectsAvailable},arenas:{activeArenas:r.activeArenas,totalMemoryUsed:i,totalMemorySaved:r.totalMemorySaved},timestamp:new Date,underPressure:this.lastPressureLevel!=="none"}}setMemoryLimit(e){this.config.memoryLimit=e;}getMemoryLimit(){return this.config.memoryLimit}onMemoryPressure(e){return this.pressureCallbacks.push(e),()=>{let t=this.pressureCallbacks.indexOf(e);t!==-1&&this.pressureCallbacks.splice(t,1);}}checkPressure(){if(this.config.memoryLimit===0)return "none";let t=this.getMemoryUsage().heapUsed/this.config.memoryLimit;return t>=this.config.criticalPressureThreshold?"critical":t>=this.config.highPressureThreshold?"high":t>=this.config.mediumPressureThreshold?"medium":t>=this.config.lowPressureThreshold?"low":"none"}start(){this.running||(this.running=true,this.config.pollInterval>0&&(this.pollTimer=setInterval(()=>{this.poll();},this.config.pollInterval)));}stop(){this.running=false,this.pollTimer&&(clearInterval(this.pollTimer),this.pollTimer=void 0);}poll(){let e=this.getMemoryUsage(),t=this.checkPressure();if(this.statsHistory.push(e),this.statsHistory.length>this.maxHistorySize&&this.statsHistory.shift(),this.emit("snapshot",e),t!==this.lastPressureLevel){this.lastPressureLevel=t,e.underPressure=t!=="none",this.emit(`pressure:${t}`,e);for(let r of this.pressureCallbacks)try{r(t,e);}catch(i){console.error("[MemoryMonitor] Pressure callback error:",i);}this.config.autoCleanup&&(t==="high"||t==="critical")&&this.triggerCleanup();}this.config.memoryLimit>0&&e.heapUsed>this.config.memoryLimit&&this.emit("limit:exceeded",e);}triggerCleanup(){let e=this.getMemoryUsage();L(),m.resetAll(),this.config.gcHints&&typeof global.gc=="function"&&global.gc();let t=this.getMemoryUsage();this.emit("cleanup:triggered",e,t);}getMemoryTrend(){if(this.statsHistory.length<2)return 0;let e=this.statsHistory[0],t=this.statsHistory[this.statsHistory.length-1],r=t.timestamp.getTime()-e.timestamp.getTime();return r===0?0:(t.heapUsed-e.heapUsed)/r*1e3}estimateTimeToLimit(){if(this.config.memoryLimit===0)return null;let e=this.getMemoryTrend();if(e<=0)return null;let t=this.getMemoryUsage();return (this.config.memoryLimit-t.heapUsed)/e*1e3}getPoolStats(){return C()}getHistory(){return [...this.statsHistory]}clearHistory(){this.statsHistory.length=0;}isRunning(){return this.running}getConfig(){return {...this.config}}updateConfig(e){Object.assign(this.config,e),e.pollInterval!==void 0&&this.running&&(this.stop(),this.start());}};function J(){return new h().getMemoryUsage()}function Q(o,e){let t=new h({memoryLimit:o,pollInterval:1e3,autoCleanup:true});return e&&t.onMemoryPressure(e),t.start(),t}var p=null;function ee(o){return p||(p=new h({memoryLimit:10*1024*1024,pollInterval:1e3,autoCleanup:true}),p.start()),p.onMemoryPressure(o)}function te(){return p}function re(){p&&(p.stop(),p=null);}var O=class{budgets=new Map;totalLimit;constructor(e=10*1024*1024){this.totalLimit=e;}allocateBudget(e,t){return this.getTotalAllocated()+t>this.totalLimit?false:(this.budgets.set(e,{name:e,allocated:t,used:0,limit:t}),true)}updateUsage(e,t){let r=this.budgets.get(e);r&&(r.used=t);}isExceeded(e){let t=this.budgets.get(e);return t?t.used>t.limit:false}getBudget(e){return this.budgets.get(e)}getAllBudgets(){return Array.from(this.budgets.values())}getTotalAllocated(){return Array.from(this.budgets.values()).reduce((e,t)=>e+t.allocated,0)}getTotalUsed(){return Array.from(this.budgets.values()).reduce((e,t)=>e+t.used,0)}freeBudget(e){this.budgets.delete(e);}getTotalLimit(){return this.totalLimit}setTotalLimit(e){this.totalLimit=e;}},x=new O(10*1024*1024);x.allocateBudget("beads",5*1024*1024);x.allocateBudget("formulas",1*1024*1024);x.allocateBudget("convoys",1*1024*1024);x.allocateBudget("wasm",2*1024*1024);x.allocateBudget("misc",1*1024*1024);var u=class{value;state="uninitialized";initPromise;idleTimer;options;stats;constructor(e){this.options={factory:e.factory,cleanup:e.cleanup??(()=>{}),idleTimeout:e.idleTimeout??0,onError:e.onError??console.error,name:e.name??"lazy-value"},this.stats={name:this.options.name,state:"uninitialized",initCount:0,disposeCount:0,errorCount:0};}async get(){return this.resetIdleTimer(),this.state==="initialized"&&this.value!==void 0?(this.stats.lastAccessTime=new Date,this.value):this.state==="initializing"&&this.initPromise?this.initPromise:(this.state==="error"&&(this.state="uninitialized"),this.state==="disposed"&&(this.state="uninitialized"),this.initialize())}getSync(){if(this.state!=="initialized"||this.value===void 0)throw new Error(`Lazy value '${this.options.name}' not initialized`);return this.resetIdleTimer(),this.stats.lastAccessTime=new Date,this.value}isInitialized(){return this.state==="initialized"&&this.value!==void 0}getState(){return this.state}async initialize(){if(this.state==="initialized"&&this.value!==void 0)return this.value;this.state="initializing",this.stats.state="initializing";let e=Date.now();return this.initPromise=(async()=>{try{let t=await this.options.factory();return this.value=t,this.state="initialized",this.stats.state="initialized",this.stats.initCount++,this.stats.lastInitTime=new Date,this.stats.lastAccessTime=new Date,this.stats.initDurationMs=Date.now()-e,t}catch(t){throw this.state="error",this.stats.state="error",this.stats.errorCount++,this.options.onError(t),t}finally{this.initPromise=void 0;}})(),this.initPromise}async dispose(){if(this.clearIdleTimer(),this.value!==void 0)try{await this.options.cleanup(this.value);}catch(e){this.options.onError(e);}this.value=void 0,this.state="disposed",this.stats.state="disposed",this.stats.disposeCount++;}getStats(){return {...this.stats}}resetIdleTimer(){this.clearIdleTimer(),this.options.idleTimeout>0&&(this.idleTimer=setTimeout(()=>{this.dispose().catch(this.options.onError);},this.options.idleTimeout));}clearIdleTimer(){this.idleTimer&&(clearTimeout(this.idleTimer),this.idleTimer=void 0);}},w=new Map;function oe(o,e){let t=w.get(o);return t||(t=new u({...e,name:e.name??o}),w.set(o,t)),t}async function ie(o){let e=w.get(o);e&&(await e.dispose(),w.delete(o));}async function N(){let o=[];for(let e of w.values())o.push(e.dispose());await Promise.all(o),w.clear();}var B=class{lazy;constructor(e,t){this.lazy=new u({...t,factory:e});}async get(){return this.lazy.get()}isLoaded(){return this.lazy.isInitialized()}async dispose(){return this.lazy.dispose()}},j=class{lazy;constructor(e,t){this.lazy=new u({...t,factory:async()=>{let r=await e();return r.initialize&&await r.initialize(),r}});}async get(){return this.lazy.get()}isInitialized(){return this.lazy.isInitialized()}async dispose(){return this.lazy.dispose()}getStats(){return this.lazy.getStats()}},G=class{lazy;cached=null;constructor(e,t){this.lazy=new u({factory:async()=>{if(this.cached)return this.cached;let r=await e();return this.cached=r,r},cleanup:()=>{this.cached=null;},name:t?.name??"lazy-wasm",idleTimeout:t?.idleTimeout??0,onError:t?.onError??console.error});}async get(){return this.lazy.get()}isLoaded(){return this.lazy.isInitialized()}clearCache(){this.cached=null;}getStats(){return this.lazy.getStats()}},V=class{lazy;watchCount=0;constructor(e,t){this.lazy=new u({...t,factory:e});}async watch(){return this.watchCount++,this.lazy.get()}async unwatch(){this.watchCount--,this.watchCount<=0&&(this.watchCount=0,await this.lazy.dispose());}getWatchCount(){return this.watchCount}isActive(){return this.lazy.isInitialized()&&this.watchCount>0}async dispose(){return this.watchCount=0,this.lazy.dispose()}};function se(o,e){let t=new u({...e,factory:o});return {get:()=>t.get(),isInitialized:()=>t.isInitialized()}}var a={initialized:false,monitor:null,config:{}};function Me(o){if(a.initialized){console.warn("[memory] Memory system already initialized");return}a.config={memoryLimit:o?.memoryLimit??10*1024*1024,autoCleanup:o?.autoCleanup??true,preWarmPools:o?.preWarmPools??false,pollInterval:o?.pollInterval??5e3},a.monitor=new h({memoryLimit:a.config.memoryLimit,autoCleanup:a.config.autoCleanup,pollInterval:a.config.pollInterval}),a.monitor.start(),a.config.preWarmPools&&R(),a.initialized=true,`${(a.config.memoryLimit/(1024*1024)).toFixed(2)}`,a.config.autoCleanup,a.config.preWarmPools;}function ae(){return a.monitor?.getMemoryUsage()??null}function Ce(){return {system:ae(),pools:C(),poolEfficiency:D(),arenas:m.getStats(),config:a.config}}function Le(){L(),m.resetAll(),N().catch(console.error),a.monitor?.triggerCleanup();}async function xe(){a.initialized&&(a.monitor?.stop(),a.monitor=null,L(),m.disposeAll(),await N(),a.initialized=false);}function we(){return a.initialized}function ze(){return a.monitor}function Ue(){return f.acquire()}function Re(o){f.release(o);}function Be(){return T.acquire()}function je(o){T.release(o);}function Ge(){return g.acquire()}function Ve(o){g.release(o);}function We(){return A.acquire()}function He(o){A.release(o);}function qe(){return v.acquire()}function $e(o){v.release(o);}export{ae as $,L as A,R as B,D as C,b as D,K as E,Y as F,X as G,_ as H,m as I,h as J,J as K,Q as L,ee as M,te as N,re as O,O as P,x as Q,u as R,oe as S,ie as T,N as U,B as V,j as W,G as X,V as Y,se as Z,Me as _,s as a,Ce as aa,c as b,Le as ba,F as c,xe as ca,k as d,we as da,U as e,ze as ea,W as f,Ue as fa,H as g,Re as ga,ne as h,Be as ha,le as i,je as ia,ce as j,Ge as ja,de as k,Ve as ka,ue as l,We as la,me as m,He as ma,n,qe as na,P as o,$e as oa,E as p,S as q,I as r,M as s,f as t,g as u,T as v,A as w,v as x,C as y,$ as z};//# sourceMappingURL=chunk-TGFYZY3C.js.map
|
|
11
|
+
//# sourceMappingURL=chunk-TGFYZY3C.js.map
|