Merci SDK API Reference

The TypeScript surface of Merci SDK v0.27.0, grouped by task. Signatures below use the SDK's single-object argument convention. The full generated export table (§8) is authoritative; §§1–7 explain the calls you actually make.

Start: Getting Started · runnable calls in examples/ (01–32) · concepts in Tutorials (01–42) · provider/engine picks in PROVIDERS.md.

1. Client Lifecycle and Bootstrap

Core Factory Functions

import {
    ProviderType,
    resolveProvider,
    initializeClient,
    loadCredentials,
    getDefaultModel,
    getToolModel,
    getEmbeddingModel,
    getEmbeddingDimensions,
    getAvailableModels
} from 'merci-sdk';
resolveProvider({ provider }): string
Resolves the active provider from environment variable PROVIDER (renamed from BACKEND), or returns the argument.
initializeClient({ provider, options }): Promise<{ client }>
Initializes the unified transport client for the selected provider.
getDefaultModel({ provider }): string
Returns the primary orchestrator/planner model ID for the given provider.
getToolModel({ provider }): string
Returns the cheap leaf-subagent model ID. Throws ConfigurationError on an unknown provider. See examples/15_delegation.mjs.
getEmbeddingModel({ provider }): string
Returns the embedding model ID for the given provider from DEFAULT_<PROVIDER>_EMBEDDING_MODEL (falling back to DEFAULT_GEMINI_EMBEDDING_MODEL / DEFAULT_EMBEDDING_MODEL). Used by client.embed() and the memory vector tier. Resolves to '' for providers whose embeddings are model-less.
getEmbeddingDimensions({ provider }): number
Returns the configured embedding output dimensionality for providers that require one (default 1024); 0 for providers where it does not apply.
getAvailableModels({ client, provider }): Promise<{ id, name }[]>
Backend profiles or models the client can address. Used by the quickstart to list what is reachable. See examples/01_quickstart.mjs.

2. ChatSession and SessionBuilder

Session Configuration Methods

const session = client.session(model)
    .withSystemMessage(str)
    .withProtocol('responses') // e.g. 'responses' on an OpenAI-compatible endpoint; provider-gated
    .withParameters({ temperature, maxTokens, reasoningEffort }) // or b => b.asJson().withSchema(jsonSchema)
    .withTools([tool1, tool2])
    .withMemory(memoryProvider)
    .withTodos(todoStore)
    .withObjective(str);
session.step({ messages, options }): AsyncGenerator<StepEvent, StepFinalState>
One turn over messages (replace history with finalState.messages; never push duplicates). Yields text / thought / tool_call_delta / quota / citations / error; throws MaxTurnsExceededError when the tool budget is spent. See examples/01_quickstart.mjs, 02_conversation.mjs.
session.run({ initialInput, options }): Promise<string>
Agentic loop to a terminal answer: tools, staged follow-ups, abort, streamed-input and token/money budgets. initialInput is text or an async iterable (one user turn per chunk). See examples/07_agent_loop.mjs.
session.getLastRun(): { text, messages, usage, citations, sources }
The last completed run in one object: the deliverable run() returned, the final message rows, and the usage/citations/sources the RUN_END event carries. Empty before a run and after a failed one. See examples/07_agent_loop.mjs.

3. Tools, Protocols and Delegation

Tooling and Delegation

import {
    createShellTool,
    SkillsLibrary,
    loadSkillsFromDirectory,
    McpClient,
    loadMcpTools,
    loadA2ATool
} from 'merci-sdk/tools';
import { withTaskAgents } from 'merci-sdk';
createShellTool({ options }): Tool
Sandboxed shell: Safe / Blocked / HITL-gated tiers, per-tool timeoutMs and outputSchema. Throws ConfigurationError on a blocked command. See examples/14_coding_agent.mjs.
loadMcpTools({ mcpClient }): Promise<Tool[]> · loadMcpToolsFrom({ command, args }): Promise<Tool[]>
MCP client over stdio (or Streamable HTTP by URL); declares sampling/elicitation/roots, plus resources/prompts. Server side: createMcpServer / createMcpHttpHandler. See examples/24_mcp_client.mjs, 25_mcp_server_http.mjs.
loadA2ATool({ agentUrl, eventEmitter }): Promise<Tool>
A2A v1.0 peer as a tool (card dialect auto-detected; origin-pinned; redirects refused). Lifecycle: getA2ATask / cancelA2ATask; serve with createA2AServer. See examples/26_a2a.mjs.
withTaskAgents({ client, agents, options }): void
Delegation roster; the task tool appears only with a reachable profile, with per-agent client/provider, transfer and budget caps. Full contract in SPAWNING.md; see examples/15_delegation.mjs, 15_delegation.mjs.

4. Budget, Guardrails, Permissions and Telemetry

Policy & Budget

import {
    createGuardrails,
    isToolPermitted
} from 'merci-sdk';

client.session(model)
    .withBudget({ budget: { maxTotalTokens: 200_000 } })
    .withGuardrails({ rules: [{ name: 'no-secrets', phase: 'input', pattern: /AKIA[0-9A-Z]{16}/ }] })
    .withPermissions({ allow: ['read_*'], deny: ['write_*'], mode: 'acceptEdits' })
    .withTelemetry({ exporter });
withBudget({ budget: { maxTotalTokens, maxBudgetUsd } })
Caps what one run may spend. The token cap always works. The USD cap is enforced against the amount the provider reports — the SDK never estimates a price and ships no price table; a provider that reports no amount emits run:budget_unreported and the run continues on the token cap.
withGuardrails({ rules })
The tripwire on what enters (phase: 'input') and leaves (phase: 'output') the model. action: 'block' refuses the run with a GuardrailViolationError; action: 'warn' reports and continues.
withPermissions({ allow, deny, mode })
Decides which tools the model may call (tool names or globs such as read_*; an argument pattern like Bash(rm:*) throws ConfigurationError) and how a gated tool is treated: default asks every time, acceptEdits approves only a tool branded editsFiles: true (and never one that also declares runsCode) — the SDK's save_artifact, or a host tool that sets the flag on its definition; a tool loaded from an MCP server never carries it — bypassPermissions approves everything.
createOtlpExporter(options)
Exports a run as an OpenTelemetry gen_ai span tree to an OTLP/HTTP endpoint: invoke_agent per run, chat {model} per vendor call (with gen_ai.usage.*), execute_tool {name} per tool call; every other event is a span event. CompositeApiObserver runs it next to the default observer.
withToolTimeout({ ms }) / withHooks({ hooks })
A per-tool deadline keeps one hanging tool from stalling the turn; the request:after hook chain now fires with the round trip.

5. Orchestration: DAG, State Machine, Discussion

Orchestration Engines

import {
    WorkflowPlanner,
    WorkflowExecutor,
    WorkflowEvaluator
} from 'merci-sdk/planning';
import { DiscussionSession, StateMachine } from 'merci-sdk';
new WorkflowPlanner({ options: { client, model } }).plan({ objective, availableTools })
LLM DAG plan/replan with fail-closed validation (duplicate ids, unknown/self dependencies, cycles, non-ancestor template refs). See examples/17_dag_workflow.mjs.
new WorkflowExecutor({ options: { client, defaultModel, tools } }).execute({ userGoal, planner, evaluator, context })
Kahn-sorted run with naive/stateMachine/discussion step engines, evaluator replan/patch loop, HITL gates, checkpoints (save/load + retryFailedSteps). See examples/17_dag_workflow.mjs, 16_plan_and_execute.mjs.
new DiscussionSession({ client, options }).discuss({ instruction }) → conclude({ instruction })
Stateless-per-turn debate over a shared ledger, then judge + aggregate. Stages separable (discuss/judge/aggregate/runTasks/planForEach). See examples/19_discussion.mjs.
new StateMachine({ graph, options: { client, defaultModel } }).run()
Verified node graph with conditional edges, shared StateContext, verify gates and failure fingerprints. See examples/18_state_machine.mjs.

6. Context, Memory and Resilience

Context Management and Resilience

import {
    LocalFileMemoryProvider,
    CompositeMemoryProvider,
    foldContext,
    compactHistory,
    NoRetryPolicy,
    ExponentialBackoffPolicy,
    createStreamingRetryPolicy,
    CircuitBreaker,
    MerciError,
    BackendError,
    MaxTurnsExceededError
} from 'merci-sdk';
foldContext(rows, { cut, summarize, markerLabel })
Deterministic context folding with explicit loss markers — zero silent truncation.
NoRetryPolicy & ExponentialBackoffPolicy & createStreamingRetryPolicy & CircuitBreaker
Classified retry policies with abort-aware jittered exponential backoff and a circuit breaker.
MerciError & BackendError & OrchestrationError
Typed hierarchical error classes carrying status codes, details, and request correlation. OrchestrationError is the DAG/state-machine/discussion control family — narrow to VerificationError, OrchestrationExhaustedError, GraphError, or OrchestrationFailedError (stable ERROR_CODES.ORCH_* codes).
MaxTurnsExceededError
Thrown when the agentic loop spends its tool-iteration budget without a final answer; opt out with errorHandlers.max_turns, or extend with autoExtend while progress continues.

7. Observability and Logging

Structured Logging, Events & Streams

import {
    log,
    configureSdkLog,
    attachEventLogger,
    createStreamLogger,
    canonicalEventNames,
    defaultDisplay
} from 'merci-sdk';
log.info / warn / error / fatal / debug / trace / success / thinking / event / check / list / totals / dump / flow / step / section / option / condition
The shared logger singleton (zero logging dependencies). fatal always prints to stderr; dump renders a boxed, redacted JSON block; event prints a summarized canonical event.
log.wire({ kind, meta, full })
LLM wire traffic ('request' | 'response' | 'retry'): a metadata brief by default (→ POST … msgs=3 params=temperature,top_p; contents=N config=… for Gemini). Full request bodies appear at level: 'trace' or full: true — messages, contents, params, config, and the parsed body. Bodies are always redacted.
log.toolResult({ n, r, full })
Tool output: truncated to one line at info, expanded (redacted) at debug/trace or full: true.
log.child({ …fields }) · log.timer({ label }) · log.isLevelEnabled({ level }) · log.configure({ level, format, colors, extended, quiet, namespaces, correlation, redact, sink, timestamps })
Scoped context (context on every JSON record), elapsed-time timers, threshold queries, and full configuration. Levels: trace < debug < info < warn < error < fatal < silent. Formats: pretty | json (one NDJSON record per line) | auto (pretty on a TTY, NDJSON when piped). Env fallbacks: LOG_LEVEL, LOG_FORMAT, NO_COLOR.
configureSdkLog({ extended, quiet, level, format, colors })
Configures the shared log singleton; level/format also honor LOG_LEVEL/LOG_FORMAT when omitted.
attachEventLogger({ emitter, log, level, filter }) → () => void
Subscribes a registry-driven catch-all to any client/session/orchestrator emitter: every canonical event is logged — summarized, redacted, level-gated — so a newly registered event is visible immediately (no hand-maintained name list). Uses onAny on a MerciEventEmitter. Returns an unsubscribe function.
createStreamLogger({ log, level, ignore }) → (event) => void
Logs the per-step agentic stream (quota, first_token, finish, truncated, compaction, …); text/thought are skipped by default because the display already renders them.
canonicalEventNames() → string[]
Every canonical event name in the EVENTS registry (unique; the bare error name is excluded to preserve Node's throw-on-unhandled semantics).
defaultDisplay({ also, stream })
The default runAgenticLoop display. stream (default 'debug', or false to disable) also attaches createStreamLogger at that level, so -v/LOG_LEVEL=debug turns on the full step stream.
Redaction
Keys matching authorization / apiKey / password / secret / token (exact or suffix, case-insensitive) are masked as [REDACTED] in every log path — pretty, NDJSON, wire bodies, tool args, and dumps.

8. Complete Export Surface (generated)

Every named export of merci-sdk (main entry)

AbortedErrorAbstractMethodErrorAGENT_EXECUTEAGENT_PLANAgentContextAgentFileErrorAgentLauncherattachEventLoggerBackendErrorBaseChatSessionbaseClientOfBODY_TIMEOUT_CODEBREAKER_OPEN_CODEBrowserComponentBudgetExceededErrorbuildDecisionRequestbuildEnvironmentBlockcanonicalEventNamesCAPABILITYCASSETTE_MODEScassetteKeycertaintyOfChatSessionBuilderchoiceQuestionCircuitBreakerclaimReplanclassifyFailureCLIENT_VIEW_BASEClientRolecompactHistorycompareProgressCompositeApiObserverCompositeMemoryProviderConfigurationErrorconfigureSdkLogcontextFromMerciEnvelopecontinueSpawncountConversationTurnscreateAgenticRuntimecreateAssistantMessagecreateCassettecreateDecisionGatecreateDecisionRerankercreateDecisionsClientcreateGuardrailscreateHookscreateLimitercreateLlmJudgecreateOtlpExportercreatePlanStageFollowUpcreateRoleClientscreateSaveArtifactToolcreateScoredJudgecreateStreamingRetryPolicycreateStreamLoggercreateSystemMessagecreateTaskToolcreateToolCallMessagecreateToolCallMessagescreateToolResultMessagecreateUnifiedMediaMessagescreateUserMessageCurlEnginecurrentRunContextDECISION_QUESTION_TYPEdecisionCalibrationdecisionTestdedupeMessagesdefaultDisplaydiscoverInstructionsDiscussionSessionemitEvententerPhaseERROR_CODESEVAL_SCORERSEventEmitterApiObserverEVENTSExecutionJournalExponentialBackoffPolicyextractUserTextFailureClassfailureFingerprintFALLBACK_MESSAGEfallbackKindfoldContextforkSpawngetAvailableModelsgetBudgetPoolgetCircuitBreakergetDecisionModelgetDefaultModelgetEmbeddingDimensionsgetEmbeddingModelgetLimitsgetSpawngetSpawnRegistrygetToolCallArgumentsgetToolCallNamegetToolModelgoalBlockForHandoffGraphErrorGuardrailViolationErrorHANDOFF_CONTEXT_MODESHANDOFF_GOAL_MODESHANDOFF_MODERATED_MARKERhasTimeoutCodeHEADER_TIMEOUT_CODEHookRegistryHOOKSInactivityTimeoutPolicyingestDocumentinitializeClientINTERACTIVE_ACTIONSisAbortErrorisEditToolisInjectionisSdkFallbackOutputisStandardisToolPermittedisTransientErrorisTransientFallbackKindJOURNAL_STATUSjournalKeyLIMIT_DEFAULTSLIMIT_REGISTRYLIMITSlistSpawnsLoadableComponentloadCredentialsLocalFileMemoryProviderlogMAX_BROWSER_URLSMaxTurnsExceededErrorMemoryComponentMemoryErrorMemoryManagerMemoryProvidermerciEnvelopeMerciErrorMerciEventEmitterNoRetryPolicynormalizeDelegationEnvelopenormalizeHandoffnormalizeHistorynormalizePermissionRulesnoulQuestionObscuraEngineOrchestrationErrorOrchestrationExhaustedErrorOrchestrationFailedErrorotelAttributePDF_MEDIA_PROVIDERSPERMISSION_MODESPHASESPlaywrightSessionPolicyErrorProtocolTypeproviderDescriptorForProviderMemoryEnginePROVIDERSprovidersForStandardProviderTypereadDecisionAnswerreloadLimitsresetLimitsresolveAgentClientresolveBrowserModeresolveLimitresolveProviderresolveRoleresolveScrapeModeresolveSearchModeRetryLedgerREVIEW_STAGE_REMINDERROLE_REGISTRYrunBatchRunContextrunDueStepsrunEvalsrunGuardedSteprunSteprunWithRunContextSchedulerErrorscoreQuestionsendToSpawnsetLimitsspawnThreadIdSqliteMemoryProviderstampEventstampStreamEventstandardForSTANDARDSStandardTypestateFingerprintStateMachinestillRequiresApprovalSTOPstopSpawnstripInjectionMetasumSpawnUsageTASK_TOOL_NAMETavilyEngineTavilyExtractEngineTIMEOUT_CODESTodoComponenttoolJournalKeytoUnifiedtoUnifiedScrapeVerificationErrorWebScrapeComponentWebSearchComponentwithAgentDelegationwithTaskAgentsWorkSourceErrorWorkspaceErrorwrapError
Export Module Signature Summary
AbortedError lib/core/errors.mjs class AbortedError extends MerciError The AbortSignal was triggered.
AbstractMethodError lib/core/errors.mjs class AbstractMethodError extends MerciError A subclass failed to implement an abstract method.
AGENT_EXECUTE lib/agentic/plan/component.mjs AGENT_EXECUTE = "execute" Execute-agent identity (full tool set).
AGENT_PLAN lib/agentic/plan/component.mjs AGENT_PLAN = "plan" Plan-agent identity (read-only).
AgentContext lib/agentic/agent-context.mjs class AgentContext The context envelope threaded through agentic runs.
AgentFileError lib/core/errors.mjs class AgentFileError extends MerciError An agent definition file (`*.agent.yaml`) failed validation or loading.
AgentLauncher lib/agentic/cli/launcher.mjs class AgentLauncher extends EventEmitter Interactive agent CLI: system commands, skill-plugin dispatch, and a tool-fed agentic loop over a backend session.
attachEventLogger lib/support/event-logger.mjs attachEventLogger({ emitter, log, level, filter }): () => void Subscribes a catch-all logger to an emitter.
BackendError lib/core/errors.mjs class BackendError extends MerciError A vendor SDK / transport call failed.
BaseChatSession lib/agentic/chat-session.mjs class BaseChatSession extends AbstractChatSession Shared OAI-family ChatSession (oai/gai/aai).
baseClientOf lib/support/utils.mjs baseClientOf({ client }): Object | null The client a view chain bottoms out at. A derived view names the client whose identity-keyed state (spawn registry, circuit breakers) it shares; following the chain lets every view of one transport read the same state.
BODY_TIMEOUT_CODE lib/support/retry-policy.mjs BODY_TIMEOUT_CODE = "BODY_TIMEOUT" Machine-readable code for response-body stalls (headers arrived, body dripped).
BREAKER_OPEN_CODE lib/support/retry-policy.mjs BREAKER_OPEN_CODE = "BREAKER_OPEN" Machine-readable code for fail-fast rejections while a circuit breaker is open (never retried — the whole point is to stop calling).
BrowserComponent lib/agentic/browser/component.mjs class BrowserComponent extends LoadableComponent Browser capability surfaced as a `browser` function tool: `navigate` (read leg, no action needed) plus the interactive actions (Playwright over `obscura serve` CDP).
BudgetExceededError lib/core/errors.mjs class BudgetExceededError extends MerciError The run exceeded a token budget configured via `session.withBudget(...)` (or the `budget` run option).
buildDecisionRequest lib/messaging/decision.mjs buildDecisionRequest({ model, state, questions }): DecisionRequest Validates one request and returns it unchanged.
buildEnvironmentBlock lib/agentic/context.mjs buildEnvironmentBlock({ root }): Promise<string> Renders the environment block: working directory, git repo, platform, date.
canonicalEventNames lib/support/event-logger.mjs canonicalEventNames(): string[] Every unique canonical event name in the `EVENTS` registry.
CAPABILITY lib/core/constants/capability.mjs CAPABILITY: Record<string, string> Registry of LoadableComponent capability ids.
CASSETTE_MODES lib/support/cassette.mjs CASSETTE_MODES: readonly string[] The cassette modes.
cassetteKey lib/support/cassette.mjs cassetteKey({ request }): string The cassette key of a vendor request.
certaintyOf lib/agentic/decision-gate.mjs certaintyOf({ answer }): number | null The certainty an answer carries, 0..1, or null when it cannot be calibrated.
ChatSessionBuilder lib/agentic/chat-session-builder.mjs class ChatSessionBuilder Fluent builder for ChatSession configuration.
choiceQuestion lib/messaging/decision.mjs choiceQuestion({ instructions, criteria }): ChoiceQuestion —
CircuitBreaker lib/support/retry-policy.mjs class CircuitBreaker Consecutive-failure circuit breaker with half-open probing.
claimReplan lib/agentic/loops/policy.mjs claimReplan<T>({ used, max, onExhausted, onClaim }): T budget is spent, else `onClaim(next, label)` with the incremented count and `[replan next/max]` label.
classifyFailure lib/agentic/loops/policy.mjs classifyFailure({ evidence }): string permission/environment boundaries are checked before verification outcomes (a failed command may be a blocked path, not a bad patch).
CLIENT_VIEW_BASE lib/support/utils.mjs CLIENT_VIEW_BASE: unique symbol A derived client view (`Object.create`) names the client whose identity-keyed state — spawn registry, circuit breakers — it shares.
ClientRole lib/core/constants/roles.mjs ClientRole: Record<string, string> The three client roles a host can resolve.
compactHistory lib/agentic/agentic-compaction.mjs compactHistory({ messages, compaction, session, signal, onEvent, promptTokens, onUsage, beforeSummarize }): Promise<Array<MessageRow>> Compacts conversation history when token usage exceeds the configured threshold.
compareProgress lib/agentic/loops/policy.mjs compareProgress({ previous, current }): number Compares two progress snapshots — a positive score means the run moved forward.
CompositeApiObserver lib/support/api-observer.mjs class CompositeApiObserver Fans one API-call notification out to several observers.
CompositeMemoryProvider lib/agentic/memory/providers.mjs class CompositeMemoryProvider extends MemoryProvider Fan-out memory provider across named banks.
ConfigurationError lib/core/errors.mjs class ConfigurationError extends MerciError The SDK was mis-configured (missing required arg, invalid option, conflicting flags).
configureSdkLog lib/support/utils.mjs configureSdkLog({ extended, quiet, level, format, colors }): void Configures the SDK logger.
contextFromMerciEnvelope lib/agentic/agent-context.mjs contextFromMerciEnvelope({ env }): AgentContext | null through).
continueSpawn lib/agentic/task.mjs continueSpawn({ client, id, prompt, signal }): Promise<Object> Continues a settled spawn's conversation with one more turn (SP3).
countConversationTurns lib/messaging/unified-message.mjs countConversationTurns({ messages }): number Counts genuine conversation turns (user messages), ignoring SDK row-injections and tool-result carriers (role:'tool' messages, tool_message rows, and tool_result / functionResponse content blocks).
createAgenticRuntime lib/index.mjs createAgenticRuntime({ roles, options, clientFactory, seams, onDecisionUsage }): Promise<AgenticRuntime> The composition root for the decision layer: resolve the three client roles, then hand back one gate (and a per-seam gate factory) plus the option fragments every flow already accepts.
createAssistantMessage lib/messaging/messages.mjs createAssistantMessage({ provider, content, thoughtSignature, reasoningContent, redactedThinking }): MessageRow Creates an assistant text message, optionally carrying a thought signature (and DeepSeek-style `reasoning_content` for multi-turn continuity).
createCassette lib/support/cassette.mjs createCassette({ path, script }): Cassette Creates a cassette.
createDecisionGate lib/agentic/decision-gate.mjs createDecisionGate({ ask, threshold, maxStateChars, seam, emitter, onUsage }): DecisionGate Builds the gate over a bound decision surface.
createDecisionReranker lib/agentic/memory/rerank.mjs createDecisionReranker({ ask, instructions, threshold, maxCandidates, emitter }): (arg0: { text: string; facts: Array<RerankableFact>; }) => Promise<Array<RerankableFact>> Builds the `reranker` option `LocalFileMemoryProvider` accepts.
createDecisionsClient lib/backends/decisions/client.mjs createDecisionsClient({ provider, apiKey, baseURL, defaultHeaders, fetchImpl, timeoutMs, emitter }): DecisionsClient Creates the decision client for one provider.
createGuardrails lib/agentic/guardrails.mjs createGuardrails({ rules }): Guardrails Creates the guardrail engine for a set of rules.
createHooks lib/core/hooks.mjs createHooks(): HookRegistry Creates an empty hook registry.
createLimiter lib/support/limiter.mjs createLimiter({ maxConcurrent, minDelayMs, shouldDelay }): { run: <T>(fn: () => Promise<T>) => Promise<T>; acquire: () => Promise<void>; release: () => void; } Creates a limiter.
createLlmJudge lib/agentic/loops/judge.mjs createLlmJudge({ client, model, criteria }): (arg0: { ctx: { getAll: () => Record<string, unknown>; }; signal?: AbortSignal | null; }) => Promise<{ passed: boolean; evidence: string; }> Returns `(ctx) => ({ passed, evidence })` ready for a LoopContract `judge`.
createOtlpExporter lib/support/otel-exporter.mjs createOtlpExporter({ endpoint, serviceName, serviceVersion, headers, batchSize, flushIntervalMs, resourceAttributes, fetchImpl }): OtlpExporter Creates an OTLP/HTTP JSON exporter for the SDK event stream.
createPlanStageFollowUp lib/agentic/plan/component.mjs createPlanStageFollowUp({ session }): (ctx: { round: number; }) => (string | null) until plan_exit has been called this run.
createRoleClients lib/index.mjs createRoleClients({ roles, options, clientFactory }): Promise<Record<string, RoleClient>> Builds one client per distinct provider + per-role options pair and returns one entry per role: the client, its provider and model, and the role's bound surface (`session`, `embed`, or `ask`). Each role resolves independently, so chat, embe…
createSaveArtifactTool lib/agentic/artifacts.mjs createSaveArtifactTool({ dir, eventEmitter }): SaveArtifactTool A tool that saves a file the run produced into the artifact directory.
createScoredJudge lib/agentic/loops/judge.mjs createScoredJudge({ client, model, schema, systemMessage, scoreField, aggregate }): Function A typed, scored grader.
createStreamingRetryPolicy lib/support/retry-policy.mjs createStreamingRetryPolicy({ overrides }): ExponentialBackoffPolicy 30s, 2 retries — matching the OpenAI/Anthropic default).
createStreamLogger lib/support/event-logger.mjs createStreamLogger({ log, level, ignore }): (event: Record<string, unknown>) => void Returns an `onEvent` handler for the agentic step stream that logs every event except those already rendered (`text`, `thought`). Compose it with the default renderer: `defaultDisplay({ also: createStreamLogger() })`.
createSystemMessage lib/messaging/messages.mjs createSystemMessage({ provider, content }): MessageRow Creates a system message in the backend's wire shape.
createTaskTool lib/agentic/task.mjs createTaskTool({ session }): Object on. Reads the client registry and parent model lazily at call time, so the tool can be registered in the ChatSessionBuilder constructor before the session fields are populated.
createToolCallMessage lib/messaging/messages.mjs createToolCallMessage({ provider, id, name, args, thoughtSignature, calls }): MessageRow Creates an assistant tool-call message in the backend's wire shape.
createToolCallMessages lib/messaging/messages.mjs createToolCallMessages({ provider, calls, thoughtSignature }): Array<MessageRow> Creates the assistant tool-call row(s) for one model turn.
createToolResultMessage lib/messaging/messages.mjs createToolResultMessage({ provider, result, thoughtSignature, protocol }): MessageRow Creates a tool result message in the target backend's wire shape.
createUnifiedMediaMessages lib/backends/media.mjs createUnifiedMediaMessages({ provider, prompt, imagePath }): Promise<Array<import('../messaging/unified-message.mjs').MessageRow>> Creates a user turn carrying an image or PDF plus a prompt, per-backend shaped (GAI/AAI/OAI embed base64 data — a PDF becomes an Anthropic `document` block / an OpenAI `file` part).
createUserMessage lib/messaging/messages.mjs createUserMessage({ provider, content }): MessageRow Creates a user message in the backend's wire shape.
CurlEngine lib/agentic/webscrape/engines.mjs class CurlEngine Curl engine — plain `fetch`, strips HTML to text.
currentRunContext lib/core/events.mjs currentRunContext(): RunContext | null The ambient RunContext of the current async execution, or null outside a run.
DECISION_QUESTION_TYPE lib/messaging/decision.mjs DECISION_QUESTION_TYPE: { NOUL: 'noul'; CHOICE: 'choice'; SCORE: 'score'; } The question types every decision wire recognizes.
decisionCalibration lib/agentic/decision-calibration.mjs decisionCalibration({ samples, bins, thresholds }): { count: number; ece: number; brier: number; bins: Array<CalibrationBin>; sweep: Array<ThresholdPoint>; } —
decisionTest lib/agentic/guardrails.mjs decisionTest({ ask, question, threshold, seam, emitter }): (text: string) => Promise<boolean> A guardrail predicate backed by the decision gate: `true` only when the gate is certain enough to skip the LLM path.
dedupeMessages lib/messaging/messages.mjs dedupeMessages({ messages }): Array<MessageRow> Removes duplicate rows by their stable merciId.
defaultDisplay lib/agentic/agentic-step-utils.mjs defaultDisplay({ also, stream }): { onEvent: (e: StepStreamEvent) => void; } Returns the default display `{ onEvent }` for runAgenticLoop consumers: thinking via the logger, text/tool deltas to stdout (the first text delta of each turn is prefixed with `Assistant > ` so the answer is labelled exactly once), newline…
discoverInstructions lib/agentic/context.mjs discoverInstructions({ root, stopAt, eventEmitter }): Promise<string | null> Discovers and renders AGENTS.md instruction files from `root` up to `stopAt` (inclusive).
DiscussionSession lib/agentic/discussion-session.mjs class DiscussionSession extends EventEmitter A multi-agent debate group: agents converse on a shared ledger, optionally judged/aggregated into a conclusion.
emitEvent lib/core/events.mjs emitEvent({ emitter, name, payload, runContext }): void The single event sink.
enterPhase lib/core/lifecycle.mjs enterPhase<T>({ ctx, phase, fn }): Promise<T> Runs `fn` inside a named lifecycle phase, emitting `phase:start` before and `phase:end` after.
ERROR_CODES lib/core/constants/limits.mjs ERROR_CODES: Readonly<{ BASE: "MERCI-ERR"; BACKEND: "MERCI-BACKEND-ERR"; MEMORY: "MERCI-MEMORY-ERR"; CONFIG: "MERCI-CONFIG-ERR"; ABORTED: "MERCI-ABORTED-ERR"; BUDGET: "MERCI-BUDGET-ERR"; MAX_TURNS: "MERCI-MAX-TURNS-ERR";… Stable machine-readable error codes carried by the MerciError hierarchy.
EVAL_SCORERS lib/agentic/evals.mjs EVAL_SCORERS: Readonly<{ outputMatches: () => EvalScorer; outputSchema: () => EvalScorer; toolsCalled: () => EvalScorer; toolSequence: () => EvalScorer; withinBudget: () => EvalScorer; judge: ({ judge, threshold, name }:… The built-in scorers.
EventEmitterApiObserver lib/support/api-observer.mjs class EventEmitterApiObserver The default ApiObserver: emits `api_request` and `api_response` on the session's `EventEmitter` and re-throws / re-emits the error via the `error` event.
EVENTS lib/core/events.mjs EVENTS: Record<string, Record<string, string>> Canonical event-name registry.
ExecutionJournal lib/agentic/journal.mjs class ExecutionJournal —
ExponentialBackoffPolicy lib/support/retry-policy.mjs class ExponentialBackoffPolicy A retry policy that retries on transient errors (connection, rate limit, timeout, HTTP 408, 409, 429 and >= 500) with capped exponential backoff and full jitter (AWS Architecture Blog: sleep = random(0, min(cap, base*2^attempt))).
extractUserText lib/agentic/guardrails.mjs extractUserText({ messages }): string The text of **every** user turn — what a caller typed into the agent.
FailureClass lib/agentic/loops/policy.mjs FailureClass: Readonly<{ TRANSIENT_INFRASTRUCTURE: "transient_infrastructure"; INVALID_TOOL_REQUEST: "invalid_tool_request"; FAILED_HYPOTHESIS: "failed_hypothesis"; VERIFICATION_FAILURE: "verification_failure"; PERMISSIO… The failure taxonomy: the classification labels returned by classifyFailure().
failureFingerprint lib/agentic/loops/policy.mjs failureFingerprint({ action, input, signature }): string Stable key for "is this the same failed attempt as before?". Action + the exact input we handed the verifier + the failure signature.
FALLBACK_MESSAGE lib/core/constants/system-message.mjs FALLBACK_MESSAGE: Record<string, string> User-visible fallback messages for degenerate responses.
fallbackKind lib/agentic/outcomes.mjs fallbackKind({ text }): 'max_iterations' | 'empty' | 'schema' | 'filtered' | null —
foldContext lib/agentic/context-fold.mjs foldContext({ rows, cut, summarize, markerLabel, wrapSummary, wrapMarker }): Promise<FoldedContext> Folds a row array at `cut`: keeps the tail and replaces the prefix with a summary row, or with an explicit loss marker when there is no usable summary.
forkSpawn lib/agentic/task.mjs forkSpawn({ client, id, newThreadId, overwrite, store, threadId }): Promise<import('./sessions.mjs').SessionCheckpoint> Branches a durable child's conversation (D10).
getAvailableModels lib/index.mjs getAvailableModels({ client, provider }): Promise<Array<{ id: string; name: string; }>> The models a backend can currently serve.
getBudgetPool lib/agentic/budget-pool.mjs getBudgetPool({ session }): { maxTotalTokens: number | null; maxBudgetUsd: number | null; usage: PoolUsage; shared: boolean; } | null The public read API: the tree's cap and spend, or null when the session has no budget.
getCircuitBreaker lib/support/retry-policy.mjs getCircuitBreaker({ client, key, options }): CircuitBreaker backend/model (or any caller key).
getDecisionModel lib/support/utils.mjs getDecisionModel({ provider }): string Resolves the decision (System One) model for a backend from secret.env.
getDefaultModel lib/support/utils.mjs getDefaultModel({ provider }): string The default model id of a backend — the tier the orchestrator and the judges run on.
getEmbeddingDimensions lib/support/utils.mjs getEmbeddingDimensions({ provider }): number Resolves the configured embedding output dimensionality for providers that require one, defaulting to 1024.
getEmbeddingModel lib/support/utils.mjs getEmbeddingModel({ provider }): string Resolves the embedding model for a backend from secret.env.
getLimits lib/core/limit-config.mjs getLimits(): Array<{ key: string; value: number; source: string; default: number; env: string; doc: string; guard: boolean; mutable: boolean; disabled: boolean; heldByGuard: boolean; timer: boolean; }> —
getSpawn lib/agentic/spawn-registry.mjs getSpawn({ client, id }): SpawnHandle | null One spawn by spawn id or background task id.
getSpawnRegistry lib/agentic/spawn-registry.mjs getSpawnRegistry(arg0?: { client?: Object | null; session?: { client?: Object | null; } | null; } | Object): SpawnRegistry The registry for a client (created once).
getToolCallArguments lib/messaging/messages.mjs getToolCallArguments({ call }): unknown Reads the tool arguments from a tool call in any shape (OAI/AAI/GAI).
getToolCallName lib/messaging/messages.mjs getToolCallName({ call }): string | undefined Reads the tool name from a tool call in any shape (OAI/AAI/GAI).
getToolModel lib/support/utils.mjs getToolModel({ provider }): string The default tool model id of a backend — the cheap tier the subagents run on.
goalBlockForHandoff lib/agentic/agent-context.mjs goalBlockForHandoff({ ctx, handoff, label }): string block when full, the exact full block + marker when moderated.
GraphError lib/core/errors.mjs class GraphError extends OrchestrationError The workflow graph is structurally unusable at runtime — a dependency cycle, an unresolved/dangling dependency, or a deadlock with no runnable step.
GuardrailViolationError lib/core/errors.mjs class GuardrailViolationError extends MerciError A guardrail refused the content.
HANDOFF_CONTEXT_MODES lib/agentic/agent-context.mjs HANDOFF_CONTEXT_MODES: string[] Valid `context` modes for a handoff.
HANDOFF_GOAL_MODES lib/agentic/agent-context.mjs HANDOFF_GOAL_MODES: string[] Valid `goal` modes for a handoff.
HANDOFF_MODERATED_MARKER lib/agentic/agent-context.mjs HANDOFF_MODERATED_MARKER = "[Handoff: context compacted; goal carried in full]" Handoff marker appended after the full goal block when goal:'moderated'.
hasTimeoutCode lib/support/retry-policy.mjs hasTimeoutCode({ error }): boolean timeout code (`TIMEOUT_CODES`: HEADER_TIMEOUT, BODY_TIMEOUT, STEP_TIMEOUT, STREAM_TIMEOUT, plus the host spellings ETIMEDOUT, TIMEOUT, timeout) — the structural contract that replaces message-substring matching.
HEADER_TIMEOUT_CODE lib/support/retry-policy.mjs HEADER_TIMEOUT_CODE = "HEADER_TIMEOUT" Machine-readable code carried by header-timeout abort errors (upstream accepted the connection but sent no response headers in time).
HookRegistry lib/core/hooks.mjs class HookRegistry The hook registry — an ordered chain of async hooks that can veto or transform a value.
HOOKS lib/core/hooks.mjs HOOKS: Readonly<{ TOOL_BEFORE: "tool:before"; TOOL_AFTER: "tool:after"; TOOL_ERROR: "tool:error"; REQUEST_BEFORE: "request:before"; REQUEST_AFTER: "request:after"; }> Canonical hook-chain names shared by the built-in pipelines and users of `withHooks` (`hooks.add({ name: HOOKS.TOOL_BEFORE, fn })`).
InactivityTimeoutPolicy lib/support/stream-timeout.mjs class InactivityTimeoutPolicy Sliding-window inactivity timeout.
ingestDocument lib/agentic/ingest.mjs ingestDocument({ client, model, path, root, provider, signal }): Promise<string> Ingests a document (image or PDF) as Markdown using a vision-capable model.
initializeClient lib/index.mjs initializeClient({ provider, options }): Promise<{ client: MerciClientInstance; provider: string; }> Builds one backend client.
INTERACTIVE_ACTIONS lib/agentic/browser/component.mjs INTERACTIVE_ACTIONS: readonly string[] The interactive actions the browser tool understands — the vocabulary of a page interaction.
isAbortError lib/core/errors.mjs isAbortError({ err, signal }): boolean Best-effort detection of an AbortSignal-triggered failure.
isEditTool lib/agentic/permissions.mjs isEditTool({ name }): boolean Whether a tool name looks like an edit (write / patch / delete / move).
isInjection lib/messaging/unified-message.mjs isInjection({ m, capId }): boolean True when `m` is an SDK row-injection.
isSdkFallbackOutput lib/agentic/outcomes.mjs isSdkFallbackOutput({ text }): boolean —
isStandard lib/core/constants/sdk.mjs isStandard({ provider, standard }): boolean Whether a provider speaks a given wire standard.
isToolPermitted lib/agentic/permissions.mjs isToolPermitted({ name, allow, deny }): boolean Whether a tool name passes the allow / deny lists.
isTransientError lib/support/retry-policy.mjs isTransientError({ error }): boolean predicate): true when a fresh default-policy instance would retry the error on attempt 0.
isTransientFallbackKind lib/agentic/outcomes.mjs isTransientFallbackKind({ kind }): boolean —
JOURNAL_STATUS lib/agentic/journal.mjs JOURNAL_STATUS: Readonly<{ INTENT: "intent"; DONE: "done"; FAILED: "failed"; INTERRUPTED: "interrupted"; }> One journal row: its identity, lifecycle, the meta the caller spread in, and the attempt history (flat — each stored attempt drops its own `attempts`).
journalKey lib/agentic/journal.mjs journalKey({ parts }): string A stable 16-character key for a journal entry, derived from its parts.
LIMIT_DEFAULTS lib/core/constants/limits.mjs LIMIT_DEFAULTS: Readonly<{ [k: string]: number; }> Default value of every limit, keyed by its logical name.
LIMIT_REGISTRY lib/core/constants/limits.mjs LIMIT_REGISTRY: Readonly<Record<string, Readonly<{ env: string; legacyEnv: ReadonlyArray<string>; default: number; min?: number; max?: number; unbounded: number; integer: boolean; timer: boolean; guard: boolean; mutable:… Every tunable limit, keyed by its logical name.
LIMITS lib/core/limit-config.mjs LIMITS: Record<string, number> Every limit as a lazy property, so a read sees the current env, file and programmatic state.
listSpawns lib/agentic/spawn-registry.mjs listSpawns({ client, status, parentId }): Array<SpawnHandle> Lists the spawns of a client, newest first.
LoadableComponent lib/core/loadable.mjs class LoadableComponent Base class for operational capabilities (skills, memory, …) that surface a payload to the model.
loadCredentials lib/support/utils.mjs loadCredentials({ provider }): Record<string, unknown> Reads a backend's credentials from the environment into the options `initializeClient` expects.
LocalFileMemoryProvider lib/agentic/memory/providers.mjs class LocalFileMemoryProvider extends MemoryProvider File-backed memory bank: one JSON file of facts with atomic saves.
log lib/support/logger.mjs log: Logger The shared logger singleton.
MAX_BROWSER_URLS lib/agentic/browser/engines.mjs MAX_BROWSER_URLS: number How many URLs one browser turn may open.
MaxTurnsExceededError lib/core/errors.mjs class MaxTurnsExceededError extends MerciError The run exhausted its tool-iteration budget without producing a final text response.
MemoryComponent lib/agentic/memory/component.mjs class MemoryComponent extends LoadableComponent The memory capability component: long-term recall/persist exposed as the memory load/save tools.
MemoryError lib/core/errors.mjs class MemoryError extends MerciError A memory subsystem operation failed (L1 load/store, L2 distillation, L3 skill).
MemoryManager lib/agentic/memory/manager.mjs class MemoryManager Coordinates long-term memory: sync-gap detection, fire-and-forget distillation of new conversation turns, and per-step memory block rendering.
MemoryProvider lib/agentic/memory/providers.mjs class MemoryProvider Base memory provider contract.
merciEnvelope lib/agentic/agent-context.mjs merciEnvelope({ ctx }): MerciEnvelope `{ objective, directive, refs }`, nulls omitted.
MerciError lib/core/errors.mjs class MerciError extends Error Base class for every SDK-thrown error.
MerciEventEmitter lib/core/emitter.mjs class MerciEventEmitter extends EventEmitter Per-subscription options: higher `priority` dispatches first, `prepend` jumps the queue, `once` removes after the first dispatch.
NoRetryPolicy lib/support/retry-policy.mjs class NoRetryPolicy A retry policy that never retries.
normalizeDelegationEnvelope lib/agentic/task.mjs normalizeDelegationEnvelope({ client, envelope, session }): DelegationEnvelope Resolves the effective envelope: the host's declaration over the restrictive defaults.
normalizeHandoff lib/agentic/agent-context.mjs normalizeHandoff({ handoff }): { goal: string; context: string | undefined; tools: string | Array<string | Object>; } Free combination: goal and context vary independently; tools defaults to inherit.
normalizeHistory lib/messaging/messages.mjs normalizeHistory({ provider, messages, options }): Array<MessageRow> Normalizes a mixed-shape history to the backend's wire format.
normalizePermissionRules lib/agentic/permissions.mjs normalizePermissionRules({ rules }): PermissionRules Normalizes a caller-supplied rule bag into the canonical shape.
noulQuestion lib/messaging/decision.mjs noulQuestion({ instructions, criteria }): NoulQuestion Builds a yes/no question.
ObscuraEngine lib/agentic/browser/engines.mjs class ObscuraEngine Obscura engine — standalone `obscura fetch <url> --dump <text|markdown>`. Zero new dependencies; binary from `opts.binaryPath ?? OBSCURA_BINARY`.
OrchestrationError lib/core/errors.mjs class OrchestrationError extends MerciError Base class for orchestration-control failures raised by the DAG executor, the state machine, the discussion engine, and their shared verify gates.
OrchestrationExhaustedError lib/core/errors.mjs class OrchestrationExhaustedError extends OrchestrationError An orchestration budget/retry/liveness cap was exhausted: step retries, iteration limit, `maxSteps`, `maxVisits`, node timeout, or a run that never produced a usable final answer.
OrchestrationFailedError lib/core/errors.mjs class OrchestrationFailedError extends OrchestrationError The run ended with unrecovered failed steps (self-heal/replan budget spent).
otelAttribute lib/support/otel-exporter.mjs otelAttribute({ key, value }): OtlpAttribute | null Encodes one OTLP attribute.
PDF_MEDIA_PROVIDERS lib/messaging/messages.mjs PDF_MEDIA_PROVIDERS: Set<string> Backends whose wire can carry an `application/pdf` document as one inline media message: Gemini/Vertex (`inlineData`), Anthropic (`document` block), OpenAI (`file` part).
PERMISSION_MODES lib/agentic/permissions.mjs PERMISSION_MODES: readonly string[] The permission modes this SDK understands.
PHASES lib/core/lifecycle.mjs PHASES: Readonly<{ RUN: "run"; STEP: "step"; WORKFLOW: "workflow"; }> Canonical phase names.
PlaywrightSession lib/agentic/browser/engines.mjs class PlaywrightSession Interactive session over `obscura serve` CDP via Playwright.
PolicyError lib/core/errors.mjs class PolicyError extends MerciError A `WORKFLOW.md` contract failed to load, parse, resolve, or render.
ProtocolType lib/core/constants/sdk.mjs ProtocolType: Record<string, string> LLM wire protocols — the request/response contract a session speaks.
providerDescriptorFor lib/core/constants/providers.mjs providerDescriptorFor({ provider }): ProviderDescriptor | null —
ProviderMemoryEngine lib/agentic/memory/engine.mjs class ProviderMemoryEngine Memory engine over a single provider.
PROVIDERS lib/core/constants/providers.mjs PROVIDERS: Record<string, ProviderDescriptor> Descriptors keyed by ProviderType value.
providersForStandard lib/core/constants/providers.mjs providersForStandard({ standard }): Array<string> —
ProviderType lib/core/constants/providers.mjs ProviderType: Record<string, string> Every concrete provider the SDK can target.
readDecisionAnswer lib/messaging/decision.mjs readDecisionAnswer({ answers, name, type }): DecisionAnswer Reads one answer from a result, refusing a missing key or a type the caller did not expect.
reloadLimits lib/core/limit-config.mjs reloadLimits(): void Re-reads `merci-limits.json` on the next resolution.
resetLimits lib/core/limit-config.mjs resetLimits(): ReturnType<typeof getLimits> Drops every programmatic override and the programmatic switch.
resolveAgentClient lib/agentic/task.mjs resolveAgentClient({ parent, agent, fallbackRegistry }): TaskClient Resolves the client that should execute an agent/profile on. This is the one place that turns a profile's `client`/`provider` into a transport, so every delegation path (task tool, MAA subagents, planForEach) agrees.
resolveBrowserMode lib/agentic/browser/engines.mjs resolveBrowserMode({ _sessionProvider, mode }): "off" | "tool" Resolves the browser mode — the strategy the browser tool runs in.
resolveLimit lib/core/limit-config.mjs resolveLimit({ key }): number Resolves one limit for the current process state.
resolveProvider lib/index.mjs resolveProvider({ provider }): string Resolves the active provider: the argument when given, otherwise `PROVIDER` from secret.env (renamed from BACKEND in 0.20).
resolveRole lib/support/utils.mjs resolveRole({ role }): { role: string; provider: string; model: string; source: { provider: 'role' | 'inherited'; model: 'role' | 'default'; }; } Resolves one client role to a provider and model.
resolveScrapeMode lib/agentic/webscrape/engines.mjs resolveScrapeMode({ sessionProvider, mode }): string Resolves the scrape mode — the strategy the web scraper runs in.
resolveSearchMode lib/agentic/websearch/engines.mjs resolveSearchMode({ sessionProvider, mode }): string Resolves the search mode — the engine the web search runs on.
RetryLedger lib/agentic/loops/policy.mjs class RetryLedger Retry budget keyed by failure fingerprint, NOT by a global counter.
REVIEW_STAGE_REMINDER lib/core/constants/plan-reminders.mjs REVIEW_STAGE_REMINDER: string Default followUp stage: review the produced answer, fix gaps, or reply DONE.
ROLE_REGISTRY lib/core/constants/roles.mjs ROLE_REGISTRY: Record<string, RoleDescriptor> Role descriptors keyed by ClientRole value.
runBatch lib/support/limiter.mjs runBatch<I, V>({ items, worker, maxConcurrent, minDelayMs, retryPolicy, signal, stopOnError, maxTotalTokens, usageOf }): Promise<Array<{ status: string; value?: V; reason?: unknown; }>> per-item retry, returning an index-aligned array of settled outcomes in INPUT order (independent of completion order): `[{status:'fulfilled', value} | {status:'rejected', reason}]`. A rejected/repeatedly-failing item never aborts its siblin…
RunContext lib/core/events.mjs class RunContext The run context — the identity (run id, parent run) every event of a run carries.
runDueSteps lib/agentic/agentic-step-utils.mjs runDueSteps({ steps }): Promise<Array<StepOutcome>> Runs the steps that are due and returns one settled result per step, in input order.
runEvals lib/agentic/evals.mjs runEvals({ cases, makeSession, scorers, concurrency, signal }): Promise<{ results: Array<EvalResult>; passRate: number; }> Runs a suite: every case on a fresh session, every scorer on every run.
runGuardedStep lib/support/retry-policy.mjs runGuardedStep<T>({ breaker, signal, run, onBreakerOpen, onFailure }): Promise<T> Runs `run` behind `breaker`, recording shared backend health.
runStep lib/agentic/step.mjs runStep({ step, deps }): Promise<{ result: string; messages: Array<import('./chat-session.mjs').ChatRow>; deltaMessages: Array<import('./chat-session.mjs').ChatRow>; compacted: boolean; turnMessages: Array<import('./chat… Runs ONE agentic step attempt in a fresh session: builds the session with the glue's policy/capabilities, runs the agentic loop, forwards stream events through the glue's event names, and captures the step's full message row + reasoning sig…
runWithRunContext lib/core/events.mjs runWithRunContext<T>({ runContext, fn }): T Installs `runContext` as the ambient correlation context for `fn`. Every `emitEvent`/`stampEvent` executed inside (across awaits and child generators) correlates automatically.
SchedulerError lib/core/errors.mjs class SchedulerError extends MerciError The scheduler API was misused: a lifecycle call out of order, a reset of a running item, or an attempt to rebind an option that was fixed at construction.
scoreQuestion lib/messaging/decision.mjs scoreQuestion({ instructions, criteria }): ScoreQuestion —
sendToSpawn lib/agentic/task.mjs sendToSpawn({ client, id, prompt, signal }): Promise<Object> `client.send({id, prompt})` — the addressing form of `continueWith`.
setLimits lib/core/limit-config.mjs setLimits({ values, disabled: nextDisabled, disabledKeys: nextDisabledKeys, allowGuardOff: nextAllowGuardOff }): ReturnType<typeof getLimits> Applies programmatic overrides.
spawnThreadId lib/agentic/spawn-registry.mjs spawnThreadId({ id }): string The deterministic thread id a durable child is stored under (D10).
SqliteMemoryProvider lib/agentic/memory/providers.mjs class SqliteMemoryProvider extends LocalFileMemoryProvider SQLite-backed memory bank.
stampEvent lib/core/events.mjs stampEvent({ name, payload, runContext }): Record<string, unknown> Standalone envelope builder for emission points outside any RunContext (parameter building, agent switching).
stampStreamEvent lib/core/events.mjs stampStreamEvent({ event, runContext }): Record<string, unknown> Adds the additive correlation fields to an onEvent stream event ({ type, ... }) without changing its shape contract.
standardFor lib/core/constants/providers.mjs standardFor({ provider }): string | null —
STANDARDS lib/core/constants/standards.mjs STANDARDS: Record<string, StandardDescriptor> Descriptors keyed by StandardType value.
StandardType lib/core/constants/standards.mjs StandardType: Record<string, string> Every wire standard the SDK speaks.
stateFingerprint lib/agentic/loops/policy.mjs stateFingerprint({ snapshot }): string same fingerprint — used to catch oscillation, not just consecutive stalls.
StateMachine lib/agentic/state-machine/machine.mjs class StateMachine extends EventEmitter A node graph machine with conditional transitions.
stillRequiresApproval lib/agentic/permissions.mjs stillRequiresApproval({ name, mode, requiresApproval, tool }): boolean Whether a gated tool still has to ask under the given permission mode.
STOP lib/core/hooks.mjs STOP: unique symbol The sentinel a hook returns to end a waterfall chain without changing the value.
stopSpawn lib/agentic/spawn-registry.mjs stopSpawn({ client, id, reason }): boolean Stops one running spawn by spawn id or background task id without aborting its parent.
stripInjectionMeta lib/messaging/messages.mjs stripInjectionMeta({ messages, keepNative }): Array<MessageRow> Returns a copy of `messages` with the non-wire keys (INJECTION_META_KEY, MERCI_ID_KEY and — unless `keepNative` — MERCI_NATIVE_KEY) removed from every message.
sumSpawnUsage lib/agentic/spawn-registry.mjs sumSpawnUsage(list: Array<SpawnUsage | null | undefined>): SpawnUsage | null Sums the numeric usage fields of every attempt.
TASK_TOOL_NAME lib/agentic/task.mjs TASK_TOOL_NAME = "task" The `task` tool's wire name.
TavilyEngine lib/agentic/websearch/engines.mjs class TavilyEngine Tavily engine — raw global `fetch` POST to https://api.tavily.com/search.
TavilyExtractEngine lib/agentic/webscrape/engines.mjs class TavilyExtractEngine Tavily extract engine — raw global `fetch` POST to https://api.tavily.com/extract.
TIMEOUT_CODES lib/core/constants/limits.mjs TIMEOUT_CODES: ReadonlySet<string> Every machine-readable code the SDK raises for a timeout.
TodoComponent lib/agentic/todos/component.mjs class TodoComponent extends LoadableComponent The todos capability component: task list management exposed as load/save tools and rendered into the system context.
toolJournalKey lib/agentic/journal.mjs toolJournalKey({ runId, boundary, name, args }): string The journal key of a tool call — the identity its outcome is recorded under.
toUnified lib/agentic/websearch/engines.mjs toUnified({ query, raw, includeVendorMetadata }): UnifiedSearchResult `{ query, answer?, sources: [{ title, url }] }` shape.
toUnifiedScrape lib/agentic/webscrape/engines.mjs toUnifiedScrape({ url, raw, includeVendorMetadata }): UnifiedScrapeResult Curl plain text) to the unified `{ url, content, truncated, _vendor? }` shape.
VerificationError lib/core/errors.mjs class VerificationError extends OrchestrationError A node/step output failed its verification or acceptance gate (deterministic criteria, judge, or a user-supplied `verify`). Carries the machine-readable evidence so a caller can replan/escalate without string-matching the message.
WebScrapeComponent lib/agentic/webscrape/component.mjs class WebScrapeComponent extends LoadableComponent Web-scrape capability surfaced as a `web_scrape` function tool.
WebSearchComponent lib/agentic/websearch/component.mjs class WebSearchComponent extends LoadableComponent Web-search capability surfaced as a `web_search` function tool.
withAgentDelegation lib/agentic/task.mjs withAgentDelegation({ client, agents, models, transports, system, tools, maxDepth, maxSpawns }): TaskClient Declares the host's delegation envelope (D1a).
withTaskAgents lib/agentic/task.mjs withTaskAgents({ client, agents, options }): TaskClient duplicate name wins) and returns the client for chaining.
WorkSourceError lib/core/errors.mjs class WorkSourceError extends MerciError A work source failed to list or refresh items.
WorkspaceError lib/core/errors.mjs class WorkspaceError extends MerciError A workspace key, path, or lifecycle operation failed.
wrapError lib/core/errors.mjs wrapError({ err, hints }): Error Wraps a thrown error in the most-specific MerciError subclass based on the available hints.

Named exports of merci-sdk/aai

ChatSessionMerciClient
Export Module Signature Summary
ChatSession lib/backends/aai.mjs class ChatSession extends BaseChatSession Manages a chat session with an Anthropic LLM.
MerciClient lib/backends/aai.mjs class MerciClient extends EventEmitter Main Merci SDK client for Anthropic.

Named exports of merci-sdk/acp

ACP_AGENT_VERSIONACP_STOP_REASONScreateAcpAgentpermissionAllowed
Export Module Signature Summary
ACP_AGENT_VERSION lib/agentic/acp-agent.mjs ACP_AGENT_VERSION: string merci version advertised in the ACP initialize handshake.
ACP_STOP_REASONS lib/agentic/acp-agent.mjs ACP_STOP_REASONS: Readonly<{ END_TURN: "end_turn"; MAX_TOKENS: "max_tokens"; REFUSAL: "refusal"; CANCELLED: "cancelled"; }> The ACP prompt stop reasons.
createAcpAgent lib/agentic/acp-agent.mjs createAcpAgent({ session, createSession, name, version, onTurnContext }): import('@agentclientprotocol/sdk/unstable').AgentApp Wraps a merci ChatSession as an ACP agent app.
permissionAllowed lib/agentic/acp-agent.mjs permissionAllowed({ response, options }): boolean Decides whether an ACP `session/request_permission` response grants the permission.

Named exports of merci-sdk/agents

AGENT_API_VERSIONAGENT_FILE_REASONSAGENT_KINDAGENT_META_GROUPSAGENT_SELECTOR_SOURCESAGENT_TOOL_GROUP_ALIASESAGENT_TOOL_GROUPSagentGroupToolNamesapplyAgentSpeccreateAgentToolboxexpandAgentGrouploadAgentDirectoryloadAgentFileparseSelectorprefixExternalPatternprefixExternalToolresolveToolsetsanitizeToolNametoTaskAgent
Export Module Signature Summary
AGENT_API_VERSION lib/agentic/agents/spec.mjs AGENT_API_VERSION = "merci.dev/v1alpha1" The one format version v1 reads.
AGENT_FILE_REASONS lib/agentic/agents/spec.mjs AGENT_FILE_REASONS: ReadonlyArray<string> Every stable reason an `AgentFileError` from this format may carry.
AGENT_KIND lib/agentic/agents/spec.mjs AGENT_KIND = "Agent" The one document kind v1 reads.
AGENT_META_GROUPS lib/agentic/agents/catalog.mjs AGENT_META_GROUPS: readonly string[] Groups that grant every tool the host can satisfy; dangerous by design.
AGENT_SELECTOR_SOURCES lib/agentic/agents/catalog.mjs AGENT_SELECTOR_SOURCES: readonly string[] The selector namespaces a file may use in `allow` / `deny`.
AGENT_TOOL_GROUP_ALIASES lib/agentic/agents/catalog.mjs AGENT_TOOL_GROUP_ALIASES: Readonly<Record<string, readonly string[]>> Beginner aliases: a readable umbrella that expands to real groups.
AGENT_TOOL_GROUPS lib/agentic/agents/catalog.mjs AGENT_TOOL_GROUPS: Readonly<Record<string, AgentToolGroup>> The groups a file may name in `spec.tools.use`. Every entry is satisfied by an existing public builder; none of them needs a new engine.
agentGroupToolNames lib/agentic/agents/catalog.mjs agentGroupToolNames({ name }): string[] | null The tool names a `use` entry yields, after alias expansion.
applyAgentSpec lib/agentic/agents/apply.mjs applyAgentSpec({ session, spec, toolbox, allowDangerous }): AgentSessionLike Applies a spec to an existing session and returns it (fluent).
createAgentToolbox lib/agentic/agents/toolbox.mjs createAgentToolbox({ workspace, approval, todos, memory, knowledge, skills, search, scrape, browser, stateMachine, delegation, tools, mcp, acp, a2a, options }): AgentToolbox Builds the immutable toolbox.
expandAgentGroup lib/agentic/agents/catalog.mjs expandAgentGroup({ name }): string[] | null Expands one `use` entry to real group names.
loadAgentDirectory lib/agentic/agents/load.mjs loadAgentDirectory({ directory, allowDangerous }): Promise<import('./spec.mjs').AgentSpec[]> Loads every regular `*.agent.yaml` in one directory.
loadAgentFile lib/agentic/agents/load.mjs loadAgentFile({ path, allowDangerous, root }): Promise<import('./spec.mjs').AgentSpec> Loads one `*.agent.yaml` file into a deep-frozen spec.
parseSelector lib/agentic/agents/toolbox.mjs parseSelector({ selector }): { source: string; owner: string | null; pattern: string; } | null Splits one selector into `{ source, owner, pattern }`. `mcp:github/issues_*` has owner `github`; `native:read` has owner null.
prefixExternalPattern lib/agentic/agents/toolbox.mjs prefixExternalPattern({ source, owner, pattern }): string The same prefixing, but `*` survives so a deny selector can stay a glob.
prefixExternalTool lib/agentic/agents/toolbox.mjs prefixExternalTool({ source, owner, name }): string The namespaced name of an external tool.
resolveToolset lib/agentic/agents/toolbox.mjs resolveToolset({ spec, toolbox, allowDangerous, mode }): ResolvedToolset Resolves a spec against a toolbox.
sanitizeToolName lib/agentic/agents/toolbox.mjs sanitizeToolName({ value }): string A wire-safe tool name: `[A-Za-z0-9_-]`, at most `agent_tool_name_max`, with a short deterministic suffix when truncation is needed.
toTaskAgent lib/agentic/agents/apply.mjs toTaskAgent({ spec, toolbox, allowDangerous, model }): Record<string, unknown> Builds the `TaskAgent` profile for `withTaskAgents`.

Named exports of merci-sdk/cassette

CASSETTE_MODESCASSETTE_VERSIONcassetteKeycreateCassette
Export Module Signature Summary
CASSETTE_MODES lib/support/cassette.mjs CASSETTE_MODES: readonly string[] The cassette modes.
CASSETTE_VERSION lib/support/cassette.mjs CASSETTE_VERSION = 1 The on-disk format version.
cassetteKey lib/support/cassette.mjs cassetteKey({ request }): string The cassette key of a vendor request.
createCassette lib/support/cassette.mjs createCassette({ path, script }): Cassette Creates a cassette.

Named exports of merci-sdk/evals

EVAL_SCORERSrunEvals
Export Module Signature Summary
EVAL_SCORERS lib/agentic/evals.mjs EVAL_SCORERS: Readonly<{ outputMatches: () => EvalScorer; outputSchema: () => EvalScorer; toolsCalled: () => EvalScorer; toolSequence: () => EvalScorer; withinBudget: () => EvalScorer; judge: ({ judge, threshold, name }:… The built-in scorers.
runEvals lib/agentic/evals.mjs runEvals({ cases, makeSession, scorers, concurrency, signal }): Promise<{ results: Array<EvalResult>; passRate: number; }> Runs a suite: every case on a fresh session, every scorer on every run.

Named exports of merci-sdk/gai

ChatSessionMerciClient
Export Module Signature Summary
ChatSession lib/backends/gai.mjs class ChatSession extends BaseChatSession Manages a chat session with an LLM.
MerciClient lib/backends/gai.mjs class MerciClient extends EventEmitter Main Merci SDK client for Google GenAI.

Named exports of merci-sdk/inbox

INBOX_STORE_VERSIONInMemoryInboxStoreLocalFileInboxStore
Export Module Signature Summary
INBOX_STORE_VERSION lib/agentic/inbox-store.mjs INBOX_STORE_VERSION = 1 The on-disk shape every inbox store speaks.
InMemoryInboxStore lib/agentic/inbox-store.mjs class InMemoryInboxStore Process-local inbox.
LocalFileInboxStore lib/agentic/inbox-store.mjs class LocalFileInboxStore File-backed inbox: one JSON file per thread, written atomically (tmp + rename, fsync) so a crash mid-save leaves the previous queue intact.

Named exports of merci-sdk/json

extractAndParseJsonfindWireHostileKeywordsguardedParseisZodSchematoWireToolParametersvalidateStrictvalidateValuezodSchemaToJsonSchema
Export Module Signature Summary
extractAndParseJson lib/support/json.mjs extractAndParseJson({ input, schema }): ParseResult (from first '{' or '[' to its MATCHING close) to bypass markdown code blocks, backticks, or conversational text, and runs it through guardedParse.
findWireHostileKeywords lib/support/json.mjs findWireHostileKeywords({ node, found }): Set<string> and a union `type` array (`{ type: ['string','null'] }`) — zod emits that form for `.nullable()` and primitive unions, and it is as wire-hostile as `anyOf`. Shared by the wire guard and the schema parity tests so both use one definition.
guardedParse lib/support/json.mjs guardedParse({ input, schema, options }): ParseResult Parses a payload against a schema (JSON Schema or Zod), repairing it when it is nearly valid.
isZodSchema lib/support/json.mjs isZodSchema({ schema }): boolean working when zod is resolved to more than one copy.
toWireToolParameters lib/support/json.mjs toWireToolParameters<T extends { name?: string; parameters?: unknown; }>({ tool, onWarn }): T plain JSON Schema, and an unconvertible (Zod v3) one is emptied rather than leaked.
validateStrict lib/support/json.mjs validateStrict({ input, schema }): ParseResult Same result contract, except a malformed payload is never repaired: it fails with `"Failed to parse JSON structure"` and `originalValid === false`. Callers keep their own error policy (throw / warn / fall back to empty) — they just get a sc…
validateValue lib/support/json.mjs validateValue({ value, schema }): { ok: boolean; details: Array<ValidationDetail> | null; } Validates an **already parsed** value against a JSON Schema without touching it. `guardedParse` compiles with `useDefaults: true` (its parser fills in the schema's defaults — right for parsing an incoming payload, wrong for checking a value…
zodSchemaToJsonSchema lib/support/json.mjs zodSchemaToJsonSchema({ zodSchema }): JsonSchema | null Returns `null` when the argument is not a Zod schema, or is Zod v3 — v4's converter cannot read a v3 instance (it throws), so callers must warn instead of sending a broken schema.

Named exports of merci-sdk/knowledge

adoptedProfileadoptOntologyAGENT_KINDSappendKnowledgeLogapplyPatchbm25ScoresbuildGraphCONFIDENCEconfidenceWeightCORE_RELATIONScorpusKeycreateKnowledgePortDEFAULT_KNOWLEDGE_DIRdocumentSurfaceEDGE_ORIGINSEDGE_POLARITIESEDGE_SHAPESedgeTextemptyGraphexpandSubgraphextractDefinitionsextractRefsfingerprintSourcesGENERIC_PROFILEgraphShagraphTextSizeheadingListHIERARCHY_RELATIONShierarchyOfhierarchyPathhubDivisorisKnownKindisKnownRelisSemanticRelisStaleisValidAtkeyOfKNOWLEDGE_BUILD_VERSIONKNOWLEDGE_SCHEMAKNOWLEDGE_VERSIONKnowledgeComponentknowledgePathsLEGAL_GRAPH_SCHEMALEGAL_PROFILElevelKindsForlexicalScoreLINT_CODESlintGraphloadCorpusloadGraphloadManifestloadOntologyLOG_FILEMANIFEST_FILEmanifestPathmemorySurfacemergeEntitiesmergeFragmentmodalityOfnodeKeynormalizeConstraintsnormalizeTextOKF_STATUSESOKF_VERSIONontologyShaparagraphListparseFrontmatterplanSurfacePROFILESprofileSourcespromotableRelationsproposeOntologyqueryGraphrankNodesreadOkfBundlereadSourcesreadTextFilereadWikiShareanchorDerivedrenderFrontmatterrenderKnowledgeBlockrenderLintReportrenderNodePagerenderOkfBundlerenderSectionMaprenderWikiresolveBundleTargetresolveProfileretrieveSubgraphSALIENCEsalienceWeightsaveGraphsaveOntologyseedNodesSEMANTIC_RELATIONSsentenceListslugsourceDeltasourceShasourceSlicestatsOfSTRUCTURAL_RELATIONSsurfaceFragmentsyncCorpustemporalViewTIERStierWeighttodosSurfacetokensOftrustTiervalidateGraphwikiSurface
Export Module Signature Summary
adoptedProfile lib/agentic/knowledge/store.mjs adoptedProfile({ dir }): Promise<{ name: string; kinds: Array<string>; relations: Array<string>; levels?: Array<string>; constraints?: import('./model.mjs').ProfileConstraints; version: number; proposalSha: string | null… The adopted vocabulary as a profile a graph can be validated against, or null when nothing was adopted.
adoptOntology lib/agentic/knowledge/store.mjs adoptOntology({ dir, proposal, expected, now }): Promise<{ version: number; sha: string; path: string; adopted: Array<string>; }> Adopts a proposal as the vocabulary.
AGENT_KINDS lib/agentic/knowledge/profile.mjs AGENT_KINDS: readonly string[] Kinds the agent writes and no parse can infer.
appendKnowledgeLog lib/agentic/knowledge/render.mjs appendKnowledgeLog({ dir, action, summary, details, timestamp }): Promise<{ path: string; timestamp: string; entry: string; }> Appends a single timestamped entry to `<dir>/log.md` under an exclusive file lock, creating `# Knowledge Log` on first write and never overwriting prior entries.
applyPatch lib/agentic/knowledge/model.mjs applyPatch({ graph, patch, profile, now, sources, restoreTombstoned }): KnowledgeGraph Applies a patch: add nodes/edges, update node fields, remove by id. Refusals are deliberate and typed by message, because an agent writes these: a dangling endpoint, an unknown kind or relation, a custom relation with no note, or a patch la…
bm25Scores lib/agentic/knowledge/query.mjs bm25Scores({ documents, query, k1, b }): number[] BM25 scores aligned with `documents`. Strings use the default tokenizer; callers that need folding or n-grams pass token arrays from `tokensOf`.
buildGraph lib/agentic/knowledge/build.mjs buildGraph({ sources, profile, title, now, hierarchy }): import('./model.mjs').KnowledgeGraph Builds a graph from one or more documents.
CONFIDENCE lib/agentic/knowledge/model.mjs CONFIDENCE: readonly string[] Confidence ladder.
confidenceWeight lib/agentic/knowledge/query.mjs confidenceWeight({ node }): number —
CORE_RELATIONS lib/agentic/knowledge/model.mjs CORE_RELATIONS: readonly string[] Relations a structural/doc parse or an author may use without a note.
corpusKey lib/agentic/knowledge/cache.mjs corpusKey({ sources, profile, buildVersion, hierarchy }): string The build identity: sources by identity and content, plus the vocabulary that shaped them and the extractor version.
createKnowledgePort lib/agentic/knowledge/port.mjs createKnowledgePort({ component, dir, profile, ontology, sources, embedder, writeBack }): KnowledgePort —
DEFAULT_KNOWLEDGE_DIR lib/agentic/knowledge/store.mjs DEFAULT_KNOWLEDGE_DIR = ".knowledge" Default directory, matching the `.knowledge` convention of the skill corpus.
documentSurface lib/agentic/knowledge/adapters.mjs documentSurface({ paths, profile, title }): import('./model.mjs').KnowledgeGraph The `document` surface: one graph from one or more text files.
EDGE_ORIGINS lib/agentic/knowledge/model.mjs EDGE_ORIGINS: readonly string[] Where an edge came from: a parse, a formula, or a judgement.
EDGE_POLARITIES lib/agentic/knowledge/model.mjs EDGE_POLARITIES: readonly string[] The only values `edge.polarity` may take.
EDGE_SHAPES lib/agentic/knowledge/model.mjs EDGE_SHAPES: readonly string[] The shapes an edge may take beyond "A rel B". - `binary` — the plain assertion; - `negative` — `polarity: 'negative'`: the relation is asserted *not* to hold (a rejected defence, a boundary); - `conditional` — `condition: <nodeId>`: the ass…
edgeText lib/agentic/knowledge/render.mjs edgeText({ edge, target, arrow }): string The text form of an edge, shared by the prompt block and the wiki so the two cannot drift.
emptyGraph lib/agentic/knowledge/component.mjs emptyGraph({ profile }): import('./model.mjs').KnowledgeGraph —
expandSubgraph lib/agentic/knowledge/query.mjs expandSubgraph({ graph, seeds, depth, maxNodes, depths, edgeFilter, direction, includeDeprecated }): Array<string> Bounded BFS.
extractDefinitions lib/agentic/knowledge/build.mjs extractDefinitions({ text }): Array<{ term: string; definition: string; offset: number; }> `"Term" means …` / `Term (the "Alias")` style definitions.
extractRefs lib/agentic/knowledge/build.mjs extractRefs({ text }): Array<{ text: string; anchor: string; }> Cross-references an agent can anchor: `Section 4.2`, `Clause 7`, `§ 4`, `Annex I`.
fingerprintSources lib/agentic/knowledge/cache.mjs fingerprintSources({ sources }): Array<SourceFingerprint> —
GENERIC_PROFILE lib/agentic/knowledge/model.mjs GENERIC_PROFILE: Readonly<{ name: "generic"; kinds: readonly string[]; relations: readonly string[]; }> Domain-neutral vocabulary: documents, claims, evidence, work items.
graphSha lib/agentic/knowledge/model.mjs graphSha({ graph }): string Stable hash of the graph's content.
graphTextSize lib/agentic/knowledge/render.mjs graphTextSize({ graph }): number Total characters of node text — the size signal the budget tiers read.
headingList lib/agentic/knowledge/build.mjs headingList({ text }): Array<{ level: number; title: string; start: number; end: number; line: number; anchor: string; }> —
HIERARCHY_RELATIONS lib/agentic/knowledge/hierarchy.mjs HIERARCHY_RELATIONS: readonly string[] Relations whose direction can describe containment.
hierarchyOf lib/agentic/knowledge/hierarchy.mjs hierarchyOf({ graph, rel, maxNodes }): HierarchyTree Derives a bounded hierarchy from `contains` (parent → child) or `part_of` (child → parent) edges.
hierarchyPath lib/agentic/knowledge/hierarchy.mjs hierarchyPath({ graph, id, tree }): import('./model.mjs').KnowledgeNode[] The root-to-node path, using the deterministic primary parent.
hubDivisor lib/agentic/knowledge/query.mjs hubDivisor({ indegree }): number —
isKnownKind lib/agentic/knowledge/model.mjs isKnownKind({ profile, kind }): boolean —
isKnownRel lib/agentic/knowledge/model.mjs isKnownRel({ profile, rel }): boolean —
isSemanticRel lib/agentic/knowledge/model.mjs isSemanticRel({ rel }): boolean —
isStale lib/agentic/knowledge/model.mjs isStale({ node, at }): boolean Whether a node is stale at an instant.
isValidAt lib/agentic/knowledge/model.mjs isValidAt({ node, at }): boolean Whether a node's internal validity window contains an instant.
keyOf lib/agentic/knowledge/build.mjs keyOf({ value }): string Normalised term key: `The Confidential Information` → `confidential information`.
KNOWLEDGE_BUILD_VERSION lib/agentic/knowledge/build.mjs KNOWLEDGE_BUILD_VERSION = 2 Bumped whenever the mechanical pass changes what it emits for the same bytes.
KNOWLEDGE_SCHEMA lib/agentic/knowledge/model.mjs KNOWLEDGE_SCHEMA = "merci.knowledge/v1" Schema id carried by `graph.json`.
KNOWLEDGE_VERSION lib/agentic/knowledge/model.mjs KNOWLEDGE_VERSION = 1 Current model version, bumped when a field changes meaning.
KnowledgeComponent lib/agentic/knowledge/component.mjs class KnowledgeComponent extends LoadableComponent The knowledge capability.
knowledgePaths lib/agentic/knowledge/store.mjs knowledgePaths({ dir }): { dir: string; graphPath: string; ontologyPath: string; } —
LEGAL_GRAPH_SCHEMA lib/agentic/knowledge/model.mjs LEGAL_GRAPH_SCHEMA = "legalgraph/v1" The schema id the legal-skills toolchain writes; accepted on import.
LEGAL_PROFILE lib/agentic/knowledge/model.mjs LEGAL_PROFILE: Readonly<{ name: "legal"; kinds: readonly string[]; relations: readonly string[]; }> The legal vocabulary the existing corpus uses (`legalgraph/v1`).
levelKindsFor lib/agentic/knowledge/model.mjs levelKindsFor({ profile, hierarchy, level }): string Resolves the kind for a one-based structural level.
lexicalScore lib/agentic/knowledge/query.mjs lexicalScore({ query, text }): number Overlap score in [0, 1]: how much of the query the node covers.
LINT_CODES lib/agentic/knowledge/lint.mjs LINT_CODES: ReadonlyArray<KnowledgeLintCode> All lint finding codes emitted by `lintGraph`.
lintGraph lib/agentic/knowledge/lint.mjs lintGraph({ graph, asOf, strict }): KnowledgeLintReport Runs semantic integrity checks over a knowledge graph.
loadCorpus lib/agentic/knowledge/cache.mjs loadCorpus({ dir }): Promise<{ graph: import('./model.mjs').KnowledgeGraph | null; manifest: CorpusManifest | null; }> Loads the persisted graph and its manifest.
loadGraph lib/agentic/knowledge/store.mjs loadGraph({ dir }): Promise<{ status: 'ok' | 'missing' | 'corrupt'; graph?: import('./model.mjs').KnowledgeGraph; reason?: string; }> Loads the graph.
loadManifest lib/agentic/knowledge/cache.mjs loadManifest({ dir }): Promise<CorpusManifest | null> —
loadOntology lib/agentic/knowledge/store.mjs loadOntology({ dir }): Promise<{ kinds: Array<string>; relations: Array<string>; promoted: Array<string>; version: number; status: string; proposalSha: string | null; constraints?: import('./model.mjs').ProfileConstraint… Loads the vocabulary.
LOG_FILE lib/agentic/knowledge/render.mjs LOG_FILE = "log.md" Append-only audit log filename inside a knowledge directory.
MANIFEST_FILE lib/agentic/knowledge/cache.mjs MANIFEST_FILE = "manifest.json" The file that records what a build was made from.
manifestPath lib/agentic/knowledge/cache.mjs manifestPath({ dir }): string —
memorySurface lib/agentic/knowledge/adapters.mjs memorySurface({ facts }): { nodes: import('./model.mjs').KnowledgeNode[]; edges: import('./model.mjs').KnowledgeEdge[]; } The `memory` surface: bank facts become `fact` nodes.
mergeEntities lib/agentic/knowledge/model.mjs mergeEntities({ graph, targetId, sourceIds, reason, mergedAt, profile, sources }): { graph: KnowledgeGraph; mergedIds: string[]; redirectedEdges: number; removedSelfLoops: number; } Deterministically merges one or more source entities into `targetId`. Re-points incident edges (`from`, `to`, `condition`), `derivedFrom`, and `supersededBy`, drops resulting self-loops and intra-merge `same_as` edges, deduplicates edges vi…
mergeFragment lib/agentic/knowledge/adapters.mjs mergeFragment({ graph, fragment, allowResurrect }): import('./model.mjs').KnowledgeGraph Merges adapter output into a graph.
modalityOf lib/agentic/knowledge/build.mjs modalityOf({ text }): 'obligation' | 'permission' | 'prohibition' | null The modality a sentence states, or null when it is descriptive.
nodeKey lib/agentic/knowledge/build.mjs nodeKey({ node }): string Stable identity of a node's content, independent of where it sits.
normalizeConstraints lib/agentic/knowledge/model.mjs normalizeConstraints({ constraints, kinds, relations, freeze }): ProfileConstraints | undefined Validates and canonicalises optional per-relation and per-kind schema constraints against a vocabulary's `kinds` and `relations`. Returns `undefined` when no constraints are declared so omitted constraints leave serialised shapes and hashes…
normalizeText lib/agentic/knowledge/model.mjs normalizeText({ text }): string Normalises line endings and strips a BOM.
OKF_STATUSES lib/agentic/knowledge/model.mjs OKF_STATUSES: readonly string[] OKF lifecycle values; a missing value means `stable`.
OKF_VERSION lib/agentic/knowledge/okf.mjs OKF_VERSION = "0.3" The OKF version this module reads and writes.
ontologySha lib/agentic/knowledge/profile.mjs ontologySha({ proposal }): string Identity of a proposal: the shape, not the timestamp.
paragraphList lib/agentic/knowledge/build.mjs paragraphList({ text, headings }): Array<{ start: number; end: number; text: string; section: { level: number; title: string; start: number; end: number; line: number; anchor: string; } | null; }> Blank-line separated blocks, each attributed to the nearest preceding heading.
parseFrontmatter lib/agentic/knowledge/okf.mjs parseFrontmatter({ text }): { data: Record<string, unknown> | null; body: string; } Splits a concept document into frontmatter and body.
planSurface lib/agentic/knowledge/adapters.mjs planSurface({ plan }): { nodes: import('./model.mjs').KnowledgeNode[]; edges: import('./model.mjs').KnowledgeEdge[]; } The `plan` surface: a task DAG becomes `step` nodes.
PROFILES lib/agentic/knowledge/model.mjs PROFILES: Readonly<{ generic: Readonly<{ name: "generic"; kinds: readonly string[]; relations: readonly string[]; }>; legal: Readonly<{ name: "legal"; kinds: readonly string[]; relations: readonly string[]; }>; }> Every shipped profile by name.
profileSources lib/agentic/knowledge/profile.mjs profileSources({ sources }): DataProfile Measures one or more documents.
promotableRelations lib/agentic/knowledge/store.mjs promotableRelations({ graph, promoteAfter }): Array<{ rel: string; notes: number; }> Custom relations that appear in enough distinct notes to deserve promotion into the vocabulary.
proposeOntology lib/agentic/knowledge/profile.mjs proposeOntology({ profile, minSupport, name, constraints }): OntologyProposal Turns a measurement into a candidate vocabulary.
queryGraph lib/agentic/knowledge/query.mjs queryGraph({ graph, id, depth, maxNodes, edgeFilter, direction, includeDeprecated }): { node: import('./model.mjs').KnowledgeNode; nodes: import('./model.mjs').KnowledgeNode[]; edges: Array<import('./model.mjs').Knowledg… The bounded neighbourhood of one node, for the explicit-id query form.
rankNodes lib/agentic/knowledge/query.mjs rankNodes({ graph, candidates, similarity, limit, hubDamping, tiePriority }): Array<RankedNode> Ranks candidates by similarity, salience, confidence and tier, damped by inbound degree unless the caller supplies an already-calibrated ranking.
readOkfBundle lib/agentic/knowledge/okf.mjs readOkfBundle({ dir }): { graph: import('./model.mjs').KnowledgeGraph; concepts: number; warnings: Array<string>; } Reads an OKF bundle into a graph.
readSources lib/agentic/knowledge/cache.mjs readSources({ paths }): Array<{ id: string; path: string; name: string; text: string; }> Reads the sources from disk, in the order given (the order is part of the key).
readTextFile lib/agentic/knowledge/adapters.mjs readTextFile({ path }): string Reads a text-like file.
readWikiSha lib/agentic/knowledge/render.mjs readWikiSha({ dir }): string | null The graph hash a previously rendered wiki carries, or null.
reanchorDerived lib/agentic/knowledge/cache.mjs reanchorDerived({ stored, fresh, external, sourceTexts }): { nodes: Array<import('./model.mjs').KnowledgeNode>; edges: Array<import('./model.mjs').KnowledgeEdge>; kept: number; dropped: number; droppedEdges: number; idMa… Moves the agent's nodes from an old graph onto a freshly built one.
renderFrontmatter lib/agentic/knowledge/okf.mjs renderFrontmatter({ data }): string Renders a frontmatter block.
renderKnowledgeBlock lib/agentic/knowledge/render.mjs renderKnowledgeBlock({ graph, result, budget, query }): string | null Renders a bounded knowledge block for the prompt.
renderLintReport lib/agentic/knowledge/lint.mjs renderLintReport({ report }): string Renders a compact Markdown summary of a `KnowledgeLintReport`, suitable for CLI/agent output or inclusion in `log.md`.
renderNodePage lib/agentic/knowledge/render.mjs renderNodePage({ graph, node, tree }): string One node's wiki page.
renderOkfBundle lib/agentic/knowledge/okf.mjs renderOkfBundle({ graph, dir, metadata }): { dir: string; concepts: number; written: number; sha: string; } Renders an OKF bundle from a graph.
renderSectionMap lib/agentic/knowledge/render.mjs renderSectionMap({ graph, budget }): string | null The map: hierarchy when structural edges justify it, headings when the graph has them, otherwise the most load-bearing nodes.
renderWiki lib/agentic/knowledge/render.mjs renderWiki({ graph, dir }): { dir: string; dirWritten: string; pages: number; sha: string; } Renders the wiki.
resolveBundleTarget lib/agentic/knowledge/okf.mjs resolveBundleTarget({ root, from, target }): string | null Resolves a link or path field against a bundle root.
resolveProfile lib/agentic/knowledge/model.mjs resolveProfile({ profile }): KnowledgeProfile Resolves a profile by name, or accepts a caller-supplied shape.
retrieveSubgraph lib/agentic/knowledge/query.mjs retrieveSubgraph({ graph, text, ids, embedder, depth, limit, scorer, edgeFilter, direction, hubDamping, includeDeprecated }): Promise<{ nodes: Array<RankedNode>; edges: import('./model.mjs').KnowledgeEdge[]; seeds: Array… The whole read path: seed → expand → rank.
SALIENCE lib/agentic/knowledge/model.mjs SALIENCE: readonly string[] Salience ladder, most to least load-bearing.
salienceWeight lib/agentic/knowledge/query.mjs salienceWeight({ node }): number —
saveGraph lib/agentic/knowledge/store.mjs saveGraph({ dir, graph }): Promise<string> Writes the graph and stamps its stats + hash.
saveOntology lib/agentic/knowledge/store.mjs saveOntology({ dir, ontology }): Promise<string> Writes the vocabulary.
seedNodes lib/agentic/knowledge/query.mjs seedNodes({ graph, text, ids, embedder, limit, scorer, includeDeprecated }): Promise<{ seeds: Array<string>; similarity: Map<string, number>; scoredIds: Array<string>; }> Picks seed nodes from three channels.
SEMANTIC_RELATIONS lib/agentic/knowledge/model.mjs SEMANTIC_RELATIONS: readonly string[] Semantic relations assert a reading, so they need a note.
sentenceList lib/agentic/knowledge/build.mjs sentenceList({ text }): Array<{ start: number; end: number; text: string; }> Sentences inside a block, by terminal punctuation.
slug lib/agentic/knowledge/build.mjs slug({ value }): string Lowercase, accent-folded, hyphenated key.
sourceDelta lib/agentic/knowledge/cache.mjs sourceDelta({ stored, current }): { added: Array<string>; changed: Array<string>; removed: Array<string>; unchanged: Array<string>; clean: boolean; } What changed between the corpus a graph was built from and the one on disk.
sourceSha lib/agentic/knowledge/build.mjs sourceSha({ text }): string Content hash of a whole source, for the corpus manifest.
sourceSlice lib/agentic/knowledge/model.mjs sourceSlice({ node, sources }): string | null The exact source text a node points at, when the caller supplied the sources.
statsOf lib/agentic/knowledge/model.mjs statsOf({ nodes, edges }): { nodes: number; edges: number; kinds: Record<string, number>; relations: Record<string, number>; coverage: number; } Counts nodes, edges, kinds and relation usage.
STRUCTURAL_RELATIONS lib/agentic/knowledge/model.mjs STRUCTURAL_RELATIONS: readonly string[] Relations that expand freely during traversal (structure, not judgement).
surfaceFragment lib/agentic/knowledge/adapters.mjs surfaceFragment({ surface, input, profile }): { nodes: Array<import('./model.mjs').KnowledgeNode>; edges: Array<import('./model.mjs').KnowledgeEdge>; sources: Array<import('./model.mjs').KnowledgeSourceRecord>; surface?:… Runs one surface's adapter.
syncCorpus lib/agentic/knowledge/cache.mjs syncCorpus(options?: SyncCorpusOptions): Promise<{ graph: import('./model.mjs').KnowledgeGraph; delta: { added: Array<string>; changed: Array<string>; removed: Array<string>; unchanged: Array<string>; clean: boolean; };… Load-or-build.
temporalView lib/agentic/knowledge/model.mjs temporalView({ graph, at }): KnowledgeGraph The graph as it stood at one instant: nodes outside their validity window are dropped with every edge that touches them.
TIERS lib/agentic/knowledge/model.mjs TIERS: readonly string[] Evidence tiers, from the legal corpus (`F`ull-text verified → `P`rovisional).
tierWeight lib/agentic/knowledge/query.mjs tierWeight({ node }): number Evidence tier, keeping the corpus's hedging in the ranking.
todosSurface lib/agentic/knowledge/adapters.mjs todosSurface({ store }): { nodes: import('./model.mjs').KnowledgeNode[]; edges: import('./model.mjs').KnowledgeEdge[]; } The `todos` surface: tasks and their declared dependencies.
tokensOf lib/agentic/knowledge/query.mjs tokensOf({ text, normalize, ngrams, stopwords }): Array<string> —
trustTier lib/agentic/knowledge/okf.mjs trustTier({ generated, verified }): 'unverified' | 'machine-confirmed' | 'human-reviewed' The OKF trust tier.
validateGraph lib/agentic/knowledge/model.mjs validateGraph({ graph, profile, strict, wikiSha, sources, promoteAfter, sourcePolicy }): { schema: string; status: 'pass' | 'warn' | 'fail'; ok: boolean; strict: boolean; graphSha: string; summary: { nodes: number; edges… Validates a graph.
wikiSurface lib/agentic/knowledge/adapters.mjs wikiSurface({ dir, profile, title, hierarchy, nested }): import('./model.mjs').KnowledgeGraph The `wiki` surface: an existing markdown corpus becomes a reference graph.

Named exports of merci-sdk/messaging

attachNativecountConversationTurnscreateAssistantMessagecreateSystemMessagecreateToolCallMessagecreateToolCallMessagescreateToolResultMessagecreateUserMessagededupeMessagesgetNativeisGenuineUserTurnisInjectionnormalizeHistorynormalizeToAAInormalizeToGAInormalizeToOAIstripInjectionMeta
Export Module Signature Summary
attachNative lib/messaging/messages.mjs attachNative({ row, provider, protocol, items }): MessageRow Attaches the provider-native replay payload to a row (non-wire; stripped by every normalizer).
countConversationTurns lib/messaging/unified-message.mjs countConversationTurns({ messages }): number Counts genuine conversation turns (user messages), ignoring SDK row-injections and tool-result carriers (role:'tool' messages, tool_message rows, and tool_result / functionResponse content blocks).
createAssistantMessage lib/messaging/messages.mjs createAssistantMessage({ provider, content, thoughtSignature, reasoningContent, redactedThinking }): MessageRow Creates an assistant text message, optionally carrying a thought signature (and DeepSeek-style `reasoning_content` for multi-turn continuity).
createSystemMessage lib/messaging/messages.mjs createSystemMessage({ provider, content }): MessageRow Creates a system message in the backend's wire shape.
createToolCallMessage lib/messaging/messages.mjs createToolCallMessage({ provider, id, name, args, thoughtSignature, calls }): MessageRow Creates an assistant tool-call message in the backend's wire shape.
createToolCallMessages lib/messaging/messages.mjs createToolCallMessages({ provider, calls, thoughtSignature }): Array<MessageRow> Creates the assistant tool-call row(s) for one model turn.
createToolResultMessage lib/messaging/messages.mjs createToolResultMessage({ provider, result, thoughtSignature, protocol }): MessageRow Creates a tool result message in the target backend's wire shape.
createUserMessage lib/messaging/messages.mjs createUserMessage({ provider, content }): MessageRow Creates a user message in the backend's wire shape.
dedupeMessages lib/messaging/messages.mjs dedupeMessages({ messages }): Array<MessageRow> Removes duplicate rows by their stable merciId.
getNative lib/messaging/messages.mjs getNative({ row }): { provider: string; protocol: string | null; items: Array<MessageRow>; } | null Reads a row's provider-native replay payload, or null when absent.
isGenuineUserTurn lib/messaging/unified-message.mjs isGenuineUserTurn({ m }): boolean True when `m` is a genuine user turn (not a tool-result carrier).
isInjection lib/messaging/unified-message.mjs isInjection({ m, capId }): boolean True when `m` is an SDK row-injection.
normalizeHistory lib/messaging/messages.mjs normalizeHistory({ provider, messages, options }): Array<MessageRow> Normalizes a mixed-shape history to the backend's wire format.
normalizeToAAI lib/messaging/messages.mjs normalizeToAAI({ msgs }): { messages: Array<MessageRow>; system: string | Array<{ type: 'text'; text: string; cache_control?: CacheControl; }> | null; } Centralized normalization of unified/OAI/GAI-style messages to Anthropic format.
normalizeToGAI lib/messaging/messages.mjs normalizeToGAI({ msgs, effectiveThoughtSignature }): { contents: Array<{ role: string; parts: Array<MessageRow>; }>; systemInstruction: string | null; } Centralized normalization of unified/OAI messages to Google GenAI Content format.
normalizeToOAI lib/messaging/messages.mjs normalizeToOAI({ model, msgs, opts }): Array<MessageRow> Centralized normalization of unified messages to OpenAI shape.
stripInjectionMeta lib/messaging/messages.mjs stripInjectionMeta({ messages, keepNative }): Array<MessageRow> Returns a copy of `messages` with the non-wire keys (INJECTION_META_KEY, MERCI_ID_KEY and — unless `keepNative` — MERCI_NATIVE_KEY) removed from every message.

Named exports of merci-sdk/oai

ChatSessionMerciClient
Export Module Signature Summary
ChatSession lib/backends/oai.mjs class ChatSession extends BaseChatSession Manages a chat session with an LLM.
MerciClient lib/backends/oai.mjs class MerciClient extends EventEmitter Main Merci SDK client.

Named exports of merci-sdk/operator

createEventRingcreateOperatorHttpHandlerDEFAULT_PREFIXESformatStatusOPERATOR_API_VERSIONOPERATOR_DEFAULTS
Export Module Signature Summary
createEventRing lib/agentic/operator/ring.mjs createEventRing({ emitter, limit, prefixes, now }): { list: (arg0?: { identifier?: string | null; limit?: number | null; }) => Array<Record<string, unknown>>; clear: () => void; stop: () => void; } —
createOperatorHttpHandler lib/agentic/operator/http.mjs createOperatorHttpHandler({ getSnapshot, getPolicySnapshot, refresh, recentEvents, basePath, statusPath, allowedHosts, allowAnyHost, maxBodyBytes, recentEventsLimit, statusMaxRows, now }): (req: import('node:http').Incom… Create a `(req, res) => Promise<void>` operator handler (§3.3). `queued: true` means this request invoked `refresh()`; `coalesced: true` means another handler request was already invoking it. A scheduler-internal in-flight tick is invisible…
DEFAULT_PREFIXES lib/agentic/operator/ring.mjs DEFAULT_PREFIXES: readonly string[] The orchestrator namespaces the ring records by default.
formatStatus lib/agentic/operator/status.mjs formatStatus({ snapshot, policy, now, maxRows }): string Render one snapshot as plain text (§3.7).
OPERATOR_API_VERSION lib/agentic/operator/index.mjs OPERATOR_API_VERSION = 1 The operator API response version.
OPERATOR_DEFAULTS lib/agentic/operator/index.mjs OPERATOR_DEFAULTS: Readonly<{ basePath: "/api/v1"; statusPath: "/"; readonly maxBodyBytes: number; readonly ringLimit: number; readonly recentEventsLimit: number; readonly statusMaxRows: number; allowedHosts: string[]; }… The documented defaults for `createOperatorHttpHandler` (§3.8). The numeric entries read the limit registry on access, so a host's limits apply to the next handler.

Named exports of merci-sdk/orchestration

createOrchestration
Export Module Signature Summary
createOrchestration lib/agentic/orchestration/facade.mjs createOrchestration(options?: OrchestrationOptions): Promise<Orchestration> Build the coordination layer around one client, one board, and one `WORKFLOW.md`.

Named exports of merci-sdk/otel

createOtlpExporterotelAttribute
Export Module Signature Summary
createOtlpExporter lib/support/otel-exporter.mjs createOtlpExporter({ endpoint, serviceName, serviceVersion, headers, batchSize, flushIntervalMs, resourceAttributes, fetchImpl }): OtlpExporter Creates an OTLP/HTTP JSON exporter for the SDK event stream.
otelAttribute lib/support/otel-exporter.mjs otelAttribute({ key, value }): OtlpAttribute | null Encodes one OTLP attribute.

Named exports of merci-sdk/planning

ApprovalCoordinatorassertStateSchemaCHECKPOINT_KINDcollectTemplateRefsgetLeafOutputinterpolateTemplatePlanPLAN_VERSIONrestoreCheckpointsaveCheckpointsortDagNodesstructuredLlmCallTaskStateunwrapCheckpointvalidateTemplateRefsWorkflowEvaluatorWorkflowExecutorWorkflowPlannerwrapCheckpoint
Export Module Signature Summary
ApprovalCoordinator lib/agentic/planning/approval.mjs class ApprovalCoordinator A single HITL approval gate.
assertStateSchema lib/agentic/planning/graph-utils.mjs assertStateSchema({ schema, value, label }): void Asserts a step/node output against an optional Zod-like state schema (`safeParse`). No-op when no schema is configured.
CHECKPOINT_KIND lib/agentic/planning/checkpoint.mjs CHECKPOINT_KIND: Readonly<{ CHAT: "chat"; STATE_MACHINE: "stateMachine"; WORKFLOW: "workflow"; }> Checkpoint payload kinds.
collectTemplateRefs lib/agentic/planning/graph-utils.mjs collectTemplateRefs({ template }): Array<{ expr: string; head: string; }> Collects `{{expr}}` template references from a string.
getLeafOutput lib/agentic/planning/graph-utils.mjs getLeafOutput({ stepsMap, outputs }): { output: string; sourceId: string | null; } Returns the last (leaf) healthy step output from a completed workflow.
interpolateTemplate lib/agentic/planning/graph-utils.mjs interpolateTemplate({ template, outputs, stepId, emitter, context, known }): string Interpolates `{{expr}}` references in a template against step outputs and run context (dotted paths supported).
Plan lib/agentic/planning/plan.mjs class Plan One plan, two executor views.
PLAN_VERSION lib/agentic/planning/plan.mjs PLAN_VERSION = 1 —
restoreCheckpoint lib/agentic/planning/checkpoint.mjs restoreCheckpoint({ saved, kind, args }): Object | string | null Restores a checkpoint of the expected kind.
saveCheckpoint lib/agentic/planning/checkpoint.mjs saveCheckpoint({ store, threadId, kind, payload }): Promise<string> Saves a tagged checkpoint through a session store.
sortDagNodes lib/agentic/planning/graph-utils.mjs sortDagNodes({ steps }): Array<string> Kahn's topological sort of the given steps.
structuredLlmCall lib/agentic/planning/planner-utils.mjs structuredLlmCall<T>({ client, model, systemMessage, schema, prompt, label, schemaName, useToolCapture, maxAttempts, timeoutMs, sessionId, signal, onUsage }): Promise<T> Calls the LLM and returns structured data matching `schema`. Retries parse failures with fresh sessions up to maxAttempts; aborts rethrow immediately.
TaskState lib/agentic/planning/task-state.mjs class TaskState The serializable state of one workflow (DAG) run.
unwrapCheckpoint lib/agentic/planning/checkpoint.mjs unwrapCheckpoint({ saved }): { version: number; kind: string; payload: string; } | null Reads a checkpoint envelope back out of a saved record.
validateTemplateRefs lib/agentic/planning/graph-utils.mjs validateTemplateRefs({ steps, contextRoots, fields, knownIds, ancestorsOnly, graph }): { unknown: Array<{ stepId: string; expr: string; }>; nonAncestor: Array<{ stepId: string; expr: string; via: string[]; }>; } Validates that every `{{...}}` reference in each step's `userPromptTemplate` names a known step id or an allowed context root, and — with `ancestorsOnly` — that a step id it names is one of that step's **ancestors**. Returns both lists so t…
WorkflowEvaluator lib/agentic/planning/evaluator.mjs class WorkflowEvaluator Structured LLM verifier for completed workflow steps.
WorkflowExecutor lib/agentic/planning/executor.mjs class WorkflowExecutor extends EventEmitter Executes a DAG of steps to completion, emitting `workflow:*` events on its EventEmitter.
WorkflowPlanner lib/agentic/planning/planner.mjs class WorkflowPlanner LLM DAG planner: produces the step plan and the self-healing replan.
wrapCheckpoint lib/agentic/planning/checkpoint.mjs wrapCheckpoint({ kind, payload }): CheckpointEnvelope Tags a payload string with its kind.

Named exports of merci-sdk/scheduler

CLAIM_STATEScreateEngineRunnercreateFileAttemptStorecreateFileClaimStorecreateFunctionWorkSourcecreateJsonFileWorkSourcecreateMemoryAttemptStorecreateMemoryClaimStorecreateMemoryWorkSourcecreateTodoWorkSourcenormalizeWorkItemSCHEDULER_DEFAULTSsortForDispatchWORK_SOURCE_CATEGORIESWorkScheduler
Export Module Signature Summary
CLAIM_STATES lib/agentic/scheduler/state.mjs CLAIM_STATES: Readonly<Record<string, ClaimState>> The scheduler's claim-state vocabulary (§3.3). Frozen; the values are the serialized names.
createEngineRunner lib/agentic/scheduler/runner.mjs createEngineRunner(options?: { engine?: string; client?: unknown; model?: unknown; store?: unknown; tools?: unknown; budget?: unknown; approval?: unknown; prompt?: unknown; objective?: unknown; planFor?: unknown; planner… Build the one-attempt runner for a scheduler.
createFileAttemptStore lib/agentic/scheduler/attempt-store.mjs createFileAttemptStore({ dir }): AttemptStore File-backed attempt store: one `<slug>.<hash>.json` per identifier.
createFileClaimStore lib/agentic/scheduler/claims.mjs createFileClaimStore({ dir, staleMs, hostId, now }): ClaimStore File-backed claim store: one `<key>.json` per identifier.
createFunctionWorkSource lib/agentic/scheduler/work-sources/function.mjs createFunctionWorkSource({ fetchByStates, fetchByIds, eventEmitter }): { fetchByStates: (arg0: { states: Array<string>; signal?: AbortSignal; }) => Promise<ReadonlyArray<WorkItem>>; fetchByIds: (arg0: { ids: Array<string… Create a work source backed by two host functions.
createJsonFileWorkSource lib/agentic/scheduler/work-sources/json-file.mjs createJsonFileWorkSource({ dir, eventEmitter }): Promise<{ fetchByStates: (arg0: { states: unknown; signal?: AbortSignal; }) => Promise<ReadonlyArray<WorkItem>>; fetchByIds: (arg0: { ids: unknown; signal?: AbortSignal; }… Create a read-only work source over a directory of `*.json` files.
createMemoryAttemptStore lib/agentic/scheduler/attempt-store.mjs createMemoryAttemptStore(): AttemptStore In-process attempt store.
createMemoryClaimStore lib/agentic/scheduler/claims.mjs createMemoryClaimStore(): ClaimStore In-process claim store.
createMemoryWorkSource lib/agentic/scheduler/work-sources/memory.mjs createMemoryWorkSource({ items, eventEmitter }): { fetchByStates: (arg0: { states: unknown; signal?: AbortSignal; }) => ReadonlyArray<WorkItem>; fetchByIds: (arg0: { ids: unknown; signal?: AbortSignal; }) => ReadonlyArra… Create a work source over an in-memory array.
createTodoWorkSource lib/agentic/scheduler/work-sources/todos.mjs createTodoWorkSource({ store, includeInternal, eventEmitter }): { fetchByStates: (arg0: { states: unknown; signal?: AbortSignal; }) => ReadonlyArray<WorkItem>; fetchByIds: (arg0: { ids: unknown; signal?: AbortSignal; })… Create a read-only work source over a `TodoComponent`-style store.
normalizeWorkItem lib/agentic/scheduler/normalize.mjs normalizeWorkItem({ raw, source }): Readonly<WorkItem> Normalize one raw adapter record into a frozen `WorkItem`. Required fields (`id`, `identifier`, `title`, `state`) must be non-empty strings after trimming; `dispatchable` must be an explicit boolean.
SCHEDULER_DEFAULTS lib/agentic/scheduler/state.mjs SCHEDULER_DEFAULTS: Readonly<{ pollIntervalMs: number; stallTimeoutMs: number; retry: Readonly<{ baseMs: number; maxMs: number; }>; continuation: Readonly<{ delayMs: number; max: number; }>; concurrency: Readonly<{ globa… The §3.14 construction defaults.
sortForDispatch lib/agentic/scheduler/normalize.mjs sortForDispatch({ items }): WorkItem[] Order items for dispatch without mutating the input.
WORK_SOURCE_CATEGORIES lib/agentic/scheduler/work-sources/index.mjs WORK_SOURCE_CATEGORIES: ReadonlyArray<WorkSourceCategory> The Symphony §11.4 categories, in their canonical order.
WorkScheduler lib/agentic/scheduler/scheduler.mjs class WorkScheduler The work-item scheduler: claims, dispatch, retries, parking, and a single-flight tick.

Named exports of merci-sdk/sessions

InMemorySessionStoreLocalFileSessionStore
Export Module Signature Summary
InMemorySessionStore lib/agentic/sessions.mjs class InMemorySessionStore A `SessionStore` in a `Map`: for tests, evals and short-lived processes.
LocalFileSessionStore lib/agentic/sessions.mjs class LocalFileSessionStore File-backed checkpoint store.

Named exports of merci-sdk/tools

A2A_COMPLETED_STATESAcpCapabilitycancelA2ATaskcapToolOutputcapToolOutputValuecreateA2AHttpHandlercreateA2AServercreateContextToolscreateMcpHttpHandlercreateMcpServercreateShellPolicyToolcreateShellToolDEFAULT_TOOL_OUTPUT_MAX_LENGTHEMPTY_OBJECT_SCHEMAexecuteToolsExternalToolCapabilityextractXmlToolCallsFileMcpTaskStoreflattenContentgetA2ATaskloadA2AToolloadMcpToolsloadMcpToolsFromloadSkillsFromDirectorymapToolsToConfigmarkToolErrorRetryableMCP_MAX_OUTPUT_LENGTHMCP_TASK_PAGE_SIZEMcpClientMcpTaskStoreraceWithAbortSkillsLibraryTOOL_OUTPUT_TRUNCATION_SUFFIXwithToolTimeout
Export Module Signature Summary
A2A_COMPLETED_STATES lib/tools/a2a.mjs A2A_COMPLETED_STATES: readonly string[] The A2A task states that mean the task has ended, whichever dialect spelled it. Frozen: it is a shared export, and a consumer that mutated it would change the answer for every other consumer in the process.
AcpCapability lib/tools/external-capability.mjs class AcpCapability extends ExternalToolCapability Agent Client Protocol (ACP) capability — a duck-typed remote-tool adapter.
cancelA2ATask lib/tools/a2a.mjs cancelA2ATask({ agentUrl, taskId, headers, timeoutMs, dialect }): Promise<boolean> Cancels a remote A2A task.
capToolOutput lib/tools/external-capability.mjs capToolOutput<T>({ text, maxLength }): T Non-strings pass through untouched.
capToolOutputValue lib/tools/external-capability.mjs capToolOutputValue({ value, maxLength, maxDepth }): { value: unknown; truncated: boolean; } Caps a tool result of **any** shape to a character budget, without changing its type.
createA2AHttpHandler lib/tools/a2a-server.mjs createA2AHttpHandler({ server, path, cardPath, allowedHosts, allowAnyHost, authorize }): (req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => Promise<void> Mounts an A2A server on a `node:http` server.
createA2AServer lib/tools/a2a-server.mjs createA2AServer({ name, description, version, skills, documentationUrl, provider, inputModes, outputModes, now, maxTerminalTasks, taskRetentionMs }): { agentCard: (opts?: { baseUrl?: string; }) => Record<string, unknown>… Creates an A2A server exposing the given skills.
createContextTools lib/tools/context-tools.mjs createContextTools({ options }): Array<import('./tool-execution.mjs').ReadyTool> The context tools — read, grep and glob over the working directory, as one tool set.
createMcpHttpHandler lib/tools/mcp-server.mjs createMcpHttpHandler(options?: { name?: string; version?: string; tools?: Array<import('./tool-execution.mjs').ToolDefinition>; root?: string; resources?: McpResourceDef[]; prompts?: McpPromptDef[]; sessionIdGenerator?:… Creates an MCP server over the Streamable HTTP transport and returns a `node:http` request handler that serves it. Three session models are supported: - **stateful** (default): one server and transport per MCP session.
createMcpServer lib/tools/mcp-server.mjs createMcpServer({ name, version, tools, root, resources, prompts, mcpProtocolVersion, legacy, taskStore, journal, approval, runContext }): Promise<McpServerHandle> Creates an MCP stdio server exposing the given tools, connected to stdin/stdout.
createShellPolicyTool lib/tools/shell-tools.mjs createShellPolicyTool({ options }): import('./tool-execution.mjs').ReadyTool `describe_shell_policy`: the effective tier of one shell-tool instance, so a model reads the host's real allowlists instead of guessing from the defaults.
createShellTool lib/tools/shell-tools.mjs createShellTool({ options }): import('./tool-execution.mjs').ReadyTool The shell tool — runs a command in the working directory, behind the approval gate.
DEFAULT_TOOL_OUTPUT_MAX_LENGTH lib/tools/external-capability.mjs DEFAULT_TOOL_OUTPUT_MAX_LENGTH: number Default byte cap on a single remote tool result's text.
EMPTY_OBJECT_SCHEMA lib/messaging/tool-schema.mjs EMPTY_OBJECT_SCHEMA: Readonly<{ type: "object"; properties: {}; }> Frozen empty JSON schema, used wherever a tool declares no parameters.
executeTools lib/tools/tool-execution.mjs executeTools({ toolCalls, toolLibrary, signal, emitter, runContext, approval, journal, boundary, hooks, toolTimeoutMs, maxParallelTools, permissionMode }): Promise<Array<Object>> `{ id, tool_call_id, name, success, result|error }` envelope; tool errors are returned (not thrown), while AbortError rethrows as cancellation.
ExternalToolCapability lib/tools/external-capability.mjs class ExternalToolCapability extends LoadableComponent A remote tool family surfaced as a capability: the tool definitions do the work (tools-first), `load()` renders a short catalog listing for the model, and there is no save leg (toSaveTool() is null — no saveToolName passed).
extractXmlToolCalls lib/messaging/tool-schema.mjs extractXmlToolCalls({ text }): Array<{ id: string; name: string; arguments: string; }> Extracts `<tool_call>` blocks from model text.
FileMcpTaskStore lib/tools/mcp-task-store.mjs class FileMcpTaskStore extends McpTaskStore A durable store: one JSON record per task under `dir`, reloaded on construction, so a task and its result survive a restart.
flattenContent lib/tools/tool-execution.mjs flattenContent({ result }): unknown string the other tool families produce.
getA2ATask lib/tools/a2a.mjs getA2ATask({ agentUrl, taskId, headers, timeoutMs }): Promise<{ state: string; taskId: string; contextId: string; text: string; artifacts: string[]; }> Reads a remote A2A task by id.
loadA2ATool lib/tools/a2a.mjs loadA2ATool({ agentUrl, eventEmitter, agentContext, headers, timeoutMs, requiresApproval }): Promise<A2AToolDef[]> (returns []) when the agent card cannot be loaded or the URL is invalid.
loadMcpTools lib/tools/mcp-client.mjs loadMcpTools({ mcpClient, trustReadOnlyHints }): Promise<McpToolSet> (schema normalization + output capping).
loadMcpToolsFrom lib/tools/mcp-client.mjs loadMcpToolsFrom({ command, args, options }): Promise<McpToolSet> Loads a remote MCP server's tools.
loadSkillsFromDirectory lib/tools/skills.mjs loadSkillsFromDirectory({ directory, eventEmitter, requireScriptApproval, inheritEnv }): Promise<Array<SkillTool>> Missing roots and missing SKILL.md files are normal skips; corruption is surfaced via sdkWarn and the SKILLS.LOAD_ERROR event.
mapToolsToConfig lib/messaging/tool-schema.mjs mapToolsToConfig({ tools }): Array<Object> Maps tool definitions onto a wire config shape: keeps only the wire fields (name/description/parameters) and wraps each schema under `parameters.schema`.
markToolErrorRetryable lib/tools/tool-execution.mjs markToolErrorRetryable<T extends Error>(error: T): T Marks a tool error as a **pre-effect** failure: the tool knows its side effect did not start, so a resume may safely run the call again.
MCP_MAX_OUTPUT_LENGTH lib/tools/mcp-client.mjs MCP_MAX_OUTPUT_LENGTH: number Byte cap on a single MCP tool result's text.
MCP_TASK_PAGE_SIZE lib/tools/mcp-task-store.mjs MCP_TASK_PAGE_SIZE: number Tasks returned by one `tasks/list` page.
McpClient lib/tools/mcp-client.mjs class McpClient Thin lifecycle wrapper around the MCP client.
McpTaskStore lib/tools/mcp-task-store.mjs class McpTaskStore In-memory task store: a task record, its abort controller and its retention timer.
raceWithAbort lib/tools/tool-execution.mjs raceWithAbort<T>({ promise, signal }): Promise<T> ignores the signal can no longer wedge the whole tool round.
SkillsLibrary lib/tools/skills.mjs class SkillsLibrary extends LoadableComponent Loadable component exposing the registered skills to the model via a list-skills load tool.
TOOL_OUTPUT_TRUNCATION_SUFFIX lib/tools/external-capability.mjs TOOL_OUTPUT_TRUNCATION_SUFFIX = "\n...[TRUNCATED TO PREVENT TOKEN OVERFLOW]" Suffix marking a capped tool result.
withToolTimeout lib/tools/tool-execution.mjs withToolTimeout<T>({ promise, timeoutMs, signal }): Promise<T> Caps a tool call that outlives its budget.

Named exports of merci-sdk/workflow-policy

createPolicyRendererloadWorkflowFileparseWorkflowMarkdownpolicyToSchedulerOptionspolicyToWorkspaceOptionsrenderPromptTemplateresolveWorkflowConfigWORKFLOW_POLICY_DEFAULTSWORKFLOW_POLICY_REASONSWORKFLOW_POLICY_WARNINGSWorkflowPolicy
Export Module Signature Summary
createPolicyRenderer lib/agentic/workflow-policy/integrate.mjs createPolicyRenderer({ policy, eventEmitter }): (arg0: { item: Record<string, unknown>; attempt?: unknown; continuation?: boolean; }) => string The engine runner's `({ item, attempt, continuation }) => string` prompt callback.
loadWorkflowFile lib/agentic/workflow-policy/file.mjs loadWorkflowFile({ path, env, maxFileBytes, now }): Promise<{ path: string; baseDir: string; config: import('./config.mjs').ResolvedWorkflowConfig; promptTemplate: string; warnings: readonly string[]; loadedAt: number; }… Reads, parses, and resolves one workflow file.
parseWorkflowMarkdown lib/agentic/workflow-policy/file.mjs parseWorkflowMarkdown({ markdown, path }): { config: Record<string, unknown>; promptTemplate: string; } Parses a `WORKFLOW.md` string.
policyToSchedulerOptions lib/agentic/workflow-policy/integrate.mjs policyToSchedulerOptions({ policy }): SchedulerOptions The scheduler options from the resolved policy.
policyToWorkspaceOptions lib/agentic/workflow-policy/integrate.mjs policyToWorkspaceOptions({ policy }): WorkspaceOptions The construction-bound workspace options.
renderPromptTemplate lib/agentic/workflow-policy/template.mjs renderPromptTemplate({ template, issue, attempt, maxRenderedChars, maxDepth }): string Parses and renders in one call.
resolveWorkflowConfig lib/agentic/workflow-policy/config.mjs resolveWorkflowConfig({ config, baseDir, env, home }): { config: ResolvedWorkflowConfig; warnings: string[]; } Resolves the inert front matter into the one validated, frozen config.
WORKFLOW_POLICY_DEFAULTS lib/agentic/workflow-policy/config.mjs WORKFLOW_POLICY_DEFAULTS: Readonly<{ path: string; watch: boolean; debounceMs: number; maxFileBytes: number; maxTemplateDepth: number; maxRenderedChars: number; promptFallback: string; }> —
WORKFLOW_POLICY_REASONS lib/agentic/workflow-policy/config.mjs WORKFLOW_POLICY_REASONS: readonly string[] Every error reason this slice can emit; `reasons` entries are `<code>` or `<code>:<detail>`.
WORKFLOW_POLICY_WARNINGS lib/agentic/workflow-policy/config.mjs WORKFLOW_POLICY_WARNINGS: readonly string[] Every warning code this slice can emit.
WorkflowPolicy lib/agentic/workflow-policy/policy.mjs class WorkflowPolicy A reload is single-flight, keeps the last good state on failure, and arms a debounced watcher only after the first load succeeds.

Named exports of merci-sdk/workspace

createWorkspaceToolsisInsideRootresolveWorkspacePathWORKSPACE_HOOKSWORKSPACE_STRATEGIESworkspaceKeyForWorkspaceManager
Export Module Signature Summary
createWorkspaceTools lib/agentic/workspace/toolbox.mjs createWorkspaceTools({ workspace, approvalCallback, eventEmitter, include, artifactsDir, context, shell, permissionMode, resolvePolicy }): { workspace: import('./manager.mjs').WorkspaceHandleLike; root: string; contextTo… Bind `read`/`grep`/`glob`, the shell tool, and the artifact tool to one workspace handle.
isInsideRoot lib/support/path-safety.mjs isInsideRoot({ root, path }): boolean True when `path` is `root` itself or sits below it. A bare string prefix would accept `/root2` for the root `/root`; the separator is part of the test.
resolveWorkspacePath lib/agentic/workspace/paths.mjs resolveWorkspacePath({ root, key }): string Resolve one workspace path under a root and assert containment, without IO.
WORKSPACE_HOOKS lib/agentic/workspace/hooks.mjs WORKSPACE_HOOKS: Readonly<{ AFTER_CREATE: "afterCreate"; BEFORE_RUN: "beforeRun"; AFTER_RUN: "afterRun"; BEFORE_REMOVE: "beforeRemove"; }> The four lifecycle hooks, in call order.
WORKSPACE_STRATEGIES lib/agentic/workspace/manager.mjs WORKSPACE_STRATEGIES: Readonly<{ DIRECTORY: "directory"; GIT_WORKTREE: "git-worktree"; }> The strategies, frozen so a caller cannot mutate the registry.
workspaceKeyFor lib/agentic/workspace/keys.mjs workspaceKeyFor({ workItemId }): string Derive the workspace directory name for a work item id. Deterministic: the same id always yields the same key, on any host.
WorkspaceManager lib/agentic/workspace/manager.mjs class WorkspaceManager —