The Stellar Agent Guard SDK exposes the following public surface. For the narrative pitch and quickstart, see the repository README.
0.x API Policy & Deprecations: During
0.x, this package adheres to an additive-only within minor policy (0.1.xreleases are additive and fixes only; breaking changes and deprecation removals occur only at minor boundaries like0.2.0). For full policy details, deprecation mechanics, and the tracking table, seedeprecations.md. Release process and versioning checklist:releasing.md.
Every constructor options object has a table (Option | Type | Default | Meaning) with source-verified defaults and PreFlightInterceptorOptions and its nested cache/check/batch options, CostPreCheckConfig / CostPreCheckOptions, GuardTelemetryConfig, and InvokeOptions. The same tables appear in the README's Constructor options.
PreFlightInterceptorconstructor(options: PreFlightInterceptorOptions)— Options table. Passcache: { ttlMs }orcache: { ttlLedgers }to opt into the short-lived cache; omit it for fresh simulations. AddmaxEntriesto bound the cache's cardinality with least-recently-used eviction.check(call: ContractCall): Promise<PreFlightDecision>— Returnsadmissible | blocked | undeterminedwithout throwing or broadcasting.checkBatch(calls: ContractCall[], options?: CheckBatchOptions): Promise<PreFlightBatchDecision>— Stages SAC transfer amounts against the committed window, with anundeterminedbatch verdict when a required policy/window read fails. An explicitinitialWindowSpent: 0nis a trusted snapshot; a failed read is not treated as zero.staging.sourcereportsprovided | ledger | absent | unavailable.assertAllowed(call: ContractCall): Promise<PreFlightDecision & { allowed: true }>— Evaluates a call and returns the decision, or throwsGuardBlockedErroron policy block orGuardUndeterminedErroron undetermined/transport failures. Never lets raw transport errors escape.assertBatchAllowed(calls: ContractCall[], options?: CheckBatchOptions): Promise<PreFlightBatchDecision & { admissible: true }>— Batch throw-on-refusal form. Returns the batch decision if all calls are admissible, or throwsGuardBlockedErroron the first blocked call orGuardUndeterminedErroron an undetermined call or transport failure.invalidate(call?: ContractCall): void— Clears all cached decisions or only entries for one call.
CostPreCheckerconstructor(config: CostPreCheckConfig)— Options table. There is no separateCostPreCheckerOptionstype.check(call: ContractCall): Promise<CostPreCheckResult>— Returnswithin_budget | over_budget | blocked | undetermined.checkWithCost(call: ContractCall): Promise<{ decision, cost }>— Returns the interceptor verdict and the cost of the same single simulation. Prefer this over callingcheck()on both classes.
invoke(options: InvokeOptions): Promise<InvokeResult>— Options table. End-to-end pipeline: probe, sign auth, simulate, and broadcast. Accepts an optionalonStep(step: InvokeStepEvent)hook reporting per-stagestart/ok/failtiming events with a 0-based retryattemptindex; callback exceptions are isolated and omitting the hook changes nothing.invoke(options)/invoke({ ...options, dryRun: true })— Broadcasts an admissible result, or returns the full pre-broadcast dry-run trace.invoke({ ...options, onSubmitted })— An optionalonSubmitted(event: SubmissionAcceptedEvent)hook, called once as soon as the network accepts the broadcast and before any confirmation polling, carrying the transaction hash (hash: nullwhen the broadcast response named no transaction — that submission fails closed). Every outcome that happened after a broadcast carries the same hash astransactionHash, so a failed poll or a spent deadline never costs the caller its recovery handle. See the invoke pipeline.submitSetPolicy(params)/submitFreeze(params)/submitUnfreeze(params)/submitRotateAgentKey(params)— The administrative submissions (set_policy,freeze,unfreeze,rotate_agent_key), each running the fullinvoke()pipeline with the admin signer as the authorizer. Besidesserver,guard,adminandsource, they acceptdryRun,pollAttempts,pollIntervalMs, and — like a normal invocation —signalandtimeoutMs. An already-aborted signal short-circuits before any RPC and returns the documented typed outcome (theerrorarm carrying anRpcTimeoutErrorwithaborted: true); a fired per-call timeout is reported the same way. Neither option relaxes the administrative authorization behaviour.startHeartbeat(options): Promise<HeartbeatHandle>— Drift-aware dead-man keep-alive. Firesheartbeat()on an interval, reports lateness (handle.missedBeats,onBeat'slateMs), routes every failure toonError, validatesinterval <= grace/3before the first beat when the grace window is readable, and stops cleanly (await handle.stop()).stop()requests cancellation through the submission context and waits for the in-flight beat;stop({ timeoutMs })/stopTimeoutMsbound that wait and return{ reason, settled, submission?, error? }. A submission that outlives several cadence slots skips the stale slots instead of firing a catch-up burst. See “Keep the dead-man switch alive”.submitHeartbeat(params): Promise<HeartbeatSubmission>— Signs and submits a singleheartbeat()with the agent's guard authorization; the default submissionstartHeartbeatuses. Accepts an optionalsignalforwarded to the underlyinginvoke()pipeline.HeartbeatIntervalError— Thrown before the first beat when the requested interval exceedsgrace / 3.HeartbeatBlockedError— The guard refused the heartbeat. A refusal is a decision, not a transport failure, so it is never retried (issue #340).isRetryableHeartbeatFailure(error): boolean— True only for the transport failures a bounded retry can plausibly fix: aBroadcastError, anRpcTimeoutError, aSimulationError. A policy refusal and an unclassifiable error are bothfalse(issue #340).DEFAULT_HEARTBEAT_RETRY_OPTIONS— The retry defaults:maxAttempts: 1(retries are opt-in),baseDelayMs: 250,maxDelayMs: 5_000(issue #340).
See the Agent Key Rotation and Recovery runbook for procedures to rotate the agent key of a custom account and recover from rotation failures.
startHeartbeat() validates its inputs before the scheduler exists, so a misconfiguration can never reach the first beat — and never even reads the grace window from the chain. Each failure names the offending field:
| Input | Accepted | Rejected |
|---|---|---|
intervalMs |
a positive, finite number | 0, negatives, NaN, Infinity (RangeError) |
maxSkewMs |
a finite, non-negative number | negatives, NaN, ±Infinity (RangeError) |
stopTimeoutMs |
a finite, non-negative number | negatives, NaN, ±Infinity (RangeError) |
graceSecs |
a non-negative bigint, or a non-negative safe integer |
negatives, fractions, NaN, ±Infinity, values beyond Number.MAX_SAFE_INTEGER (RangeError); a non-number, non-bigint (TypeError) |
onBeat, onError, onWarning, readPolicy, submit, now, wait |
a function | anything else (TypeError) |
retry.maxAttempts |
an integer >= 1 |
0, negatives, fractions (RangeError) |
retry.baseDelayMs, retry.maxDelayMs |
a finite number >= 0 |
negatives, NaN, ±Infinity (RangeError) |
A rejected startHeartbeat() submits nothing and reads no policy.
A failed heartbeat used to wait for the next fixed interval before trying again — so an RPC outage that landed near the grace boundary could freeze an account even after connectivity returned. retry adds a bounded, jittered retry:
const hb = await startHeartbeat({
server,
guard: GUARD_ID,
signer: agentKeypair,
intervalMs: 30_000,
retry: { maxAttempts: 3 }, // opt-in: the default is one attempt per beat
onWarning: (message) => logger.warn(message),
onError: (error) => logger.error("heartbeat failed", error),
});- Only transport failures are retried: a
BroadcastError, anRpcTimeoutErroror aSimulationError. A policy block is never retried — the guard made a decision, and hammering a call it has already refused only adds load. An error the SDK cannot classify is reported, not retried. - The delay before attempt n is a full-jitter sample of
[0, min(maxDelayMs, baseDelayMs · 2ⁿ⁻¹)), so agents that hit the same outage do not retry in a synchronized herd.retry.randommakes it deterministic. - The attempt that failed and the delay before the next one are announced through
onWarning; the failure that ends the beat is reported once throughonError, with the original error. Nothing escapes as an unhandled rejection. - A successful beat reports how many attempts it took in
onBeat'sattempt. - The backoff uses the same abortable wait as the cadence, so
stop()(or an abort) ends it at once and starts no further attempt.
submit(beat, { signal }) receives an AbortSignal that stop() aborts before it starts waiting. The default stop is still graceful: it waits for the submission promise to settle, so a transport that honours the signal shuts down promptly. A transport that may never settle can be bounded:
const result = await hb.stop({ timeoutMs: 5_000 });
// { reason: "completed" | "timeout" | "aborted", settled: boolean,
// submission?: HeartbeatSubmission, error?: unknown }stop() is idempotent: every call returns the same shared result. On a graceful settle the in-flight submission's value or terminal error is returned; on timeout/aborted, the submission has already been asked to cancel and any eventual result follows the normal onBeat / onError channels. Set stopTimeoutMs on startHeartbeat to apply a default bound to stop() (including an abort-signal shutdown).
The heartbeat loop keeps a fixed cadence. When a submission outlives one or more intervals, the stale slots are skipped instead of being fired back-to-back: each is counted once in handle.missedBeats, and the next beat waits for the next future deadline. A late wake still reports lateMs relative to the slot the beat represents. The same-second duplicate courtesy and the contract's own authority are unchanged.
CostPreChecker reports fees as exact integer stroops — the raw value is the
source of truth, and it is what a maxFeeStroops ceiling is compared against.
formatFee() renders the same number in XLM, the unit operators think in, using
integer math only (XLM has 7 decimal places; float rounding on
money-adjacent output in a security tool is not acceptable) and with no trailing
zeros. Fees are non-negative: a negative bigint or signed string throws
TypeError instead of rendering an impossible amount. A ceiling of 0n is a
real, maximally strict ceiling; only omitting maxFeeStroops disables the check.
import { formatFee } from "stellar-agent-guard-sdk";
cost.totalFeeStroops; // 12345n — stroops (exact, source of truth)
formatFee(cost.totalFeeStroops); // "0.0012345" — same value in XLM
formatFee(1n); // "0.0000001" — one stroop
formatFee(9_999_999n); // "0.9999999" — largest sub-XLM valuePriced within_budget and over_budget results may include a breakdown parsed from the same Soroban simulation that produced resourceFeeStroops:
if (decision.kind === "within_budget" && decision.breakdown) {
console.log(decision.breakdown);
// {
// instructions, // SorobanResources.instructions
// diskReadBytes, // SorobanResources.diskReadBytes
// writeBytes, // SorobanResources.writeBytes
// readOnlyEntries, // footprint.readOnly.length
// readWriteEntries, // footprint.readWrite.length
// storageEntries // readOnlyEntries + readWriteEntries
// }
}breakdown is undefined when the simulation is undetermined, malformed, or missing any required resource field; the SDK never fabricates zero values. The stellar-sdk v17 Soroban resource payload has no memBytes field, so this API reports the actual writeBytes/disk resource fields rather than relabeling them as memory usage.
Priced decisions carry provenance: { ledger: number } | null, read from the same simulation response that produced the quote. It identifies the ledger snapshot the quote describes; it is informational and is not a promise about where a transaction will land. When the simulation does not establish a usable ledger, provenance is null rather than a fabricated number. blocked and undetermined decisions always have provenance: null.
PreFlightInterceptor.check() answers may this proceed? and
CostPreChecker.check() answers what will it cost? — but calling both runs the
enforced simulation twice, against two ledger snapshots. The extra RPC is the
lesser problem: the fee reported for a call can then differ from the fee implied
by the verdict that was actually enforced, so the price no longer corresponds to
the approved decision.
CostPreChecker.checkWithCost() returns both from a single simulation:
const { decision, cost } = await costChecker.checkWithCost(call);
if (decision.kind === "blocked") {
console.log("refused:", decision.reason); // nothing was charged
} else if (cost.kind === "over_budget") {
console.log("too expensive:", formatFee(cost.totalFeeStroops), "XLM");
} else if (decision.allowed) {
console.log("approved at", formatFee(cost.totalFeeStroops), "XLM");
}Prefer this over calling interceptor.check(call) and costChecker.check(call)
in sequence. That two-call pattern still works and its types are unchanged, but
it carries the fee-drift caveat above. precheckCostWithDecision() is the
one-shot form.
event-schema.md— every telemetry event and field, each labelled with its stability tier: Stable (relied on), Append-only (new values may appear, existing ones will not be removed or renamed), Best-effort (may change in any release), Internal (implementation detail, not a contract).GuardTelemetryListenerconstructor(config?: GuardTelemetryInputConfig | GuardTelemetryLocalConfig)— Options table.watch(params?: GuardTelemetryWatchParams): AsyncIterable<GuardEventPage>— Tails on-chain and uncommitted events.params.signalaborts at loop boundaries: no RPC call before the first pull, no poll after an abort, and the delay between polls is cut short. A request already in flight cannot be cancelled — see Aborting a watch.params.retry?: TelemetryRetryOptionstunes the bounded poll-retry envelope ({ maxRetries?, baseDelayMs?, maxDelayMs? }); the defaults (DEFAULT_TELEMETRY_RETRY_OPTIONS={ maxRetries: 5, baseDelayMs: 100 }, backoff capped atpollIntervalMs) match the historical behavior, every value is validated before the first poll, and every backoff delay is abort-aware (issue #285).params.maxBufferedPages?: numberbounds the look-ahead pump in front of the consumer (DEFAULT_MAX_BUFFERED_PAGES=2): at most that many pages are prefetched plus one request in flight, a slow consumer throttles the fetches instead of growing an unconsumed backlog, each page's cursor is saved at delivery so the stored cursor never leads the consumer, and0restores strict consumer-paced polling (issue #36). A non-integer or negative bound throws aTypeErrorbefore the first poll.watchAll(params?: GuardTelemetryUnifiedParams): AsyncIterable<GuardEvent>— Merges the committed ledger stream with thediagnosticsbatches you feed it into one ordered, de-duplicated stream, so a single loop sees blocked decisions too. Each event carriesstream: 'committed' | 'diagnostic'and, for diagnostics,observedAt. Ordering and de-duplication rules:event-schema.md.serializeEvent(event: GuardEvent): string— Canonical single-line JSON for deterministic JSON-lines log shipping. Fixed key order, dropsundefined, keepsnull, rendersbigintas a decimal string. Unversioned legacy (v0) format. Contract:event-schema.md.serializeEventRecord(event: GuardEvent): string— Persisted-record envelope{ "v": 1, "event": { … } }with the same event projection asserializeEvent();vis explicit so a reader can tell a record written by a newer SDK. See Versioned event records.parseEventRecord(line: string): { version, event }— Reads either a versioned envelope or a legacy bare line (reported asversion: 0).
validateGuardPolicy(policy: unknown, options?: ValidatePolicyOptions | string): PolicyFailure[]— Validates policy configuration against SPEC §8 rules prior to broadcast, accumulating all failures for complete form UX. Also checks everyi128andu64field against its wire maximum, reportinginteger_out_of_rangebefore encoding.policyAddressComparisonKey(address: unknown): string | null— Returns the canonical comparison key produced by Stellar SDK address parsing for a valid account or contract address. Invalid inputs returnnull; they are not case-folded or normalized into a match.validatePolicyForEncoding(policy: unknown): PolicyEncodingFailure[]— Checks that a draft can be represented as the contract'sPolicyConfigScValat all, without encoding it or throwing. Each failure carries a dottedpathinto the draft (for exampleprotocols[1].contractorrecipient_window_caps[0].cap), a stablerule, and a human-readablemessage; an empty array meanspolicyToScValwill accept the draft. This is the form-validation counterpart tovalidateGuardPolicy: it checks wire representability (types, address and symbol syntax,u64/i128bounds), whilevalidateGuardPolicychecks SPEC §8 policy semantics. UsevalidateGuardPolicybefore broadcasting andvalidatePolicyForEncodingwhen the editor needs to explain why encoding itself would fail.POLICY_RULE_IDS— Canonical array of policy validation rule identifiers: SPEC §8 rules plus the SDK-specificinteger_out_of_rangewire-representability rule.policyToScVal(policy: PolicyConfig): xdr.ScVal— Encodes a policy as the contract's canonical sorted ScVal struct. The draft is validated before any partialScValis constructed: a field that cannot be represented throwsPolicyEncodeErrorcarrying every actionable failure path, rather than leaking a low-levelnativeToScVal/Addressexception. Anumberis accepted only when it is a safe integer; an unsafenumberand every numeric string are rejected instead of being silently rounded or coerced, because the contract's caps arei128/u64and the SDK refuses to narrow them. Valid policies encode byte-for-byte as before.policyToScVal(policy: PolicyConfig): xdr.ScVal— Encodes a policy as the contract's canonical sorted ScVal struct. Emits the contractPolicyConfigstruct's full field set, includingrecipient_window_caps,blocked_recipients, theu32protocol_calls_per_windowand the emptyasset_capsvector, byte-aligned with the contracts repo's shared encode-parity vectors (issue #260);ProtocolRulemaps carry the per-rulepausedflag.decodePolicy(scVal: xdr.ScVal): PolicyConfig— Strictly decodespolicy()/set-policy ScVal data, including Option/Vec and numeric normalization.policyFromScVal(scVal)— Alias for callers using the issue's original function name.policyToJson(policy)/policyFromJson(value)— Versioned, lossless JSON shape for persistence and transport, not ScVal encoding. All integer fields are decimal strings; parsing rejects numbers, unknown fields, invalid addresses, and values outside theiru64/i128ranges with aPolicyDecodeErrorfield path. The top-levelversionis currently1, and the parser accepts only versions supported by this SDK; unknown versions fail closed atpolicy.version. Incompatible format changes will increment the version, so consumers should explicitly migrate stored payloads before parsing them with a version that does not support their existing format.encodePolicyJson/decodePolicyJsonare equivalent aliases.describePolicy(policy: PolicyConfig | null, options?: DescribePolicyOptions): string— A compact, log-friendly rendering of the policy in force. See Describing a policy.verifyAgentSignature(publicKey, payload, signature): boolean— Verify-only Ed25519 check against a strkey or raw 32-byte key.GuardError,SimulationError,SigningError,BroadcastError,PolicyDecodeError, andContractResponseError— Typed operational failure hierarchy. Invalid input is separate:InvalidInputError,InvalidFeeCeilingError, andPolicyEncodeErrorextendTypeError.PolicyEncodeError— A policy draft could not be encoded. It is the pre-submission counterpart toPolicyDecodeError:path,field, andruledescribe the first failure, whilefailures: readonly PolicyEncodingFailure[]holds all of them (withPolicyEncodingRuleIdvaluesinvalid_type,missing_field,invalid_address,invalid_symbol, andinteger_out_of_range) so a policy-editor form can highlight every bad field in one pass. Nothing is encoded when it throws.decodeCheckResult(raw): CheckResult— DecodesAllowedorBlocked(reason).decodeAuthDecision(event: SorobanRpc.Api.GetEventsResponse.Event): AuthDecisionEvent | nulldecodeGuardEventXdr(xdrBase64: string, source?: 'ledger' | 'diagnostic'): GuardAuthDecision | null— Offline decode of a raw base64 event XDR. Accepts either aDiagnosticEvent(whatgetEvents()and a simulation error carry) or aContractEvent(what a block explorer exposes) and returns the same decision the object-path decode produces. Malformed base64, an XDR that is not a contract event, and an event that is not anevent_auth_checkeddecision all returnnull— it never throws, so fixture checks and operator copy-paste cannot crash a long-running process.guardEventsFromDiagnostics(events: xdr.DiagnosticEvent[]): GuardEvent[]— Each decodedGuardEventcarries a stableid:ledger:<txHash>:<topic>for committed events,diag:<sha256>for blocked ones (which are rolled back and have no hash to anchor on). Same event re-parsed → same id; two different blocks in one simulation → different ids. Format and collision notes:event-schema.md.GuardLogger,GuardLoggerInput,GuardLogMeta,GUARD_LOG_LEVELS— the optional, structurally-typed log sink shared by every config above;SILENT_LOGGERis what a config resolves to when none is supplied. See Optional logging.explainReason(reason: string | number, locale?, overrides?): string— Human-readable explanation of contract reason codes. The default call is unchanged; the optionallocalecatalog and per-reasonoverrideslocalise or reword a refusal without an i18n dependency. Reason keys, titles and remediation text:reasonMessages/reasonMessagesEn.isDeadManFrozen(status: GuardStatus): booleandeadManRemaining(status: GuardStatus, policy: PolicyConfig | null): bigint | nulldmsUrgency(status: GuardStatus, policy: PolicyConfig | null, nowSecs?: bigint, warnRatio = DMS_WARN_RATIO_DEFAULT): 'ok' | 'warn' | 'expired' | 'unknown'— Dead-man countdown urgency for dashboards:warnfromwarnRatio(defaultDMS_WARN_RATIO_DEFAULT= 0.8) of the grace period,expiredonce the grace has elapsed.unknownexactly wheredeadManRemainingisnull(no policy, switch disabled, never heartbeated — never ≠ expired).policyDiff(a: PolicyConfig, b: PolicyConfig): PolicyChange[]— Structured change list between two policies for operator display (e.g. when the policy revision bumps; dashboard change-history feed: stellar-agent-guard-dashboard#17). Lists compare as sets, so a pure reorder is no change; valid addresses compare throughpolicyAddressComparisonKey, and protocols match by contract. Duplicate members in malformed drafts collapse by set membership; the first duplicate protocol or recipient cap wins. The helper is deterministic but does not replace validation before encoding or submission.
A consumer that wants "the last N decisions, right now" — a dashboard panel, an agent status endpoint — can opt into a bounded in-memory window instead of maintaining its own store:
import { GuardTelemetryListener } from "stellar-agent-guard-sdk";
const listener = new GuardTelemetryListener({
server,
guard: GUARD_ID,
buffer: { max: 200 }, // opt-in; omitted → no buffer is allocated
});
// ...drive it with listener.watch() or listener.watchAll(), then read on demand:
const lastBlocked = listener.recent({ stream: "diagnostic" });
const capRefusals = listener.recent({ reason: "per_tx_cap_exceeded" });
const recentWindow = listener.recent({ fromLedger: 4_700_000 });recent(filter?) returns the retained events oldest-first, filtered by any of stream, reason, fromLedger, toLedger. The buffer is FIFO and non-durable: it holds only what this listener decoded in this process, and a restart empties it. Persistence across restarts is a cursor store (tracked separately), not something this buffer pretends to provide.
recent() returns detached snapshots, not references into the buffer's own state. The array is new, and so is every event in it: the top-level fields, the decoded decision, the decoded data, and the opt-in raw payload are all copies. A consumer that edits what it was handed cannot change what the listener still retains, and the next recent() reports the retained event rather than the consumer's edit.
const snapshot = listener.recent();
snapshot[0]!.ledger = 999; // the copy
snapshot[0]!.data = { forged: true }; // the copy
listener.recent()[0]!.ledger; // → the retained ledger, unchangedThe copy is structural rather than a re-serialisation: byte arrays are copied, and a class instance keeps its prototype, so an XDR value inside a raw payload still answers like the XDR value it was. The cost is paid per call by a caller that actually reads a snapshot — a listener with no buffer configured allocates nothing at all, and recent() returns [].
When a decoded verdict looks wrong, attach the undecoded source event to the SDK bug report. Decoding discards it by default — the raw payload carries XDR ScVals and host-shaped objects, and retaining one per event is a memory decision — so it is opt-in:
// Committed feed: opt in on the listener.
const listener = new GuardTelemetryListener({ server, guard: GUARD_ID, includeRaw: true });
// Diagnostic feed: opt in at the decode site.
const events = guardEventsFromDiagnostics(diagnosticEvents, GUARD_ID, { includeRaw: true });
// Every event then carries `raw`: the `rpc.Api.EventResponse` for a committed
// event, or the host-shaped diagnostic object for a blocked one.
const event = (await listener.poll({ startLedger })).events[0];
console.error(JSON.stringify(event.raw, (_key, value) =>
typeof value === "bigint" ? value.toString() : value));When includeRaw is not set, raw is absent (undefined) — nothing is retained. Leave it off in a long-running fleet; turn it on for the debugging session or the bug-report window. The id field stays stable either way, so a raw event can be correlated with the decoded event it produced.
reasonMessages exposes each reason's numeric code and its stable title/body/remediation keys, and reasonMessagesEn holds the built-in English text — so a dashboard can render a table, and a consumer can key its own translations, without the SDK taking an i18n dependency:
import { reasonMessages, reasonMessagesEn, explainReason } from "stellar-agent-guard-sdk";
for (const [reason, { code, titleKey, remediationKey }] of Object.entries(reasonMessages)) {
console.log(code, reasonMessagesEn[reason as keyof typeof reasonMessagesEn].title, remediationKey);
}
// Localise one reason; a missing key falls back to English.
explainReason("per_tx_cap_exceeded", {
[reasonMessages.per_tx_cap_exceeded.bodyKey]: "Le montant dépasse le plafond par transaction.",
});
// Or override individual reasons outright.
explainReason("paused", undefined, { paused: "Agent paused by the operator." });serializeEvent(event) gives you one canonical JSON line per event, so a log pipeline gets a stable, diffable record with no logger dependency in the SDK:
import { serializeEvent } from "stellar-agent-guard-sdk";
for await (const event of listener.watchAll({ diagnostics })) {
logger.info(serializeEvent(event)); // one deterministic JSON line per event
}Key order, the drop-undefined/keep-null policy, and the bigint-to-decimal-string normalization are documented in event-schema.md.
For persisted records, prefer the versioned envelope so a future schema change is distinguishable from a historical line:
import { parseEventRecord, serializeEventRecord } from "stellar-agent-guard-sdk";
logger.info(serializeEventRecord(event)); // {"v":1,"event":{…}}
const { version, event: decoded } = parseEventRecord(storedLine); // version 0 = legacydescribePolicy(policy) renders the policy in force as one log-friendly line. The summary is complete: it names the constraints that materially change which transfers are allowed — the per-recipient window caps, the blocked recipients, and the active window with its state — so a reader never has to open the policy to learn that it is narrower than the first line suggests.
import { describePolicy } from "stellar-agent-guard-sdk";
describePolicy(policy);
// per-tx cap 1000, rolling window 150 / 60s, 1 asset(s), 1 allowlisted recipient(s),
// 0 allowlisted protocol(s), active, dead-man switch off, 2 blocked recipient(s),
// 1 per-recipient window cap(s), active window 2026-01-01T00:00:00.000Z ->
// 2026-02-01T00:00:00.000Z (active)- Quiet by default. Recipient lists are reported as counts, never as addresses: a summary is a log line, and a policy can name hundreds of recipients.
detail: trueis the explicit way to ask for the addresses themselves (the allowlist, the blocklist and the per-recipient caps). - Stable output. The recipient lists are sorted, so the same policy always renders the same way regardless of the order the policy stores them in.
- The active window is judged against a moment.
nowSecs(a number or a bigint) pins that moment; it defaults to the current time. The state is one ofunbounded(no window),scheduled(not open yet),active, orexpired. - An optional constraint that is absent and one that is empty are the same thing — the constraint is not in force — so neither produces a clause. A boundary a
Datecannot represent is rendered as raw seconds instead of throwing.
describePolicy(policy, { detail: true, nowSecs: 1_700_000_000 });freezePolicy(policy) is the immutable boundary helper: it returns a policy whose properties and every nested collection are frozen, so a later mutation throws in strict mode (ESM modules are always strict) instead of silently producing a wrong verdict. It returns ReadonlyPolicyConfig, the type the SDK's internal consumers use.
It copies; it does not freeze its input. The policy object, assets, recipients, protocols (each rule and its fns array), recipient_window_caps (each entry) and blocked_recipients are all copied before they are frozen. The caller's object shares no mutable state with the returned one and can still be edited or reused:
import { freezePolicy, policyToScVal } from "stellar-agent-guard-sdk";
const config = { /* a reusable configuration object */ } satisfies PolicyConfig;
const policy = freezePolicy(config);
policyToScVal(policy); // encodes the frozen copy
config.per_tx_cap = 2_000n; // still legal: the caller owns `config`- Ownership is explicit. An SDK-owned immutable value never implies a side effect on the caller's value, so the copy is a fix for the earlier behaviour where the input was frozen in place and the same reference was returned. An address, a
bigintcap or a boolean is an immutable primitive and is kept by value, so the copy costs one array/object per collection — not a deep value copy — and is still cheap enough to call once when a policy first enters the SDK. - Deep, not shallow. A partially frozen policy would let a caller mutate a rule's
fnsarray or arecipient_window_capsentry after the SDK accepted it, which is exactly how a passing pre-flight check turns into a wrong verdict. - Contents are unchanged. Copying and freezing do not add, drop, normalise or validate fields, so the fail-closed policy behaviour and
policyToScValoutput are identical to the policy passed in. Optional collections the caller omitted stay omitted.