@walkeros/mcp 4.8.1 → 4.8.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-SUHJP3BB.js → chunk-4K6NNGYC.js} +98 -132
- package/dist/chunk-4K6NNGYC.js.map +1 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/specs.js +1 -1
- package/dist/stdio.js +100 -134
- package/dist/stdio.js.map +1 -1
- package/package.json +4 -4
- package/dist/chunk-SUHJP3BB.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -16,7 +16,7 @@ import {
|
|
|
16
16
|
unavailableOperation,
|
|
17
17
|
wrapListedRecord,
|
|
18
18
|
wrapUserData
|
|
19
|
-
} from "./chunk-
|
|
19
|
+
} from "./chunk-4K6NNGYC.js";
|
|
20
20
|
|
|
21
21
|
// src/server.ts
|
|
22
22
|
import {
|
|
@@ -567,7 +567,7 @@ Every component in a flow is a **step**: sources capture events, transformers pr
|
|
|
567
567
|
- **Consent** gates destinations (\`config.consent\`) and individual fields (a value's \`consent\`). A mapping rule's \`consent\` is not enforced yet. Privacy-first by design.
|
|
568
568
|
- **Routing** uses one grammar in every chain field (\`source.before\`, \`source.next\`, \`transformer.before\`, \`transformer.next\`, \`collector.next\`, \`destination.before\`, \`destination.next\`). A route is a string ID, a sequence (\`["a", "b"]\`), or a RouteConfig: \`{ match?, next }\`, \`{ match?, one: [...] }\` (first match wins), \`{ match?, many: [...] }\` (every match becomes its own copy of the event with its own id and finishes the rest of the path on its own, never merged), or \`{ match?, stop: true }\` (ends that copy). In a sequence, a member's own \`next\` runs right after it, then the sequence continues. \`match\` reads \`{ ingest, event }\` and each route is evaluated when the event reaches it. A \`stop\` in \`collector.next\` drops the event for every destination; per-destination filtering belongs in \`destination.before\`. An array of only route configs is an implicit \`one\`. The optional \`match\` field is omitted to mean always-match (no wildcard literal).
|
|
569
569
|
- **Pass-through steps** are transformer entries with no \`code\` and no \`package\`. The runtime synthesizes the push for them automatically. Three flavors share this shape: a \`before\` / \`next\`-only step (named hop reusable across destinations), a \`cache\`-only step (dedup, rate-limit), and a \`mapping\`-only step (declarative event-to-event transform). A pass-through must declare at least one of \`before\`, \`next\`, \`cache\`, or \`mapping\`.
|
|
570
|
-
- **Mapping at the transformer position** uses the same \`Mapping.Config\` shape as destinations, but the semantic is event-to-event: only config-level \`policy\` and a rule's \`condition\`, \`policy\`, \`name\` (rename) and \`ignore\` (drop from chain) apply. Everything that shapes a vendor payload or gates a destination is a no-op there: config-level \`consent\`, \`include\`, \`data\`, and a rule's \`consent\`, \`include\`, \`remove\`, \`batch\`, \`settings\`, \`extend\`, \`data\`, \`silent
|
|
570
|
+
- **Mapping at the transformer position** uses the same \`Mapping.Config\` shape as destinations, but the semantic is event-to-event: only config-level \`policy\` and a rule's \`condition\`, \`policy\`, \`name\` (rename) and \`ignore\` (drop from chain) apply. Everything that shapes a vendor payload or gates a destination is a no-op there: config-level \`consent\`, \`include\`, \`data\`, and a rule's \`consent\`, \`include\`, \`remove\`, \`batch\`, \`settings\`, \`extend\`, \`data\`, \`silent\`. At a source only config-level \`consent\` and \`policy\` and a rule's \`condition\`, \`policy\`, \`name\` and \`ignore\` apply (edit the event there with \`policy\`); at a destination a rule's \`extend\` applies only inside a package's own \`settings.mapping\`. Validation and the bundle reject these keys (\`MAPPING_NO_OP\`). A \`config.mapping\` wins over a step-level \`mapping\`.
|
|
571
571
|
- **Closed-schema rule on transformer entries:** known keys only. Operative keys are \`code\`, \`package\`, \`before\`, \`next\`, \`cache\`, \`mapping\`. Combined with structural keys (\`config\`, \`env\`, \`validate\`, \`disabled\`, \`id\`, etc.). Unknown top-level keys on a transformer step are errors (catches typos like \`dedup: {}\` instead of nested under \`cache\`). \`code\` + \`package\` together is a conflict.
|
|
572
572
|
- **Cache** memoizes step output on a configured store. Set \`cache.stop: true\` to short-circuit the chain on HIT (sources default to stop-on-HIT); in a source chain or \`collector.next\` that halts the event for all destinations. Set \`cache.namespace\` to prefix keys; omit it to write keys directly. \`CacheRule.match\` is optional, omit for always-match.
|
|
573
573
|
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/server.ts","../src/tools/bundle.ts","../src/tools/simulate.ts","../src/tools/simulate-description.ts","../src/tools/egress.ts","../src/tools/push.ts","../src/tool-handlers.ts","../src/instructions.ts","../src/telemetry.ts","../src/runtime/local.ts","../src/runtime/bundle-cache.ts"],"sourcesContent":["import {\n McpServer,\n ResourceTemplate,\n} from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport { isObject } from '@walkeros/core';\n\nimport { createToolHandlers } from './tool-handlers.js';\nimport type { ToolSpec } from './tool-spec.js';\nimport { KNOWLEDGE_RESOURCES, PROMPTS } from './specs.js';\nimport type { PromptSpec, ResourceSpec } from './knowledge-spec.js';\nimport { SERVER_INSTRUCTIONS } from './instructions.js';\nimport { createMcpEmitter, type McpEmitter } from './telemetry.js';\nimport type { FlowRuntime } from './runtime/types.js';\n\nexport interface Logger {\n debug?(message: string, meta?: Record<string, unknown>): void;\n info?(message: string, meta?: Record<string, unknown>): void;\n warn?(message: string, meta?: Record<string, unknown>): void;\n error?(message: string, meta?: Record<string, unknown>): void;\n}\n\nexport interface CreateServerOptions {\n /** Required: the runtime decides what the process may read and run. */\n runtime: FlowRuntime;\n version?: string;\n logger?: Logger;\n}\n\n/**\n * Module-scoped singleton emitter, populated once the MCP `initialize`\n * handshake completes and clientInfo is known. The stdio entrypoint reads\n * this to emit process-level `error throw` events from uncaughtException /\n * unhandledRejection hooks, where the Server instance isn't in scope.\n */\nlet currentEmitter: McpEmitter | undefined;\n\nexport function getMcpEmitterSingleton(): McpEmitter | undefined {\n return currentEmitter;\n}\n\n/**\n * Internal: reset for tests that want a clean slate between cases.\n * Not exported from the package.\n */\nexport function __resetMcpEmitterSingletonForTesting(): void {\n currentEmitter = undefined;\n}\n\n/** An MCP tool answers a failure as a result flagged `isError`. */\nfunction isToolError(result: unknown): boolean {\n return isObject(result) && result.isError === true;\n}\n\n/**\n * Run one tool call and record its outcome: an answer flagged `isError` and a\n * throw are failures. Telemetry never reaches the caller: an emit that fails\n * is dropped, a throw is re-thrown unchanged. Each handler is wrapped when it\n * is registered, never by patching the SDK's registry. The emitter is looked\n * up at call time, so wrapping happens before the emitter exists.\n */\nexport async function trackInvoke<T>(\n tool: string,\n run: () => Promise<T>,\n emitter: () => McpEmitter | undefined = getMcpEmitterSingleton,\n): Promise<T> {\n const start = Date.now();\n const record = (outcome: 'success' | 'error') => {\n emitter()\n ?.emitInvoke(tool, outcome, Date.now() - start)\n .catch(() => {});\n };\n try {\n const result = await run();\n record(isToolError(result) ? 'error' : 'success');\n return result;\n } catch (error) {\n record('error');\n throw error;\n }\n}\n\n/** The one registration path: the spec's own metadata and handler. */\nfunction registerToolSpec(server: McpServer, spec: ToolSpec): void {\n server.registerTool(\n spec.name,\n {\n title: spec.title,\n description: spec.description,\n inputSchema: spec.inputSchema,\n ...(spec.outputSchema ? { outputSchema: spec.outputSchema } : {}),\n annotations: spec.annotations,\n },\n (args) => trackInvoke(spec.name, () => spec.handler(args)),\n );\n}\n\n/** A knowledge resource, static or templated, as the spec describes it. */\nexport function registerResourceSpec(\n server: McpServer,\n spec: ResourceSpec,\n): void {\n if (spec.kind === 'static') {\n server.registerResource(\n spec.name,\n spec.uri,\n { description: spec.description, mimeType: spec.mimeType },\n async (uri) => ({\n contents: [{ uri: uri.toString(), ...(await spec.read()) }],\n }),\n );\n return;\n }\n server.registerResource(\n spec.name,\n new ResourceTemplate(spec.uriTemplate, {\n list: async () => ({ resources: await spec.list() }),\n }),\n {\n title: spec.title,\n description: spec.description,\n mimeType: spec.mimeType,\n },\n async (uri, variables) => ({\n contents: [{ uri: uri.toString(), ...(await spec.read(variables)) }],\n }),\n );\n}\n\n/** A prompt with its description, arguments and handler. */\nexport function registerPromptSpec(server: McpServer, spec: PromptSpec): void {\n server.registerPrompt(\n spec.name,\n { description: spec.description, argsSchema: spec.argsSchema },\n (args) => spec.handler(args),\n );\n}\n\nexport function createWalkerOSMcpServer(opts: CreateServerOptions): McpServer {\n const packageVersion = opts.version ?? '0.0.0';\n const server = new McpServer(\n {\n name: 'walkeros-flow',\n version: packageVersion,\n },\n { instructions: SERVER_INSTRUCTIONS },\n );\n\n for (const spec of Object.values(createToolHandlers(opts.runtime)))\n registerToolSpec(server, spec);\n\n for (const spec of KNOWLEDGE_RESOURCES) registerResourceSpec(server, spec);\n for (const spec of PROMPTS) registerPromptSpec(server, spec);\n\n // MCP SDK fires `oninitialized` after the `initialized` notification, which\n // follows a successful `initialize` request. At that point `getClientVersion`\n // returns the negotiated client identity. We create the emitter here and\n // emit `mcp start`, so consent, debug, and endpoint resolution happen lazily\n // at the moment a real client connects.\n const priorOnInitialized = server.server.oninitialized;\n server.server.oninitialized = () => {\n try {\n priorOnInitialized?.();\n } catch {\n // existing handler must not prevent telemetry setup\n }\n const clientInfo = server.server.getClientVersion();\n void createMcpEmitter({\n clientInfo,\n packageVersion,\n })\n .then(async (emitter) => {\n currentEmitter = emitter;\n await emitter.emitStart();\n })\n .catch(() => {\n // telemetry must never break the server; swallow setup/emit errors.\n });\n };\n\n return server;\n}\n","import { schemas } from '@walkeros/cli/dev';\nimport { mcpResult, mcpError } from '@walkeros/core';\nimport { BundleOutputShape } from '../schemas/output.js';\n\nimport type { ToolSpec } from '../tool-spec.js';\nimport { parseToolInput } from './parse-input.js';\nimport {\n refusalHint,\n unavailableOperation,\n type FlowRuntime,\n} from '../runtime/types.js';\n\nconst TITLE = 'Bundle Flow';\nconst DESCRIPTION =\n 'Bundle a walkerOS flow configuration into deployable JavaScript. ' +\n 'Resolves all destinations, sources, and transformers, then outputs ' +\n 'a tree-shaken production bundle. Returns bundle statistics.';\n\nconst inputSchema = {\n ...schemas.BundleInputShape,\n};\n\nconst annotations = {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n} as const;\n\nexport function createFlowBundleToolSpec(runtime: FlowRuntime): ToolSpec {\n return {\n name: 'flow_bundle',\n title: TITLE,\n description: DESCRIPTION,\n inputSchema,\n outputSchema: BundleOutputShape,\n annotations,\n handler: (input) => flowBundleHandlerBody(runtime, input),\n };\n}\n\nasync function flowBundleHandlerBody(runtime: FlowRuntime, input: unknown) {\n const parsed = parseToolInput(inputSchema, input);\n if (!parsed.ok) return parsed.error;\n const { configPath, flow, stats, output } = parsed.data;\n // Bundling compiles the config and resolves every package it names. A\n // runtime that must not do that in its process provides no `bundle`.\n if (!runtime.bundle) {\n const refusal = unavailableOperation('bundle');\n return mcpError(refusal, refusal.hint);\n }\n try {\n const result = await runtime.bundle(configPath, {\n flowName: flow,\n stats: stats ?? true,\n output,\n });\n\n if (!result) {\n return mcpResult(\n { success: false, message: 'Bundle produced no output' },\n {\n warnings: [\n 'The build returned no result. The flow may be empty or misconfigured.',\n ],\n next: ['Run flow_validate to check your configuration'],\n },\n );\n }\n\n return mcpResult(\n { success: true, ...result },\n {\n next: [\n 'Use flow_simulate to test',\n 'Use runneros or the walkerOS app to run the bundle',\n ],\n },\n );\n } catch (error) {\n return mcpError(\n error,\n refusalHint(error, 'Run flow_validate for detailed error messages'),\n );\n }\n}\n","import { z } from 'zod';\nimport { schemas } from '@walkeros/cli/dev';\nimport { filterValues, mcpResult, mcpError } from '@walkeros/core';\nimport type { Flow, Ingest, Simulation, WalkerOS } from '@walkeros/core';\nimport { SimulateOutputShape } from '../schemas/output.js';\nimport { FLOW_SIMULATE_DESCRIPTION } from './simulate-description.js';\n\nimport type { ToolSpec } from '../tool-spec.js';\nimport { parseToolInput } from './parse-input.js';\nimport { readRun, scrubbed, scrubbedError } from './egress.js';\nimport {\n refusalHint,\n unavailableOperation,\n type FlowRuntime,\n type SimulateStepType,\n} from '../runtime/types.js';\n\ninterface DestinationSummary {\n received: boolean;\n calls: number;\n payload?: unknown;\n}\n\nconst STEP_TYPES: readonly SimulateStepType[] = [\n 'source',\n 'transformer',\n 'collector',\n 'destination',\n];\n\nfunction isStepType(value: string): value is SimulateStepType {\n return STEP_TYPES.some((t) => t === value);\n}\n\nconst TITLE = 'Simulate Flow';\nconst COMMANDS: readonly [Flow.StepCommand, ...Flow.StepCommand[]] = [\n 'config',\n 'consent',\n 'user',\n 'run',\n];\n\nconst inputSchema = {\n configPath: schemas.SimulateInputShape.configPath,\n event: z\n .union([z.record(z.string(), z.unknown()), z.string()])\n .optional()\n .describe(\n \"For destinations: { name, data, consent? }; the event's consent counts \" +\n \"toward the destination's consent requirement, on top of state.consent. \" +\n \"With command: the command's data, e.g. { marketing: true } for consent. \" +\n 'For sources: { content, trigger? } where content is the walkerOS event ' +\n \"{ name, data }. A web source's page URL goes in trigger.options.url \" +\n '(default http://localhost). ' +\n 'Can also be a JSON string or file path.',\n ),\n flow: schemas.SimulateInputShape.flow,\n platform: schemas.SimulateInputShape.platform,\n // Override the (optional) CLI `step` shape: the simulate handler hard-requires\n // a target step (no all-steps mode), so the registered schema must be honest.\n step: z\n .string()\n .describe(\n 'Required. Target step as \"type.name\", e.g. \"source.demo\", \"collector.default\", \"destination.gtag\", \"transformer.router\". ' +\n 'A collector step runs enrichment and then collector.next, returning every event the destinations would receive (none after a stop).',\n ),\n verbose: z\n .boolean()\n .optional()\n .describe('Include full payload per destination (default: false)'),\n ingest: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'Pipeline context a step reads via ctx.ingest, e.g. { url } for a ' +\n 'request decoder or { ip, userAgent } for a conversion API. Used for ' +\n 'transformer, collector and destination steps (their before chains ' +\n 'included); _meta is always set by the runtime.',\n ),\n state: z\n .object({\n consent: z.record(z.string(), z.boolean()).optional(),\n user: z.record(z.string(), z.unknown()).optional(),\n globals: z.record(z.string(), z.unknown()).optional(),\n timing: z.number().optional(),\n })\n .optional()\n .describe(\n 'Collector state the step starts from. consent: every step (starts a ' +\n 'destination that requires consent and feeds its consent check; for a ' +\n 'source, the consent a consent-gated source waits for). ' +\n 'user/globals/timing: collector steps, seeded before enrichment runs.',\n ),\n command: z\n .enum(COMMANDS)\n .optional()\n .describe(\n 'Destination steps only: run this collector command with event as its ' +\n 'data instead of pushing it, as a step example with command does.',\n ),\n};\n\nconst annotations = {\n // Simulation downloads the packages a config names and runs caller-controlled\n // flow code in process. Destinations are mocked, but that code is not, so the\n // hints stay conservative: side effects possible, repeat calls not assumed\n // safe, external systems reachable.\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n} as const;\n\nexport function createFlowSimulateToolSpec(runtime: FlowRuntime): ToolSpec {\n return {\n name: 'flow_simulate',\n title: TITLE,\n description: FLOW_SIMULATE_DESCRIPTION,\n inputSchema,\n outputSchema: SimulateOutputShape,\n annotations,\n handler: (input) => flowSimulateHandlerBody(runtime, input),\n };\n}\n\n/** Plain values kept as walkerOS properties; values no property can hold dropped. */\nfunction toProperties(\n value: Record<string, unknown> | undefined,\n): WalkerOS.Properties | undefined {\n if (!value) return undefined;\n const properties: WalkerOS.Properties = {};\n for (const [key, entry] of Object.entries(value)) {\n const property = filterValues(entry);\n if (property !== undefined) properties[key] = property;\n }\n return properties;\n}\n\nasync function flowSimulateHandlerBody(runtime: FlowRuntime, input: unknown) {\n const parsed = parseToolInput(inputSchema, input);\n if (!parsed.ok) return parsed.error;\n const {\n configPath,\n event,\n flow,\n platform,\n step,\n verbose,\n ingest,\n state,\n command,\n } = parsed.data;\n // Simulation compiles the config and imports the bundle, running caller\n // controlled flow code. A runtime that must not do that in its process\n // provides no `simulate`, whatever the input looks like.\n if (!runtime.simulate) {\n const refusal = unavailableOperation('simulate');\n return mcpError(refusal, refusal.hint);\n }\n let known: string[] = [];\n try {\n if (!event) {\n throw new Error(\n 'event is required. For sources provide { content, trigger? }, for destinations provide { name, data }.',\n );\n }\n\n if (!step) {\n throw new Error(\n 'step is required. Specify a target like \"source.browser\", \"destination.gtag\", or \"transformer.demo\".',\n );\n }\n\n // Resolve string event input (JSON string)\n let resolvedEvent: unknown = event;\n if (typeof event === 'string') {\n try {\n resolvedEvent = JSON.parse(event);\n } catch {\n throw new Error(\n 'Event string must be valid JSON. Got: ' + event.substring(0, 50),\n );\n }\n }\n\n // Parse step into type and id\n const dotIndex = step.indexOf('.');\n if (dotIndex === -1) {\n throw new Error(\n `Invalid step format \"${step}\". Use \"type.name\" (e.g. \"source.browser\", \"destination.gtag\").`,\n );\n }\n const stepType = step.substring(0, dotIndex);\n const stepId = step.substring(dotIndex + 1);\n\n if (!isStepType(stepType)) {\n throw new Error(\n `Unknown step type \"${stepType}\". Use \"source\", \"collector\", \"transformer\", or \"destination\".`,\n );\n }\n\n if (command !== undefined && stepType !== 'destination') {\n throw new Error('command applies to destination steps only.');\n }\n\n // Read once: the simulation runs on exactly the config whose secrets\n // mask the result.\n const run = await readRun(runtime, configPath);\n known = run.knownSecrets;\n\n const result: Simulation.Result = await runtime.simulate(configPath, {\n stepType,\n stepId,\n event: resolvedEvent,\n flow,\n ingest,\n state: state && {\n consent: state.consent,\n user: toProperties(state.user),\n globals: toProperties(state.globals),\n timing: state.timing,\n },\n command,\n config: run.config,\n });\n\n const success = !result.error;\n const errorMessage = result.error?.message;\n\n // Source simulation: captured events are result.events, the source's\n // own walker commands its `elb` calls. Mock-env calls stay verbose-only.\n if (result.step === 'source') {\n const eventCount = result.events.length;\n const commandCount = result.calls.filter(\n (call) => call.fn === 'elb',\n ).length;\n const summary =\n `Source captured ${eventCount} event${eventCount !== 1 ? 's' : ''}` +\n ` and ${commandCount} command${commandCount !== 1 ? 's' : ''}`;\n const shownCalls = verbose\n ? result.calls\n : result.calls.filter((call) => call.fn === 'elb');\n\n return mcpResult(\n scrubbed(\n {\n success,\n error: errorMessage,\n summary,\n capturedEvents: result.events,\n ...(shownCalls.length > 0 ? { calls: shownCalls } : {}),\n duration: result.duration,\n },\n known,\n ),\n {\n next:\n eventCount + commandCount > 0\n ? [\n 'Use flow_simulate with a destination step to test downstream processing',\n ]\n : [\n 'Check source package examples with package_get, verify trigger type matches',\n ],\n },\n );\n }\n\n // Transformer simulation: surface the transformed events\n if (result.step === 'transformer') {\n return mcpResult(\n scrubbed(\n {\n success,\n error: errorMessage,\n summary: `Transformer processed event`,\n capturedEvents: result.events,\n duration: result.duration,\n },\n known,\n ),\n {\n next: ['Use flow_bundle to build for production'],\n },\n );\n }\n\n // Collector simulation: surface the enriched event\n if (result.step === 'collector') {\n return mcpResult(\n scrubbed(\n {\n success,\n error: errorMessage,\n summary: `Collector enriched event`,\n capturedEvents: result.events,\n duration: result.duration,\n },\n known,\n ),\n {\n next: ['Use flow_simulate with a destination step to test delivery'],\n },\n );\n }\n\n // Destination simulation: count intercepted env calls, key by step name\n const destinations: Record<string, DestinationSummary> = {};\n const callCount = result.calls.length;\n const destSummary: DestinationSummary = {\n received: callCount > 0,\n calls: callCount,\n };\n if (verbose && callCount > 0) {\n destSummary.payload = result.calls;\n }\n destinations[result.name] = destSummary;\n\n const destCount = Object.keys(destinations).length;\n const receivedCount = Object.values(destinations).filter(\n (d) => d.received,\n ).length;\n\n const warnings: string[] = [];\n if (receivedCount === 0 && success) warnings.push(notReceived(result));\n\n const resultObj = {\n success,\n error: errorMessage,\n summary: `${receivedCount}/${destCount} destinations received the event`,\n destinations,\n ...(result.skipped ? { skipped: result.skipped } : {}),\n duration: result.duration,\n };\n\n return mcpResult(scrubbed(resultObj, known), {\n next: ['Use flow_bundle to build for production'],\n ...(warnings.length > 0 ? { warnings } : {}),\n });\n } catch (error) {\n const hint = 'Run flow_validate for detailed error messages';\n return scrubbedError(mcpError(error, refusalHint(error, hint)), known);\n }\n}\n\nfunction keysOf(consent: WalkerOS.Consent | undefined): string {\n const keys = Object.entries(consent ?? {})\n .filter(([, granted]) => granted)\n .map(([key]) => key);\n return keys.length > 0 ? keys.join(', ') : 'none';\n}\n\n/** Why a destination received nothing, from the result's own `skipped`. */\nfunction notReceived(result: Simulation.Result): string {\n const { skipped } = result;\n if (skipped?.reason === 'pending') {\n const require = skipped.require ?? [];\n const waits = require.length ? require.join(', ') : 'its require';\n const advice = require.includes('consent')\n ? 'pass state.consent (e.g. { functional: true }) to start it.'\n : `it starts once the flow provides ${waits}; a simulation cannot seed that.`;\n return `Destination waits for ${waits} (require) and never started: ${advice}`;\n }\n if (skipped?.reason === 'consent') {\n return (\n `Consent skip: requires ${keysOf(skipped.required)}; granted ${keysOf(skipped.granted)}. ` +\n \"Grant it in state.consent or in the event's consent.\"\n );\n }\n return (\n 'Destination made no calls. Common causes: ' +\n '(1) mapping rules do not match the event name or ignore it, ' +\n '(2) policy redacted required fields, ' +\n '(3) a before chain stopped the event.'\n );\n}\n","/**\n * The flow_simulate tool description, kept apart from the tool module so that\n * module stays the only place that imports node-only code.\n */\nexport const FLOW_SIMULATE_DESCRIPTION =\n 'Simulate events through a walkerOS flow without making real API calls. ' +\n 'For destinations: event is a walkerOS event { name: \"entity action\", data: {...} }. ' +\n 'For sources: event is { content, trigger?: { type?, options? } }, where content is the ' +\n 'walkerOS event { name: \"entity action\", data: {...} }. Only the simulated source starts. ' +\n 'step (required) targets the step to simulate, e.g. \"destination.gtag\". ' +\n 'Use flow_examples to discover available test data. ' +\n 'A destination simulation starts only its target destination. ' +\n \"A source's own walker commands (e.g. a CMP's walker consent) are returned as elb calls. \" +\n 'Consent: state.consent is the collector consent the step starts from ' +\n '(any step; a consent-gated source such as the session source waits for it). A destination with ' +\n 'require: [\"consent\"] waits until consent is present, so pass state.consent to start it; ' +\n 'a destination with consent: { marketing: true } receives an event only when that ' +\n \"consent is granted in state.consent or in the event's own consent. \" +\n 'When a destination sends nothing, the result says why (waiting for its require, or a consent skip). ' +\n 'command runs a step example with command (e.g. \"consent\") on a destination: ' +\n \"event is the command's data, state.consent still applies first. \" +\n 'Mapping transforms event names and data at the destination level. ' +\n 'Policy redacts or injects fields before mapping runs.';\n","import type { PushResult } from '@walkeros/cli';\nimport { isObject, mcpError, mcpResult } from '@walkeros/core';\nimport { scrubJson, scrubSecrets } from '@walkeros/core/node';\nimport type { FlowRuntime, LoadedRun } from '../runtime/types.js';\n\n/**\n * Simulate and push results carry recorded vendor calls, network requests and\n * vendor responses whose values can hold credentials. They egress like a log\n * line: `scrubJson` (masking the values of the secrets the flow references,\n * `known`, and credential patterns), then parse back into the structured\n * result.\n */\nexport function scrubbed(\n result: Record<string, unknown>,\n known: readonly string[],\n): Record<string, unknown> {\n const parsed = parseObject(scrubJson(result, { known }));\n if (!parsed) throw new Error('Result could not be redacted as JSON.');\n return parsed;\n}\n\n/** An error response as built by `mcpError`; a stub may lack the structured copy. */\ntype ErrorResponse = Omit<ReturnType<typeof mcpError>, 'structuredContent'> & {\n structuredContent?: Record<string, unknown>;\n};\n\n/**\n * The error response egresses the same way: its structured copy is scrubbed,\n * and the text is that copy serialized (as `mcpError` builds it), so it stays\n * valid JSON. Without a structured copy that scrubs, each text part is\n * scrubbed as a line instead, so the error message is never lost.\n */\nexport function scrubbedError(\n response: ErrorResponse,\n known: readonly string[],\n): ReturnType<typeof mcpError> {\n let structuredContent: Record<string, unknown> | undefined;\n try {\n if (response.structuredContent)\n structuredContent = scrubbed(response.structuredContent, known);\n } catch {\n structuredContent = undefined;\n }\n if (structuredContent) {\n return {\n ...response,\n content: [{ type: 'text', text: JSON.stringify(structuredContent) }],\n structuredContent,\n };\n }\n return {\n ...response,\n content: response.content.map((part) => ({\n ...part,\n text: scrubSecrets(part.text, { known }),\n })),\n structuredContent: { error: 'The error could not be redacted.' },\n };\n}\n\n/**\n * A push result as it egresses: scrubbed and parsed back. `success` and\n * `duration` come from the CLI, never from a vendor, and stay as they are so\n * the output schema always holds. A push already happened, so this never\n * throws: if the scrubbed text does not parse, the text alone carries the\n * result and the structured copy keeps the scalars.\n */\nexport function scrubbedPushResult(\n result: PushResult,\n known: readonly string[],\n): ReturnType<typeof mcpResult> {\n const text = scrubJson(result, { known, space: 2 });\n const parsed = parseObject(text);\n if (parsed)\n return mcpResult({\n ...parsed,\n success: result.success,\n duration: result.duration,\n });\n return {\n content: [{ type: 'text', text }],\n structuredContent: { success: result.success, duration: result.duration },\n };\n}\n\nfunction parseObject(text: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(text);\n return isObject(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The run input read once: `loadRun`, else, on a runtime without it, the\n * values its `knownSecrets` returns. A failed read rejects, so the caller\n * stops instead of egressing with pattern masking only.\n */\nexport async function readRun(\n runtime: FlowRuntime,\n input: string,\n): Promise<LoadedRun> {\n if (runtime.loadRun) return runtime.loadRun(input);\n return {\n knownSecrets: runtime.knownSecrets ? await runtime.knownSecrets(input) : [],\n };\n}\n","import { z } from 'zod';\nimport type { PushResult } from '@walkeros/cli';\nimport { schemas } from '@walkeros/cli/dev';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { mcpError } from '@walkeros/core';\nimport { PushOutputShape } from '../schemas/output.js';\n\nimport type { ToolSpec } from '../tool-spec.js';\nimport { parseToolInput } from './parse-input.js';\nimport { readRun, scrubbedError, scrubbedPushResult } from './egress.js';\nimport {\n refusalHint,\n unavailableOperation,\n type FlowRuntime,\n} from '../runtime/types.js';\n\nconst TITLE = 'Push Events';\nconst DESCRIPTION =\n 'Push a real event through a walkerOS flow to actual destinations. ' +\n 'Makes real API calls to real endpoints. ' +\n 'Best suited for server-side flows; web flows should use flow_simulate for testing.';\n\nconst inputSchema = {\n configPath: schemas.PushInputShape.configPath,\n event: z\n .record(z.string(), z.unknown())\n .describe(\n 'Event object, e.g. { name: \"page view\", data: { title: \"Home\" } }',\n ),\n flow: schemas.PushInputShape.flow,\n platform: schemas.PushInputShape.platform,\n};\n\nconst annotations = {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n} as const;\n\nexport function createFlowPushToolSpec(runtime: FlowRuntime): ToolSpec {\n return {\n name: 'flow_push',\n title: TITLE,\n description: DESCRIPTION,\n inputSchema,\n outputSchema: PushOutputShape,\n annotations,\n handler: (input) => flowPushHandlerBody(runtime, input),\n };\n}\n\nasync function flowPushHandlerBody(\n runtime: FlowRuntime,\n input: unknown,\n): Promise<CallToolResult> {\n const parsed = parseToolInput(inputSchema, input);\n if (!parsed.ok) return parsed.error;\n const { configPath, event, flow, platform } = parsed.data;\n // Push compiles the config, imports it, and makes real outbound calls. A\n // runtime that must not do that in its process provides no `push`.\n if (!runtime.push) {\n const refusal = unavailableOperation('push');\n return mcpError(refusal, refusal.hint);\n }\n // Push results can carry vendor requests and responses: they egress with\n // the flow's secret values and credential patterns masked. The config is\n // read once, so the push runs on exactly the config whose secrets mask the\n // result; a config that cannot be read stops the push.\n let known: string[] = [];\n try {\n const run = await readRun(runtime, configPath);\n known = run.knownSecrets;\n const result: PushResult = await runtime.push(configPath, event, {\n flow,\n platform,\n config: run.config,\n });\n\n if (!result.success) {\n return scrubbedError(\n mcpError(\n new Error(result.error || 'Push failed'),\n 'Check destination configuration and connectivity.',\n ),\n known,\n );\n }\n\n return scrubbedPushResult(result, known);\n } catch (error) {\n return scrubbedError(\n mcpError(\n error,\n refusalHint(\n error,\n 'Check configPath and event format. For web flows, use flow_simulate.',\n ),\n ),\n known,\n );\n }\n}\n","import type { FlowRuntime } from './runtime/types.js';\nimport type { ToolSpec } from './tool-spec.js';\nimport { createLocalToolSpecs, type LocalToolSpecs } from './specs.js';\nimport { createFlowBundleToolSpec } from './tools/bundle.js';\nimport { createFlowSimulateToolSpec } from './tools/simulate.js';\nimport { createFlowPushToolSpec } from './tools/push.js';\n\n/**\n * The eight tools of the local server, keyed by name, over one runtime: the\n * five shared specs plus the three that run caller code. A type alias, not an\n * interface, so it is assignable to Record<string, ToolSpec>.\n */\nexport type LocalServerToolSpecs = LocalToolSpecs & {\n flow_bundle: ToolSpec;\n flow_simulate: ToolSpec;\n flow_push: ToolSpec;\n};\n\nexport function createToolHandlers(runtime: FlowRuntime): LocalServerToolSpecs {\n return {\n ...createLocalToolSpecs(runtime),\n flow_bundle: createFlowBundleToolSpec(runtime),\n flow_simulate: createFlowSimulateToolSpec(runtime),\n flow_push: createFlowPushToolSpec(runtime),\n };\n}\n","export const SERVER_INSTRUCTIONS = `walkerOS is an open-source, privacy-first event data collection platform. Define event pipelines as code using JSON flow configurations.\n\n## Rules\n\n- **Never guess package names.** Always use \\`package_search\\` first to find exact names, then \\`package_get\\` for details.\n- **Never construct flow configs from memory.** Read \\`walkeros://reference/flow-schema\\` and use \\`package_get\\` for package-specific schemas.\n- **Always validate.** Run \\`flow_validate\\` after every config change. If validation fails, fix and re-validate. By default it checks every flow and step, package settings included; a valid result can still list \\`details.skipped\\` checks, so read them before trusting it (\\`strict: true\\` turns warnings and skips into failures: \\`valid\\` is false).\n- **Simulate before you build.** Use \\`flow_simulate\\` to test with mocked API calls before \\`flow_bundle\\` or \\`flow_push\\`.\n\n## Two walkerOS MCP servers\n\nThis server runs on your machine and works on flow files. Its tools read a file path, an http(s) URL or inline JSON, and validate, simulate, bundle and push flows here. It needs no account and no token.\n\nWhat the walkerOS app stores (projects, saved flows, deployments, previews, Observe sessions, frames, release history, secrets, feedback) is served by the hosted walkerOS MCP server at \\`https://app.walkeros.io/api/mcp\\`. Add it to your MCP client as a remote server; it signs you in with OAuth. Both servers offer \\`flow_validate\\`, \\`flow_examples\\`, \\`flow_load\\`, \\`package_search\\` and \\`package_get\\`: use the hosted one for a saved flow and this one for a file.\n\nTo simulate, bundle or push a saved flow here, ask the hosted \\`flow_manage\\` for a config link (\\`action: \"config_url\"\\`) and pass that URL as the input of \\`flow_load\\`, \\`flow_simulate\\`, \\`flow_bundle\\` or \\`flow_push\\`. A link lasts about ten minutes; an expired one fails with its HTTP status.\n\n## Workflow\n\n1. \\`flow_load({ platform: \"web\" })\\` or \\`flow_load({ source: \"./flow.json\" })\\`: create or load\n2. \\`package_search({ type: \"destination\", platform: \"web\" })\\`: discover packages\n3. \\`package_get({ package: \"...\" })\\`: read schemas, hints, examples\n4. Use the \\`add-step\\` prompt: guided step addition\n5. Use the \\`setup-mapping\\` prompt: event transformation config\n6. \\`flow_validate({ type: \"flow\", input: \"flow.json\" })\\`: verify\n7. \\`flow_simulate({ configPath: \"flow.json\", step: \"destination.<name>\", event: { ... } })\\`: test\n8. \\`flow_bundle({ configPath: \"flow.json\" })\\`: build\n\n## Architecture: Source → Collector → Destination(s)\n\nEvery component in a flow is a **step**: sources capture events, transformers process them, destinations deliver them, stores provide shared state. Steps connect via chains: \\`source.next\\` runs before the collector, \\`collector.next\\` runs once per event before the destination fan-out (all destinations), and \\`destination.before\\` runs for one destination.\n\n## Flow Config Structure\n\n\\`\\`\\`json\n{\n \"version\": 4,\n \"flows\": {\n \"default\": {\n \"config\": { \"platform\": \"web\" },\n \"sources\": { \"<name>\": { \"package\": \"<npm-package>\", \"config\": {} } },\n \"destinations\": { \"<name>\": { \"package\": \"<npm-package>\", \"config\": { \"settings\": {} } } }\n }\n }\n}\n\\`\\`\\`\n\n- \\`version: 4\\` is required\n- Each flow declares its target via \\`config.platform\\` (\\`\"web\"\\` or \\`\"server\"\\`)\n- Destination settings go inside \\`config.settings\\`, not directly on the destination\n- Event format: \\`{ name: \"entity action\", data: {...}, entity: \"...\", action: \"...\" }\\`\n\n## Key Concepts\n\n- **Mapping** transforms events using data/map/loop/set/condition rules. Same syntax on sources and destinations. Mapping rules use NESTED entity → action keying: event name \"product add\" maps to \\`{ \"product\": { \"add\": Rule } }\\`. Wildcards: \\`{ \"*\": { \"view\": Rule } }\\`.\n- **Contracts** define event schemas using entity-action keying. Can generate FROM mappings or scaffold mappings FROM contracts.\n- **Variables** (\\$var, \\$env, \\$secret, \\$code, \\$store) enable DRY, environment-aware config. \\`$var.name\\` is a reusable flow variable from the top-level \\`variables\\` block; whole-string refs preserve native type (object/array/scalar), inline interpolation requires a scalar, deep paths via \\`$var.name.deep.path\\`. \\`$env.NAME[:default]\\` is an environment variable resolved at bundle/deploy time (non-secret config only). \\`$secret.NAME\\` is a managed secret the deploy pipeline injects into the server runner at runtime; credentials, tokens, and private keys must use \\`$secret\\`, not \\`$env\\`.\n- **Consent** gates destinations (\\`config.consent\\`) and individual fields (a value's \\`consent\\`). A mapping rule's \\`consent\\` is not enforced yet. Privacy-first by design.\n- **Routing** uses one grammar in every chain field (\\`source.before\\`, \\`source.next\\`, \\`transformer.before\\`, \\`transformer.next\\`, \\`collector.next\\`, \\`destination.before\\`, \\`destination.next\\`). A route is a string ID, a sequence (\\`[\"a\", \"b\"]\\`), or a RouteConfig: \\`{ match?, next }\\`, \\`{ match?, one: [...] }\\` (first match wins), \\`{ match?, many: [...] }\\` (every match becomes its own copy of the event with its own id and finishes the rest of the path on its own, never merged), or \\`{ match?, stop: true }\\` (ends that copy). In a sequence, a member's own \\`next\\` runs right after it, then the sequence continues. \\`match\\` reads \\`{ ingest, event }\\` and each route is evaluated when the event reaches it. A \\`stop\\` in \\`collector.next\\` drops the event for every destination; per-destination filtering belongs in \\`destination.before\\`. An array of only route configs is an implicit \\`one\\`. The optional \\`match\\` field is omitted to mean always-match (no wildcard literal).\n- **Pass-through steps** are transformer entries with no \\`code\\` and no \\`package\\`. The runtime synthesizes the push for them automatically. Three flavors share this shape: a \\`before\\` / \\`next\\`-only step (named hop reusable across destinations), a \\`cache\\`-only step (dedup, rate-limit), and a \\`mapping\\`-only step (declarative event-to-event transform). A pass-through must declare at least one of \\`before\\`, \\`next\\`, \\`cache\\`, or \\`mapping\\`.\n- **Mapping at the transformer position** uses the same \\`Mapping.Config\\` shape as destinations, but the semantic is event-to-event: only config-level \\`policy\\` and a rule's \\`condition\\`, \\`policy\\`, \\`name\\` (rename) and \\`ignore\\` (drop from chain) apply. Everything that shapes a vendor payload or gates a destination is a no-op there: config-level \\`consent\\`, \\`include\\`, \\`data\\`, and a rule's \\`consent\\`, \\`include\\`, \\`remove\\`, \\`batch\\`, \\`settings\\`, \\`extend\\`, \\`data\\`, \\`silent\\`; validation warns about them (\\`TRANSFORMER_MAPPING_NO_OP\\`). A \\`config.mapping\\` wins over a step-level \\`mapping\\`.\n- **Closed-schema rule on transformer entries:** known keys only. Operative keys are \\`code\\`, \\`package\\`, \\`before\\`, \\`next\\`, \\`cache\\`, \\`mapping\\`. Combined with structural keys (\\`config\\`, \\`env\\`, \\`validate\\`, \\`disabled\\`, \\`id\\`, etc.). Unknown top-level keys on a transformer step are errors (catches typos like \\`dedup: {}\\` instead of nested under \\`cache\\`). \\`code\\` + \\`package\\` together is a conflict.\n- **Cache** memoizes step output on a configured store. Set \\`cache.stop: true\\` to short-circuit the chain on HIT (sources default to stop-on-HIT); in a source chain or \\`collector.next\\` that halts the event for all destinations. Set \\`cache.namespace\\` to prefix keys; omit it to write keys directly. \\`CacheRule.match\\` is optional, omit for always-match.\n\n## Simulation Tips\n\n- Destinations with \\`require: [\"consent\"]\\` stay **pending** until a \\`\"walker consent\"\\` event fires. Simulation will error \"not found\" for pending destinations, remove \\`require\\` from config when testing with \\`flow_simulate\\`.\n- Destinations with \\`consent: { marketing: true }\\` silently skip events that lack matching consent. Include \\`consent\\` in the event: \\`{ name: \"page view\", data: {...}, consent: { marketing: true } }\\`.\n- **Mapping** transforms event names and data at the destination level. Events without a matching mapping rule pass through unmodified.\n- **Policy** modifies the event before mapping runs, use it to inject computed fields or redact sensitive data.\n\n## Reference Resources\n\nRead these before constructing configs manually: \\`walkeros://reference/flow-schema\\`, \\`walkeros://reference/mapping\\`, \\`walkeros://reference/event-model\\`, \\`walkeros://reference/consent\\`, \\`walkeros://reference/variables\\`, \\`walkeros://reference/contract\\`, \\`walkeros://reference/examples\\`.`;\n","import { randomUUID } from 'crypto';\nimport { telemetry } from '@walkeros/cli';\n\n/**\n * Options for the MCP telemetry emitter wrapper.\n *\n * `clientInfo` mirrors the MCP SDK shape negotiated during initialize.\n * When the client doesn't send one, we record the client name as \"unknown\"\n * inside the per-event data so downstream analytics can still bucket the\n * event. The walkerOS source identifier is the package itself (`mcp`), not\n * the client.\n */\nexport interface McpEmitterOptions {\n clientInfo?: { name: string; version: string };\n packageVersion: string;\n}\n\n/**\n * MCP-specific event emitter.\n *\n * Wraps `@walkeros/cli`'s `telemetry.createEmitter` with:\n * - `source.type` fixed to `\"mcp\"`\n * - `source.platform` fixed to `\"server\"`\n * - per-emission `source.tool` for `cmd invoke` events\n * - a fresh session UUID per MCP server instance\n *\n * Surfaces the narrow set of events the MCP server needs to emit.\n */\nexport interface McpEmitter {\n emitStart(): Promise<void>;\n emitInvoke(\n tool: string,\n outcome: 'success' | 'error',\n timingMs: number,\n ): Promise<void>;\n emitError(kind: 'uncaught' | 'unhandledRejection' | 'startup'): Promise<void>;\n}\n\n/**\n * Build an MCP telemetry emitter.\n *\n * All consent, debug, and endpoint resolution is delegated to the CLI's\n * underlying `telemetry.createEmitter`. This wrapper only provides\n * MCP-specific field mapping and event shorthands.\n */\nexport async function createMcpEmitter(\n opts: McpEmitterOptions,\n): Promise<McpEmitter> {\n const clientName = opts.clientInfo?.name || 'unknown';\n const session = randomUUID();\n\n const emitter = await telemetry.createEmitter({\n source: {\n type: 'mcp',\n platform: 'server',\n },\n packageVersion: opts.packageVersion,\n session,\n });\n\n return {\n async emitStart() {\n const ci = telemetry.getCiInfo();\n await emitter.send('mcp start', {\n ...ci,\n client: clientName,\n });\n },\n async emitInvoke(tool, outcome, timingMs) {\n await emitter.send(\n 'cmd invoke',\n { outcome, client: clientName },\n timingMs,\n { tool },\n );\n },\n async emitError(kind) {\n await emitter.send('error throw', { kind });\n },\n };\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n collectKnownSecrets,\n loadConfig,\n loadJsonConfig,\n bundle,\n push,\n simulateSource,\n simulateTransformer,\n simulateCollector,\n simulateDestination,\n} from '@walkeros/cli';\nimport { isObject } from '@walkeros/core';\nimport { isFlowJson } from '../tools/narrow.js';\nimport type { Flow, WalkerOS } from '@walkeros/core';\nimport { schemas } from '@walkeros/core/dev';\nimport { getOrBuildBundle } from './bundle-cache.js';\nimport type { FlowRuntime } from './types.js';\n\n/**\n * The full-capability runtime for the user's own machine (stdio, the developer\n * CLI). It wraps the `@walkeros/cli` loaders and runners exactly as the tools\n * called them before the runtime seam existed, so local behaviour is unchanged:\n * a config may be a file path, an http(s) URL or inline JSON, and bundling,\n * simulation and push run in this process.\n *\n * This is the only module in the package that may bind those cli functions;\n * the tools reach them through the `FlowRuntime` interface and nothing else.\n */\nexport function createLocalRuntime(): FlowRuntime {\n return {\n load: (input) => loadJsonConfig(input),\n\n baseDir(input) {\n const file = path.resolve(input);\n return fs.existsSync(file) && fs.statSync(file).isFile()\n ? path.dirname(file)\n : undefined;\n },\n\n bundle: (input, opts) =>\n bundle(input, {\n flowName: opts.flowName,\n stats: opts.stats,\n buildOverrides: opts.output ? { output: opts.output } : undefined,\n }),\n\n async simulate(input, opts) {\n // Reuse a prebuilt bundle across calls with the same resolved config. The\n // simulate fns take their fast `mode: 'prebuilt'` branch when given a\n // bundlePath, skipping the per-call rebuild. On any bundle failure fall\n // back to undefined so the simulate fn rebuilds and surfaces its own error.\n let bundlePath: string | undefined;\n try {\n bundlePath = await getOrBuildBundle(input);\n } catch {\n bundlePath = undefined;\n }\n const common = { bundlePath, flow: opts.flow, silent: true };\n const config = opts.config ?? input;\n\n switch (opts.stepType) {\n case 'source':\n return simulateSource(config, opts.event, {\n sourceId: opts.stepId,\n ...common,\n consent: opts.state?.consent,\n });\n case 'transformer':\n return simulateTransformer(config, partialEvent(opts.event), {\n transformerId: opts.stepId,\n ...common,\n ingest: opts.ingest,\n consent: opts.state?.consent,\n });\n case 'collector':\n return simulateCollector(config, partialEvent(opts.event), {\n collectorName: opts.stepId,\n ...common,\n state: opts.state,\n ingest: opts.ingest,\n });\n case 'destination':\n return simulateDestination(config, eventObject(opts.event), {\n destinationId: opts.stepId,\n ...common,\n ingest: opts.ingest,\n consent: opts.state?.consent,\n command: opts.command,\n });\n }\n },\n\n knownSecrets: async (input) =>\n collectKnownSecrets(await loadJsonConfig<Flow.Json>(input)),\n\n async loadRun(input) {\n // One read, detected the way push detects its input: content that\n // parses as JSON is a config, anything else a prebuilt bundle, which\n // carries no config and so no secrets to resolve.\n const content = await loadConfig(input, { json: false });\n const config =\n typeof content === 'string' ? parseJson(content) : undefined;\n if (!isFlowJson(config)) return { knownSecrets: [] };\n return { config, knownSecrets: collectKnownSecrets(config) };\n },\n\n push: (input, event, opts) =>\n push(input, event, {\n json: true,\n flow: opts.flow,\n platform: opts.platform,\n ...(opts.config !== undefined && { raw: opts.config }),\n }),\n };\n}\n\n/**\n * The event a transformer or collector step runs on, checked against the\n * partial event schema the CLI applies. The value passes through as given.\n */\nfunction partialEvent(value: unknown): WalkerOS.DeepPartialEvent {\n if (isPartialEvent(value)) return value;\n const parsed = schemas.PartialEventSchema.safeParse(value);\n throw new Error(parsed.error?.message ?? 'Invalid event');\n}\n\nfunction isPartialEvent(value: unknown): value is WalkerOS.DeepPartialEvent {\n return schemas.PartialEventSchema.safeParse(value).success;\n}\n\n/** A destination step's event, or a command's data: an object. */\nfunction eventObject(value: unknown): Record<string, unknown> {\n if (isObject(value)) return value;\n throw new Error('event must be an object.');\n}\n\nfunction parseJson(content: string): unknown {\n try {\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n}\n","import { createHash } from 'node:crypto';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { mkdir, rm, writeFile } from 'node:fs/promises';\nimport { rmSync } from 'node:fs';\nimport { bundle } from '@walkeros/cli';\n\n/**\n * Content-addressed cache of prebuilt simulate bundles for the MCP\n * `flow_simulate` tool. Each `flow_simulate` call otherwise re-bundles the\n * whole flow (`mode: 'build'`), which dominates latency. By keying a prebuilt\n * ESM by the hash of the *resolved* config content, repeated simulations of the\n * same flow reuse one bundle and a changed flow rebuilds.\n *\n * The CLI simulate functions accept a `bundlePath`; passing it takes their\n * `mode: 'prebuilt'` branch and skips the bundle step entirely.\n */\n\ninterface CacheEntry {\n bundlePath: string;\n dir: string;\n}\n\n/** LRU bound: enough to cover a few flows iterated in one session without\n * leaking temp dirs. Oldest entry is evicted (and its dir removed) on insert. */\nconst MAX_ENTRIES = 8;\n\n/** Insertion-ordered map gives us LRU for free: delete+set on access moves the\n * key to the end; the first key is the least-recently used. */\nconst cache = new Map<string, CacheEntry>();\n\n/** In-flight builds, deduped by key so two concurrent identical simulate calls\n * bundle once instead of racing to write the same artifact. */\nconst inFlight = new Map<string, Promise<string>>();\n\nlet cleanupRegistered = false;\n\nfunction hashConfig(resolvedConfig: string): string {\n return createHash('sha256').update(resolvedConfig).digest('hex');\n}\n\n/**\n * Inline JSON config content is cacheable: its full content is the cache key,\n * so an edit always re-keys. A file path or URL is NOT: `resolveConfigPath`\n * returns it unchanged, so the key would be the path string and an edit to the\n * file behind it would silently reuse a stale bundle. Such inputs skip the\n * cache and take the simulate fns' build path (which re-reads the file).\n *\n * The discriminator matches how the CLI simulate fns treat `configPath`: a\n * string that parses as JSON is inline config; anything else is a path/URL.\n */\nfunction isInlineJsonConfig(resolvedConfig: string): boolean {\n const trimmed = resolvedConfig.trimStart();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return false;\n try {\n JSON.parse(resolvedConfig);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction registerProcessCleanup(): void {\n if (cleanupRegistered) return;\n cleanupRegistered = true;\n const cleanup = () => {\n for (const entry of cache.values()) {\n // Synchronous best-effort removal on exit; async fs is not safe here.\n try {\n rmSync(entry.dir, { recursive: true, force: true });\n } catch {\n // Temp dir already gone or unwritable; nothing to recover.\n }\n }\n cache.clear();\n };\n process.once('exit', cleanup);\n}\n\nasync function evictIfNeeded(): Promise<void> {\n while (cache.size > MAX_ENTRIES) {\n const oldestKey = cache.keys().next().value;\n if (oldestKey === undefined) break;\n const evicted = cache.get(oldestKey);\n cache.delete(oldestKey);\n if (evicted) await rm(evicted.dir, { recursive: true, force: true });\n }\n}\n\n/**\n * Build the resolved config into a prebuilt simulate ESM and return its path,\n * reusing a cached bundle when the same resolved config was bundled before.\n *\n * `resolvedConfig` is the exact string the simulate functions would otherwise\n * receive as `configPath` (a file path, a URL or inline JSON). Keying on it\n * means inline content that changes between calls rebuilds correctly.\n *\n * Returns `undefined` for file-path / URL configs (see `isInlineJsonConfig`):\n * those bypass the cache so an edited file is never served from a stale bundle.\n * The caller then passes the original configPath with no bundlePath, taking the\n * simulate fns' build path exactly as before.\n *\n * The producer mirrors the CLI build-mode bundle: target `simulate`\n * (skipWrapper + withDev, /dev graph inlined) written as ESM. The flow's own\n * platform is preserved via the bundler's platform defaults; only the output\n * format is pinned to ESM so the CLI can import it directly.\n */\nexport async function getOrBuildBundle(\n resolvedConfig: string,\n): Promise<string | undefined> {\n if (!isInlineJsonConfig(resolvedConfig)) return undefined;\n\n registerProcessCleanup();\n const key = hashConfig(resolvedConfig);\n\n const cached = cache.get(key);\n if (cached) {\n // Refresh LRU position.\n cache.delete(key);\n cache.set(key, cached);\n return cached.bundlePath;\n }\n\n const pending = inFlight.get(key);\n if (pending) return pending;\n\n const build = (async () => {\n const dir = path.join(\n os.tmpdir(),\n `walkeros-mcp-bundle-${key.slice(0, 16)}`,\n );\n await rm(dir, { recursive: true, force: true });\n await mkdir(dir, { recursive: true });\n const bundlePath = path.join(dir, 'flow.mjs');\n\n // Touch the file first so a producer that only mutates (rather than writes)\n // still leaves a real artifact; the bundler overwrites it with the real ESM.\n await writeFile(bundlePath, '', 'utf-8');\n\n // Load-bearing: `bundle()` derives platform from the flow config and\n // intentionally ignores `preset.platform` (the 'simulate' preset is node),\n // so a web flow still bundles browser-platform, equivalent to build-mode.\n // If `bundle()` ever honors `preset.platform`, web simulations via this\n // cache would silently bundle for node and diverge.\n await bundle(resolvedConfig, {\n target: 'simulate',\n silent: true,\n buildOverrides: { output: bundlePath, format: 'esm', minify: false },\n });\n\n cache.set(key, { bundlePath, dir });\n await evictIfNeeded();\n return bundlePath;\n })();\n\n inFlight.set(key, build);\n try {\n return await build;\n } finally {\n inFlight.delete(key);\n }\n}\n\n/** Test-only: clear the cache and remove all temp dirs. */\nexport async function __resetBundleCacheForTests(): Promise<void> {\n inFlight.clear();\n const dirs = Array.from(cache.values(), (e) => e.dir);\n cache.clear();\n await Promise.all(\n dirs.map((dir) => r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AAO,IAAI;AACrD,UAAI,CAAC,WAAW,MAAM,EAAG,QAAO,EAAE,cAAc,CAAC,EAAE;AACnD,aAAO,EAAE,QAAQ,cAAc,oBAAoB,MAAM,EAAE;AAAA,IAC7D;AAAA,IAEA,MAAM,CAAC,OAAO,OAAO,SACnB,KAAK,OAAO,OAAO;AAAA,MACjB,MAAM;AAAA,MACN,MAAM,KAAK;AAAA,MACX,UAAU,KAAK;AAAA,MACf,GAAI,KAAK,WAAW,UAAa,EAAE,KAAK,KAAK,OAAO;AAAA,IACtD,CAAC;AAAA,EACL;AACF;AAMA,SAAS,aAAa,OAA2C;AAC/D,MAAI,eAAe,KAAK,EAAG,QAAO;AAClC,QAAM,SAASC,SAAQ,mBAAmB,UAAU,KAAK;AACzD,QAAM,IAAI,MAAM,OAAO,OAAO,WAAW,eAAe;AAC1D;AAEA,SAAS,eAAe,OAAoD;AAC1E,SAAOA,SAAQ,mBAAmB,UAAU,KAAK,EAAE;AACrD;AAGA,SAAS,YAAY,OAAyC;AAC5D,MAAIC,UAAS,KAAK,EAAG,QAAO;AAC5B,QAAM,IAAI,MAAM,0BAA0B;AAC5C;AAEA,SAAS,UAAU,SAA0B;AAC3C,MAAI;AACF,WAAO,KAAK,MAAM,OAAO;AAAA,EAC3B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["isObject","schemas","mcpResult","mcpError","mcpResult","TITLE","inputSchema","schemas","annotations","mcpError","mcpResult","require","z","schemas","mcpError","TITLE","DESCRIPTION","inputSchema","schemas","z","annotations","mcpError","isObject","path","bundle","isObject","schemas","bundle","schemas","isObject"]}
|
|
1
|
+
{"version":3,"sources":["../src/server.ts","../src/tools/bundle.ts","../src/tools/simulate.ts","../src/tools/simulate-description.ts","../src/tools/egress.ts","../src/tools/push.ts","../src/tool-handlers.ts","../src/instructions.ts","../src/telemetry.ts","../src/runtime/local.ts","../src/runtime/bundle-cache.ts"],"sourcesContent":["import {\n McpServer,\n ResourceTemplate,\n} from '@modelcontextprotocol/sdk/server/mcp.js';\n\nimport { isObject } from '@walkeros/core';\n\nimport { createToolHandlers } from './tool-handlers.js';\nimport type { ToolSpec } from './tool-spec.js';\nimport { KNOWLEDGE_RESOURCES, PROMPTS } from './specs.js';\nimport type { PromptSpec, ResourceSpec } from './knowledge-spec.js';\nimport { SERVER_INSTRUCTIONS } from './instructions.js';\nimport { createMcpEmitter, type McpEmitter } from './telemetry.js';\nimport type { FlowRuntime } from './runtime/types.js';\n\nexport interface Logger {\n debug?(message: string, meta?: Record<string, unknown>): void;\n info?(message: string, meta?: Record<string, unknown>): void;\n warn?(message: string, meta?: Record<string, unknown>): void;\n error?(message: string, meta?: Record<string, unknown>): void;\n}\n\nexport interface CreateServerOptions {\n /** Required: the runtime decides what the process may read and run. */\n runtime: FlowRuntime;\n version?: string;\n logger?: Logger;\n}\n\n/**\n * Module-scoped singleton emitter, populated once the MCP `initialize`\n * handshake completes and clientInfo is known. The stdio entrypoint reads\n * this to emit process-level `error throw` events from uncaughtException /\n * unhandledRejection hooks, where the Server instance isn't in scope.\n */\nlet currentEmitter: McpEmitter | undefined;\n\nexport function getMcpEmitterSingleton(): McpEmitter | undefined {\n return currentEmitter;\n}\n\n/**\n * Internal: reset for tests that want a clean slate between cases.\n * Not exported from the package.\n */\nexport function __resetMcpEmitterSingletonForTesting(): void {\n currentEmitter = undefined;\n}\n\n/** An MCP tool answers a failure as a result flagged `isError`. */\nfunction isToolError(result: unknown): boolean {\n return isObject(result) && result.isError === true;\n}\n\n/**\n * Run one tool call and record its outcome: an answer flagged `isError` and a\n * throw are failures. Telemetry never reaches the caller: an emit that fails\n * is dropped, a throw is re-thrown unchanged. Each handler is wrapped when it\n * is registered, never by patching the SDK's registry. The emitter is looked\n * up at call time, so wrapping happens before the emitter exists.\n */\nexport async function trackInvoke<T>(\n tool: string,\n run: () => Promise<T>,\n emitter: () => McpEmitter | undefined = getMcpEmitterSingleton,\n): Promise<T> {\n const start = Date.now();\n const record = (outcome: 'success' | 'error') => {\n emitter()\n ?.emitInvoke(tool, outcome, Date.now() - start)\n .catch(() => {});\n };\n try {\n const result = await run();\n record(isToolError(result) ? 'error' : 'success');\n return result;\n } catch (error) {\n record('error');\n throw error;\n }\n}\n\n/** The one registration path: the spec's own metadata and handler. */\nfunction registerToolSpec(server: McpServer, spec: ToolSpec): void {\n server.registerTool(\n spec.name,\n {\n title: spec.title,\n description: spec.description,\n inputSchema: spec.inputSchema,\n ...(spec.outputSchema ? { outputSchema: spec.outputSchema } : {}),\n annotations: spec.annotations,\n },\n (args) => trackInvoke(spec.name, () => spec.handler(args)),\n );\n}\n\n/** A knowledge resource, static or templated, as the spec describes it. */\nexport function registerResourceSpec(\n server: McpServer,\n spec: ResourceSpec,\n): void {\n if (spec.kind === 'static') {\n server.registerResource(\n spec.name,\n spec.uri,\n { description: spec.description, mimeType: spec.mimeType },\n async (uri) => ({\n contents: [{ uri: uri.toString(), ...(await spec.read()) }],\n }),\n );\n return;\n }\n server.registerResource(\n spec.name,\n new ResourceTemplate(spec.uriTemplate, {\n list: async () => ({ resources: await spec.list() }),\n }),\n {\n title: spec.title,\n description: spec.description,\n mimeType: spec.mimeType,\n },\n async (uri, variables) => ({\n contents: [{ uri: uri.toString(), ...(await spec.read(variables)) }],\n }),\n );\n}\n\n/** A prompt with its description, arguments and handler. */\nexport function registerPromptSpec(server: McpServer, spec: PromptSpec): void {\n server.registerPrompt(\n spec.name,\n { description: spec.description, argsSchema: spec.argsSchema },\n (args) => spec.handler(args),\n );\n}\n\nexport function createWalkerOSMcpServer(opts: CreateServerOptions): McpServer {\n const packageVersion = opts.version ?? '0.0.0';\n const server = new McpServer(\n {\n name: 'walkeros-flow',\n version: packageVersion,\n },\n { instructions: SERVER_INSTRUCTIONS },\n );\n\n for (const spec of Object.values(createToolHandlers(opts.runtime)))\n registerToolSpec(server, spec);\n\n for (const spec of KNOWLEDGE_RESOURCES) registerResourceSpec(server, spec);\n for (const spec of PROMPTS) registerPromptSpec(server, spec);\n\n // MCP SDK fires `oninitialized` after the `initialized` notification, which\n // follows a successful `initialize` request. At that point `getClientVersion`\n // returns the negotiated client identity. We create the emitter here and\n // emit `mcp start`, so consent, debug, and endpoint resolution happen lazily\n // at the moment a real client connects.\n const priorOnInitialized = server.server.oninitialized;\n server.server.oninitialized = () => {\n try {\n priorOnInitialized?.();\n } catch {\n // existing handler must not prevent telemetry setup\n }\n const clientInfo = server.server.getClientVersion();\n void createMcpEmitter({\n clientInfo,\n packageVersion,\n })\n .then(async (emitter) => {\n currentEmitter = emitter;\n await emitter.emitStart();\n })\n .catch(() => {\n // telemetry must never break the server; swallow setup/emit errors.\n });\n };\n\n return server;\n}\n","import { schemas } from '@walkeros/cli/dev';\nimport { mcpResult, mcpError } from '@walkeros/core';\nimport { BundleOutputShape } from '../schemas/output.js';\n\nimport type { ToolSpec } from '../tool-spec.js';\nimport { parseToolInput } from './parse-input.js';\nimport {\n refusalHint,\n unavailableOperation,\n type FlowRuntime,\n} from '../runtime/types.js';\n\nconst TITLE = 'Bundle Flow';\nconst DESCRIPTION =\n 'Bundle a walkerOS flow configuration into deployable JavaScript. ' +\n 'Resolves all destinations, sources, and transformers, then outputs ' +\n 'a tree-shaken production bundle. Returns bundle statistics.';\n\nconst inputSchema = {\n ...schemas.BundleInputShape,\n};\n\nconst annotations = {\n readOnlyHint: false,\n destructiveHint: false,\n idempotentHint: false,\n openWorldHint: true,\n} as const;\n\nexport function createFlowBundleToolSpec(runtime: FlowRuntime): ToolSpec {\n return {\n name: 'flow_bundle',\n title: TITLE,\n description: DESCRIPTION,\n inputSchema,\n outputSchema: BundleOutputShape,\n annotations,\n handler: (input) => flowBundleHandlerBody(runtime, input),\n };\n}\n\nasync function flowBundleHandlerBody(runtime: FlowRuntime, input: unknown) {\n const parsed = parseToolInput(inputSchema, input);\n if (!parsed.ok) return parsed.error;\n const { configPath, flow, stats, output } = parsed.data;\n // Bundling compiles the config and resolves every package it names. A\n // runtime that must not do that in its process provides no `bundle`.\n if (!runtime.bundle) {\n const refusal = unavailableOperation('bundle');\n return mcpError(refusal, refusal.hint);\n }\n try {\n const result = await runtime.bundle(configPath, {\n flowName: flow,\n stats: stats ?? true,\n output,\n });\n\n if (!result) {\n return mcpResult(\n { success: false, message: 'Bundle produced no output' },\n {\n warnings: [\n 'The build returned no result. The flow may be empty or misconfigured.',\n ],\n next: ['Run flow_validate to check your configuration'],\n },\n );\n }\n\n return mcpResult(\n { success: true, ...result },\n {\n next: [\n 'Use flow_simulate to test',\n 'Use runneros or the walkerOS app to run the bundle',\n ],\n },\n );\n } catch (error) {\n return mcpError(\n error,\n refusalHint(error, 'Run flow_validate for detailed error messages'),\n );\n }\n}\n","import { z } from 'zod';\nimport { schemas } from '@walkeros/cli/dev';\nimport { filterValues, mcpResult, mcpError } from '@walkeros/core';\nimport type { Flow, Ingest, Simulation, WalkerOS } from '@walkeros/core';\nimport { SimulateOutputShape } from '../schemas/output.js';\nimport { FLOW_SIMULATE_DESCRIPTION } from './simulate-description.js';\n\nimport type { ToolSpec } from '../tool-spec.js';\nimport { parseToolInput } from './parse-input.js';\nimport { readRun, scrubbed, scrubbedError } from './egress.js';\nimport {\n refusalHint,\n unavailableOperation,\n type FlowRuntime,\n type SimulateStepType,\n} from '../runtime/types.js';\n\ninterface DestinationSummary {\n received: boolean;\n calls: number;\n payload?: unknown;\n}\n\nconst STEP_TYPES: readonly SimulateStepType[] = [\n 'source',\n 'transformer',\n 'collector',\n 'destination',\n];\n\nfunction isStepType(value: string): value is SimulateStepType {\n return STEP_TYPES.some((t) => t === value);\n}\n\nconst TITLE = 'Simulate Flow';\nconst COMMANDS: readonly [Flow.StepCommand, ...Flow.StepCommand[]] = [\n 'config',\n 'consent',\n 'user',\n 'run',\n];\n\nconst inputSchema = {\n configPath: schemas.SimulateInputShape.configPath,\n event: z\n .union([z.record(z.string(), z.unknown()), z.string()])\n .optional()\n .describe(\n \"For destinations: { name, data, consent? }; the event's consent counts \" +\n \"toward the destination's consent requirement, on top of state.consent. \" +\n \"With command: the command's data, e.g. { marketing: true } for consent. \" +\n 'For sources: { content, trigger? } where content is the walkerOS event ' +\n \"{ name, data }. A web source's page URL goes in trigger.options.url \" +\n '(default http://localhost). ' +\n 'Can also be a JSON string or file path.',\n ),\n flow: schemas.SimulateInputShape.flow,\n platform: schemas.SimulateInputShape.platform,\n // Override the (optional) CLI `step` shape: the simulate handler hard-requires\n // a target step (no all-steps mode), so the registered schema must be honest.\n step: z\n .string()\n .describe(\n 'Required. Target step as \"type.name\", e.g. \"source.demo\", \"collector.default\", \"destination.gtag\", \"transformer.router\". ' +\n 'A collector step runs enrichment and then collector.next, returning every event the destinations would receive (none after a stop).',\n ),\n verbose: z\n .boolean()\n .optional()\n .describe('Include full payload per destination (default: false)'),\n ingest: z\n .record(z.string(), z.unknown())\n .optional()\n .describe(\n 'Pipeline context a step reads via ctx.ingest, e.g. { url } for a ' +\n 'request decoder or { ip, userAgent } for a conversion API. Used for ' +\n 'transformer, collector and destination steps (their before chains ' +\n 'included); _meta is always set by the runtime.',\n ),\n state: z\n .object({\n consent: z.record(z.string(), z.boolean()).optional(),\n user: z.record(z.string(), z.unknown()).optional(),\n globals: z.record(z.string(), z.unknown()).optional(),\n timing: z.number().optional(),\n })\n .optional()\n .describe(\n 'Collector state the step starts from. consent: every step (starts a ' +\n 'destination that requires consent and feeds its consent check; for a ' +\n 'source, the consent a consent-gated source waits for). ' +\n 'user/globals/timing: collector steps, seeded before enrichment runs.',\n ),\n command: z\n .enum(COMMANDS)\n .optional()\n .describe(\n 'Destination steps only: run this collector command with event as its ' +\n 'data instead of pushing it, as a step example with command does.',\n ),\n};\n\nconst annotations = {\n // Simulation downloads the packages a config names and runs caller-controlled\n // flow code in process. Destinations are mocked, but that code is not, so the\n // hints stay conservative: side effects possible, repeat calls not assumed\n // safe, external systems reachable.\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n} as const;\n\nexport function createFlowSimulateToolSpec(runtime: FlowRuntime): ToolSpec {\n return {\n name: 'flow_simulate',\n title: TITLE,\n description: FLOW_SIMULATE_DESCRIPTION,\n inputSchema,\n outputSchema: SimulateOutputShape,\n annotations,\n handler: (input) => flowSimulateHandlerBody(runtime, input),\n };\n}\n\n/** Plain values kept as walkerOS properties; values no property can hold dropped. */\nfunction toProperties(\n value: Record<string, unknown> | undefined,\n): WalkerOS.Properties | undefined {\n if (!value) return undefined;\n const properties: WalkerOS.Properties = {};\n for (const [key, entry] of Object.entries(value)) {\n const property = filterValues(entry);\n if (property !== undefined) properties[key] = property;\n }\n return properties;\n}\n\nasync function flowSimulateHandlerBody(runtime: FlowRuntime, input: unknown) {\n const parsed = parseToolInput(inputSchema, input);\n if (!parsed.ok) return parsed.error;\n const {\n configPath,\n event,\n flow,\n platform,\n step,\n verbose,\n ingest,\n state,\n command,\n } = parsed.data;\n // Simulation compiles the config and imports the bundle, running caller\n // controlled flow code. A runtime that must not do that in its process\n // provides no `simulate`, whatever the input looks like.\n if (!runtime.simulate) {\n const refusal = unavailableOperation('simulate');\n return mcpError(refusal, refusal.hint);\n }\n let known: string[] = [];\n try {\n if (!event) {\n throw new Error(\n 'event is required. For sources provide { content, trigger? }, for destinations provide { name, data }.',\n );\n }\n\n if (!step) {\n throw new Error(\n 'step is required. Specify a target like \"source.browser\", \"destination.gtag\", or \"transformer.demo\".',\n );\n }\n\n // Resolve string event input (JSON string)\n let resolvedEvent: unknown = event;\n if (typeof event === 'string') {\n try {\n resolvedEvent = JSON.parse(event);\n } catch {\n throw new Error(\n 'Event string must be valid JSON. Got: ' + event.substring(0, 50),\n );\n }\n }\n\n // Parse step into type and id\n const dotIndex = step.indexOf('.');\n if (dotIndex === -1) {\n throw new Error(\n `Invalid step format \"${step}\". Use \"type.name\" (e.g. \"source.browser\", \"destination.gtag\").`,\n );\n }\n const stepType = step.substring(0, dotIndex);\n const stepId = step.substring(dotIndex + 1);\n\n if (!isStepType(stepType)) {\n throw new Error(\n `Unknown step type \"${stepType}\". Use \"source\", \"collector\", \"transformer\", or \"destination\".`,\n );\n }\n\n if (command !== undefined && stepType !== 'destination') {\n throw new Error('command applies to destination steps only.');\n }\n\n // Read once: the simulation runs on exactly the config whose secrets\n // mask the result.\n const run = await readRun(runtime, configPath);\n known = run.knownSecrets;\n\n const result: Simulation.Result = await runtime.simulate(configPath, {\n stepType,\n stepId,\n event: resolvedEvent,\n flow,\n ingest,\n state: state && {\n consent: state.consent,\n user: toProperties(state.user),\n globals: toProperties(state.globals),\n timing: state.timing,\n },\n command,\n config: run.config,\n });\n\n const success = !result.error;\n const errorMessage = result.error?.message;\n\n // Source simulation: captured events are result.events, the source's\n // own walker commands its `elb` calls. Mock-env calls stay verbose-only.\n if (result.step === 'source') {\n const eventCount = result.events.length;\n const commandCount = result.calls.filter(\n (call) => call.fn === 'elb',\n ).length;\n const summary =\n `Source captured ${eventCount} event${eventCount !== 1 ? 's' : ''}` +\n ` and ${commandCount} command${commandCount !== 1 ? 's' : ''}`;\n const shownCalls = verbose\n ? result.calls\n : result.calls.filter((call) => call.fn === 'elb');\n\n return mcpResult(\n scrubbed(\n {\n success,\n error: errorMessage,\n summary,\n capturedEvents: result.events,\n ...(shownCalls.length > 0 ? { calls: shownCalls } : {}),\n duration: result.duration,\n },\n known,\n ),\n {\n next:\n eventCount + commandCount > 0\n ? [\n 'Use flow_simulate with a destination step to test downstream processing',\n ]\n : [\n 'Check source package examples with package_get, verify trigger type matches',\n ],\n },\n );\n }\n\n // Transformer simulation: surface the transformed events\n if (result.step === 'transformer') {\n return mcpResult(\n scrubbed(\n {\n success,\n error: errorMessage,\n summary: `Transformer processed event`,\n capturedEvents: result.events,\n duration: result.duration,\n },\n known,\n ),\n {\n next: ['Use flow_bundle to build for production'],\n },\n );\n }\n\n // Collector simulation: surface the enriched event\n if (result.step === 'collector') {\n return mcpResult(\n scrubbed(\n {\n success,\n error: errorMessage,\n summary: `Collector enriched event`,\n capturedEvents: result.events,\n duration: result.duration,\n },\n known,\n ),\n {\n next: ['Use flow_simulate with a destination step to test delivery'],\n },\n );\n }\n\n // Destination simulation: count intercepted env calls, key by step name\n const destinations: Record<string, DestinationSummary> = {};\n const callCount = result.calls.length;\n const destSummary: DestinationSummary = {\n received: callCount > 0,\n calls: callCount,\n };\n if (verbose && callCount > 0) {\n destSummary.payload = result.calls;\n }\n destinations[result.name] = destSummary;\n\n const destCount = Object.keys(destinations).length;\n const receivedCount = Object.values(destinations).filter(\n (d) => d.received,\n ).length;\n\n const warnings: string[] = [];\n if (receivedCount === 0 && success) warnings.push(notReceived(result));\n\n const resultObj = {\n success,\n error: errorMessage,\n summary: `${receivedCount}/${destCount} destinations received the event`,\n destinations,\n ...(result.skipped ? { skipped: result.skipped } : {}),\n duration: result.duration,\n };\n\n return mcpResult(scrubbed(resultObj, known), {\n next: ['Use flow_bundle to build for production'],\n ...(warnings.length > 0 ? { warnings } : {}),\n });\n } catch (error) {\n const hint = 'Run flow_validate for detailed error messages';\n return scrubbedError(mcpError(error, refusalHint(error, hint)), known);\n }\n}\n\nfunction keysOf(consent: WalkerOS.Consent | undefined): string {\n const keys = Object.entries(consent ?? {})\n .filter(([, granted]) => granted)\n .map(([key]) => key);\n return keys.length > 0 ? keys.join(', ') : 'none';\n}\n\n/** Why a destination received nothing, from the result's own `skipped`. */\nfunction notReceived(result: Simulation.Result): string {\n const { skipped } = result;\n if (skipped?.reason === 'pending') {\n const require = skipped.require ?? [];\n const waits = require.length ? require.join(', ') : 'its require';\n const advice = require.includes('consent')\n ? 'pass state.consent (e.g. { functional: true }) to start it.'\n : `it starts once the flow provides ${waits}; a simulation cannot seed that.`;\n return `Destination waits for ${waits} (require) and never started: ${advice}`;\n }\n if (skipped?.reason === 'consent') {\n return (\n `Consent skip: requires ${keysOf(skipped.required)}; granted ${keysOf(skipped.granted)}. ` +\n \"Grant it in state.consent or in the event's consent.\"\n );\n }\n return (\n 'Destination made no calls. Common causes: ' +\n '(1) mapping rules do not match the event name or ignore it, ' +\n '(2) policy redacted required fields, ' +\n '(3) a before chain stopped the event.'\n );\n}\n","/**\n * The flow_simulate tool description, kept apart from the tool module so that\n * module stays the only place that imports node-only code.\n */\nexport const FLOW_SIMULATE_DESCRIPTION =\n 'Simulate events through a walkerOS flow without making real API calls. ' +\n 'For destinations: event is a walkerOS event { name: \"entity action\", data: {...} }. ' +\n 'For sources: event is { content, trigger?: { type?, options? } }, where content is the ' +\n 'walkerOS event { name: \"entity action\", data: {...} }. Only the simulated source starts. ' +\n 'step (required) targets the step to simulate, e.g. \"destination.gtag\". ' +\n 'Use flow_examples to discover available test data. ' +\n 'A destination simulation starts only its target destination. ' +\n \"A source's own walker commands (e.g. a CMP's walker consent) are returned as elb calls. \" +\n 'Consent: state.consent is the collector consent the step starts from ' +\n '(any step; a consent-gated source such as the session source waits for it). A destination with ' +\n 'require: [\"consent\"] waits until consent is present, so pass state.consent to start it; ' +\n 'a destination with consent: { marketing: true } receives an event only when that ' +\n \"consent is granted in state.consent or in the event's own consent. \" +\n 'When a destination sends nothing, the result says why (waiting for its require, or a consent skip). ' +\n 'command runs a step example with command (e.g. \"consent\") on a destination: ' +\n \"event is the command's data, state.consent still applies first. \" +\n 'Mapping transforms event names and data at the destination level. ' +\n 'Policy redacts or injects fields before mapping runs.';\n","import type { PushResult } from '@walkeros/cli';\nimport { isObject, mcpError, mcpResult } from '@walkeros/core';\nimport { scrubJson, scrubSecrets } from '@walkeros/core/node';\nimport type { FlowRuntime, LoadedRun } from '../runtime/types.js';\n\n/**\n * Simulate and push results carry recorded vendor calls, network requests and\n * vendor responses whose values can hold credentials. They egress like a log\n * line: `scrubJson` (masking the values of the secrets the flow references,\n * `known`, and credential patterns), then parse back into the structured\n * result.\n */\nexport function scrubbed(\n result: Record<string, unknown>,\n known: readonly string[],\n): Record<string, unknown> {\n const parsed = parseObject(scrubJson(result, { known }));\n if (!parsed) throw new Error('Result could not be redacted as JSON.');\n return parsed;\n}\n\n/** An error response as built by `mcpError`; a stub may lack the structured copy. */\ntype ErrorResponse = Omit<ReturnType<typeof mcpError>, 'structuredContent'> & {\n structuredContent?: Record<string, unknown>;\n};\n\n/**\n * The error response egresses the same way: its structured copy is scrubbed,\n * and the text is that copy serialized (as `mcpError` builds it), so it stays\n * valid JSON. Without a structured copy that scrubs, each text part is\n * scrubbed as a line instead, so the error message is never lost.\n */\nexport function scrubbedError(\n response: ErrorResponse,\n known: readonly string[],\n): ReturnType<typeof mcpError> {\n let structuredContent: Record<string, unknown> | undefined;\n try {\n if (response.structuredContent)\n structuredContent = scrubbed(response.structuredContent, known);\n } catch {\n structuredContent = undefined;\n }\n if (structuredContent) {\n return {\n ...response,\n content: [{ type: 'text', text: JSON.stringify(structuredContent) }],\n structuredContent,\n };\n }\n return {\n ...response,\n content: response.content.map((part) => ({\n ...part,\n text: scrubSecrets(part.text, { known }),\n })),\n structuredContent: { error: 'The error could not be redacted.' },\n };\n}\n\n/**\n * A push result as it egresses: scrubbed and parsed back. `success` and\n * `duration` come from the CLI, never from a vendor, and stay as they are so\n * the output schema always holds. A push already happened, so this never\n * throws: if the scrubbed text does not parse, the text alone carries the\n * result and the structured copy keeps the scalars.\n */\nexport function scrubbedPushResult(\n result: PushResult,\n known: readonly string[],\n): ReturnType<typeof mcpResult> {\n const text = scrubJson(result, { known, space: 2 });\n const parsed = parseObject(text);\n if (parsed)\n return mcpResult({\n ...parsed,\n success: result.success,\n duration: result.duration,\n });\n return {\n content: [{ type: 'text', text }],\n structuredContent: { success: result.success, duration: result.duration },\n };\n}\n\nfunction parseObject(text: string): Record<string, unknown> | undefined {\n try {\n const parsed: unknown = JSON.parse(text);\n return isObject(parsed) ? parsed : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * The run input read once: `loadRun`, else, on a runtime without it, the\n * values its `knownSecrets` returns. A failed read rejects, so the caller\n * stops instead of egressing with pattern masking only.\n */\nexport async function readRun(\n runtime: FlowRuntime,\n input: string,\n): Promise<LoadedRun> {\n if (runtime.loadRun) return runtime.loadRun(input);\n return {\n knownSecrets: runtime.knownSecrets ? await runtime.knownSecrets(input) : [],\n };\n}\n","import { z } from 'zod';\nimport type { PushResult } from '@walkeros/cli';\nimport { schemas } from '@walkeros/cli/dev';\nimport type { CallToolResult } from '@modelcontextprotocol/sdk/types.js';\nimport { mcpError } from '@walkeros/core';\nimport { PushOutputShape } from '../schemas/output.js';\n\nimport type { ToolSpec } from '../tool-spec.js';\nimport { parseToolInput } from './parse-input.js';\nimport { readRun, scrubbedError, scrubbedPushResult } from './egress.js';\nimport {\n refusalHint,\n unavailableOperation,\n type FlowRuntime,\n} from '../runtime/types.js';\n\nconst TITLE = 'Push Events';\nconst DESCRIPTION =\n 'Push a real event through a walkerOS flow to actual destinations. ' +\n 'Makes real API calls to real endpoints. ' +\n 'Best suited for server-side flows; web flows should use flow_simulate for testing.';\n\nconst inputSchema = {\n configPath: schemas.PushInputShape.configPath,\n event: z\n .record(z.string(), z.unknown())\n .describe(\n 'Event object, e.g. { name: \"page view\", data: { title: \"Home\" } }',\n ),\n flow: schemas.PushInputShape.flow,\n platform: schemas.PushInputShape.platform,\n};\n\nconst annotations = {\n readOnlyHint: false,\n destructiveHint: true,\n idempotentHint: false,\n openWorldHint: true,\n} as const;\n\nexport function createFlowPushToolSpec(runtime: FlowRuntime): ToolSpec {\n return {\n name: 'flow_push',\n title: TITLE,\n description: DESCRIPTION,\n inputSchema,\n outputSchema: PushOutputShape,\n annotations,\n handler: (input) => flowPushHandlerBody(runtime, input),\n };\n}\n\nasync function flowPushHandlerBody(\n runtime: FlowRuntime,\n input: unknown,\n): Promise<CallToolResult> {\n const parsed = parseToolInput(inputSchema, input);\n if (!parsed.ok) return parsed.error;\n const { configPath, event, flow, platform } = parsed.data;\n // Push compiles the config, imports it, and makes real outbound calls. A\n // runtime that must not do that in its process provides no `push`.\n if (!runtime.push) {\n const refusal = unavailableOperation('push');\n return mcpError(refusal, refusal.hint);\n }\n // Push results can carry vendor requests and responses: they egress with\n // the flow's secret values and credential patterns masked. The config is\n // read once, so the push runs on exactly the config whose secrets mask the\n // result; a config that cannot be read stops the push.\n let known: string[] = [];\n try {\n const run = await readRun(runtime, configPath);\n known = run.knownSecrets;\n const result: PushResult = await runtime.push(configPath, event, {\n flow,\n platform,\n config: run.config,\n });\n\n if (!result.success) {\n return scrubbedError(\n mcpError(\n new Error(result.error || 'Push failed'),\n 'Check destination configuration and connectivity.',\n ),\n known,\n );\n }\n\n return scrubbedPushResult(result, known);\n } catch (error) {\n return scrubbedError(\n mcpError(\n error,\n refusalHint(\n error,\n 'Check configPath and event format. For web flows, use flow_simulate.',\n ),\n ),\n known,\n );\n }\n}\n","import type { FlowRuntime } from './runtime/types.js';\nimport type { ToolSpec } from './tool-spec.js';\nimport { createLocalToolSpecs, type LocalToolSpecs } from './specs.js';\nimport { createFlowBundleToolSpec } from './tools/bundle.js';\nimport { createFlowSimulateToolSpec } from './tools/simulate.js';\nimport { createFlowPushToolSpec } from './tools/push.js';\n\n/**\n * The eight tools of the local server, keyed by name, over one runtime: the\n * five shared specs plus the three that run caller code. A type alias, not an\n * interface, so it is assignable to Record<string, ToolSpec>.\n */\nexport type LocalServerToolSpecs = LocalToolSpecs & {\n flow_bundle: ToolSpec;\n flow_simulate: ToolSpec;\n flow_push: ToolSpec;\n};\n\nexport function createToolHandlers(runtime: FlowRuntime): LocalServerToolSpecs {\n return {\n ...createLocalToolSpecs(runtime),\n flow_bundle: createFlowBundleToolSpec(runtime),\n flow_simulate: createFlowSimulateToolSpec(runtime),\n flow_push: createFlowPushToolSpec(runtime),\n };\n}\n","export const SERVER_INSTRUCTIONS = `walkerOS is an open-source, privacy-first event data collection platform. Define event pipelines as code using JSON flow configurations.\n\n## Rules\n\n- **Never guess package names.** Always use \\`package_search\\` first to find exact names, then \\`package_get\\` for details.\n- **Never construct flow configs from memory.** Read \\`walkeros://reference/flow-schema\\` and use \\`package_get\\` for package-specific schemas.\n- **Always validate.** Run \\`flow_validate\\` after every config change. If validation fails, fix and re-validate. By default it checks every flow and step, package settings included; a valid result can still list \\`details.skipped\\` checks, so read them before trusting it (\\`strict: true\\` turns warnings and skips into failures: \\`valid\\` is false).\n- **Simulate before you build.** Use \\`flow_simulate\\` to test with mocked API calls before \\`flow_bundle\\` or \\`flow_push\\`.\n\n## Two walkerOS MCP servers\n\nThis server runs on your machine and works on flow files. Its tools read a file path, an http(s) URL or inline JSON, and validate, simulate, bundle and push flows here. It needs no account and no token.\n\nWhat the walkerOS app stores (projects, saved flows, deployments, previews, Observe sessions, frames, release history, secrets, feedback) is served by the hosted walkerOS MCP server at \\`https://app.walkeros.io/api/mcp\\`. Add it to your MCP client as a remote server; it signs you in with OAuth. Both servers offer \\`flow_validate\\`, \\`flow_examples\\`, \\`flow_load\\`, \\`package_search\\` and \\`package_get\\`: use the hosted one for a saved flow and this one for a file.\n\nTo simulate, bundle or push a saved flow here, ask the hosted \\`flow_manage\\` for a config link (\\`action: \"config_url\"\\`) and pass that URL as the input of \\`flow_load\\`, \\`flow_simulate\\`, \\`flow_bundle\\` or \\`flow_push\\`. A link lasts about ten minutes; an expired one fails with its HTTP status.\n\n## Workflow\n\n1. \\`flow_load({ platform: \"web\" })\\` or \\`flow_load({ source: \"./flow.json\" })\\`: create or load\n2. \\`package_search({ type: \"destination\", platform: \"web\" })\\`: discover packages\n3. \\`package_get({ package: \"...\" })\\`: read schemas, hints, examples\n4. Use the \\`add-step\\` prompt: guided step addition\n5. Use the \\`setup-mapping\\` prompt: event transformation config\n6. \\`flow_validate({ type: \"flow\", input: \"flow.json\" })\\`: verify\n7. \\`flow_simulate({ configPath: \"flow.json\", step: \"destination.<name>\", event: { ... } })\\`: test\n8. \\`flow_bundle({ configPath: \"flow.json\" })\\`: build\n\n## Architecture: Source → Collector → Destination(s)\n\nEvery component in a flow is a **step**: sources capture events, transformers process them, destinations deliver them, stores provide shared state. Steps connect via chains: \\`source.next\\` runs before the collector, \\`collector.next\\` runs once per event before the destination fan-out (all destinations), and \\`destination.before\\` runs for one destination.\n\n## Flow Config Structure\n\n\\`\\`\\`json\n{\n \"version\": 4,\n \"flows\": {\n \"default\": {\n \"config\": { \"platform\": \"web\" },\n \"sources\": { \"<name>\": { \"package\": \"<npm-package>\", \"config\": {} } },\n \"destinations\": { \"<name>\": { \"package\": \"<npm-package>\", \"config\": { \"settings\": {} } } }\n }\n }\n}\n\\`\\`\\`\n\n- \\`version: 4\\` is required\n- Each flow declares its target via \\`config.platform\\` (\\`\"web\"\\` or \\`\"server\"\\`)\n- Destination settings go inside \\`config.settings\\`, not directly on the destination\n- Event format: \\`{ name: \"entity action\", data: {...}, entity: \"...\", action: \"...\" }\\`\n\n## Key Concepts\n\n- **Mapping** transforms events using data/map/loop/set/condition rules. Same syntax on sources and destinations. Mapping rules use NESTED entity → action keying: event name \"product add\" maps to \\`{ \"product\": { \"add\": Rule } }\\`. Wildcards: \\`{ \"*\": { \"view\": Rule } }\\`.\n- **Contracts** define event schemas using entity-action keying. Can generate FROM mappings or scaffold mappings FROM contracts.\n- **Variables** (\\$var, \\$env, \\$secret, \\$code, \\$store) enable DRY, environment-aware config. \\`$var.name\\` is a reusable flow variable from the top-level \\`variables\\` block; whole-string refs preserve native type (object/array/scalar), inline interpolation requires a scalar, deep paths via \\`$var.name.deep.path\\`. \\`$env.NAME[:default]\\` is an environment variable resolved at bundle/deploy time (non-secret config only). \\`$secret.NAME\\` is a managed secret the deploy pipeline injects into the server runner at runtime; credentials, tokens, and private keys must use \\`$secret\\`, not \\`$env\\`.\n- **Consent** gates destinations (\\`config.consent\\`) and individual fields (a value's \\`consent\\`). A mapping rule's \\`consent\\` is not enforced yet. Privacy-first by design.\n- **Routing** uses one grammar in every chain field (\\`source.before\\`, \\`source.next\\`, \\`transformer.before\\`, \\`transformer.next\\`, \\`collector.next\\`, \\`destination.before\\`, \\`destination.next\\`). A route is a string ID, a sequence (\\`[\"a\", \"b\"]\\`), or a RouteConfig: \\`{ match?, next }\\`, \\`{ match?, one: [...] }\\` (first match wins), \\`{ match?, many: [...] }\\` (every match becomes its own copy of the event with its own id and finishes the rest of the path on its own, never merged), or \\`{ match?, stop: true }\\` (ends that copy). In a sequence, a member's own \\`next\\` runs right after it, then the sequence continues. \\`match\\` reads \\`{ ingest, event }\\` and each route is evaluated when the event reaches it. A \\`stop\\` in \\`collector.next\\` drops the event for every destination; per-destination filtering belongs in \\`destination.before\\`. An array of only route configs is an implicit \\`one\\`. The optional \\`match\\` field is omitted to mean always-match (no wildcard literal).\n- **Pass-through steps** are transformer entries with no \\`code\\` and no \\`package\\`. The runtime synthesizes the push for them automatically. Three flavors share this shape: a \\`before\\` / \\`next\\`-only step (named hop reusable across destinations), a \\`cache\\`-only step (dedup, rate-limit), and a \\`mapping\\`-only step (declarative event-to-event transform). A pass-through must declare at least one of \\`before\\`, \\`next\\`, \\`cache\\`, or \\`mapping\\`.\n- **Mapping at the transformer position** uses the same \\`Mapping.Config\\` shape as destinations, but the semantic is event-to-event: only config-level \\`policy\\` and a rule's \\`condition\\`, \\`policy\\`, \\`name\\` (rename) and \\`ignore\\` (drop from chain) apply. Everything that shapes a vendor payload or gates a destination is a no-op there: config-level \\`consent\\`, \\`include\\`, \\`data\\`, and a rule's \\`consent\\`, \\`include\\`, \\`remove\\`, \\`batch\\`, \\`settings\\`, \\`extend\\`, \\`data\\`, \\`silent\\`. At a source only config-level \\`consent\\` and \\`policy\\` and a rule's \\`condition\\`, \\`policy\\`, \\`name\\` and \\`ignore\\` apply (edit the event there with \\`policy\\`); at a destination a rule's \\`extend\\` applies only inside a package's own \\`settings.mapping\\`. Validation and the bundle reject these keys (\\`MAPPING_NO_OP\\`). A \\`config.mapping\\` wins over a step-level \\`mapping\\`.\n- **Closed-schema rule on transformer entries:** known keys only. Operative keys are \\`code\\`, \\`package\\`, \\`before\\`, \\`next\\`, \\`cache\\`, \\`mapping\\`. Combined with structural keys (\\`config\\`, \\`env\\`, \\`validate\\`, \\`disabled\\`, \\`id\\`, etc.). Unknown top-level keys on a transformer step are errors (catches typos like \\`dedup: {}\\` instead of nested under \\`cache\\`). \\`code\\` + \\`package\\` together is a conflict.\n- **Cache** memoizes step output on a configured store. Set \\`cache.stop: true\\` to short-circuit the chain on HIT (sources default to stop-on-HIT); in a source chain or \\`collector.next\\` that halts the event for all destinations. Set \\`cache.namespace\\` to prefix keys; omit it to write keys directly. \\`CacheRule.match\\` is optional, omit for always-match.\n\n## Simulation Tips\n\n- Destinations with \\`require: [\"consent\"]\\` stay **pending** until a \\`\"walker consent\"\\` event fires. Simulation will error \"not found\" for pending destinations, remove \\`require\\` from config when testing with \\`flow_simulate\\`.\n- Destinations with \\`consent: { marketing: true }\\` silently skip events that lack matching consent. Include \\`consent\\` in the event: \\`{ name: \"page view\", data: {...}, consent: { marketing: true } }\\`.\n- **Mapping** transforms event names and data at the destination level. Events without a matching mapping rule pass through unmodified.\n- **Policy** modifies the event before mapping runs, use it to inject computed fields or redact sensitive data.\n\n## Reference Resources\n\nRead these before constructing configs manually: \\`walkeros://reference/flow-schema\\`, \\`walkeros://reference/mapping\\`, \\`walkeros://reference/event-model\\`, \\`walkeros://reference/consent\\`, \\`walkeros://reference/variables\\`, \\`walkeros://reference/contract\\`, \\`walkeros://reference/examples\\`.`;\n","import { randomUUID } from 'crypto';\nimport { telemetry } from '@walkeros/cli';\n\n/**\n * Options for the MCP telemetry emitter wrapper.\n *\n * `clientInfo` mirrors the MCP SDK shape negotiated during initialize.\n * When the client doesn't send one, we record the client name as \"unknown\"\n * inside the per-event data so downstream analytics can still bucket the\n * event. The walkerOS source identifier is the package itself (`mcp`), not\n * the client.\n */\nexport interface McpEmitterOptions {\n clientInfo?: { name: string; version: string };\n packageVersion: string;\n}\n\n/**\n * MCP-specific event emitter.\n *\n * Wraps `@walkeros/cli`'s `telemetry.createEmitter` with:\n * - `source.type` fixed to `\"mcp\"`\n * - `source.platform` fixed to `\"server\"`\n * - per-emission `source.tool` for `cmd invoke` events\n * - a fresh session UUID per MCP server instance\n *\n * Surfaces the narrow set of events the MCP server needs to emit.\n */\nexport interface McpEmitter {\n emitStart(): Promise<void>;\n emitInvoke(\n tool: string,\n outcome: 'success' | 'error',\n timingMs: number,\n ): Promise<void>;\n emitError(kind: 'uncaught' | 'unhandledRejection' | 'startup'): Promise<void>;\n}\n\n/**\n * Build an MCP telemetry emitter.\n *\n * All consent, debug, and endpoint resolution is delegated to the CLI's\n * underlying `telemetry.createEmitter`. This wrapper only provides\n * MCP-specific field mapping and event shorthands.\n */\nexport async function createMcpEmitter(\n opts: McpEmitterOptions,\n): Promise<McpEmitter> {\n const clientName = opts.clientInfo?.name || 'unknown';\n const session = randomUUID();\n\n const emitter = await telemetry.createEmitter({\n source: {\n type: 'mcp',\n platform: 'server',\n },\n packageVersion: opts.packageVersion,\n session,\n });\n\n return {\n async emitStart() {\n const ci = telemetry.getCiInfo();\n await emitter.send('mcp start', {\n ...ci,\n client: clientName,\n });\n },\n async emitInvoke(tool, outcome, timingMs) {\n await emitter.send(\n 'cmd invoke',\n { outcome, client: clientName },\n timingMs,\n { tool },\n );\n },\n async emitError(kind) {\n await emitter.send('error throw', { kind });\n },\n };\n}\n","import * as fs from 'fs';\nimport * as path from 'path';\nimport {\n collectKnownSecrets,\n loadConfig,\n loadJsonConfig,\n bundle,\n push,\n simulateSource,\n simulateTransformer,\n simulateCollector,\n simulateDestination,\n} from '@walkeros/cli';\nimport { isObject } from '@walkeros/core';\nimport { isFlowJson } from '../tools/narrow.js';\nimport type { Flow, WalkerOS } from '@walkeros/core';\nimport { schemas } from '@walkeros/core/dev';\nimport { getOrBuildBundle } from './bundle-cache.js';\nimport type { FlowRuntime } from './types.js';\n\n/**\n * The full-capability runtime for the user's own machine (stdio, the developer\n * CLI). It wraps the `@walkeros/cli` loaders and runners exactly as the tools\n * called them before the runtime seam existed, so local behaviour is unchanged:\n * a config may be a file path, an http(s) URL or inline JSON, and bundling,\n * simulation and push run in this process.\n *\n * This is the only module in the package that may bind those cli functions;\n * the tools reach them through the `FlowRuntime` interface and nothing else.\n */\nexport function createLocalRuntime(): FlowRuntime {\n return {\n load: (input) => loadJsonConfig(input),\n\n baseDir(input) {\n const file = path.resolve(input);\n return fs.existsSync(file) && fs.statSync(file).isFile()\n ? path.dirname(file)\n : undefined;\n },\n\n bundle: (input, opts) =>\n bundle(input, {\n flowName: opts.flowName,\n stats: opts.stats,\n buildOverrides: opts.output ? { output: opts.output } : undefined,\n }),\n\n async simulate(input, opts) {\n // Reuse a prebuilt bundle across calls with the same resolved config. The\n // simulate fns take their fast `mode: 'prebuilt'` branch when given a\n // bundlePath, skipping the per-call rebuild. On any bundle failure fall\n // back to undefined so the simulate fn rebuilds and surfaces its own error.\n let bundlePath: string | undefined;\n try {\n bundlePath = await getOrBuildBundle(input);\n } catch {\n bundlePath = undefined;\n }\n const common = { bundlePath, flow: opts.flow, silent: true };\n const config = opts.config ?? input;\n\n switch (opts.stepType) {\n case 'source':\n return simulateSource(config, opts.event, {\n sourceId: opts.stepId,\n ...common,\n consent: opts.state?.consent,\n });\n case 'transformer':\n return simulateTransformer(config, partialEvent(opts.event), {\n transformerId: opts.stepId,\n ...common,\n ingest: opts.ingest,\n consent: opts.state?.consent,\n });\n case 'collector':\n return simulateCollector(config, partialEvent(opts.event), {\n collectorName: opts.stepId,\n ...common,\n state: opts.state,\n ingest: opts.ingest,\n });\n case 'destination':\n return simulateDestination(config, eventObject(opts.event), {\n destinationId: opts.stepId,\n ...common,\n ingest: opts.ingest,\n consent: opts.state?.consent,\n command: opts.command,\n });\n }\n },\n\n knownSecrets: async (input) =>\n collectKnownSecrets(await loadJsonConfig<Flow.Json>(input)),\n\n async loadRun(input) {\n // One read, detected the way push detects its input: content that\n // parses as JSON is a config, anything else a prebuilt bundle, which\n // carries no config and so no secrets to resolve.\n const content = await loadConfig(input, { json: false });\n const config =\n typeof content === 'string' ? parseJson(content) : undefined;\n if (!isFlowJson(config)) return { knownSecrets: [] };\n return { config, knownSecrets: collectKnownSecrets(config) };\n },\n\n push: (input, event, opts) =>\n push(input, event, {\n json: true,\n flow: opts.flow,\n platform: opts.platform,\n ...(opts.config !== undefined && { raw: opts.config }),\n }),\n };\n}\n\n/**\n * The event a transformer or collector step runs on, checked against the\n * partial event schema the CLI applies. The value passes through as given.\n */\nfunction partialEvent(value: unknown): WalkerOS.DeepPartialEvent {\n if (isPartialEvent(value)) return value;\n const parsed = schemas.PartialEventSchema.safeParse(value);\n throw new Error(parsed.error?.message ?? 'Invalid event');\n}\n\nfunction isPartialEvent(value: unknown): value is WalkerOS.DeepPartialEvent {\n return schemas.PartialEventSchema.safeParse(value).success;\n}\n\n/** A destination step's event, or a command's data: an object. */\nfunction eventObject(value: unknown): Record<string, unknown> {\n if (isObject(value)) return value;\n throw new Error('event must be an object.');\n}\n\nfunction parseJson(content: string): unknown {\n try {\n return JSON.parse(content);\n } catch {\n return undefined;\n }\n}\n","import { createHash } from 'node:crypto';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { mkdir, rm, writeFile } from 'node:fs/promises';\nimport { rmSync } from 'node:fs';\nimport { bundle } from '@walkeros/cli';\n\n/**\n * Content-addressed cache of prebuilt simulate bundles for the MCP\n * `flow_simulate` tool. Each `flow_simulate` call otherwise re-bundles the\n * whole flow (`mode: 'build'`), which dominates latency. By keying a prebuilt\n * ESM by the hash of the *resolved* config content, repeated simulations of the\n * same flow reuse one bundle and a changed flow rebuilds.\n *\n * The CLI simulate functions accept a `bundlePath`; passing it takes their\n * `mode: 'prebuilt'` branch and skips the bundle step entirely.\n */\n\ninterface CacheEntry {\n bundlePath: string;\n dir: string;\n}\n\n/** LRU bound: enough to cover a few flows iterated in one session without\n * leaking temp dirs. Oldest entry is evicted (and its dir removed) on insert. */\nconst MAX_ENTRIES = 8;\n\n/** Insertion-ordered map gives us LRU for free: delete+set on access moves the\n * key to the end; the first key is the least-recently used. */\nconst cache = new Map<string, CacheEntry>();\n\n/** In-flight builds, deduped by key so two concurrent identical simulate calls\n * bundle once instead of racing to write the same artifact. */\nconst inFlight = new Map<string, Promise<string>>();\n\nlet cleanupRegistered = false;\n\nfunction hashConfig(resolvedConfig: string): string {\n return createHash('sha256').update(resolvedConfig).digest('hex');\n}\n\n/**\n * Inline JSON config content is cacheable: its full content is the cache key,\n * so an edit always re-keys. A file path or URL is NOT: `resolveConfigPath`\n * returns it unchanged, so the key would be the path string and an edit to the\n * file behind it would silently reuse a stale bundle. Such inputs skip the\n * cache and take the simulate fns' build path (which re-reads the file).\n *\n * The discriminator matches how the CLI simulate fns treat `configPath`: a\n * string that parses as JSON is inline config; anything else is a path/URL.\n */\nfunction isInlineJsonConfig(resolvedConfig: string): boolean {\n const trimmed = resolvedConfig.trimStart();\n if (!trimmed.startsWith('{') && !trimmed.startsWith('[')) return false;\n try {\n JSON.parse(resolvedConfig);\n return true;\n } catch {\n return false;\n }\n}\n\nfunction registerProcessCleanup(): void {\n if (cleanupRegistered) return;\n cleanupRegistered = true;\n const cleanup = () => {\n for (const entry of cache.values()) {\n // Synchronous best-effort removal on exit; async fs is not safe here.\n try {\n rmSync(entry.dir, { recursive: true, force: true });\n } catch {\n // Temp dir already gone or unwritable; nothing to recover.\n }\n }\n cache.clear();\n };\n process.once('exit', cleanup);\n}\n\nasync function evictIfNeeded(): Promise<void> {\n while (cache.size > MAX_ENTRIES) {\n const oldestKey = cache.keys().next().value;\n if (oldestKey === undefined) break;\n const evicted = cache.get(oldestKey);\n cache.delete(oldestKey);\n if (evicted) await rm(evicted.dir, { recursive: true, force: true });\n }\n}\n\n/**\n * Build the resolved config into a prebuilt simulate ESM and return its path,\n * reusing a cached bundle when the same resolved config was bundled before.\n *\n * `resolvedConfig` is the exact string the simulate functions would otherwise\n * receive as `configPath` (a file path, a URL or inline JSON). Keying on it\n * means inline content that changes between calls rebuilds correctly.\n *\n * Returns `undefined` for file-path / URL configs (see `isInlineJsonConfig`):\n * those bypass the cache so an edited file is never served from a stale bundle.\n * The caller then passes the original configPath with no bundlePath, taking the\n * simulate fns' build path exactly as before.\n *\n * The producer mirrors the CLI build-mode bundle: target `simulate`\n * (skipWrapper + withDev, /dev graph inlined) written as ESM. The flow's own\n * platform is preserved via the bundler's platform defaults; only the output\n * format is pinned to ESM so the CLI can import it directly.\n */\nexport async function getOrBuildBundle(\n resolvedConfig: string,\n): Promise<string | undefined> {\n if (!isInlineJsonConfig(resolvedConfig)) return undefined;\n\n registerProcessCleanup();\n const key = hashConfig(resolvedConfig);\n\n const cached = cache.get(key);\n if (cached) {\n // Refresh LRU position.\n cache.delete(key);\n cache.set(key, cached);\n return cached.bundlePath;\n }\n\n const pending = inFlight.get(key);\n if (pending) return pending;\n\n const build = (async () => {\n const dir = path.join(\n os.tmpdir(),\n `walkeros-mcp-bundle-${key.slice(0, 16)}`,\n );\n await rm(dir, { recursive: true, force: true });\n await mkdir(dir, { recursive: true });\n const bundlePath = path.join(dir, 'flow.mjs');\n\n // Touch the file first so a producer that only mutates (rather than writes)\n // still leaves a real artifact; the bundler overwrites it with the real ESM.\n await writeFile(bundlePath, '', 'utf-8');\n\n // Load-bearing: `bundle()` derives platform from the flow config and\n // intentionally ignores `preset.platform` (the 'simulate' preset is node),\n // so a web flow still bundles browser-platform, equivalent to build-mode.\n // If `bundle()` ever honors `preset.platform`, web simulations via this\n // cache would silently bundle for node and diverge.\n await bundle(resolvedConfig, {\n target: 'simulate',\n silent: true,\n buildOverrides: { output: bundlePath, format: 'esm', minify: false },\n });\n\n cache.set(key, { bundlePath, dir });\n await evictIfNeeded();\n return bundlePath;\n })();\n\n inFlight.set(key, build);\n try {\n return await build;\n } finally {\n inFlight.delete(key);\n }\n}\n\n/** Test-only: clear the cache and remove all temp dirs. */\nexport async function __resetBundleCacheForTests(): Promise<void> {\n inFlight.clear();\n const dirs = Array.from(cache.values(), (e) => e.dir);\n cache.clear();\n await Promise.all(\n dirs.map((dir) => rm(dir, { recursive: true, force: true })),\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,EACE;AAAA,EACA;AAAA,OACK;AAEP,SAAS,YAAAA,iBAAgB;;;ACLzB,SAAS,eAAe;AACxB,SAAS,WAAW,gBAAgB;AAWpC,IAAM,QAAQ;AACd,IAAM,cAC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B,MAAM;AAAA,MACN,MAAM,KAAK;AAAA,MACX,UAAU,KAAK;AAAA,MACf,GAAI,KAAK,WAAW,UAAa,EAAE,KAAK,KAAK,OAAO;AAAA,IACtD,CAAC;AAAA,EACL;AACF;AAMA,SAAS,aAAa,OAA2C;AAC/D,MAAI,eAAe,KAAK,EAAG,QAAO;AAClC,QAAM,SAASC,SAAQ,mBAAmB,UAAU,KAAK;AACzD,QAAM,IAAI,MAAM,OAAO,OAAO,WAAW,eAAe;AAC1D;AAEA,SAAS,eAAe,OAAoD;AAC1E,SAAOA,SAAQ,mBAAmB,UAAU,KAAK,EAAE;AACrD;AAGA,SAAS,YAAY,OAAyC;AAC5D,MAAIC,UAAS,KAAK,EAAG,QAAO;AAC5B,QAAM,IAAI,MAAM,0BAA0B;AAC5C;AAEA,SAAS,UAAU,SAA0B;AAC3C,MAAI;AACF,WAAO,KAAK,MAAM,OAAO;AAAA,EAC3B,QAAQ;AACN,WAAO;AAAA,EACT;AACF;","names":["isObject","schemas","mcpResult","mcpError","mcpResult","TITLE","inputSchema","schemas","annotations","mcpError","mcpResult","require","z","schemas","mcpError","TITLE","DESCRIPTION","inputSchema","schemas","z","annotations","mcpError","isObject","path","bundle","isObject","schemas","bundle","schemas","isObject"]}
|