Skip to main content

@flow-state-dev/memory

Interfaces​

CreateMemoryCapabilityOptions​

Options for createMemoryCapability. The subset of MemorySystemConfig that drives capability construction; lifecycle-side options (source, maxAssistantChars, consolidationModel, pruneModel, name, inputSchema) are intentionally excluded — they belong to system().

Properties​

digest?​
digest?: true | DigestSystemConfig;

Digest tier config. true for defaults. Omit to disable. Requires semantic.

episodic?​
episodic?: true | EpisodicMemoryConfig;

Episodic memory config. true for defaults. Omit to disable.

hygiene?​
hygiene?: boolean | HygieneConfig;

Memory hygiene configuration. Only the confidenceDecay slice affects this capability — it drives recall ranking. Janitor scheduling is a lifecycle concern owned by system().

model​
model: string | string[];

Default model id (or fallback chain) for the recall tool's filter call. Required.

semantic?​
semantic?: true | SemanticMemoryConfig;

Semantic memory config. true for defaults. Omit to disable. Requires episodic.

tool?​
tool?: MemoryToolConfig;

Recall-tool config. Omit to use defaults (llm-filter strategy).

working​
working: true | WorkingMemorySystemConfig;

Working memory config. true for defaults. Required.


DigestBlocksConfig​

Resolved digest configuration passed into the digest blocks.

Properties​

flowIsolation?​
flowIsolation?: boolean;

Derived from the episodic and semantic tiers; undefined takes the flow's default.

maxTokens​
maxTokens: number;

Hard cap on digest output tokens.

scope​
scope: "user" | "org";

Resource scope (mirrors semantic).

topN​
topN: object;

How many top-by-reinforcement facts to feed into the prompt.

episodes​
episodes: number;
facts​
facts: number;

DigestMemoryCapabilityConfig​

Config for digest memory capability. system() derives flowIsolation from the episodic and semantic tiers; a caller composing tiers by hand sets it to true whenever either source is isolated.

Extends​

Properties​

flowIsolation?​
flowIsolation?: boolean;

The resource's own flowIsolation. true keys the store per flow instance, false shares it across flows, and either wins over the flow's isolateUserState / isolateOrgState default. Omit it to take that default.

Inherited from​

MemoryResourceOptions.flowIsolation

scope?​
scope?: "user" | "org";

Resource scope. Default: 'user'. Should mirror semantic memory's scope.


DigestSystemConfig​

Configuration for the digest tier within memory.system().

Properties​

maxTokens?​
maxTokens?: number;

Hard cap on digest output tokens. Default: 400.

topN?​
topN?: object;

Top-N inputs to the regeneration prompt.

episodes?​
episodes?: number;

Top-N recent-and-significant episodes. Default: 10.

facts?​
facts?: number;

Top-N semantic facts by reinforcement count. Default: 30.


EpisodicMemoryCapabilityConfig​

Config for episodic memory capability.

Extends​

Properties​

flowIsolation?​
flowIsolation?: boolean;

The resource's own flowIsolation. true keys the store per flow instance, false shares it across flows, and either wins over the flow's isolateUserState / isolateOrgState default. Omit it to take that default.

Inherited from​

MemoryResourceOptions.flowIsolation

maxEpisodes?​
maxEpisodes?: number;

Max episodes to retain. Default: 200.

scope?​
scope?: "user" | "org";

Resource scope. Default: 'user'.


EpisodicMemoryConfig​

Configuration for the episodic memory module within memory.system().

Properties​

flowIsolation?​
flowIsolation?: boolean;

Isolate this tier per flow instance (true) or share it across flows (false), whatever the flow's isolateUserState / isolateOrgState says. Omit to take the flow's default.

maxEpisodes?​
maxEpisodes?: number;

Maximum episodes to retain. Default: 200.

scope?​
scope?: "user" | "org";

Scope for episodic storage. Default: 'user'.

significanceThreshold?​
significanceThreshold?: number;

Minimum importance for an item to be encoded as an episode. Default: 0.6.


EpisodicTTLConfig​

TTL configuration for cullByTTL. Mirrors HygieneConfig.episodicTTL so the janitor can pass its resolved config through unchanged.

Properties​

operator​
operator: "OR" | "AND";

'OR' (default) — cull when either turn-count OR wall-time threshold fires. 'AND' — require both thresholds. Knowledge is preserved in consolidation-derived semantic facts either way; 'OR' is the conservative, default-on shape.

persistentDays​
persistentDays: number;

Cull persistent episodes encoded more than this many days ago.

persistentTurns​
persistentTurns: number;

Cull persistent episodes encoded more than this many turns ago.


HygieneConfig​

Configuration for the memory hygiene pass.

Drives the janitor block that decays semantic-fact confidence over time and applies durability-based TTL to episodic episodes. Default-on: omitting hygiene from memory.system() opts into DEFAULT_HYGIENE_CONFIG. Pass false to turn it off — no decay, unbounded growth.

Properties​

confidenceDecay?​
confidenceDecay?:
| boolean
| {
cullFloor?: number;
halfLife?: number;
};

Confidence-decay configuration. true uses defaults; an object overrides selected fields; false disables the semantic branch entirely (recall ranking falls back to raw fact.confidence).

Union Members​

boolean


Type Literal​
{
cullFloor?: number;
halfLife?: number;
}
cullFloor?​
cullFloor?: number;

Effective-confidence threshold below which facts are culled. Default 0.1.

halfLife?​
halfLife?: number;

Half-life in days. Default 180.

episodicTTL?​
episodicTTL?:
| boolean
| {
operator?: "OR" | "AND";
permanentStaleDays?: number;
persistentDays?: number;
persistentTurns?: number;
};

Episodic TTL configuration. true uses defaults; an object overrides selected fields; false disables the episodic branch entirely.

Union Members​

boolean


Type Literal​
{
operator?: "OR" | "AND";
permanentStaleDays?: number;
persistentDays?: number;
persistentTurns?: number;
}
operator?​
operator?: "OR" | "AND";

'OR' (default) — cull when either threshold fires. 'AND' — require both.

permanentStaleDays?​
permanentStaleDays?: number;

Days of silence after which permanent episodes pick up stale: true. Default 180.

persistentDays?​
persistentDays?: number;

Cull persistent episodes encoded more than this many days ago. Default 90.

persistentTurns?​
persistentTurns?: number;

Cull persistent episodes encoded more than this many turns ago. Default 500.

schedule?​
schedule?: "onConsolidation" | "onCapture" | "manual";

When the janitor runs.

  • 'onConsolidation' (default): appended to the consolidation chain; runs whenever consolidation runs (matches the cadence of fact updates).
  • 'onCapture': appended to the capture pipeline; runs every turn. Decay is slow, so this is rarely worth the cost — reserved for high-churn deployments.
  • 'manual': never auto-wired. Invoke mem.janitor directly when custom scheduling is required.

MemoryCapability​

The composed memory capability returned by createMemoryCapability.

Extends DefinedCapability with the typed resource maps, the per-tier capabilities, and the recall tool block. Install via uses: [memCap] on a generator; register { ...memCap.sessionResources, ...memCap.userResources } on the flow.

For type-safe resource access, use sessionResources / userResources — tiers.*.resources is typed broadly (DeclaredResourceEntry) and is only for installing a single tier in isolation via uses: [memCap.tiers.working].

Extends​

  • DefinedCapability

Properties​

__brand​
readonly __brand: "Capability";

Brand — set by defineCapability() to identify capability objects.

Inherited from​

DefinedCapability.__brand

__configInType?​
readonly __configInType?: unknown;

Type-only carrier for the .config() argument type. Set by defineCapability to z.input of the config schema (or the explicit schemaless type), or never when the capability declares no config. Holds no runtime value.

Inherited from​

DefinedCapability.__configInType

__presetDefs?​
readonly __presetDefs?: Record<string, PresetDef<any>> & object;

Raw preset definitions. Set internally by defineCapability().

Type Declaration​
default?​
default?: string[];
Inherited from​

DefinedCapability.__presetDefs

connectToolBlock?​
readonly connectToolBlock?: BlockDefinition<ZodObject<{
depth: ZodOptional<ZodNumber>;
from: ZodString;
to: ZodOptional<ZodString>;
}, "strip", ZodTypeAny, {
depth?: number;
from: string;
to?: string;
}, {
depth?: number;
from: string;
to?: string;
}>, ZodTypeAny, {
depth?: number;
from: string;
to?: string;
}, RecallToolResult>;

The memory/connect relation-graph tool — present only when the relations tier is enabled. undefined when relations are off.

fns?​
fns?: (ctx) => TFns;
Parameters​
ctx​

BlockContext

Returns​

TFns

Inherited from​

DefinedCapability.fns

itemVisibility?​
itemVisibility?: ItemVisibility | readonly ItemVisibility[];

Allowlist of block itemVisibility this capability attaches to. See CapabilityConfig.itemVisibility.

Inherited from​

DefinedCapability.itemVisibility

name​
readonly name: string;
Inherited from​

DefinedCapability.name

orgStateSchema?​
orgStateSchema?: ZodTypeAny;
Inherited from​

DefinedCapability.orgStateSchema

recallToolBlock​
readonly recallToolBlock: BlockDefinition<any>;
requestStateSchema?​
requestStateSchema?: ZodTypeAny;
Inherited from​

DefinedCapability.requestStateSchema

resources?​
resources?: Record<string, DeclaredResourceEntry>;
Inherited from​

DefinedCapability.resources

resourcesType?​
readonly resourcesType?: unknown;
Inherited from​

DefinedCapability.resourcesType

sequencerStateSchema?​
sequencerStateSchema?: ZodTypeAny;
Inherited from​

DefinedCapability.sequencerStateSchema

sequencerStateType?​
readonly sequencerStateType?: unknown;
Inherited from​

DefinedCapability.sequencerStateType

sessionResources​
readonly sessionResources: object;
memorySystem​
memorySystem: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
default.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
default.lastConsolidationTurn​
lastConsolidationTurn: number;
default.lastProcessedIndex​
lastProcessedIndex: number;
default.readMessages​
readMessages: object[] | null;
ref​
readonly ref: "memorySystem";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: ZodObject<{
episodicWritesSinceLastConsolidation: ZodDefault<ZodNumber>;
evictedPersistentSinceLastConsolidation: ZodDefault<ZodNumber>;
lastConsolidationTurn: ZodDefault<ZodNumber>;
lastProcessedIndex: ZodDefault<ZodNumber>;
readMessages: ZodDefault<ZodNullable<ZodArray<ZodObject<{
id: ZodString;
ts: ZodNumber;
}, "strip", ZodTypeAny, {
id: string;
ts: number;
}, {
id: string;
ts: number;
}>, "many">>>;
}, "strip", ZodTypeAny, {
episodicWritesSinceLastConsolidation: number;
evictedPersistentSinceLastConsolidation: number;
lastConsolidationTurn: number;
lastProcessedIndex: number;
readMessages: object[] | null;
}, {
episodicWritesSinceLastConsolidation?: number;
evictedPersistentSinceLastConsolidation?: number;
lastConsolidationTurn?: number;
lastProcessedIndex?: number;
readMessages?: object[] | null;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
ClientType.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
ClientType.lastConsolidationTurn​
lastConsolidationTurn: number;
ClientType.lastProcessedIndex​
lastProcessedIndex: number;
ClientType.readMessages​
readMessages: object[] | null;
ContextType​
ContextType: ResourceContext<{
episodicWritesSinceLastConsolidation: number;
evictedPersistentSinceLastConsolidation: number;
lastConsolidationTurn: number;
lastProcessedIndex: number;
readMessages: object[] | null;
}>;
StateType​
StateType: object;
StateType.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
StateType.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
StateType.lastConsolidationTurn​
lastConsolidationTurn: number;
StateType.lastProcessedIndex​
lastProcessedIndex: number;
StateType.readMessages​
readMessages: object[] | null;
workingMemory​
workingMemory: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.currentTurn​
currentTurn: number;
default.entries​
entries: object[];
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: ZodObject<{
currentTurn: ZodDefault<ZodNumber>;
entries: ZodDefault<ZodArray<ZodObject<{
addedAtTurn: ZodNumber;
category: ZodDefault<ZodEnum<...>>;
content: ZodString;
durability: ZodDefault<ZodEnum<...>>;
id: ZodString;
importance: ZodNumber;
lastAccessedAtTurn: ZodNumber;
metadata: ZodOptional<ZodRecord<..., ...>>;
pinned: ZodBoolean;
salience: ZodNumber;
}, "strip", ZodTypeAny, {
addedAtTurn: number;
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<..., ...>;
pinned: boolean;
salience: number;
}, {
addedAtTurn: number;
category?: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability?: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<..., ...>;
pinned: boolean;
salience: number;
}>, "many">>;
}, "strip", ZodTypeAny, {
currentTurn: number;
entries: object[];
}, {
currentTurn?: number;
entries?: object[];
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.currentTurn​
currentTurn: number;
ClientType.entries​
entries: object[];
ContextType​
ContextType: ResourceContext<{
currentTurn: number;
entries: object[];
}>;
StateType​
StateType: object;
StateType.currentTurn​
currentTurn: number;
StateType.entries​
entries: object[];
sessionStateSchema?​
sessionStateSchema?: ZodTypeAny;
Inherited from​

DefinedCapability.sessionStateSchema

sessionStateType?​
readonly sessionStateType?: unknown;

Type-only escape hatch carriers. These fields hold no runtime value; InferCapability* utilities read them via infer to override the type derived from the corresponding schema. Useful when the schema infers to a shape that's too loose for consumer ctx (e.g. z.record(z.any())).

Inherited from​

DefinedCapability.sessionStateType

stateSchema?​
stateSchema?: ZodTypeAny;

Own-state contribution — see PresetDef.stateSchema.

Inherited from​

DefinedCapability.stateSchema

stateSchemaType?​
readonly stateSchemaType?: unknown;
Inherited from​

DefinedCapability.stateSchemaType

targetStateSchemas?​
targetStateSchemas?: Record<string, ZodTypeAny>;
Inherited from​

DefinedCapability.targetStateSchemas

targetStatesType?​
readonly targetStatesType?: unknown;
Inherited from​

DefinedCapability.targetStatesType

tiers​
readonly tiers: object;
digest?​
digest?: CapabilityRef;
episodic?​
episodic?: CapabilityRef;
semantic?​
semantic?: CapabilityRef;
working​
working: CapabilityRef;
userResources​
readonly userResources: object;
digestMemory?​
digestMemory?: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.digest?​
digest?: object;
default.digest.content​
content: string;
default.digest.generatedAt​
generatedAt: string;
default.digest.generatedAtTurn​
generatedAtTurn: number;
default.digest.sourceSignature​
sourceSignature: object;
default.digest.sourceSignature.episodeCount​
episodeCount: number;
default.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
default.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
default.totalGenerated​
totalGenerated: number;
flowIsolation?​
readonly flowIsolation?: boolean;
ref​
readonly ref: "digestMemory";
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
digest: ZodOptional<ZodObject<{
content: ZodString;
generatedAt: ZodString;
generatedAtTurn: ZodNumber;
sourceSignature: ZodObject<{
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}, "strip", ZodTypeAny, {
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}, {
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}>;
}, "strip", ZodTypeAny, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}>>;
totalGenerated: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated: number;
}, {
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.digest?​
digest?: object;
ClientType.digest.content​
content: string;
ClientType.digest.generatedAt​
generatedAt: string;
ClientType.digest.generatedAtTurn​
generatedAtTurn: number;
ClientType.digest.sourceSignature​
sourceSignature: object;
ClientType.digest.sourceSignature.episodeCount​
episodeCount: number;
ClientType.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
ClientType.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
ClientType.totalGenerated​
totalGenerated: number;
ContextType​
ContextType: ResourceContext<{
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated: number;
}>;
StateType​
StateType: object;
StateType.digest?​
digest?: object;
StateType.digest.content​
content: string;
StateType.digest.generatedAt​
generatedAt: string;
StateType.digest.generatedAtTurn​
generatedAtTurn: number;
StateType.digest.sourceSignature​
sourceSignature: object;
StateType.digest.sourceSignature.episodeCount​
episodeCount: number;
StateType.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
StateType.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
StateType.totalGenerated​
totalGenerated: number;
episodicMemory?​
episodicMemory?: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.episodes​
episodes: object[];
default.totalEncoded​
totalEncoded: number;
flowIsolation?​
readonly flowIsolation?: boolean;
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
episodes: ZodDefault<ZodArray<ZodObject<{
category: ZodEnum<...>;
consolidated: ZodDefault<...>;
content: ZodString;
context: ZodObject<..., ..., ..., ..., ...>;
durability: ZodDefault<...>;
encodedAt: ZodString;
id: ZodString;
occurredAtTurn: ZodNumber;
significance: ZodNumber;
stale: ZodDefault<...>;
subject: ZodDefault<...>;
}, "strip", ZodTypeAny, {
category: ... | ... | ... | ... | ... | ... | ... | ... | ...;
consolidated: boolean;
content: string;
context: {
precedingTopic?: ...;
sessionId: ...;
};
durability: ... | ...;
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale: boolean;
subject: string;
}, {
category: ... | ... | ... | ... | ... | ... | ... | ... | ...;
consolidated?: ... | ... | ...;
content: string;
context: {
precedingTopic?: ...;
sessionId: ...;
};
durability?: ... | ... | ...;
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale?: ... | ... | ...;
subject?: ... | ...;
}>, "many">>;
totalEncoded: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
episodes: object[];
totalEncoded: number;
}, {
episodes?: object[];
totalEncoded?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.episodes​
episodes: object[];
ClientType.totalEncoded​
totalEncoded: number;
ContextType​
ContextType: ResourceContext<{
episodes: object[];
totalEncoded: number;
}>;
StateType​
StateType: object;
StateType.episodes​
episodes: object[];
StateType.totalEncoded​
totalEncoded: number;
semanticMemory?​
semanticMemory?: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.facts​
facts: object[];
default.totalConsolidations​
totalConsolidations: number;
default.totalExtracted​
totalExtracted: number;
edges?​
readonly edges?: EdgeSlotConfig;
flowIsolation?​
readonly flowIsolation?: boolean;
ref​
readonly ref: "semanticMemory";
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
facts: ZodDefault<ZodArray<ZodObject<{
category: ZodEnum<...>;
confidence: ZodNumber;
content: ZodString;
extractedAt: ZodString;
id: ZodString;
lastReinforced: ZodOptional<...>;
reinforcementCount: ZodDefault<...>;
sourceEpisodeIds: ZodArray<..., ...>;
subject: ZodDefault<...>;
}, "strip", ZodTypeAny, {
category: ... | ... | ... | ... | ... | ... | ...;
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: ... | ...;
reinforcementCount: number;
sourceEpisodeIds: ...[];
subject: string;
}, {
category: ... | ... | ... | ... | ... | ... | ...;
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: ... | ...;
reinforcementCount?: ... | ...;
sourceEpisodeIds: ...[];
subject?: ... | ...;
}>, "many">>;
totalConsolidations: ZodDefault<ZodNumber>;
totalExtracted: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
facts: object[];
totalConsolidations: number;
totalExtracted: number;
}, {
facts?: object[];
totalConsolidations?: number;
totalExtracted?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.facts​
facts: object[];
ClientType.totalConsolidations​
totalConsolidations: number;
ClientType.totalExtracted​
totalExtracted: number;
ContextType​
ContextType: ResourceContext<{
facts: object[];
totalConsolidations: number;
totalExtracted: number;
}>;
StateType​
StateType: object;
StateType.facts​
facts: object[];
StateType.totalConsolidations​
totalConsolidations: number;
StateType.totalExtracted​
totalExtracted: number;
userStateSchema?​
userStateSchema?: ZodTypeAny;
Inherited from​

DefinedCapability.userStateSchema

uses?​
uses?: UsesSlot;
Inherited from​

DefinedCapability.uses

Methods​

config()​
config<Self>(this, value): ConfiguredCapability<string, Record<string, (...args) => any>, string, Record<string, PresetDef<any>>, undefined, undefined, undefined, undefined, undefined> & PreserveCarriers<Self>;

Apply typed open configuration declared via defineCapability({ config }). Returns a new configured reference (does not mutate the original), one hop from the base so diamond dedup still works. Composes with .presets() in either order. A compile error on a capability that declares no config (__configInType is never).

Type Parameters​
Self​

Self

Parameters​
this​

Self

value​

ConfigArgOf<Self>

Returns​

ConfiguredCapability<string, Record<string, (...args) => any>, string, Record<string, PresetDef<any>>, undefined, undefined, undefined, undefined, undefined> & PreserveCarriers<Self>

Inherited from​

DefinedCapability.config

presets()​
presets<Self>(this, overrides): ConfiguredCapability<string, Record<string, (...args) => any>, string, Record<string, PresetDef<any>>, undefined, undefined, undefined, undefined, undefined> & PreserveCarriers<Self>;

Configure which presets are active. Returns a new capability reference with the overrides recorded (does not mutate the original). Uses Object.create() to preserve base reference identity for diamond dedup.

Polymorphic over this so escape-hatch carriers (and any .config() argument type) survive the chain — .presets().config() keeps both.

Type Parameters​
Self​

Self

Parameters​
this​

Self

overrides​

PresetOverrides<TPresetNames, TPresets>

Returns​

ConfiguredCapability<string, Record<string, (...args) => any>, string, Record<string, PresetDef<any>>, undefined, undefined, undefined, undefined, undefined> & PreserveCarriers<Self>

Inherited from​

DefinedCapability.presets

with()​
with<Self>(this, bag): ConfiguredCapability<string, Record<string, (...args) => any>, string, Record<string, PresetDef<any>>, undefined, undefined, undefined, undefined, undefined> & PreserveCarriers<Self>;

Normalized consumer builder — collapses .config() and .presets() into one flat call. Preset-named keys become preset overrides; the rest become the config value. .with({ allowed, dynamicActivation: true }) is exactly .config({ allowed }).presets({ dynamicActivation: true }).

The argument is the config input intersected with the (all-optional) preset overrides. When the capability declares no config, the config half collapses away, so .with() accepts preset overrides alone; when it declares no presets, the preset half is empty, so .with() accepts the config value alone (including a scalar/array config, routed wholesale at runtime). Composes with .config()/.presets() and preserves escape-hatch carriers.

Type Parameters​
Self​

Self

Parameters​
this​

Self

bag​

WithArg<Self, string, Record<string, PresetDef<any>>>

Returns​

ConfiguredCapability<string, Record<string, (...args) => any>, string, Record<string, PresetDef<any>>, undefined, undefined, undefined, undefined, undefined> & PreserveCarriers<Self>

Inherited from​

DefinedCapability.with


MemoryCapabilityResources​

The resource maps a caller spreads into defineFlow's resources.

Properties​

sessionResources​
sessionResources: object;
memorySystem​
memorySystem: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
default.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
default.lastConsolidationTurn​
lastConsolidationTurn: number;
default.lastProcessedIndex​
lastProcessedIndex: number;
default.readMessages​
readMessages: object[] | null;
ref​
readonly ref: "memorySystem";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: ZodObject<{
episodicWritesSinceLastConsolidation: ZodDefault<ZodNumber>;
evictedPersistentSinceLastConsolidation: ZodDefault<ZodNumber>;
lastConsolidationTurn: ZodDefault<ZodNumber>;
lastProcessedIndex: ZodDefault<ZodNumber>;
readMessages: ZodDefault<ZodNullable<ZodArray<ZodObject<{
id: ZodString;
ts: ZodNumber;
}, "strip", ZodTypeAny, {
id: string;
ts: number;
}, {
id: string;
ts: number;
}>, "many">>>;
}, "strip", ZodTypeAny, {
episodicWritesSinceLastConsolidation: number;
evictedPersistentSinceLastConsolidation: number;
lastConsolidationTurn: number;
lastProcessedIndex: number;
readMessages: object[] | null;
}, {
episodicWritesSinceLastConsolidation?: number;
evictedPersistentSinceLastConsolidation?: number;
lastConsolidationTurn?: number;
lastProcessedIndex?: number;
readMessages?: object[] | null;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
ClientType.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
ClientType.lastConsolidationTurn​
lastConsolidationTurn: number;
ClientType.lastProcessedIndex​
lastProcessedIndex: number;
ClientType.readMessages​
readMessages: object[] | null;
ContextType​
ContextType: ResourceContext<{
episodicWritesSinceLastConsolidation: number;
evictedPersistentSinceLastConsolidation: number;
lastConsolidationTurn: number;
lastProcessedIndex: number;
readMessages: object[] | null;
}>;
StateType​
StateType: object;
StateType.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
StateType.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
StateType.lastConsolidationTurn​
lastConsolidationTurn: number;
StateType.lastProcessedIndex​
lastProcessedIndex: number;
StateType.readMessages​
readMessages: object[] | null;
workingMemory​
workingMemory: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.currentTurn​
currentTurn: number;
default.entries​
entries: object[];
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: ZodObject<{
currentTurn: ZodDefault<ZodNumber>;
entries: ZodDefault<ZodArray<ZodObject<{
addedAtTurn: ZodNumber;
category: ZodDefault<ZodEnum<...>>;
content: ZodString;
durability: ZodDefault<ZodEnum<...>>;
id: ZodString;
importance: ZodNumber;
lastAccessedAtTurn: ZodNumber;
metadata: ZodOptional<ZodRecord<..., ...>>;
pinned: ZodBoolean;
salience: ZodNumber;
}, "strip", ZodTypeAny, {
addedAtTurn: number;
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<..., ...>;
pinned: boolean;
salience: number;
}, {
addedAtTurn: number;
category?: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability?: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<..., ...>;
pinned: boolean;
salience: number;
}>, "many">>;
}, "strip", ZodTypeAny, {
currentTurn: number;
entries: object[];
}, {
currentTurn?: number;
entries?: object[];
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.currentTurn​
currentTurn: number;
ClientType.entries​
entries: object[];
ContextType​
ContextType: ResourceContext<{
currentTurn: number;
entries: object[];
}>;
StateType​
StateType: object;
StateType.currentTurn​
currentTurn: number;
StateType.entries​
entries: object[];
userResources​
userResources: object;
digestMemory?​
digestMemory?: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.digest?​
digest?: object;
default.digest.content​
content: string;
default.digest.generatedAt​
generatedAt: string;
default.digest.generatedAtTurn​
generatedAtTurn: number;
default.digest.sourceSignature​
sourceSignature: object;
default.digest.sourceSignature.episodeCount​
episodeCount: number;
default.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
default.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
default.totalGenerated​
totalGenerated: number;
flowIsolation?​
readonly flowIsolation?: boolean;
ref​
readonly ref: "digestMemory";
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
digest: ZodOptional<ZodObject<{
content: ZodString;
generatedAt: ZodString;
generatedAtTurn: ZodNumber;
sourceSignature: ZodObject<{
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}, "strip", ZodTypeAny, {
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}, {
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}>;
}, "strip", ZodTypeAny, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}>>;
totalGenerated: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated: number;
}, {
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.digest?​
digest?: object;
ClientType.digest.content​
content: string;
ClientType.digest.generatedAt​
generatedAt: string;
ClientType.digest.generatedAtTurn​
generatedAtTurn: number;
ClientType.digest.sourceSignature​
sourceSignature: object;
ClientType.digest.sourceSignature.episodeCount​
episodeCount: number;
ClientType.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
ClientType.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
ClientType.totalGenerated​
totalGenerated: number;
ContextType​
ContextType: ResourceContext<{
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated: number;
}>;
StateType​
StateType: object;
StateType.digest?​
digest?: object;
StateType.digest.content​
content: string;
StateType.digest.generatedAt​
generatedAt: string;
StateType.digest.generatedAtTurn​
generatedAtTurn: number;
StateType.digest.sourceSignature​
sourceSignature: object;
StateType.digest.sourceSignature.episodeCount​
episodeCount: number;
StateType.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
StateType.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
StateType.totalGenerated​
totalGenerated: number;
episodicMemory?​
episodicMemory?: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.episodes​
episodes: object[];
default.totalEncoded​
totalEncoded: number;
flowIsolation?​
readonly flowIsolation?: boolean;
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
episodes: ZodDefault<ZodArray<ZodObject<{
category: ZodEnum<...>;
consolidated: ZodDefault<...>;
content: ZodString;
context: ZodObject<..., ..., ..., ..., ...>;
durability: ZodDefault<...>;
encodedAt: ZodString;
id: ZodString;
occurredAtTurn: ZodNumber;
significance: ZodNumber;
stale: ZodDefault<...>;
subject: ZodDefault<...>;
}, "strip", ZodTypeAny, {
category: ... | ... | ... | ... | ... | ... | ... | ... | ...;
consolidated: boolean;
content: string;
context: {
precedingTopic?: ...;
sessionId: ...;
};
durability: ... | ...;
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale: boolean;
subject: string;
}, {
category: ... | ... | ... | ... | ... | ... | ... | ... | ...;
consolidated?: ... | ... | ...;
content: string;
context: {
precedingTopic?: ...;
sessionId: ...;
};
durability?: ... | ... | ...;
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale?: ... | ... | ...;
subject?: ... | ...;
}>, "many">>;
totalEncoded: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
episodes: object[];
totalEncoded: number;
}, {
episodes?: object[];
totalEncoded?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.episodes​
episodes: object[];
ClientType.totalEncoded​
totalEncoded: number;
ContextType​
ContextType: ResourceContext<{
episodes: object[];
totalEncoded: number;
}>;
StateType​
StateType: object;
StateType.episodes​
episodes: object[];
StateType.totalEncoded​
totalEncoded: number;
semanticMemory?​
semanticMemory?: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.facts​
facts: object[];
default.totalConsolidations​
totalConsolidations: number;
default.totalExtracted​
totalExtracted: number;
edges?​
readonly edges?: EdgeSlotConfig;
flowIsolation?​
readonly flowIsolation?: boolean;
ref​
readonly ref: "semanticMemory";
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
facts: ZodDefault<ZodArray<ZodObject<{
category: ZodEnum<...>;
confidence: ZodNumber;
content: ZodString;
extractedAt: ZodString;
id: ZodString;
lastReinforced: ZodOptional<...>;
reinforcementCount: ZodDefault<...>;
sourceEpisodeIds: ZodArray<..., ...>;
subject: ZodDefault<...>;
}, "strip", ZodTypeAny, {
category: ... | ... | ... | ... | ... | ... | ...;
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: ... | ...;
reinforcementCount: number;
sourceEpisodeIds: ...[];
subject: string;
}, {
category: ... | ... | ... | ... | ... | ... | ...;
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: ... | ...;
reinforcementCount?: ... | ...;
sourceEpisodeIds: ...[];
subject?: ... | ...;
}>, "many">>;
totalConsolidations: ZodDefault<ZodNumber>;
totalExtracted: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
facts: object[];
totalConsolidations: number;
totalExtracted: number;
}, {
facts?: object[];
totalConsolidations?: number;
totalExtracted?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.facts​
facts: object[];
ClientType.totalConsolidations​
totalConsolidations: number;
ClientType.totalExtracted​
totalExtracted: number;
ContextType​
ContextType: ResourceContext<{
facts: object[];
totalConsolidations: number;
totalExtracted: number;
}>;
StateType​
StateType: object;
StateType.facts​
facts: object[];
StateType.totalConsolidations​
totalConsolidations: number;
StateType.totalExtracted​
totalExtracted: number;

MemoryContextFormatterOptions​

Options for createMemoryContextFormatter.

Properties​

digest?​
digest?: boolean;

Include the rolling digest. Default: true. No-op when no digest tier is configured.

episodic?​
episodic?: EpisodicSectionOption;

Include most-recent episodes. Default: false. limit defaults to 5.

semantic?​
semantic?: SemanticSectionOption;

Include top-N semantic facts. Default: false. topN defaults to 10.

working?​
working?: boolean;

Include working memory entries. Default: true.


MemoryProvider​

Read-side contract a memory implementation must satisfy.

Extended by​

Methods​

formatContext()​
formatContext(input, ctx): MemoryContextSections | undefined;
Parameters​
input​

unknown

ctx​

any

Returns​

MemoryContextSections | undefined

recall()​
recall(ctx, cue?): RankedMemoryItem[];
Parameters​
ctx​

any

cue?​

string

Returns​

RankedMemoryItem[]


MemoryResourceOptions​

Options the memory resource factories share.

Extended by​

Properties​

flowIsolation?​
flowIsolation?: boolean;

The resource's own flowIsolation. true keys the store per flow instance, false shares it across flows, and either wins over the flow's isolateUserState / isolateOrgState default. Omit it to take that default.


MemorySystem​

The full memory system returned by memory.system().

Extends​

Properties​

capability​
capability: CapabilityRef;

Composed memory capability for all configured tiers.

Use on generators to auto-install resources, context formatting, typed helpers, and the agent-invocable recall tool. Five orthogonal section presets toggle independently — three default-on, two default-off:

  • digest (default-on) — render the rolling digest in the prompt. No-op when no digest tier is configured.
  • working (default-on) — render current working-memory entries.
  • recall (default-on) — install the memory/recall tool.
  • semantic (default-off) — render top-N semantic facts.
  • episodic (default-off) — render most-recent episodes.

Inclusion is independent of processing — the capture pipeline still runs digestRegenerate, consolidation, prune etc. for whichever tiers are configured. Turning off a preset just suppresses the section in that one generator's prompt.

// Primary agent — default; digest + working + recall
generator({ uses: [mem.capability] })

// Worker — recall tool only, no memory injected into the prompt
generator({
uses: [mem.capability.with({ digest: false, working: false })],
})

// Add semantic facts alongside the defaults
generator({ uses: [mem.capability.with({ semantic: true })] })

// For non-default top-N / limit values, bypass presets and use the
// factory directly:
generator({
uses: [mem.capability.with({ digest: false, working: false })],
context: {
memory: createMemoryContextFormatter({
digest: true,
working: true,
episodic: { limit: 10 },
}),
},
})

For handlers, opt out of every section preset to keep just resources + helpers:

handler({
uses: [mem.capability.with({
digest: false, working: false, recall: false,
})],
execute: async (input, ctx) => {
const items = ctx.cap.memory.recall()
await ctx.cap.workingMemory.add({ content: '...', importance: 0.8 })
},
})
capture​
capture: any;

Unified capture pipeline: observe → reflect → tick (+ consolidation when semantic). Takes string input.

captureFromItems​
captureFromItems: any;

Self-serving capture: reads last user message + truncated assistant response from session items. Use with .sideChain() after the generator.

consolidate?​
consolidate?: SequencerDefinition<any, any, undefined, undefined>;

Standalone consolidation sequencer (when semantic configured).

contextFormatter​
contextFormatter: (input, ctx) => MemoryContextSections | undefined;

Context formatter for generator context arrays.

Returns an object whose keys become nested XML tags under the parent key the formatter is registered against — e.g. context: { memory: mem.contextFormatter } produces <memory><digest>…</digest><working>…</working></memory>. Returning a pre-formatted string with embedded tags would be XML-escaped by the context aggregator's leaf renderer. Returns undefined when every section is empty so the generator omits <memory> entirely.

The convenience export uses the default { digest, working } configuration — equivalent to createMemoryContextFormatter(). For richer mixes (semantic facts, recent episodes, custom limits) call createMemoryContextFormatter(options) directly.

Parameters​
input​

unknown

ctx​

any

Returns​

MemoryContextSections | undefined

digest?​
digest?: object;

Digest tier — resource and helpers. Undefined if not configured. The digest is the always-on, narrative-shaped memory summary used by the simplified formatter.

helpers​
helpers: object;
helpers.computeSourceSignature​
computeSourceSignature: (semRef, epRef?) => object;

Compute a fresh source signature from the current semantic and (optional) episodic store state. Used both at digest write time and when comparing stored vs. current state for staleness.

Parameters​
semRef​

SemRef

epRef?​

EpRef

Returns​

object

episodeCount​
episodeCount: number;
semanticFactCount​
semanticFactCount: number;
semanticReinforcementSum​
semanticReinforcementSum: number;
helpers.isStale​
isStale: (ref, semRef, epRef?) => boolean;

True when the digest is missing or its stored sourceSignature differs from a freshly computed one — i.e. the underlying stores have changed since the last regeneration. Cheap; called on every consolidation / prune completion before deciding to spend an LLM call.

Parameters​
ref​

DigestRef

semRef​

SemRef

epRef?​

EpRef

Returns​

boolean

resource​
resource: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.digest?​
digest?: object;
default.digest.content​
content: string;
default.digest.generatedAt​
generatedAt: string;
default.digest.generatedAtTurn​
generatedAtTurn: number;
default.digest.sourceSignature​
sourceSignature: object;
default.digest.sourceSignature.episodeCount​
episodeCount: number;
default.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
default.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
default.totalGenerated​
totalGenerated: number;
flowIsolation?​
readonly flowIsolation?: boolean;
ref​
readonly ref: "digestMemory";
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
digest: ZodOptional<ZodObject<{
content: ZodString;
generatedAt: ZodString;
generatedAtTurn: ZodNumber;
sourceSignature: ZodObject<{
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}, "strip", ZodTypeAny, {
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}, {
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}>;
}, "strip", ZodTypeAny, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}>>;
totalGenerated: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated: number;
}, {
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.digest?​
digest?: object;
ClientType.digest.content​
content: string;
ClientType.digest.generatedAt​
generatedAt: string;
ClientType.digest.generatedAtTurn​
generatedAtTurn: number;
ClientType.digest.sourceSignature​
sourceSignature: object;
ClientType.digest.sourceSignature.episodeCount​
episodeCount: number;
ClientType.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
ClientType.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
ClientType.totalGenerated​
totalGenerated: number;
ContextType​
ContextType: ResourceContext<{
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated: number;
}>;
StateType​
StateType: object;
StateType.digest?​
digest?: object;
StateType.digest.content​
content: string;
StateType.digest.generatedAt​
generatedAt: string;
StateType.digest.generatedAtTurn​
generatedAtTurn: number;
StateType.digest.sourceSignature​
sourceSignature: object;
StateType.digest.sourceSignature.episodeCount​
episodeCount: number;
StateType.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
StateType.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
StateType.totalGenerated​
totalGenerated: number;
digestMemoryCapability?​
digestMemoryCapability?: CapabilityRef;

Digest memory capability (when digest configured).

episodic?​
episodic?: object;

Episodic memory module — resource and helpers. Undefined if not configured.

helpers​
helpers: object;
helpers.encode​
encode: (ref, episode, maxEpisodes) => Promise<{
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
consolidated: boolean;
content: string;
context: {
precedingTopic?: string;
sessionId: string;
};
durability: "persistent" | "permanent";
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale: boolean;
subject: string;
}>;

Encode a new episode into episodic memory.

Generates a unique ID and sets encodedAt to the current time. When the store reaches maxEpisodes, the oldest consolidated episode is evicted first; if none are consolidated, the oldest unconsolidated episode is evicted instead.

Parameters​
ref​

EpRef

episode​

EncodeEpisodeInput

maxEpisodes​

number

Returns​

Promise<{ category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; consolidated: boolean; content: string; context: { precedingTopic?: string; sessionId: string; }; durability: "persistent" | "permanent"; encodedAt: string; id: string; occurredAtTurn: number; significance: number; stale: boolean; subject: string; }>

helpers.markConsolidated​
markConsolidated: (ref, episodeIds) => Promise<void>;

Mark episodes as consolidated (promoted to semantic memory). No-op for episode IDs that don't exist in the store.

Parameters​
ref​

EpRef

episodeIds​

string[]

Returns​

Promise<void>

helpers.recent​
recent: (ref, limit?) => object[];

Get recent episodes sorted by occurredAtTurn descending (most recent first). Optionally limit the number of results.

Parameters​
ref​

EpRef

limit?​

number

Returns​

object[]

resource​
resource: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.episodes​
episodes: object[];
default.totalEncoded​
totalEncoded: number;
flowIsolation?​
readonly flowIsolation?: boolean;
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
episodes: ZodDefault<ZodArray<ZodObject<{
category: ZodEnum<...>;
consolidated: ZodDefault<...>;
content: ZodString;
context: ZodObject<..., ..., ..., ..., ...>;
durability: ZodDefault<...>;
encodedAt: ZodString;
id: ZodString;
occurredAtTurn: ZodNumber;
significance: ZodNumber;
stale: ZodDefault<...>;
subject: ZodDefault<...>;
}, "strip", ZodTypeAny, {
category: ... | ... | ... | ... | ... | ... | ... | ... | ...;
consolidated: boolean;
content: string;
context: {
precedingTopic?: ...;
sessionId: ...;
};
durability: ... | ...;
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale: boolean;
subject: string;
}, {
category: ... | ... | ... | ... | ... | ... | ... | ... | ...;
consolidated?: ... | ... | ...;
content: string;
context: {
precedingTopic?: ...;
sessionId: ...;
};
durability?: ... | ... | ...;
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale?: ... | ... | ...;
subject?: ... | ...;
}>, "many">>;
totalEncoded: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
episodes: object[];
totalEncoded: number;
}, {
episodes?: object[];
totalEncoded?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.episodes​
episodes: object[];
ClientType.totalEncoded​
totalEncoded: number;
ContextType​
ContextType: ResourceContext<{
episodes: object[];
totalEncoded: number;
}>;
StateType​
StateType: object;
StateType.episodes​
episodes: object[];
StateType.totalEncoded​
totalEncoded: number;
episodicMemoryCapability?​
episodicMemoryCapability?: CapabilityRef;

Episodic memory capability (when episodic configured).

formatContext​
formatContext: (input, ctx) => MemoryContextSections | undefined;

Alias of contextFormatter exposed under the MemoryProvider name.

Parameters​
input​

unknown

ctx​

any

Returns​

MemoryContextSections | undefined

Overrides​

MemoryProvider.formatContext

janitor?​
janitor?: BlockDefinition<ZodAny, ZodTypeAny, any, void>;

Memory hygiene janitor block (when hygiene !== false and at least one of semantic/episodic is configured). State-mutation-only — invoke directly via .tap()/.sideChain() for custom scheduling, or rely on the auto-wiring driven by hygiene.schedule.

janitorResource?​
janitorResource?: object & ResourceConfig<JsonObject> & object;

Session-scoped janitor tracking resource (when janitor is configured).

Type Declaration​
default​
readonly default: object;
default.lastCulledEpisodeIds​
lastCulledEpisodeIds: string[];
default.lastCulledFactIds​
lastCulledFactIds: string[];
default.lastMarkedStaleEpisodeIds​
lastMarkedStaleEpisodeIds: string[];
default.lastRunAt?​
lastRunAt?: string;
default.lastRunTurn​
lastRunTurn: number;
default.totalRuns​
totalRuns: number;
ref​
readonly ref: "janitor";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: ZodObject<{
lastCulledEpisodeIds: ZodDefault<ZodArray<ZodString, "many">>;
lastCulledFactIds: ZodDefault<ZodArray<ZodString, "many">>;
lastMarkedStaleEpisodeIds: ZodDefault<ZodArray<ZodString, "many">>;
lastRunAt: ZodOptional<ZodString>;
lastRunTurn: ZodDefault<ZodNumber>;
totalRuns: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
lastCulledEpisodeIds: string[];
lastCulledFactIds: string[];
lastMarkedStaleEpisodeIds: string[];
lastRunAt?: string;
lastRunTurn: number;
totalRuns: number;
}, {
lastCulledEpisodeIds?: string[];
lastCulledFactIds?: string[];
lastMarkedStaleEpisodeIds?: string[];
lastRunAt?: string;
lastRunTurn?: number;
totalRuns?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.lastCulledEpisodeIds​
lastCulledEpisodeIds: string[];
ClientType.lastCulledFactIds​
lastCulledFactIds: string[];
ClientType.lastMarkedStaleEpisodeIds​
lastMarkedStaleEpisodeIds: string[];
ClientType.lastRunAt?​
lastRunAt?: string;
ClientType.lastRunTurn​
lastRunTurn: number;
ClientType.totalRuns​
totalRuns: number;
ContextType​
ContextType: ResourceContext<{
lastCulledEpisodeIds: string[];
lastCulledFactIds: string[];
lastMarkedStaleEpisodeIds: string[];
lastRunAt?: string;
lastRunTurn: number;
totalRuns: number;
}>;
StateType​
StateType: object;
StateType.lastCulledEpisodeIds​
lastCulledEpisodeIds: string[];
StateType.lastCulledFactIds​
lastCulledFactIds: string[];
StateType.lastMarkedStaleEpisodeIds​
lastMarkedStaleEpisodeIds: string[];
StateType.lastRunAt?​
lastRunAt?: string;
StateType.lastRunTurn​
lastRunTurn: number;
StateType.totalRuns​
totalRuns: number;
prune?​
prune?: SequencerDefinition<any, any, undefined, undefined>;

Standalone prune sequencer (when semantic configured).

recall​
recall: (ctx, cue?) => RankedMemoryItem[];

Cross-store recall helper.

Parameters​
ctx​

any

cue?​

string

Returns​

RankedMemoryItem[]

Overrides​

MemoryProvider.recall

regenerateDigest?​
regenerateDigest?: SequencerDefinition<unknown, any, undefined, undefined>;

Manual digest regeneration block. Pre-bound with force: true so it always runs regardless of staleness — useful in tests and after bulk-loading memory in setup. Undefined when digest is not configured.

semantic?​
semantic?: object;

Semantic memory module — resource and helpers. Undefined if not configured.

helpers​
helpers: object;
helpers.addFact​
addFact: (ref, fact) => Promise<{
category: | "identity"
| "preference"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount: number;
sourceEpisodeIds: string[];
subject: string;
}>;

Add a new semantic fact. Generates ID and sets extractedAt and lastReinforced to the same ISO timestamp (creation counts as the first reinforcement). The dual-timestamp seeding is what lets the effectiveConfidence decay model anchor every fact from day zero — facts created before this fix have lastReinforced: undefined and fall back to extractedAt at read time.

Parameters​
ref​

SemRef

fact​

Omit<{ category: | "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; confidence: number; content: string; extractedAt: string; id: string; lastReinforced?: string; reinforcementCount: number; sourceEpisodeIds: string[]; subject: string; }, | "id" | "subject" | "extractedAt" | "lastReinforced" | "reinforcementCount"> & object

Returns​

Promise<{ category: | "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; confidence: number; content: string; extractedAt: string; id: string; lastReinforced?: string; reinforcementCount: number; sourceEpisodeIds: string[]; subject: string; }>

helpers.allFacts​
allFacts: (ref, subject?) => object[];

Get all facts, sorted by reinforcementCount descending (most established first). When subject is provided, returns only facts about that subject.

Parameters​
ref​

SemRef

subject?​

string

Returns​

object[]

helpers.query​
query: (ref, q, limit?, subject?) => object[];

Query semantic facts by keyword relevance (synchronous, token-overlap). For small stores (≤50), returns all facts sorted by reinforcementCount. For larger stores, filters by token overlap with the query. When subject is provided, scopes to that subject only.

Parameters​
ref​

SemRef

q​

string

limit?​

number

subject?​

string

Returns​

object[]

helpers.reinforce​
reinforce: (ref, factId, sourceEpisodeIds, confidenceBoost?) => Promise<
| {
category: | "identity"
| "preference"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount: number;
sourceEpisodeIds: string[];
subject: string;
}
| undefined>;

Reinforce an existing fact — bump confidence and reinforcementCount, merge new source episode IDs, update lastReinforced timestamp. Returns the updated fact, or undefined if factId not found.

Parameters​
ref​

SemRef

factId​

string

sourceEpisodeIds​

string[]

confidenceBoost?​

number

Returns​

Promise< | { category: | "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; confidence: number; content: string; extractedAt: string; id: string; lastReinforced?: string; reinforcementCount: number; sourceEpisodeIds: string[]; subject: string; } | undefined>

helpers.removeFact​
removeFact: (ref, factId) => Promise<void>;

Remove a fact by ID. No-op if not found.

Parameters​
ref​

SemRef

factId​

string

Returns​

Promise<void>

helpers.updateFact​
updateFact: (ref, factId, newContent, sourceEpisodeIds, newConfidence?) => Promise<
| {
category: | "identity"
| "preference"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount: number;
sourceEpisodeIds: string[];
subject: string;
}
| undefined>;

Update an existing fact's content while preserving its identity and provenance. Used when information changes (e.g., "works at Google" → "works at Stripe"). Merges new source episode IDs, sets lastReinforced, increments reinforcementCount. Returns the updated fact, or undefined if factId not found.

Parameters​
ref​

SemRef

factId​

string

newContent​

string

sourceEpisodeIds​

string[]

newConfidence?​

number

Returns​

Promise< | { category: | "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; confidence: number; content: string; extractedAt: string; id: string; lastReinforced?: string; reinforcementCount: number; sourceEpisodeIds: string[]; subject: string; } | undefined>

resource​
resource: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.facts​
facts: object[];
default.totalConsolidations​
totalConsolidations: number;
default.totalExtracted​
totalExtracted: number;
edges?​
readonly edges?: EdgeSlotConfig;
flowIsolation?​
readonly flowIsolation?: boolean;
ref​
readonly ref: "semanticMemory";
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
facts: ZodDefault<ZodArray<ZodObject<{
category: ZodEnum<...>;
confidence: ZodNumber;
content: ZodString;
extractedAt: ZodString;
id: ZodString;
lastReinforced: ZodOptional<...>;
reinforcementCount: ZodDefault<...>;
sourceEpisodeIds: ZodArray<..., ...>;
subject: ZodDefault<...>;
}, "strip", ZodTypeAny, {
category: ... | ... | ... | ... | ... | ... | ...;
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: ... | ...;
reinforcementCount: number;
sourceEpisodeIds: ...[];
subject: string;
}, {
category: ... | ... | ... | ... | ... | ... | ...;
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: ... | ...;
reinforcementCount?: ... | ...;
sourceEpisodeIds: ...[];
subject?: ... | ...;
}>, "many">>;
totalConsolidations: ZodDefault<ZodNumber>;
totalExtracted: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
facts: object[];
totalConsolidations: number;
totalExtracted: number;
}, {
facts?: object[];
totalConsolidations?: number;
totalExtracted?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.facts​
facts: object[];
ClientType.totalConsolidations​
totalConsolidations: number;
ClientType.totalExtracted​
totalExtracted: number;
ContextType​
ContextType: ResourceContext<{
facts: object[];
totalConsolidations: number;
totalExtracted: number;
}>;
StateType​
StateType: object;
StateType.facts​
facts: object[];
StateType.totalConsolidations​
totalConsolidations: number;
StateType.totalExtracted​
totalExtracted: number;
semanticMemoryCapability?​
semanticMemoryCapability?: CapabilityRef;

Semantic memory capability (when semantic configured).

sessionResources​
sessionResources: object;

Session-scoped resources for this memory system. Spread into defineFlow's single flat resources map:

resources: { ...mem.sessionResources, ...mem.userResources }

Always includes workingMemory and memorySystem.

janitor?​
janitor?: object & ResourceConfig<JsonObject> & object;

Session-scoped janitor resource — included when hygiene is enabled.

Type Declaration​
default​
readonly default: object;
default.lastCulledEpisodeIds​
lastCulledEpisodeIds: string[];
default.lastCulledFactIds​
lastCulledFactIds: string[];
default.lastMarkedStaleEpisodeIds​
lastMarkedStaleEpisodeIds: string[];
default.lastRunAt?​
lastRunAt?: string;
default.lastRunTurn​
lastRunTurn: number;
default.totalRuns​
totalRuns: number;
ref​
readonly ref: "janitor";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: ZodObject<{
lastCulledEpisodeIds: ZodDefault<ZodArray<ZodString, "many">>;
lastCulledFactIds: ZodDefault<ZodArray<ZodString, "many">>;
lastMarkedStaleEpisodeIds: ZodDefault<ZodArray<ZodString, "many">>;
lastRunAt: ZodOptional<ZodString>;
lastRunTurn: ZodDefault<ZodNumber>;
totalRuns: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
lastCulledEpisodeIds: string[];
lastCulledFactIds: string[];
lastMarkedStaleEpisodeIds: string[];
lastRunAt?: string;
lastRunTurn: number;
totalRuns: number;
}, {
lastCulledEpisodeIds?: string[];
lastCulledFactIds?: string[];
lastMarkedStaleEpisodeIds?: string[];
lastRunAt?: string;
lastRunTurn?: number;
totalRuns?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.lastCulledEpisodeIds​
lastCulledEpisodeIds: string[];
ClientType.lastCulledFactIds​
lastCulledFactIds: string[];
ClientType.lastMarkedStaleEpisodeIds​
lastMarkedStaleEpisodeIds: string[];
ClientType.lastRunAt?​
lastRunAt?: string;
ClientType.lastRunTurn​
lastRunTurn: number;
ClientType.totalRuns​
totalRuns: number;
ContextType​
ContextType: ResourceContext<{
lastCulledEpisodeIds: string[];
lastCulledFactIds: string[];
lastMarkedStaleEpisodeIds: string[];
lastRunAt?: string;
lastRunTurn: number;
totalRuns: number;
}>;
StateType​
StateType: object;
StateType.lastCulledEpisodeIds​
lastCulledEpisodeIds: string[];
StateType.lastCulledFactIds​
lastCulledFactIds: string[];
StateType.lastMarkedStaleEpisodeIds​
lastMarkedStaleEpisodeIds: string[];
StateType.lastRunAt?​
lastRunAt?: string;
StateType.lastRunTurn​
lastRunTurn: number;
StateType.totalRuns​
totalRuns: number;
memorySystem​
memorySystem: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
default.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
default.lastConsolidationTurn​
lastConsolidationTurn: number;
default.lastProcessedIndex​
lastProcessedIndex: number;
default.readMessages​
readMessages: object[] | null;
ref​
readonly ref: "memorySystem";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: ZodObject<{
episodicWritesSinceLastConsolidation: ZodDefault<ZodNumber>;
evictedPersistentSinceLastConsolidation: ZodDefault<ZodNumber>;
lastConsolidationTurn: ZodDefault<ZodNumber>;
lastProcessedIndex: ZodDefault<ZodNumber>;
readMessages: ZodDefault<ZodNullable<ZodArray<ZodObject<{
id: ZodString;
ts: ZodNumber;
}, "strip", ZodTypeAny, {
id: string;
ts: number;
}, {
id: string;
ts: number;
}>, "many">>>;
}, "strip", ZodTypeAny, {
episodicWritesSinceLastConsolidation: number;
evictedPersistentSinceLastConsolidation: number;
lastConsolidationTurn: number;
lastProcessedIndex: number;
readMessages: object[] | null;
}, {
episodicWritesSinceLastConsolidation?: number;
evictedPersistentSinceLastConsolidation?: number;
lastConsolidationTurn?: number;
lastProcessedIndex?: number;
readMessages?: object[] | null;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
ClientType.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
ClientType.lastConsolidationTurn​
lastConsolidationTurn: number;
ClientType.lastProcessedIndex​
lastProcessedIndex: number;
ClientType.readMessages​
readMessages: object[] | null;
ContextType​
ContextType: ResourceContext<{
episodicWritesSinceLastConsolidation: number;
evictedPersistentSinceLastConsolidation: number;
lastConsolidationTurn: number;
lastProcessedIndex: number;
readMessages: object[] | null;
}>;
StateType​
StateType: object;
StateType.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
StateType.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
StateType.lastConsolidationTurn​
lastConsolidationTurn: number;
StateType.lastProcessedIndex​
lastProcessedIndex: number;
StateType.readMessages​
readMessages: object[] | null;
workingMemory​
workingMemory: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.currentTurn​
currentTurn: number;
default.entries​
entries: object[];
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: ZodObject<{
currentTurn: ZodDefault<ZodNumber>;
entries: ZodDefault<ZodArray<ZodObject<{
addedAtTurn: ZodNumber;
category: ZodDefault<ZodEnum<...>>;
content: ZodString;
durability: ZodDefault<ZodEnum<...>>;
id: ZodString;
importance: ZodNumber;
lastAccessedAtTurn: ZodNumber;
metadata: ZodOptional<ZodRecord<..., ...>>;
pinned: ZodBoolean;
salience: ZodNumber;
}, "strip", ZodTypeAny, {
addedAtTurn: number;
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<..., ...>;
pinned: boolean;
salience: number;
}, {
addedAtTurn: number;
category?: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability?: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<..., ...>;
pinned: boolean;
salience: number;
}>, "many">>;
}, "strip", ZodTypeAny, {
currentTurn: number;
entries: object[];
}, {
currentTurn?: number;
entries?: object[];
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.currentTurn​
currentTurn: number;
ClientType.entries​
entries: object[];
ContextType​
ContextType: ResourceContext<{
currentTurn: number;
entries: object[];
}>;
StateType​
StateType: object;
StateType.currentTurn​
currentTurn: number;
StateType.entries​
entries: object[];
tool​
tool: object;

Agent-invocable memory tools.

Install on a generator via tools: [mem.tool.recall()]. The tool searches stored memory (semantic facts + past episodes) on demand; working memory is intentionally excluded — it lives in the formatter.

Strategy and defaults are configured at memory.system({ tool }) time.

connect?​
connect?: () => BlockDefinition<ZodObject<{
depth: ZodOptional<ZodNumber>;
from: ZodString;
to: ZodOptional<ZodString>;
}, "strip", ZodTypeAny, {
depth?: number;
from: string;
to?: string;
}, {
depth?: number;
from: string;
to?: string;
}>>;

Connect-tool factory (relations tier) — returns the memory/connect block. Present only when relations is enabled; otherwise omitted (calling it would have no graph to traverse).

Returns​

BlockDefinition<ZodObject<{ depth: ZodOptional<ZodNumber>; from: ZodString; to: ZodOptional<ZodString>; }, "strip", ZodTypeAny, { depth?: number; from: string; to?: string; }, { depth?: number; from: string; to?: string; }>>

recall​
recall: () => BlockDefinition<any>;

Recall-tool factory — returns the handler block, ready to install.

Returns​

BlockDefinition<any>

userResources​
userResources: object;

User-scoped resources for this memory system. Spread into defineFlow's single flat resources map alongside sessionResources. Populated based on which memory tiers are configured: episodicMemory (if episodic enabled), semanticMemory (if semantic enabled).

digestMemory?​
digestMemory?: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.digest?​
digest?: object;
default.digest.content​
content: string;
default.digest.generatedAt​
generatedAt: string;
default.digest.generatedAtTurn​
generatedAtTurn: number;
default.digest.sourceSignature​
sourceSignature: object;
default.digest.sourceSignature.episodeCount​
episodeCount: number;
default.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
default.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
default.totalGenerated​
totalGenerated: number;
flowIsolation?​
readonly flowIsolation?: boolean;
ref​
readonly ref: "digestMemory";
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
digest: ZodOptional<ZodObject<{
content: ZodString;
generatedAt: ZodString;
generatedAtTurn: ZodNumber;
sourceSignature: ZodObject<{
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}, "strip", ZodTypeAny, {
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}, {
episodeCount: ...;
semanticFactCount: ...;
semanticReinforcementSum: ...;
}>;
}, "strip", ZodTypeAny, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}>>;
totalGenerated: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated: number;
}, {
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.digest?​
digest?: object;
ClientType.digest.content​
content: string;
ClientType.digest.generatedAt​
generatedAt: string;
ClientType.digest.generatedAtTurn​
generatedAtTurn: number;
ClientType.digest.sourceSignature​
sourceSignature: object;
ClientType.digest.sourceSignature.episodeCount​
episodeCount: number;
ClientType.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
ClientType.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
ClientType.totalGenerated​
totalGenerated: number;
ContextType​
ContextType: ResourceContext<{
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated: number;
}>;
StateType​
StateType: object;
StateType.digest?​
digest?: object;
StateType.digest.content​
content: string;
StateType.digest.generatedAt​
generatedAt: string;
StateType.digest.generatedAtTurn​
generatedAtTurn: number;
StateType.digest.sourceSignature​
sourceSignature: object;
StateType.digest.sourceSignature.episodeCount​
episodeCount: number;
StateType.digest.sourceSignature.semanticFactCount​
semanticFactCount: number;
StateType.digest.sourceSignature.semanticReinforcementSum​
semanticReinforcementSum: number;
StateType.totalGenerated​
totalGenerated: number;
episodicMemory?​
episodicMemory?: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.episodes​
episodes: object[];
default.totalEncoded​
totalEncoded: number;
flowIsolation?​
readonly flowIsolation?: boolean;
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
episodes: ZodDefault<ZodArray<ZodObject<{
category: ZodEnum<...>;
consolidated: ZodDefault<...>;
content: ZodString;
context: ZodObject<..., ..., ..., ..., ...>;
durability: ZodDefault<...>;
encodedAt: ZodString;
id: ZodString;
occurredAtTurn: ZodNumber;
significance: ZodNumber;
stale: ZodDefault<...>;
subject: ZodDefault<...>;
}, "strip", ZodTypeAny, {
category: ... | ... | ... | ... | ... | ... | ... | ... | ...;
consolidated: boolean;
content: string;
context: {
precedingTopic?: ...;
sessionId: ...;
};
durability: ... | ...;
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale: boolean;
subject: string;
}, {
category: ... | ... | ... | ... | ... | ... | ... | ... | ...;
consolidated?: ... | ... | ...;
content: string;
context: {
precedingTopic?: ...;
sessionId: ...;
};
durability?: ... | ... | ...;
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale?: ... | ... | ...;
subject?: ... | ...;
}>, "many">>;
totalEncoded: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
episodes: object[];
totalEncoded: number;
}, {
episodes?: object[];
totalEncoded?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.episodes​
episodes: object[];
ClientType.totalEncoded​
totalEncoded: number;
ContextType​
ContextType: ResourceContext<{
episodes: object[];
totalEncoded: number;
}>;
StateType​
StateType: object;
StateType.episodes​
episodes: object[];
StateType.totalEncoded​
totalEncoded: number;
semanticMemory?​
semanticMemory?: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.facts​
facts: object[];
default.totalConsolidations​
totalConsolidations: number;
default.totalExtracted​
totalExtracted: number;
edges?​
readonly edges?: EdgeSlotConfig;
flowIsolation?​
readonly flowIsolation?: boolean;
ref​
readonly ref: "semanticMemory";
scope​
readonly scope: "user" | "org";
stateSchema​
readonly stateSchema: ZodObject<{
facts: ZodDefault<ZodArray<ZodObject<{
category: ZodEnum<...>;
confidence: ZodNumber;
content: ZodString;
extractedAt: ZodString;
id: ZodString;
lastReinforced: ZodOptional<...>;
reinforcementCount: ZodDefault<...>;
sourceEpisodeIds: ZodArray<..., ...>;
subject: ZodDefault<...>;
}, "strip", ZodTypeAny, {
category: ... | ... | ... | ... | ... | ... | ...;
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: ... | ...;
reinforcementCount: number;
sourceEpisodeIds: ...[];
subject: string;
}, {
category: ... | ... | ... | ... | ... | ... | ...;
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: ... | ...;
reinforcementCount?: ... | ...;
sourceEpisodeIds: ...[];
subject?: ... | ...;
}>, "many">>;
totalConsolidations: ZodDefault<ZodNumber>;
totalExtracted: ZodDefault<ZodNumber>;
}, "strip", ZodTypeAny, {
facts: object[];
totalConsolidations: number;
totalExtracted: number;
}, {
facts?: object[];
totalConsolidations?: number;
totalExtracted?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.facts​
facts: object[];
ClientType.totalConsolidations​
totalConsolidations: number;
ClientType.totalExtracted​
totalExtracted: number;
ContextType​
ContextType: ResourceContext<{
facts: object[];
totalConsolidations: number;
totalExtracted: number;
}>;
StateType​
StateType: object;
StateType.facts​
facts: object[];
StateType.totalConsolidations​
totalConsolidations: number;
StateType.totalExtracted​
totalExtracted: number;
working​
working: object;

Working memory module — resource and helpers.

helpers​
helpers: object;
helpers.add​
add: (ref, entry, config?) => Promise<{
addedAtTurn: number;
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}>;

Add an entry to working memory.

If the number of entries reaches capacity, the lowest-salience non-pinned entry is evicted. If all entries are pinned, the new entry is added anyway (exceeding capacity).

Returns the fully-formed entry that was added.

Parameters​
ref​

WmRef

entry​

AddEntryInput

config?​

WorkingMemoryHelperConfig

Returns​

Promise<{ addedAtTurn: number; category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability: "transient" | "session" | "persistent" | "permanent"; id: string; importance: number; lastAccessedAtTurn: number; metadata?: Record<string, any>; pinned: boolean; salience: number; }>

helpers.computeDecay​
computeDecay: (elapsed, strategy, rate) => number;

Compute the decay factor for a given elapsed turn count.

  • power-law: ACT-R activation decay — (1 + elapsed)^(-rate). With default rate 0.5 this gives fast initial decay with a long tail.
  • exponential: exp(-rate × elapsed).
  • none: always returns 1 (no decay).

Negative elapsed values are clamped to 0.

Parameters​
elapsed​

number

strategy​

DecayStrategy

rate​

number

Returns​

number

helpers.computeSalience​
computeSalience: (entry, currentTurn, decay) => number;

Compute the current salience of an entry: importance × decay(elapsed). Result is clamped to [0, 1].

Parameters​
entry​
addedAtTurn​

number

category​

| "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"

content​

string

durability​

"transient" | "session" | "persistent" | "permanent"

id​

string

importance​

number

lastAccessedAtTurn​

number

metadata?​

Record<string, any>

pinned​

boolean

salience​

number

currentTurn​

number

decay​

WorkingMemoryDecayConfig

Returns​

number

helpers.evict​
evict: (ref, id) => Promise<boolean>;

Remove an entry by ID. Explicit eviction overrides pin status. Returns true if the entry was found and removed, false otherwise.

Parameters​
ref​

WmRef

id​

string

Returns​

Promise<boolean>

helpers.items​
items: (ref) => object[];

Get current working memory entries sorted by salience descending. Synchronous read — returns a snapshot of the current state. Ties are broken by array position (stable sort).

Parameters​
ref​

WmRef

Returns​

object[]

helpers.pin​
pin: (ref, id, config?) => Promise<boolean>;

Pin an entry to protect it from automatic eviction. Returns false if the entry doesn't exist or if maxPinnedSlots is reached.

Parameters​
ref​

WmRef

id​

string

config?​

WorkingMemoryHelperConfig

Returns​

Promise<boolean>

helpers.refresh​
refresh: (ref, id, config?) => Promise<boolean>;

Refresh an entry: reset its lastAccessedAtTurn to the current turn and recompute its salience. Models the "access boost" in memory theory. Returns true if the entry was found, false otherwise (no-op for missing IDs).

Parameters​
ref​

WmRef

id​

string

config?​

WorkingMemoryHelperConfig

Returns​

Promise<boolean>

helpers.tick​
tick: (ref, config?) => Promise<void>;

Advance the turn counter by 1 and recompute salience for all entries. This is the "clock" for decay — call it once per interaction turn.

Parameters​
ref​

WmRef

config?​

WorkingMemoryHelperConfig

Returns​

Promise<void>

helpers.unpin​
unpin: (ref, id) => Promise<boolean>;

Remove pin protection from an entry. Returns true if the entry was found (regardless of prior pin state), false if not found.

Parameters​
ref​

WmRef

id​

string

Returns​

Promise<boolean>

resource​
resource: object & ResourceConfig<JsonObject> & object;
Type Declaration​
default​
readonly default: object;
default.currentTurn​
currentTurn: number;
default.entries​
entries: object[];
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: ZodObject<{
currentTurn: ZodDefault<ZodNumber>;
entries: ZodDefault<ZodArray<ZodObject<{
addedAtTurn: ZodNumber;
category: ZodDefault<ZodEnum<...>>;
content: ZodString;
durability: ZodDefault<ZodEnum<...>>;
id: ZodString;
importance: ZodNumber;
lastAccessedAtTurn: ZodNumber;
metadata: ZodOptional<ZodRecord<..., ...>>;
pinned: ZodBoolean;
salience: ZodNumber;
}, "strip", ZodTypeAny, {
addedAtTurn: number;
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<..., ...>;
pinned: boolean;
salience: number;
}, {
addedAtTurn: number;
category?: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability?: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<..., ...>;
pinned: boolean;
salience: number;
}>, "many">>;
}, "strip", ZodTypeAny, {
currentTurn: number;
entries: object[];
}, {
currentTurn?: number;
entries?: object[];
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.currentTurn​
currentTurn: number;
ClientType.entries​
entries: object[];
ContextType​
ContextType: ResourceContext<{
currentTurn: number;
entries: object[];
}>;
StateType​
StateType: object;
StateType.currentTurn​
currentTurn: number;
StateType.entries​
entries: object[];
workingMemoryCapability​
workingMemoryCapability: CapabilityRef;

Working memory capability. Available on all block kinds.


MemorySystemConfig​

Top-level configuration for memory.system().

Properties​

consolidationModel?​
consolidationModel?: string | string[];

Model override for the consolidation generator. Defaults to model. Consolidation has heavier structured-output demands than the observer, so a stronger primary with a cheap fallback (e.g. ['gpt-6.1-sol', 'gpt-6-luna']) is a common configuration.

digest?​
digest?: true | DigestSystemConfig;

Digest tier config. true for defaults; omit to disable.

Requires semantic (the digest summarises the same store the semantic tier owns). Scope is inherited from semantic; there is no separate digest.scope knob.

episodic?​
episodic?: true | EpisodicMemoryConfig;

Episodic memory config. true for defaults. Omit to disable.

evaluator?​
evaluator?: CaptureEvaluatorBlock;

Optional evaluator asked before the observer on each capture: is anything in the new messages worth remembering? remember runs the observer as usual; skip writes nothing and marks the messages read. An evaluator error fails that capture and leaves the messages unread. Usually captureEvaluator(model); any evaluator block built with captureQuestions works. Omit it and capture is unchanged.

hygiene?​
hygiene?: boolean | HygieneConfig;

Memory hygiene configuration. Default-on. Pass false to turn it off: no confidence decay, no episodic TTL, stores grow without bound.

inputSchema?​
inputSchema?: ZodTypeAny;

Optional input schema for source override.

maxAssistantChars?​
maxAssistantChars?: number;

Max chars of assistant response to include in captureFromItems. Default: 500.

model​
model: string | string[];

Default model id (or fallback chain) used by every memory generator unless overridden. Pass an array (e.g. ['gpt-6-luna', 'gpt-6.1-sol']) to build a fallback chain — the generator walks the list on retryable provider errors.

name?​
name?: string;

Optional custom name for the capture pipeline.

pruneModel?​
pruneModel?: string | string[];

Model override for the prune generator. Defaults to model.

semantic?​
semantic?: true | SemanticMemoryConfig;

Semantic memory config. true for defaults. Omit to disable. Requires episodic.

source?​
source?: (input, ctx) => string;

Optional custom source function — overrides reading from ctx.session.items.

Parameters​
input​

unknown

ctx​

any

Returns​

string

tool?​
tool?: MemoryToolConfig;

Recall-tool config. Omit to use defaults (llm-filter strategy).

working​
working: true | WorkingMemorySystemConfig;

Working memory config. true for defaults. Required.


MemoryToolConfig​

Configuration for the agent-invocable recall tool.

Properties​

defaults?​
defaults?: object;

Defaults for tool input handling.

limit?​
limit?: number;

Default limit. Default: 5.

perItemCharCap?​
perItemCharCap?: number;

Per-item char cap on returned content. Default: 400.

model?​
model?: string;

Model id for the strategy's LLM filter call (when applicable). Defaults to MemorySystemConfig.model.

strategy?​
strategy?: "llm-filter" | RetrievalStrategy;

Retrieval strategy. Either a built-in name or a custom RetrievalStrategy object. Default: 'llm-filter'.


RelationsConfig​

Configuration for the relations (typed-edge knowledge graph) tier.

Relations are opt-in and default OFF: omitting semantic.relations adds zero behaviour and leaves the semantic store byte-for-byte unchanged. When enabled, consolidation also extracts typed directed edges between subjects (e.g. user --married to--> moni) and stores them on the semantic resource's framework edges field.

Properties​

createImplicitEntities?​
createImplicitEntities?: boolean;

When an extracted edge references an endpoint that is not a known fact subject, mint a node for it instead of dropping the edge. Default false (unknown endpoints are dropped).

maxEdges?​
maxEdges?: number;

Max stored edges. On overflow the framework culls lowest-confidence edges.

vocabulary?​
vocabulary?: string[];

Curated relation vocabulary. When set, consolidation drops (and warns on) any extracted edge whose type is not in the list. Omit for free-text relation types.


ResolvedHygieneConfig​

Resolved hygiene configuration passed into the janitor block. The factory (memory.system()) collapses true | false | object shapes into this concrete form before reaching here.

Properties​

confidenceDecay​
confidenceDecay:
| false
| {
cullFloor: number;
halfLife: number;
};

Confidence-decay parameters, or false to skip the semantic branch.

episodicTTL​
episodicTTL: false | EpisodicTTLConfig & object;

Episodic-TTL parameters, or false to skip the episodic branch.

schedule​
schedule: "onConsolidation" | "onCapture" | "manual";

Where the janitor is auto-scheduled, or 'manual' for no auto-wiring.


RetrievalStrategy​

Pluggable retrieval backend.

Strategies expose blocks rather than a single rank() method so the recall tool can compose them as a sequencer (prepare → optional filter → format) without any handler reaching into asRuntime() to invoke a generator. V1 ships llm-filter (prepare + filter); future backends (vector, keyword) supply only prepareBlock.

Properties​

filterBlock?​
filterBlock?: BlockDefinition<any, any, any, any>;

Optional LLM filter step. Strategies without an LLM call (vector, keyword) omit this; the recall tool then skips straight to format and returns the intrinsic-ranked top-N. Input: { query: string; limit: number; candidates: MemoryItem[] }. Output: { selectedIds: string[] }.

formatBlock?​
formatBlock?: BlockDefinition<any, any, any, any>;

Optional override; when omitted, the recall tool installs its default format handler (caps content per-item, drops hallucinated IDs, builds the result envelope). Input: PrepareEnvelope & { selectedIds?: string[] }. Output: RecallToolResult.

name​
name: string;

Strategy identifier; surfaced on tool results as strategy.

prepareBlock​
prepareBlock: BlockDefinition<any, any>;

Reads stores, ranks candidates intrinsically, returns the carrier envelope. Input: RecallToolInput (the tool's input, with limit defaulted/clamped). Output: PrepareEnvelope.


SemanticMemoryCapabilityConfig​

Config for semantic memory capability.

Extends​

Properties​

edges?​
edges?: EdgeSlotConfig;

Edge-slot config for the relations tier. When set, the semantic resource is created with a typed-edge graph (edges field + .edges API). Omit to disable relations (no edge field, no behaviour change).

flowIsolation?​
flowIsolation?: boolean;

The resource's own flowIsolation. true keys the store per flow instance, false shares it across flows, and either wins over the flow's isolateUserState / isolateOrgState default. Omit it to take that default.

Inherited from​

MemoryResourceOptions.flowIsolation

scope?​
scope?: "user" | "org";

Resource scope. Default: 'user'.


SemanticMemoryConfig​

Configuration for the semantic memory module within memory.system().

Properties​

consolidation?​
consolidation?: object;
episodicThreshold?​
episodicThreshold?: number;

Consolidate after this many new episodic entries. Default: 5.

minInterval?​
minInterval?: number;

Don't consolidate more than once per N turns. Default: DEFAULT_CONSOLIDATION_CONFIG.minInterval.

onEviction?​
onEviction?: boolean;

Also consolidate when persistent items evicted from WM. Default: true.

flowIsolation?​
flowIsolation?: boolean;

Isolate this tier per flow instance (true) or share it across flows (false), whatever the flow's isolateUserState / isolateOrgState says. Omit to take the flow's default. Not inherited from episodic.

pruneThreshold?​
pruneThreshold?: number;

Prune when fact count reaches this threshold. Default: 20. 0 to disable.

relations?​
relations?: boolean | RelationsConfig;

Relations (typed-edge knowledge graph) tier. Opt-in, default OFF. true for defaults; an object for curated vocabulary / size cap / implicit entities. Omit to disable — no edge field, no edge extraction, no behaviour change to the personalization path.

scope?​
scope?: "user" | "org";

Scope for semantic storage. Default: same as episodic, or 'user'.


WorkingMemoryBlockConfig​

Base config shared by all working memory blocks.

Extended by​

Properties​

capacity?​
capacity?: number;
decay?​
decay?: Partial<WorkingMemoryDecayConfig>;
maxPinnedSlots?​
maxPinnedSlots?: number;

WorkingMemoryCaptureConfig​

Config for the bundled capture sequencer.

Extends​

Properties​

capacity?​
capacity?: number;
Inherited from​

WorkingMemoryObserveConfig.capacity

decay?​
decay?: Partial<WorkingMemoryDecayConfig>;
Inherited from​

WorkingMemoryObserveConfig.decay

maxExtractPerTurn?​
maxExtractPerTurn?: number;

Maximum observations to extract per turn. Default: 3.

Inherited from​

WorkingMemoryObserveConfig.maxExtractPerTurn

maxPinnedSlots?​
maxPinnedSlots?: number;
Inherited from​

WorkingMemoryObserveConfig.maxPinnedSlots

model?​
model?: string;

Model ID for the extraction LLM. Default: 'gpt-6-luna'.

Inherited from​

WorkingMemoryObserveConfig.model

name?​
name?: string;
Inherited from​

WorkingMemoryObserveConfig.name


WorkingMemoryDecayConfig​

Decay configuration for working memory salience computation.

Properties​

rate​
rate: number;
strategy​
strategy: DecayStrategy;

WorkingMemoryHelperConfig​

Configuration for working memory helper operations.

Properties​

capacity?​
capacity?: number;

Maximum number of entries. Default: 7 (Miller's number).

decay?​
decay?: Partial<WorkingMemoryDecayConfig>;

Decay configuration. Default: power-law with rate 0.5.

maxPinnedSlots?​
maxPinnedSlots?: number;

Maximum pinned slots. Default: 2.


WorkingMemoryObserveConfig​

Config for the observe generator.

Extends​

Extended by​

Properties​

capacity?​
capacity?: number;
Inherited from​

WorkingMemoryBlockConfig.capacity

decay?​
decay?: Partial<WorkingMemoryDecayConfig>;
Inherited from​

WorkingMemoryBlockConfig.decay

maxExtractPerTurn?​
maxExtractPerTurn?: number;

Maximum observations to extract per turn. Default: 3.

maxPinnedSlots?​
maxPinnedSlots?: number;
Inherited from​

WorkingMemoryBlockConfig.maxPinnedSlots

model?​
model?: string;

Model ID for the extraction LLM. Default: 'gpt-6-luna'.

name?​
name?: string;

WorkingMemorySystemConfig​

Configuration for the working memory module within memory.system().

Properties​

capacity?​
capacity?: number;
decay?​
decay?: Partial<WorkingMemoryDecayConfig>;
maxPinnedSlots?​
maxPinnedSlots?: number;

Type Aliases​

AddEntryInput​

type AddEntryInput = object;

Input for adding an entry. ID is auto-generated if omitted.

Properties​

category?​
category?:
| "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content​
content: string;
durability?​
durability?: "transient" | "session" | "persistent" | "permanent";
id?​
id?: string;
importance​
importance: number;
metadata?​
metadata?: Record<string, any>;
pinned?​
pinned?: boolean;

AddSemanticFactInput​

type AddSemanticFactInput = Omit<SemanticFact,
| "id"
| "extractedAt"
| "lastReinforced"
| "reinforcementCount"
| "subject"> & object;

Input type for adding a new semantic fact via capability helpers.

Type Declaration​

subject?​
subject?: string;

BuiltInStrategyName​

type BuiltInStrategyName = "llm-filter";

Built-in strategy names.


CaptureChoice​

type CaptureChoice = "remember" | "skip";

What the capture evaluator answers: remember or skip.


CaptureEvaluatorBlock​

type CaptureEvaluatorBlock = BlockDefinition<ZodTypeAny, ZodTypeAny, string, {
answers: {
capture: ChoiceAnswer<CaptureChoice>;
};
}>;

The evaluator block system({ evaluator }) accepts: any block that takes the window text and answers capture with remember or skip. Built by captureEvaluator, or by hand with core's evaluator() and captureQuestions. Extra questions are allowed and ignored.


CaptureQuestions​

type CaptureQuestions = typeof captureQuestions;

The question set capture reads: { capture: choice(remember | skip) }.


ConnectToolInput​

type ConnectToolInput = z.infer<typeof connectToolInputSchema>;

Inferred input shape from connectToolInputSchema.


ConsolidationOutput​

type ConsolidationOutput = z.infer<typeof consolidationOutputSchema>;

CreateConnectToolOptions​

type CreateConnectToolOptions = object;

Options for createConnectTool.

Properties​

strategyName?​
strategyName?: string;

Strategy identifier surfaced on results. Defaults to 'graph'.


CreateRecallToolOptions​

type CreateRecallToolOptions = object;

Options for createRecallTool.

Properties​

defaults?​
defaults?: object;

Defaults applied when the agent's input or factory consumer omits values.

limit?​
limit?: number;

Default limit. Default: 5.

perItemCharCap?​
perItemCharCap?: number;

Hard char cap per result item. Default: 400.

strategy​
strategy: RetrievalStrategy;

Strategy whose blocks compose the pipeline. Constructed once, reused per call.


DecayStrategy​

type DecayStrategy = "power-law" | "exponential" | "none";

Decay strategies for working memory salience computation.


Digest​

type Digest = z.infer<typeof digestSchema>;

DigestMemoryState​

type DigestMemoryState = z.infer<typeof digestMemoryStateSchema>;

DigestRegenerateConfig​

type DigestRegenerateConfig = MemorySystemBlocksConfig & object;

Combined config for the digest blocks. Adds an optional shared resource reference so all digest blocks (and the memory system at large) share the same defineResource() instance.

Type Declaration​

_digestResource?​
_digestResource?: ReturnType<typeof createDigestMemoryResource>;
digest​
digest: DigestBlocksConfig;

DigestSourceSignature​

type DigestSourceSignature = z.infer<typeof digestSourceSignatureSchema>;

EncodeEpisodeInput​

type EncodeEpisodeInput = Omit<Episode, "id" | "encodedAt" | "consolidated" | "stale">;

Input for encoding a new episode — ID, encodedAt, consolidated, and stale are generated automatically. durability must be supplied by the caller (reflect routes only 'persistent' and 'permanent' items here). subject is the observer-computed owner of the episode ('user' or a lowercase name); reflect passes its normalized subject so consolidation inherits ownership rather than re-deriving it.


Episode​

type Episode = z.infer<typeof episodeSchema>;

A single episodic memory record.


EpisodicMemoryState​

type EpisodicMemoryState = z.infer<typeof episodicMemoryStateSchema>;

The full episodic memory state.


EpisodicSectionOption​

type EpisodicSectionOption =
| boolean
| {
limit?: number;
};

Section enable flag with optional limit knob (episodic).


GraphExpandOptions​

type GraphExpandOptions = object;

Options for graphExpandCandidates.

Properties​

depth?​
depth?: number;

Max hops for the ego-graph around each matched focal node. Default 2.


JanitorState​

type JanitorState = z.infer<typeof janitorStateSchema>;

Janitor tracking state.


LlmFilterStrategyOptions​

type LlmFilterStrategyOptions = object;

Options for createLlmFilterStrategy.

Properties​

exactPhrasePassThrough?​
exactPhrasePassThrough?: boolean;

Include the Stage 1.5 exact-phrase pass-through. Default: true.

model​
model: string;

Model id used for the filter call.


MemoryCapabilityPreset​

type MemoryCapabilityPreset = typeof MEMORY_CAPABILITY_PRESETS[number];

Union of valid preset names on the composed memory capability.


MemoryContextSections​

type MemoryContextSections = object;

Sections returned by a memory context formatter. Each is omitted when empty.

Properties​

digest?​
digest?: string;
episodic?​
episodic?: string;
semantic?​
semantic?: string;
working?​
working?: string;

MemoryContextValue​

type MemoryContextValue =
| {
digest?: string;
episodic?: string;
semantic?: string;
working?: string;
}
| undefined;

Object-shaped return type understood by the context aggregator.


MemoryItem​

type MemoryItem = object;

Unified memory item passed through retrieval strategies and the recall pipeline. Strategies operate on this shape so they don't have to special-case stores. Source-specific fields are present only for their owning source.

Properties​

category?​
category?: string;
confidence?​
confidence?: number;
content​
content: string;
encodedAt?​
encodedAt?: string;
from?​
from?: string;

Edge tail node (canonical subject string). Relation-only.

id​
id: string;
lastReinforced?​
lastReinforced?: string;
occurredAtTurn?​
occurredAtTurn?: number;
reinforcementCount?​
reinforcementCount?: number;
relationType?​
relationType?: string;

Edge relation type, e.g. "married to". Relation-only.

significance?​
significance?: number;
source​
source: MemoryItemSource;
subject?​
subject?: string;
to?​
to?: string;

Edge head node (canonical subject string). Relation-only.


MemoryItemSource​

type MemoryItemSource = "semantic" | "episodic" | "relation";

Source store of a recalled memory item. relation items originate from the semantic resource's typed-edge graph (relations tier) rather than a fact/episode store.


MemorySystemState​

type MemorySystemState = z.infer<typeof memorySystemStateSchema>;

Memory system tracking state type.


Observations​

type Observations = z.infer<typeof workingMemoryObservationsSchema>;

PrepareEnvelope​

type PrepareEnvelope = z.infer<typeof prepareEnvelopeSchema>;

Carrier envelope threaded between recall pipeline steps.

prepareBlock produces it; the optional filterBlock reads { query, limit, candidates } and returns { selectedIds }, which the recall tool's internal merge step folds back into the envelope; formatBlock consumes the envelope (with optional selectedIds) and produces the result.


PrepareInput​

type PrepareInput = z.infer<typeof prepareInputSchema>;

Input shape passed to RetrievalStrategy.prepareBlock. The recall tool's factory enriches RecallToolInput (resolves the optional limit, stamps the strategy name, propagates the per-item char cap) before invoking prepare. Strategies must copy strategyName and perItemCharCap unchanged into the envelope.


PruneOutput​

type PruneOutput = z.infer<typeof pruneOutputSchema>;

RankedMemoryItem​

type RankedMemoryItem = ProviderRankedMemoryItem;

A ranked memory item from cross-store recall.

Re-exported from ./provider.ts so existing import paths (@flow-state-dev/memory) keep resolving.


RankedMemorySource​

type RankedMemorySource = "working" | "episodic" | "semantic";

Source store of a ranked recall result.


RecallResultItem​

type RecallResultItem = object;

A single result item as the agent observes it.

Properties​

content​
content: string;

Content, possibly truncated to the per-item char cap.

id​
id: string;
metadata​
metadata: Record<string, unknown>;

Source-specific metadata (semantic: confidence/reinforcementCount/...; episodic: occurredAtTurn/significance/...).

score​
score: number;

Strategy-normalised score in [0, 1].

source​
source: MemoryItemSource;
truncated​
truncated: boolean;

True iff content was truncated by the per-item cap.


RecallToolInput​

type RecallToolInput = z.infer<typeof recallToolInputSchema>;

Inferred input shape from recallToolInputSchema.


RecallToolResult​

type RecallToolResult =
| {
query: string;
results: RecallResultItem[];
strategy: string;
totalMatched: number;
truncatedTo: number;
}
| {
error: string;
query: string;
strategy: string;
};

Envelope returned by the recall tool.

totalMatched is the count returned by the strategy before the user-facing limit was applied; agents compare it to truncatedTo to decide whether to re-query with narrower terms.

On error, returns { error, query, strategy }. The agent receives the error payload directly so it can recover; no exception escapes into the generator.


ResolveStrategyOptions​

type ResolveStrategyOptions = object;

Options understood by resolveStrategy when constructing a built-in.

Properties​

exactPhrasePassThrough?​
exactPhrasePassThrough?: boolean;

Forwarded to createLlmFilterStrategy. Default: true.

model​
model: string;

Model used by llm-filter (and any future strategies that need an LLM).


SemanticFact​

type SemanticFact = z.infer<typeof semanticFactSchema>;

A single semantic fact.


SemanticMemoryState​

type SemanticMemoryState = z.infer<typeof semanticMemoryStateSchema>;

The full semantic memory state.


SemanticSectionOption​

type SemanticSectionOption =
| boolean
| {
topN?: number;
};

Section enable flag with optional limit knob (semantic).


UnifiedObservations​

type UnifiedObservations = z.infer<typeof unifiedObservationsSchema>;

WorkingMemoryEntry​

type WorkingMemoryEntry = z.infer<typeof workingMemoryEntrySchema>;

A single working memory entry.


WorkingMemoryState​

type WorkingMemoryState = z.infer<typeof workingMemoryStateSchema>;

The full working memory state: entries + turn counter.

Variables​

captureQuestions​

const captureQuestions: object;

The one question capture asks, keyed capture, with options remember and skip. Pass it as an evaluator's questions (or spread it into a larger set) when building the block by hand. Keep the key and both option names: capture reads them.

Type Declaration​

capture​
capture: ChoiceQuestion;

CONNECT_STRATEGY​

const CONNECT_STRATEGY: "graph" = "graph";

Strategy identifier surfaced on the connect tool's result envelope.


connectToolDescription​

const connectToolDescription: string;

Description shown to the LLM when the connect tool is installed. Exported so consumers wiring custom tool sets can reuse the wording.


connectToolInputSchema​

const connectToolInputSchema: z.ZodObject<{
depth: z.ZodOptional<z.ZodNumber>;
from: z.ZodString;
to: z.ZodOptional<z.ZodString>;
}, "strip", z.ZodTypeAny, {
depth?: number;
from: string;
to?: string;
}, {
depth?: number;
from: string;
to?: string;
}>;

Zod schema for the connect tool's input parameters.


consolidationOutputSchema​

const consolidationOutputSchema: z.ZodObject<{
edges: z.ZodArray<z.ZodObject<{
action: z.ZodEnum<["new", "reinforce", "supersede"]>;
confidence: z.ZodNumber;
from: z.ZodString;
sourceEpisodeIds: z.ZodArray<z.ZodString, "many">;
targetEdgeId: z.ZodString;
to: z.ZodString;
type: z.ZodString;
}, "strip", z.ZodTypeAny, {
action: "new" | "reinforce" | "supersede";
confidence: number;
from: string;
sourceEpisodeIds: string[];
targetEdgeId: string;
to: string;
type: string;
}, {
action: "new" | "reinforce" | "supersede";
confidence: number;
from: string;
sourceEpisodeIds: string[];
targetEdgeId: string;
to: string;
type: string;
}>, "many">;
facts: z.ZodArray<z.ZodObject<{
action: z.ZodEnum<["new", "reinforce", "update", "invalidate"]>;
category: z.ZodEnum<["identity", "relationship", "preference", "belief", "profession", "attribute", "pattern"]>;
confidence: z.ZodNumber;
content: z.ZodString;
sourceEpisodeIds: z.ZodArray<z.ZodString, "many">;
subject: z.ZodDefault<z.ZodString>;
targetFactId: z.ZodDefault<z.ZodString>;
}, "strip", z.ZodTypeAny, {
action: "invalidate" | "new" | "reinforce" | "update";
category: | "attribute"
| "belief"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship";
confidence: number;
content: string;
sourceEpisodeIds: string[];
subject: string;
targetFactId: string;
}, {
action: "invalidate" | "new" | "reinforce" | "update";
category: | "attribute"
| "belief"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship";
confidence: number;
content: string;
sourceEpisodeIds: string[];
subject?: string;
targetFactId?: string;
}>, "many">;
}, "strip", z.ZodTypeAny, {
edges: object[];
facts: object[];
}, {
edges: object[];
facts: object[];
}>;

Output schema for the consolidation generator with the relations tier on: facts plus typed relation edges. Strict-mode safe (all fields fixed shape). Used as the generator's outputSchema only when relations is enabled.


DEFAULT_CONNECT_DEPTH​

const DEFAULT_CONNECT_DEPTH: 2 = 2;

Default traversal depth when the agent omits depth.


DEFAULT_CONSOLIDATION_CONFIG​

const DEFAULT_CONSOLIDATION_CONFIG: object;

Default configuration for semantic memory consolidation.

Type Declaration​

episodicThreshold​
episodicThreshold: number;
minInterval​
minInterval: number;
onEviction​
onEviction: boolean;

DEFAULT_DIGEST_CONFIG​

const DEFAULT_DIGEST_CONFIG: object;

Default configuration for the digest tier.

Type Declaration​

maxTokens​
readonly maxTokens: 400;
topN​
readonly topN: object;
topN.episodes​
readonly episodes: 10;
topN.facts​
readonly facts: 30;

DEFAULT_EPISODIC_CONFIG​

const DEFAULT_EPISODIC_CONFIG: object;

Default configuration for episodic memory.

Type Declaration​

maxEpisodes​
maxEpisodes: number;
scope​
scope: "user";
significanceThreshold​
significanceThreshold: number;

DEFAULT_EPISODIC_LIMIT​

const DEFAULT_EPISODIC_LIMIT: 5 = 5;

Default episode count injected when the episodic section is enabled.


DEFAULT_HYGIENE_CONFIG​

const DEFAULT_HYGIENE_CONFIG: object;

Default hygiene configuration values. Exported so callers building custom janitor flows can read the same defaults the memory system uses.

confidenceDecay.halfLife — 180 days; conservative. Industry analogs cluster lower (7–30 days first-contact, 90–140 days for reinforced); the issue authors deliberately picked a long horizon so existing users see no surprise in the first weeks. Tunable.

confidenceDecay.cullFloor — facts whose effective confidence drops below this value are removed by cullByEffectiveConfidence.

episodicTTL.persistentTurns / persistentDays — wall-time and turn-count thresholds for culling persistent episodes. Combined with operator: 'OR' the janitor culls when either threshold fires.

episodicTTL.permanentStaleDays — permanent episodes are NEVER culled; after this many days of silence they pick up a stale: true marker that operators can inspect.

Type Declaration​

confidenceDecay​
confidenceDecay: object;
confidenceDecay.cullFloor​
cullFloor: number;
confidenceDecay.halfLife​
halfLife: number;
episodicTTL​
episodicTTL: object;
episodicTTL.operator​
operator: "OR";
episodicTTL.permanentStaleDays​
permanentStaleDays: number;
episodicTTL.persistentDays​
persistentDays: number;
episodicTTL.persistentTurns​
persistentTurns: number;
schedule​
schedule: "onConsolidation";

DEFAULT_OBSERVER_CONFIG​

const DEFAULT_OBSERVER_CONFIG: object;

Default configuration for the memory observer.

Type Declaration​

maxAssistantChars​
maxAssistantChars: number;

DEFAULT_PER_ITEM_CHAR_CAP​

const DEFAULT_PER_ITEM_CHAR_CAP: 400 = 400;

Default per-item char cap applied to result content.


DEFAULT_PRUNE_CONFIG​

const DEFAULT_PRUNE_CONFIG: object;

Default configuration for semantic memory pruning.

Type Declaration​

pruneThreshold​
pruneThreshold: number;

DEFAULT_RECALL_LIMIT​

const DEFAULT_RECALL_LIMIT: 5 = 5;

Default limit when the agent omits it from tool input.


DEFAULT_SEMANTIC_TOP_N​

const DEFAULT_SEMANTIC_TOP_N: 10 = 10;

Default top-N facts injected when the semantic section is enabled.


DEFAULT_WORKING_MEMORY_CONFIG​

const DEFAULT_WORKING_MEMORY_CONFIG: object;

Default configuration values.

Type Declaration​

capacity​
readonly capacity: 7;
decay​
readonly decay: object;
decay.rate​
readonly rate: 0.5;
decay.strategy​
readonly strategy: "power-law";
maxPinnedSlots​
readonly maxPinnedSlots: 2;

defaultFormatBlock​

const defaultFormatBlock: BlockDefinition;

Default format handler installed when a strategy omits formatBlock.

Three branches:

  • empty candidates → empty result envelope (no LLM cost was incurred).
  • filter ran (selectedIds present) → resolve IDs against candidates, drop hallucinations, build result.
  • filter skipped → surface intrinsic-ranked top-N from prepare. Used by strategies that don't ship a filterBlock (vector, keyword) and by the llm-filter strategy when prepare set shouldFilter = false.

digestMemoryCapability​

const digestMemoryCapability: DefinedCapability & object;

Digest memory capability with default config (user-scoped).

Type Declaration​

__configInType?​
readonly __configInType?: undefined;
resourcesType?​
readonly resourcesType?: unknown;
sequencerStateType?​
readonly sequencerStateType?: unknown;
sessionStateType?​
readonly sessionStateType?: unknown;
stateSchemaType?​
readonly stateSchemaType?: unknown;
targetStatesType?​
readonly targetStatesType?: unknown;

digestMemoryStateSchema​

const digestMemoryStateSchema: z.ZodObject<{
digest: z.ZodOptional<z.ZodObject<{
content: z.ZodString;
generatedAt: z.ZodString;
generatedAtTurn: z.ZodNumber;
sourceSignature: z.ZodObject<{
episodeCount: z.ZodNumber;
semanticFactCount: z.ZodNumber;
semanticReinforcementSum: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
}, {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
}>;
}, "strip", z.ZodTypeAny, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}>>;
totalGenerated: z.ZodDefault<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated: number;
}, {
digest?: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
totalGenerated?: number;
}>;

Schema for the full digest memory state.


digestOutputSchema​

const digestOutputSchema: z.ZodString;

Generator output schema — bare text by design ("the digest is text, not a structured object"). Using z.string() opts the generator into core's streaming text path, so a response that hits maxTokens produces a shorter-but-valid string rather than an unparseable truncated JSON object.


digestRegenerateInputSchema​

const digestRegenerateInputSchema: z.ZodOptional<z.ZodObject<{
force: z.ZodOptional<z.ZodBoolean>;
}, "strip", z.ZodTypeAny, {
force?: boolean;
}, {
force?: boolean;
}>>;

Input to the digest sequencer. force: true bypasses the staleness guard.


digestSchema​

const digestSchema: z.ZodObject<{
content: z.ZodString;
generatedAt: z.ZodString;
generatedAtTurn: z.ZodNumber;
sourceSignature: z.ZodObject<{
episodeCount: z.ZodNumber;
semanticFactCount: z.ZodNumber;
semanticReinforcementSum: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
}, {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
}>;
}, "strip", z.ZodTypeAny, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}, {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}>;

Schema for a generated digest.


digestSourceSignatureSchema​

const digestSourceSignatureSchema: z.ZodObject<{
episodeCount: z.ZodNumber;
semanticFactCount: z.ZodNumber;
semanticReinforcementSum: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
}, {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
}>;

Signature of the source stores at the moment a digest was generated. Compared against current store state to decide whether regeneration is worthwhile — the digest's primary cost guard.


episodeSchema​

const episodeSchema: z.ZodObject<{
category: z.ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>;
consolidated: z.ZodDefault<z.ZodBoolean>;
content: z.ZodString;
context: z.ZodObject<{
precedingTopic: z.ZodOptional<z.ZodString>;
sessionId: z.ZodString;
}, "strip", z.ZodTypeAny, {
precedingTopic?: string;
sessionId: string;
}, {
precedingTopic?: string;
sessionId: string;
}>;
durability: z.ZodDefault<z.ZodEnum<["persistent", "permanent"]>>;
encodedAt: z.ZodString;
id: z.ZodString;
occurredAtTurn: z.ZodNumber;
significance: z.ZodNumber;
stale: z.ZodDefault<z.ZodBoolean>;
subject: z.ZodDefault<z.ZodString>;
}, "strip", z.ZodTypeAny, {
category: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
consolidated: boolean;
content: string;
context: {
precedingTopic?: string;
sessionId: string;
};
durability: "permanent" | "persistent";
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale: boolean;
subject: string;
}, {
category: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
consolidated?: boolean;
content: string;
context: {
precedingTopic?: string;
sessionId: string;
};
durability?: "permanent" | "persistent";
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale?: boolean;
subject?: string;
}>;

Schema for a single episodic memory record.


episodicMemoryCapability​

const episodicMemoryCapability: DefinedCapability & object;

Episodic memory capability with default config (user-scoped, 200 max episodes).

Type Declaration​

__configInType?​
readonly __configInType?: undefined;
resourcesType?​
readonly resourcesType?: unknown;
sequencerStateType?​
readonly sequencerStateType?: unknown;
sessionStateType?​
readonly sessionStateType?: unknown;
stateSchemaType?​
readonly stateSchemaType?: unknown;
targetStatesType?​
readonly targetStatesType?: unknown;

episodicMemoryStateSchema​

const episodicMemoryStateSchema: z.ZodObject<{
episodes: z.ZodDefault<z.ZodArray<z.ZodObject<{
category: z.ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>;
consolidated: z.ZodDefault<z.ZodBoolean>;
content: z.ZodString;
context: z.ZodObject<{
precedingTopic: z.ZodOptional<z.ZodString>;
sessionId: z.ZodString;
}, "strip", z.ZodTypeAny, {
precedingTopic?: string;
sessionId: string;
}, {
precedingTopic?: string;
sessionId: string;
}>;
durability: z.ZodDefault<z.ZodEnum<["persistent", "permanent"]>>;
encodedAt: z.ZodString;
id: z.ZodString;
occurredAtTurn: z.ZodNumber;
significance: z.ZodNumber;
stale: z.ZodDefault<z.ZodBoolean>;
subject: z.ZodDefault<z.ZodString>;
}, "strip", z.ZodTypeAny, {
category: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
consolidated: boolean;
content: string;
context: {
precedingTopic?: string;
sessionId: string;
};
durability: "permanent" | "persistent";
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale: boolean;
subject: string;
}, {
category: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
consolidated?: boolean;
content: string;
context: {
precedingTopic?: string;
sessionId: string;
};
durability?: "permanent" | "persistent";
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale?: boolean;
subject?: string;
}>, "many">>;
totalEncoded: z.ZodDefault<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
episodes: object[];
totalEncoded: number;
}, {
episodes?: object[];
totalEncoded?: number;
}>;

Schema for the full episodic memory state.


EXACT_PHRASE_CAP​

const EXACT_PHRASE_CAP: 5 = 5;

Maximum exact-phrase pass-throughs added to the candidate set.


GRAPH_EXPAND_CAP​

const GRAPH_EXPAND_CAP: 10 = 10;

Maximum relation candidates appended to the candidate set per recall.


janitorResource​

const janitorResource: object & ResourceConfig & object;

Session-scoped tracking resource for the memory janitor.

Each run overwrites the lastCulled* arrays with the IDs touched. Inspect via DevTool or the resource registry to see what the most recent run did.

Type Declaration​

default​
readonly default: object;
default.lastCulledEpisodeIds​
lastCulledEpisodeIds: string[];
default.lastCulledFactIds​
lastCulledFactIds: string[];
default.lastMarkedStaleEpisodeIds​
lastMarkedStaleEpisodeIds: string[];
default.lastRunAt?​
lastRunAt?: string;
default.lastRunTurn​
lastRunTurn: number;
default.totalRuns​
totalRuns: number;
ref​
readonly ref: "janitor";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: z.ZodObject<{
lastCulledEpisodeIds: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
lastCulledFactIds: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
lastMarkedStaleEpisodeIds: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
lastRunAt: z.ZodOptional<z.ZodString>;
lastRunTurn: z.ZodDefault<z.ZodNumber>;
totalRuns: z.ZodDefault<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
lastCulledEpisodeIds: string[];
lastCulledFactIds: string[];
lastMarkedStaleEpisodeIds: string[];
lastRunAt?: string;
lastRunTurn: number;
totalRuns: number;
}, {
lastCulledEpisodeIds?: string[];
lastCulledFactIds?: string[];
lastMarkedStaleEpisodeIds?: string[];
lastRunAt?: string;
lastRunTurn?: number;
totalRuns?: number;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.lastCulledEpisodeIds​
lastCulledEpisodeIds: string[];
ClientType.lastCulledFactIds​
lastCulledFactIds: string[];
ClientType.lastMarkedStaleEpisodeIds​
lastMarkedStaleEpisodeIds: string[];
ClientType.lastRunAt?​
lastRunAt?: string;
ClientType.lastRunTurn​
lastRunTurn: number;
ClientType.totalRuns​
totalRuns: number;
ContextType​
ContextType: ResourceContext;
StateType​
StateType: object;
StateType.lastCulledEpisodeIds​
lastCulledEpisodeIds: string[];
StateType.lastCulledFactIds​
lastCulledFactIds: string[];
StateType.lastMarkedStaleEpisodeIds​
lastMarkedStaleEpisodeIds: string[];
StateType.lastRunAt?​
lastRunAt?: string;
StateType.lastRunTurn​
lastRunTurn: number;
StateType.totalRuns​
totalRuns: number;

janitorStateSchema​

const janitorStateSchema: z.ZodObject<{
lastCulledEpisodeIds: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
lastCulledFactIds: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
lastMarkedStaleEpisodeIds: z.ZodDefault<z.ZodArray<z.ZodString, "many">>;
lastRunAt: z.ZodOptional<z.ZodString>;
lastRunTurn: z.ZodDefault<z.ZodNumber>;
totalRuns: z.ZodDefault<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
lastCulledEpisodeIds: string[];
lastCulledFactIds: string[];
lastMarkedStaleEpisodeIds: string[];
lastRunAt?: string;
lastRunTurn: number;
totalRuns: number;
}, {
lastCulledEpisodeIds?: string[];
lastCulledFactIds?: string[];
lastMarkedStaleEpisodeIds?: string[];
lastRunAt?: string;
lastRunTurn?: number;
totalRuns?: number;
}>;

Schema for the session-scoped janitor tracking resource.

lastCulled* arrays hold the IDs touched on the MOST RECENT run only — the resource is a snapshot, not a history. Each janitor pass overwrites them. This is the V1 observability surface; an evicted-memory event stream is intentionally out of scope.


MEMORY_CAPABILITY_PRESETS​

const MEMORY_CAPABILITY_PRESETS: readonly ["digest", "working", "semantic", "episodic", "recall"];

Orthogonal section presets exposed on the composed memory capability.

Each preset toggles one slice of the memory surface independently:

  • digest — inject the rolling digest into the prompt under <memory><digest>…</digest></memory> (default on). No-op when no digest tier is configured.
  • working — inject working-memory entries under <memory><working>…</working></memory> (default on).
  • recall — install the agent-invocable memory/recall tool that searches semantic + episodic stores on demand (default on).
  • semantic — inject the top-N semantic facts (by reinforcement count) under <memory><semantic>…</semantic></memory> (default off; opt-in for content-rich generators). No-op when no semantic tier is configured.
  • episodic — inject the most-recent episodes under <memory><episodic>…</episodic></memory> (default off). No-op when no episodic tier is configured.

Inclusion is independent of processing: the capture pipeline still runs memory/digest/regenerate, consolidation, prune, etc. for whichever tiers are configured on memorySystem({...}) — turning off a preset just suppresses the section in that one generator's prompt.

Default-on set: ['digest', 'working', 'recall']. Authors who want non-default topN / limit values should bypass the preset and use createMemoryContextFormatter({...}) directly in context: { memory: … }.


memorySystemResource​

const memorySystemResource: object & ResourceConfig & object;

Session-scoped resource for memory system tracking (watermark + consolidation counters).

Type Declaration​

default​
readonly default: object;
default.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
default.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
default.lastConsolidationTurn​
lastConsolidationTurn: number;
default.lastProcessedIndex​
lastProcessedIndex: number;
default.readMessages​
readMessages: object[] | null;
ref​
readonly ref: "memorySystem";
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: z.ZodObject<{
episodicWritesSinceLastConsolidation: z.ZodDefault<z.ZodNumber>;
evictedPersistentSinceLastConsolidation: z.ZodDefault<z.ZodNumber>;
lastConsolidationTurn: z.ZodDefault<z.ZodNumber>;
lastProcessedIndex: z.ZodDefault<z.ZodNumber>;
readMessages: z.ZodDefault<z.ZodNullable<z.ZodArray<z.ZodObject<{
id: z.ZodString;
ts: z.ZodNumber;
}, "strip", ZodTypeAny, {
id: string;
ts: number;
}, {
id: string;
ts: number;
}>, "many">>>;
}, "strip", ZodTypeAny, {
episodicWritesSinceLastConsolidation: number;
evictedPersistentSinceLastConsolidation: number;
lastConsolidationTurn: number;
lastProcessedIndex: number;
readMessages: object[] | null;
}, {
episodicWritesSinceLastConsolidation?: number;
evictedPersistentSinceLastConsolidation?: number;
lastConsolidationTurn?: number;
lastProcessedIndex?: number;
readMessages?: object[] | null;
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
ClientType.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
ClientType.lastConsolidationTurn​
lastConsolidationTurn: number;
ClientType.lastProcessedIndex​
lastProcessedIndex: number;
ClientType.readMessages​
readMessages: object[] | null;
ContextType​
ContextType: ResourceContext;
StateType​
StateType: object;
StateType.episodicWritesSinceLastConsolidation​
episodicWritesSinceLastConsolidation: number;
StateType.evictedPersistentSinceLastConsolidation​
evictedPersistentSinceLastConsolidation: number;
StateType.lastConsolidationTurn​
lastConsolidationTurn: number;
StateType.lastProcessedIndex​
lastProcessedIndex: number;
StateType.readMessages​
readMessages: object[] | null;

memorySystemStateSchema​

const memorySystemStateSchema: z.ZodObject<{
episodicWritesSinceLastConsolidation: z.ZodDefault<z.ZodNumber>;
evictedPersistentSinceLastConsolidation: z.ZodDefault<z.ZodNumber>;
lastConsolidationTurn: z.ZodDefault<z.ZodNumber>;
lastProcessedIndex: z.ZodDefault<z.ZodNumber>;
readMessages: z.ZodDefault<z.ZodNullable<z.ZodArray<z.ZodObject<{
id: z.ZodString;
ts: z.ZodNumber;
}, "strip", ZodTypeAny, {
id: string;
ts: number;
}, {
id: string;
ts: number;
}>, "many">>>;
}, "strip", ZodTypeAny, {
episodicWritesSinceLastConsolidation: number;
evictedPersistentSinceLastConsolidation: number;
lastConsolidationTurn: number;
lastProcessedIndex: number;
readMessages: object[] | null;
}, {
episodicWritesSinceLastConsolidation?: number;
evictedPersistentSinceLastConsolidation?: number;
lastConsolidationTurn?: number;
lastProcessedIndex?: number;
readMessages?: object[] | null;
}>;

Schema for the memory system tracking state.


PRE_RANK_EPISODIC_CAP​

const PRE_RANK_EPISODIC_CAP: 30 = 30;

Maximum episodes admitted to the pre-rank pool before the LLM filter call.

Episodes are scored intrinsically (significance × recency-decay) and the top-N kept. Semantic facts are not capped here — they pass through unconditionally because the semantic store is already bounded by pruneThreshold and pooling both stores under one cap was starving facts out of the candidate set whenever many high-significance recent episodes existed.


pruneOutputSchema​

const pruneOutputSchema: z.ZodObject<{
merges: z.ZodArray<z.ZodObject<{
mergedContent: z.ZodString;
reason: z.ZodString;
sourceFactIds: z.ZodArray<z.ZodString, "many">;
}, "strip", z.ZodTypeAny, {
mergedContent: string;
reason: string;
sourceFactIds: string[];
}, {
mergedContent: string;
reason: string;
sourceFactIds: string[];
}>, "many">;
removals: z.ZodArray<z.ZodObject<{
factId: z.ZodString;
reason: z.ZodString;
}, "strip", z.ZodTypeAny, {
factId: string;
reason: string;
}, {
factId: string;
reason: string;
}>, "many">;
}, "strip", z.ZodTypeAny, {
merges: object[];
removals: object[];
}, {
merges: object[];
removals: object[];
}>;

Output schema for the prune generator.


recallToolDescription​

const recallToolDescription: string;

Description shown to the LLM when the recall tool is installed.

Exported so consumers wiring custom tools (or building variants on top of createRecallTool) can reuse the same wording. The "do not re-retrieve" line is the single biggest lever against over-retrieval.


recallToolInputSchema​

const recallToolInputSchema: z.ZodObject<{
limit: z.ZodOptional<z.ZodNumber>;
query: z.ZodString;
sinceTurn: z.ZodOptional<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
limit?: number;
query: string;
sinceTurn?: number;
}, {
limit?: number;
query: string;
sinceTurn?: number;
}>;

Zod schema for the recall tool's input parameters.


RECENCY_HALF_LIFE​

const RECENCY_HALF_LIFE: 50 = 50;

Recency half-life (in turns) for episode decay.


semanticCategoryEnum​

const semanticCategoryEnum: z.ZodEnum<["identity", "relationship", "preference", "belief", "profession", "attribute", "pattern"]>;

Semantic fact categories.


semanticFactSchema​

const semanticFactSchema: z.ZodObject<{
category: z.ZodEnum<["identity", "relationship", "preference", "belief", "profession", "attribute", "pattern"]>;
confidence: z.ZodNumber;
content: z.ZodString;
extractedAt: z.ZodString;
id: z.ZodString;
lastReinforced: z.ZodOptional<z.ZodString>;
reinforcementCount: z.ZodDefault<z.ZodNumber>;
sourceEpisodeIds: z.ZodArray<z.ZodString, "many">;
subject: z.ZodDefault<z.ZodString>;
}, "strip", z.ZodTypeAny, {
category: | "attribute"
| "belief"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount: number;
sourceEpisodeIds: string[];
subject: string;
}, {
category: | "attribute"
| "belief"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount?: number;
sourceEpisodeIds: string[];
subject?: string;
}>;

Schema for a single semantic fact.


semanticMemoryCapability​

const semanticMemoryCapability: DefinedCapability & object;

Semantic memory capability with default config (user-scoped).

Type Declaration​

__configInType?​
readonly __configInType?: undefined;
resourcesType?​
readonly resourcesType?: unknown;
sequencerStateType?​
readonly sequencerStateType?: unknown;
sessionStateType?​
readonly sessionStateType?: unknown;
stateSchemaType?​
readonly stateSchemaType?: unknown;
targetStatesType?​
readonly targetStatesType?: unknown;

semanticMemoryStateSchema​

const semanticMemoryStateSchema: z.ZodObject<{
facts: z.ZodDefault<z.ZodArray<z.ZodObject<{
category: z.ZodEnum<["identity", "relationship", "preference", "belief", "profession", "attribute", "pattern"]>;
confidence: z.ZodNumber;
content: z.ZodString;
extractedAt: z.ZodString;
id: z.ZodString;
lastReinforced: z.ZodOptional<z.ZodString>;
reinforcementCount: z.ZodDefault<z.ZodNumber>;
sourceEpisodeIds: z.ZodArray<z.ZodString, "many">;
subject: z.ZodDefault<z.ZodString>;
}, "strip", z.ZodTypeAny, {
category: | "attribute"
| "belief"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount: number;
sourceEpisodeIds: string[];
subject: string;
}, {
category: | "attribute"
| "belief"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount?: number;
sourceEpisodeIds: string[];
subject?: string;
}>, "many">>;
totalConsolidations: z.ZodDefault<z.ZodNumber>;
totalExtracted: z.ZodDefault<z.ZodNumber>;
}, "strip", z.ZodTypeAny, {
facts: object[];
totalConsolidations: number;
totalExtracted: number;
}, {
facts?: object[];
totalConsolidations?: number;
totalExtracted?: number;
}>;

Schema for the full semantic memory state.


TRUNCATION_MARKER​

const TRUNCATION_MARKER: "… [truncated, re-query with narrower terms for full content]" = "\u2026 [truncated, re-query with narrower terms for full content]";

Truncation marker appended to capped content.


unifiedObservationsSchema​

const unifiedObservationsSchema: z.ZodObject<{
items: z.ZodArray<z.ZodObject<{
category: z.ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>;
content: z.ZodString;
durability: z.ZodEnum<["transient", "session", "persistent", "permanent"]>;
importance: z.ZodNumber;
subject: z.ZodDefault<z.ZodString>;
}, "strip", z.ZodTypeAny, {
category: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
content: string;
durability: "permanent" | "persistent" | "session" | "transient";
importance: number;
subject: string;
}, {
category: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
content: string;
durability: "permanent" | "persistent" | "session" | "transient";
importance: number;
subject?: string;
}>, "many">;
}, "strip", z.ZodTypeAny, {
items: object[];
}, {
items: object[];
}>;

Output schema for the unified observer generator.


workingMemoryCapability​

const workingMemoryCapability: DefinedCapability & object;

Working memory capability with default config (capacity 7, power-law decay).

Type Declaration​

__configInType?​
readonly __configInType?: undefined;
resourcesType?​
readonly resourcesType?: unknown;
sequencerStateType?​
readonly sequencerStateType?: unknown;
sessionStateType?​
readonly sessionStateType?: unknown;
stateSchemaType?​
readonly stateSchemaType?: unknown;
targetStatesType?​
readonly targetStatesType?: unknown;

workingMemoryEntrySchema​

const workingMemoryEntrySchema: z.ZodObject<{
addedAtTurn: z.ZodNumber;
category: z.ZodDefault<z.ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>>;
content: z.ZodString;
durability: z.ZodDefault<z.ZodEnum<["transient", "session", "persistent", "permanent"]>>;
id: z.ZodString;
importance: z.ZodNumber;
lastAccessedAtTurn: z.ZodNumber;
metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
pinned: z.ZodBoolean;
salience: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
addedAtTurn: number;
category: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
content: string;
durability: "permanent" | "persistent" | "session" | "transient";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}, {
addedAtTurn: number;
category?: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
content: string;
durability?: "permanent" | "persistent" | "session" | "transient";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}>;

Schema for a single working memory entry.


workingMemoryObservationsSchema​

const workingMemoryObservationsSchema: z.ZodObject<{
observations: z.ZodArray<z.ZodObject<{
content: z.ZodString;
importance: z.ZodNumber;
pinned: z.ZodDefault<z.ZodBoolean>;
replaces: z.ZodDefault<z.ZodString>;
}, "strip", z.ZodTypeAny, {
content: string;
importance: number;
pinned: boolean;
replaces: string;
}, {
content: string;
importance: number;
pinned?: boolean;
replaces?: string;
}>, "many">;
}, "strip", z.ZodTypeAny, {
observations: object[];
}, {
observations: object[];
}>;

Schema for the observations array produced by the observe block and consumed by the remember block. Exported so flow authors can build custom pipelines between observe and remember.


workingMemoryResource​

const workingMemoryResource: object & ResourceConfig & object;

Session-scoped resource definition for working memory.

Working memory is intrinsically session-bound: it tracks what's currently in mind for the active conversation. Blocks declare it via the unified resources: { workingMemory: workingMemoryResource } map and access it via ctx.resources.get('workingMemory') regardless of scope.

Type Declaration​

default​
readonly default: object;
default.currentTurn​
currentTurn: number;
default.entries​
entries: object[];
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: z.ZodObject<{
currentTurn: z.ZodDefault<z.ZodNumber>;
entries: z.ZodDefault<z.ZodArray<z.ZodObject<{
addedAtTurn: z.ZodNumber;
category: z.ZodDefault<z.ZodEnum<[..., ..., ..., ..., ..., ..., ..., ..., ...]>>;
content: z.ZodString;
durability: z.ZodDefault<z.ZodEnum<[..., ..., ..., ...]>>;
id: z.ZodString;
importance: z.ZodNumber;
lastAccessedAtTurn: z.ZodNumber;
metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
pinned: z.ZodBoolean;
salience: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
addedAtTurn: number;
category: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
content: string;
durability: "permanent" | "persistent" | "session" | "transient";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}, {
addedAtTurn: number;
category?: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
content: string;
durability?: "permanent" | "persistent" | "session" | "transient";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}>, "many">>;
}, "strip", z.ZodTypeAny, {
currentTurn: number;
entries: object[];
}, {
currentTurn?: number;
entries?: object[];
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.currentTurn​
currentTurn: number;
ClientType.entries​
entries: object[];
ContextType​
ContextType: ResourceContext;
StateType​
StateType: object;
StateType.currentTurn​
currentTurn: number;
StateType.entries​
entries: object[];

workingMemoryResources​

const workingMemoryResources: object;

Pre-keyed resource declaration for working memory.

Use this in a block or capability's resources to avoid hard-coding the resource key:

resources: workingMemoryResources
// or compose with other resources:
resources: { ...workingMemoryResources, myResource }

Type Declaration​

workingMemory​
readonly workingMemory: object & ResourceConfig & object;
Type Declaration​
default​
readonly default: object;
default.currentTurn​
currentTurn: number;
default.entries​
entries: object[];
scope​
readonly scope: "session";
stateSchema​
readonly stateSchema: z.ZodObject<{
currentTurn: z.ZodDefault<z.ZodNumber>;
entries: z.ZodDefault<z.ZodArray<z.ZodObject<{
addedAtTurn: z.ZodNumber;
category: z.ZodDefault<z.ZodEnum<...>>;
content: z.ZodString;
durability: z.ZodDefault<z.ZodEnum<...>>;
id: z.ZodString;
importance: z.ZodNumber;
lastAccessedAtTurn: z.ZodNumber;
metadata: z.ZodOptional<z.ZodRecord<..., ...>>;
pinned: z.ZodBoolean;
salience: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
addedAtTurn: number;
category: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
content: string;
durability: "permanent" | "persistent" | "session" | "transient";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<..., ...>;
pinned: boolean;
salience: number;
}, {
addedAtTurn: number;
category?: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
content: string;
durability?: "permanent" | "persistent" | "session" | "transient";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<..., ...>;
pinned: boolean;
salience: number;
}>, "many">>;
}, "strip", z.ZodTypeAny, {
currentTurn: number;
entries: object[];
}, {
currentTurn?: number;
entries?: object[];
}>;
writable​
readonly writable: true;
ClientType​
ClientType: object;
ClientType.currentTurn​
currentTurn: number;
ClientType.entries​
entries: object[];
ContextType​
ContextType: ResourceContext;
StateType​
StateType: object;
StateType.currentTurn​
currentTurn: number;
StateType.entries​
entries: object[];

workingMemoryStateSchema​

const workingMemoryStateSchema: z.ZodObject<{
currentTurn: z.ZodDefault<z.ZodNumber>;
entries: z.ZodDefault<z.ZodArray<z.ZodObject<{
addedAtTurn: z.ZodNumber;
category: z.ZodDefault<z.ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>>;
content: z.ZodString;
durability: z.ZodDefault<z.ZodEnum<["transient", "session", "persistent", "permanent"]>>;
id: z.ZodString;
importance: z.ZodNumber;
lastAccessedAtTurn: z.ZodNumber;
metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
pinned: z.ZodBoolean;
salience: z.ZodNumber;
}, "strip", z.ZodTypeAny, {
addedAtTurn: number;
category: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
content: string;
durability: "permanent" | "persistent" | "session" | "transient";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}, {
addedAtTurn: number;
category?: | "attribute"
| "belief"
| "event"
| "identity"
| "pattern"
| "preference"
| "profession"
| "relationship"
| "task";
content: string;
durability?: "permanent" | "persistent" | "session" | "transient";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}>, "many">>;
}, "strip", z.ZodTypeAny, {
currentTurn: number;
entries: object[];
}, {
currentTurn?: number;
entries?: object[];
}>;

Schema for the full working memory state.

Functions​

addSemanticFact()​

function addSemanticFact(ref, fact): Promise<{
category: | "identity"
| "preference"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount: number;
sourceEpisodeIds: string[];
subject: string;
}>;

Add a new semantic fact. Generates ID and sets extractedAt and lastReinforced to the same ISO timestamp (creation counts as the first reinforcement). The dual-timestamp seeding is what lets the effectiveConfidence decay model anchor every fact from day zero — facts created before this fix have lastReinforced: undefined and fall back to extractedAt at read time.

Parameters​

ref​

SemRef

fact​

Omit<{ category: | "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; confidence: number; content: string; extractedAt: string; id: string; lastReinforced?: string; reinforcementCount: number; sourceEpisodeIds: string[]; subject: string; }, | "id" | "subject" | "extractedAt" | "lastReinforced" | "reinforcementCount"> & object

Returns​

Promise<{ category: | "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; confidence: number; content: string; extractedAt: string; id: string; lastReinforced?: string; reinforcementCount: number; sourceEpisodeIds: string[]; subject: string; }>


addWorkingMemory()​

function addWorkingMemory(
ref,
entry,
config?
): Promise<{
addedAtTurn: number;
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}>;

Add an entry to working memory.

If the number of entries reaches capacity, the lowest-salience non-pinned entry is evicted. If all entries are pinned, the new entry is added anyway (exceeding capacity).

Returns the fully-formed entry that was added.

Parameters​

ref​

WmRef

entry​

AddEntryInput

config?​

WorkingMemoryHelperConfig

Returns​

Promise<{ addedAtTurn: number; category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability: "transient" | "session" | "persistent" | "permanent"; id: string; importance: number; lastAccessedAtTurn: number; metadata?: Record<string, any>; pinned: boolean; salience: number; }>


advanceWorkingMemory()​

function advanceWorkingMemory(ref, config?): Promise<void>;

Advance the turn counter by 1 and recompute salience for all entries. This is the "clock" for decay — call it once per interaction turn.

Parameters​

ref​

WmRef

config?​

WorkingMemoryHelperConfig

Returns​

Promise<void>


buildDigestContext()​

function buildDigestContext(input): string;

Build the user-message context for the digest generator. Pure function so tests can verify prompt shape (especially: previous digest is included for iterative regeneration) without an LLM call.

Parameters​

input​
episodes​

object[]

facts​

object[]

previous?​

string

triggered​

boolean

Returns​

string


buildObserveContext()​

function buildObserveContext(allItems, lastProcessedIndex): string | undefined;

Selects and formats the conversation messages the observer should extract memories from, for the prompt's context.

Only message items (user turns + assistant replies) carry memorable content. Every other item type — block_trace, state_change, router_decision, reasoning, tool_output, and the memory subsystem's own observer/reflect output — is execution noise that pollutes the prompt and skews extraction, so the watermarked slice is narrowed to message items.

lastProcessedIndex is a watermark into the full session item log (the reflect handler advances it over every item, regardless of type), so selection filters by the original index first, then narrows to messages — keeping the watermark and the type filter independent and correct.

Returns undefined when no new message items exist past the watermark.

Parameters​

allItems​

readonly Record<string, any>[]

lastProcessedIndex​

number

Returns​

string | undefined


buildResult()​

function buildResult(
ordered,
env,
totalMatched
): RecallToolResult;

Build the success envelope from an ordered list of items. Score is the position-based rank, normalised so the top result is 1.

Parameters​

ordered​

MemoryItem[]

env​
candidates​

MemoryItem[]

limit​

number

perItemCharCap​

number

query​

string

shouldFilter​

boolean

sinceTurn?​

number

strategyName​

string

totalMatched​

number

Returns​

RecallToolResult


buildResultMetadata()​

function buildResultMetadata(source, raw): Record<string, unknown>;

Build the source-specific metadata block surfaced to the agent.

Parameters​

source​

MemoryItemSource

raw​

MemoryItem

Returns​

Record<string, unknown>


capContent()​

function capContent(content, cap): object;

Cap content length, appending the truncation marker when triggered.

Cap < marker length is treated as a hard slice with no marker — keeps the function total without surprising negative-slice math.

Parameters​

content​

string

cap​

number

Returns​

object

content​
content: string;
truncated​
truncated: boolean;

captureEvaluator()​

function captureEvaluator(model): EvaluatorDefinition<ZodTypeAny, any, {
capture: ChoiceQuestion<"remember" | "skip">;
}>;

Build core's evaluator block asking memory's capture question on the model the app names. Pass the result as system({ evaluator }).

The model is passed through untouched: a model string resolves when the block runs, the same way the app's generator model strings do; a model instance (e.g. openai.evaluationModel("gpt-6-luna")) is used as given.

Parameters​

model​

string | EvaluationModel

Returns​

EvaluatorDefinition<ZodTypeAny, any, { capture: ChoiceQuestion<"remember" | "skip">; }>

Example​

const mem = system({
model: 'openai/gpt-6-luna',
working: true,
evaluator: captureEvaluator('typesafe-ai/jev'),
})

computeDecay()​

function computeDecay(
elapsed,
strategy,
rate
): number;

Compute the decay factor for a given elapsed turn count.

  • power-law: ACT-R activation decay — (1 + elapsed)^(-rate). With default rate 0.5 this gives fast initial decay with a long tail.
  • exponential: exp(-rate × elapsed).
  • none: always returns 1 (no decay).

Negative elapsed values are clamped to 0.

Parameters​

elapsed​

number

strategy​

DecayStrategy

rate​

number

Returns​

number


computeDigestSourceSignature()​

function computeDigestSourceSignature(semRef, epRef?): object;

Compute a fresh source signature from the current semantic and (optional) episodic store state. Used both at digest write time and when comparing stored vs. current state for staleness.

Parameters​

semRef​

SemRef

epRef?​

EpRef

Returns​

object

episodeCount​
episodeCount: number;
semanticFactCount​
semanticFactCount: number;
semanticReinforcementSum​
semanticReinforcementSum: number;

computeSalience()​

function computeSalience(
entry,
currentTurn,
decay
): number;

Compute the current salience of an entry: importance × decay(elapsed). Result is clamped to [0, 1].

Parameters​

entry​
addedAtTurn​

number

category​

| "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"

content​

string

durability​

"transient" | "session" | "persistent" | "permanent"

id​

string

importance​

number

lastAccessedAtTurn​

number

metadata?​

Record<string, any>

pinned​

boolean

salience​

number

currentTurn​

number

decay​

WorkingMemoryDecayConfig

Returns​

number


createConnectTool()​

function createConnectTool(opts?): BlockDefinition<ZodObject<{
depth: ZodOptional<ZodNumber>;
from: ZodString;
to: ZodOptional<ZodString>;
}, "strip", ZodTypeAny, {
depth?: number;
from: string;
to?: string;
}, {
depth?: number;
from: string;
to?: string;
}>, ZodTypeAny, {
depth?: number;
from: string;
to?: string;
}, RecallToolResult>;

Create the connect tool — a handler the agent calls as a tool.

Returns a block named memory/connect. Reads the edge API from ctx.resources.semanticMemory.edges; when that is absent the relations tier is disabled and the tool returns an error envelope so the agent can recover.

Parameters​

opts?​

CreateConnectToolOptions

Returns​

BlockDefinition<ZodObject<{ depth: ZodOptional<ZodNumber>; from: ZodString; to: ZodOptional<ZodString>; }, "strip", ZodTypeAny, { depth?: number; from: string; to?: string; }, { depth?: number; from: string; to?: string; }>, ZodTypeAny, { depth?: number; from: string; to?: string; }, RecallToolResult>


createDigestEntry()​

function createDigestEntry(): (_input, ctx) =>
| {
digest: string;
}
| undefined;

Returns a context entry function that emits { digest: string } or undefined. Defensive against a missing/uninitialised digest resource so a generator running before the digest is first persisted just skips the section instead of throwing.

Returns​

(_input, ctx) => | { digest: string; } | undefined


createDigestMemoryCapability()​

function createDigestMemoryCapability(config?): DefinedCapability<"digestMemory", {
content: () => string | undefined;
get: () =>
| {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
}
| undefined;
}, never, Record<string, PresetDef<any>>, undefined, {
digestMemory: object & ResourceConfig<JsonObject> & object;
}, undefined, undefined, undefined> & object;

Create a digest memory capability.

Declares digestMemory resource in the configured scope and exposes read helpers via ctx.cap.digestMemory. Regeneration is not exposed here — it is a sequencer (one LLM call), not a sync helper. The memory.system() factory exposes regeneration as mem.regenerateDigest.

Parameters​

config?​

DigestMemoryCapabilityConfig

Returns​

DefinedCapability<"digestMemory", { content: () => string | undefined; get: () => | { content: string; generatedAt: string; generatedAtTurn: number; sourceSignature: { episodeCount: number; semanticFactCount: number; semanticReinforcementSum: number; }; } | undefined; }, never, Record<string, PresetDef<any>>, undefined, { digestMemory: object & ResourceConfig<JsonObject> & object; }, undefined, undefined, undefined> & object


createDigestMemoryResource()​

function createDigestMemoryResource(scope, options?): object & ResourceConfig<JsonObject> & object;

Create a digest memory resource definition at the given scope.

Scope mirrors the semantic store's scope — the factory enforces this intrinsically. Persists across sessions; lives at 'user' or 'org'.

options.flowIsolation is the resource's own flowIsolation. Omit it to take the flow's isolateUserState / isolateOrgState default.

Parameters​

scope​

"user" | "org"

options?​

MemoryResourceOptions

Returns​

object & ResourceConfig<JsonObject> & object


createEpisodicEntry()​

function createEpisodicEntry(options?): (_input, ctx) =>
| {
episodic: string;
}
| undefined;

Returns a context entry function that emits { episodic: string } or undefined. Pulls the most-recent N episodes (by occurredAtTurn descending). Recency-only ordering matches the user expectation of "what happened recently" — digest-style significance ranking is reserved for digest regeneration where a longer-horizon view matters.

Parameters​

options?​
limit?​

number

Returns​

(_input, ctx) => | { episodic: string; } | undefined


createEpisodicMemoryCapability()​

function createEpisodicMemoryCapability(config?): DefinedCapability<"episodicMemory", {
encode: (episode) => Promise<{
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
consolidated: boolean;
content: string;
context: {
precedingTopic?: string;
sessionId: string;
};
durability: "persistent" | "permanent";
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale: boolean;
subject: string;
}>;
markConsolidated: (episodeIds) => Promise<void>;
recent: (limit?) => object[];
}, never, Record<string, PresetDef<any>>, undefined, {
episodicMemory: object & ResourceConfig<JsonObject> & object;
}, undefined, undefined, undefined> & object;

Create an episodic memory capability.

Declares episodicMemory resource in the configured scope and exposes typed helpers via ctx.cap.episodicMemory.

Parameters​

config?​

EpisodicMemoryCapabilityConfig

Returns​

DefinedCapability<"episodicMemory", { encode: (episode) => Promise<{ category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; consolidated: boolean; content: string; context: { precedingTopic?: string; sessionId: string; }; durability: "persistent" | "permanent"; encodedAt: string; id: string; occurredAtTurn: number; significance: number; stale: boolean; subject: string; }>; markConsolidated: (episodeIds) => Promise<void>; recent: (limit?) => object[]; }, never, Record<string, PresetDef<any>>, undefined, { episodicMemory: object & ResourceConfig<JsonObject> & object; }, undefined, undefined, undefined> & object


createEpisodicMemoryResource()​

function createEpisodicMemoryResource(scope, options?): object & ResourceConfig<JsonObject> & object;

Create an episodic memory resource definition at the given scope.

Each resource carries its scope intrinsically. Episodic memory persists across sessions, so it lives at 'user' or 'org' scope; pick the scope that matches the access pattern and storage boundary you want.

Blocks and capabilities install the returned definition via the unified resources: { episodicMemory: <created> } map and access it through ctx.resources.get('episodicMemory') regardless of scope.

options.flowIsolation is the resource's own flowIsolation. Omit it to take the flow's isolateUserState / isolateOrgState default.

Parameters​

scope​

"user" | "org"

options?​

MemoryResourceOptions

Returns​

object & ResourceConfig<JsonObject> & object


createLlmFilterStrategy()​

function createLlmFilterStrategy(opts): RetrievalStrategy;

Create the V1 llm-filter retrieval strategy.

Returns a strategy whose prepareBlock and filterBlock are constructed once at factory time; the recall tool factory composes them into a sequencer (no handler calls a block via asRuntime).

Parameters​

opts​

LlmFilterStrategyOptions

Returns​

RetrievalStrategy


createMemoryCapability()​

function createMemoryCapability(options): MemoryCapability;

Build the composed memory capability for the configured tiers.

One of two parallel entry points (see system()). Returns a DefinedCapability extended with sessionResources, userResources, tiers, and recallToolBlock — install it on a generator with uses: [mem] and register { ...mem.sessionResources, ...mem.userResources } on the flow.

Parameters​

options​

CreateMemoryCapabilityOptions

Returns​

MemoryCapability


createMemoryContextFormatter()​

function createMemoryContextFormatter(options?): (_input, ctx) => MemoryContextValue;

Build a single context formatter that combines whichever sections the caller asks for. With no options, defaults to { digest: true, working: true } — the same behaviour as the previous mem.contextFormatter. Pass semantic / episodic to opt into the richer sections; pass false for any default-on section to suppress it.

Use this when bypassing the capability's preset machinery — for example, to inject a custom mix into a generator's context: { memory: … } slot with non-default topN / limit values.

Parameters​

options?​

MemoryContextFormatterOptions

Returns​

(_input, ctx) => MemoryContextValue


createRecallTool()​

function createRecallTool(opts): BlockDefinition<any, any, any, any>;

Create the recall tool — a sequencer the agent calls as a tool.

Returned block has the same name (memory/recall) and description as before; only the kind shifts from handler to sequencer. Tools accept any BlockDefinition, so generators install it the same way.

Parameters​

opts​

CreateRecallToolOptions

Returns​

BlockDefinition<any, any, any, any>


createSemanticEntry()​

function createSemanticEntry(options?): (_input, ctx) =>
| {
semantic: string;
}
| undefined;

Returns a context entry function that emits { semantic: string } or undefined. Pulls the top-N semantic facts by reinforcement count via the shared topFacts helper so the selection matches what the digest sees.

Parameters​

options?​
topN?​

number

Returns​

(_input, ctx) => | { semantic: string; } | undefined


createSemanticMemoryCapability()​

function createSemanticMemoryCapability(config?): DefinedCapability<"semanticMemory", {
addFact: (fact) => Promise<{
category: | "identity"
| "preference"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount: number;
sourceEpisodeIds: string[];
subject: string;
}>;
allFacts: (subject?) => object[];
query: (q, limit?, subject?) => object[];
reinforce: (factId, sourceEpisodeIds, confidenceBoost?) => Promise<
| {
category: | "identity"
| "preference"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount: number;
sourceEpisodeIds: string[];
subject: string;
}
| undefined>;
removeFact: (factId) => Promise<void>;
updateFact: (factId, newContent, sourceEpisodeIds, newConfidence?) => Promise<
| {
category: | "identity"
| "preference"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount: number;
sourceEpisodeIds: string[];
subject: string;
}
| undefined>;
}, never, Record<string, PresetDef<any>>, undefined, {
semanticMemory: object & ResourceConfig<JsonObject> & object;
}, undefined, undefined, undefined> & object;

Create a semantic memory capability.

Declares semanticMemory resource in the configured scope and exposes typed helpers via ctx.cap.semanticMemory.

Parameters​

config?​

SemanticMemoryCapabilityConfig

Returns​

DefinedCapability<"semanticMemory", { addFact: (fact) => Promise<{ category: | "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; confidence: number; content: string; extractedAt: string; id: string; lastReinforced?: string; reinforcementCount: number; sourceEpisodeIds: string[]; subject: string; }>; allFacts: (subject?) => object[]; query: (q, limit?, subject?) => object[]; reinforce: (factId, sourceEpisodeIds, confidenceBoost?) => Promise< | { category: | "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; confidence: number; content: string; extractedAt: string; id: string; lastReinforced?: string; reinforcementCount: number; sourceEpisodeIds: string[]; subject: string; } | undefined>; removeFact: (factId) => Promise<void>; updateFact: (factId, newContent, sourceEpisodeIds, newConfidence?) => Promise< | { category: | "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; confidence: number; content: string; extractedAt: string; id: string; lastReinforced?: string; reinforcementCount: number; sourceEpisodeIds: string[]; subject: string; } | undefined>; }, never, Record<string, PresetDef<any>>, undefined, { semanticMemory: object & ResourceConfig<JsonObject> & object; }, undefined, undefined, undefined> & object


createSemanticMemoryResource()​

function createSemanticMemoryResource(
scope,
relations?,
options?
): object & ResourceConfig<JsonObject> & object;

Create a semantic memory resource definition with the given scope. Follows the same factory pattern as createEpisodicMemoryResource.

When relations is passed (relations tier enabled), the resource declares an edges slot so the framework injects an edges: Edge[] field into the state and attaches the ResourceEdgeApi to the live ref. When it is omitted, the resource carries no edges field and no edge API — the chat-personalization path is byte-for-byte unchanged.

options.flowIsolation is the resource's own flowIsolation. Omit it to take the flow's isolateUserState / isolateOrgState default.

Parameters​

scope​

"user" | "org"

relations?​

EdgeSlotConfig

options?​

MemoryResourceOptions

Returns​

object & ResourceConfig<JsonObject> & object


createWorkingEntry()​

function createWorkingEntry(): (_input, ctx) =>
| {
working: string;
}
| undefined;

Returns a context entry function that emits { working: string } or undefined. Reads the working-memory resource and renders its current entries via formatForContext (salience-sorted bullet list).

Returns​

(_input, ctx) => | { working: string; } | undefined


createWorkingMemoryCapability()​

function createWorkingMemoryCapability(config?): DefinedCapability<"workingMemory", {
add: (entry) => Promise<{
addedAtTurn: number;
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}>;
evict: (id) => Promise<boolean>;
format: () => string;
items: () => object[];
pin: (id) => Promise<boolean>;
refresh: (id) => Promise<boolean>;
tick: () => Promise<void>;
unpin: (id) => Promise<boolean>;
}, never, Record<string, PresetDef<any>>, undefined, {
workingMemory: object & ResourceConfig<JsonObject> & object;
}, undefined, undefined, undefined> & object;

Create a working memory capability with custom config.

Declares workingMemory session resource and exposes typed helpers via ctx.cap.workingMemory. No presets — works on all block kinds.

For generator context injection, use workingMemoryContextFormatter in the generator's context array alongside this capability.

Parameters​

config?​

WorkingMemoryHelperConfig

Returns​

DefinedCapability<"workingMemory", { add: (entry) => Promise<{ addedAtTurn: number; category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability: "transient" | "session" | "persistent" | "permanent"; id: string; importance: number; lastAccessedAtTurn: number; metadata?: Record<string, any>; pinned: boolean; salience: number; }>; evict: (id) => Promise<boolean>; format: () => string; items: () => object[]; pin: (id) => Promise<boolean>; refresh: (id) => Promise<boolean>; tick: () => Promise<void>; unpin: (id) => Promise<boolean>; }, never, Record<string, PresetDef<any>>, undefined, { workingMemory: object & ResourceConfig<JsonObject> & object; }, undefined, undefined, undefined> & object


cullByEffectiveConfidence()​

function cullByEffectiveConfidence(
ref,
now,
halfLife,
cullFloor
): Promise<string[]>;

Cull facts whose effective (time-decayed) confidence has dropped below cullFloor. Returns the IDs of removed facts so callers can record what the janitor pass evicted.

Decay anchor and formula live in effectiveConfidence. Facts whose lastReinforced is missing (created before the V1 bug fix) decay from extractedAt.

Parameters​

ref​

SemRef

now​

number

halfLife​

number

cullFloor​

number

Returns​

Promise<string[]>


cullByTTL()​

function cullByTTL(
ref,
currentTurn,
now,
ttl
): Promise<string[]>;

Cull persistent episodes that have crossed the configured TTL thresholds.

Permanent episodes are NEVER touched here — they are sacrosanct and only pick up a stale: true marker via markStale. Returns the IDs of culled episodes so the caller can record them on the janitor resource.

Parameters​

ref​

EpRef

currentTurn​

number

now​

number

ttl​

EpisodicTTLConfig

Returns​

Promise<string[]>


digestIsStale()​

function digestIsStale(
ref,
semRef,
epRef?
): boolean;

True when the digest is missing or its stored sourceSignature differs from a freshly computed one — i.e. the underlying stores have changed since the last regeneration. Cheap; called on every consolidation / prune completion before deciding to spend an LLM call.

Parameters​

ref​

DigestRef

semRef​

SemRef

epRef?​

EpRef

Returns​

boolean


digestRegenerate()​

function digestRegenerate(config): SequencerDefinition<
| {
force?: boolean;
}
| undefined, any, undefined, undefined>;

Assembles the digest regeneration sequencer: guard → (if triggered) → generate → persist

Manual invocation (via mem.regenerateDigest()) pre-binds force: true to bypass the guard's staleness check.

Parameters​

config​

DigestRegenerateConfig

Returns​

SequencerDefinition< | { force?: boolean; } | undefined, any, undefined, undefined>


digestRegenerateGenerate()​

function digestRegenerateGenerate(config): BlockDefinition<ZodAny, ZodString, any, string>;

Generator block — one LLM call producing the digest narrative.

Iterative: the previous digest is fed back in as the framing baseline. Bounded by config.digest.maxTokens at the provider level.

Parameters​

config​

DigestRegenerateConfig

Returns​

BlockDefinition<ZodAny, ZodString, any, string>


digestRegenerateGuard()​

function digestRegenerateGuard(config): BlockDefinition<ZodOptional<ZodObject<{
force: ZodOptional<ZodBoolean>;
}, "strip", ZodTypeAny, {
force?: boolean;
}, {
force?: boolean;
}>>, ZodObject<{
episodes: ZodArray<ZodObject<{
category: ZodString;
content: ZodString;
occurredAtTurn: ZodNumber;
significance: ZodNumber;
subject: ZodString;
}, "strip", ZodTypeAny, {
category: string;
content: string;
occurredAtTurn: number;
significance: number;
subject: string;
}, {
category: string;
content: string;
occurredAtTurn: number;
significance: number;
subject: string;
}>, "many">;
facts: ZodArray<ZodObject<{
category: ZodString;
confidence: ZodNumber;
content: ZodString;
reinforcementCount: ZodNumber;
subject: ZodString;
}, "strip", ZodTypeAny, {
category: string;
confidence: number;
content: string;
reinforcementCount: number;
subject: string;
}, {
category: string;
confidence: number;
content: string;
reinforcementCount: number;
subject: string;
}>, "many">;
previous: ZodOptional<ZodString>;
triggered: ZodBoolean;
}, "strip", ZodTypeAny, {
episodes: object[];
facts: object[];
previous?: string;
triggered: boolean;
}, {
episodes: object[];
facts: object[];
previous?: string;
triggered: boolean;
}>,
| {
force?: boolean;
}
| undefined, {
episodes: object[];
facts: object[];
previous?: string;
triggered: boolean;
}>;

Guard handler — reads digest, semantic, and episodic state; decides whether to trigger regeneration based on sourceSignature drift.

force: true on the input bypasses the staleness check (used by the manual mem.regenerateDigest() escape hatch).

Parameters​

config​

DigestRegenerateConfig

Returns​

BlockDefinition<ZodOptional<ZodObject<{ force: ZodOptional<ZodBoolean>; }, "strip", ZodTypeAny, { force?: boolean; }, { force?: boolean; }>>, ZodObject<{ episodes: ZodArray<ZodObject<{ category: ZodString; content: ZodString; occurredAtTurn: ZodNumber; significance: ZodNumber; subject: ZodString; }, "strip", ZodTypeAny, { category: string; content: string; occurredAtTurn: number; significance: number; subject: string; }, { category: string; content: string; occurredAtTurn: number; significance: number; subject: string; }>, "many">; facts: ZodArray<ZodObject<{ category: ZodString; confidence: ZodNumber; content: ZodString; reinforcementCount: ZodNumber; subject: ZodString; }, "strip", ZodTypeAny, { category: string; confidence: number; content: string; reinforcementCount: number; subject: string; }, { category: string; confidence: number; content: string; reinforcementCount: number; subject: string; }>, "many">; previous: ZodOptional<ZodString>; triggered: ZodBoolean; }, "strip", ZodTypeAny, { episodes: object[]; facts: object[]; previous?: string; triggered: boolean; }, { episodes: object[]; facts: object[]; previous?: string; triggered: boolean; }>, | { force?: boolean; } | undefined, { episodes: object[]; facts: object[]; previous?: string; triggered: boolean; }>


digestRegeneratePersist()​

function digestRegeneratePersist(config): BlockDefinition<ZodString, ZodAny, string,
| {
digest?: undefined;
persisted: boolean;
}
| {
digest: {
content: string;
generatedAt: string;
generatedAtTurn: number;
sourceSignature: {
episodeCount: number;
semanticFactCount: number;
semanticReinforcementSum: number;
};
};
persisted: boolean;
}>;

Persist handler — writes the generated digest along with a fresh source-state signature. Reads semanticMemory (and optional episodicMemory) to compute the signature at write time; per-scope mutation serialization means the signature observed here equals the one the guard observed for any single sequencer run. No-ops on empty content so a truncated LLM response doesn't overwrite a previous good digest.

Parameters​

config​

DigestRegenerateConfig

Returns​

BlockDefinition<ZodString, ZodAny, string, | { digest?: undefined; persisted: boolean; } | { digest: { content: string; generatedAt: string; generatedAtTurn: number; sourceSignature: { episodeCount: number; semanticFactCount: number; semanticReinforcementSum: number; }; }; persisted: boolean; }>


edgeToMemoryItem()​

function edgeToMemoryItem(edge): MemoryItem;

Convert a relation edge to the unified MemoryItem shape. Content renders as "<from> <type> <to>" so the agent reads the relation as a sentence; the structured from/to/relationType/confidence fields carry the typed data for downstream consumers. The item id is the edge id so dedup against an already-included set works by id.

Parameters​

edge​
confidence​

number

createdAt​

string

from​

string

id​

string

source​

string[]

to​

string

type​

string

validFrom​

string | null

validUntil​

string | null

Returns​

MemoryItem


effectiveConfidence()​

function effectiveConfidence(
fact,
now?,
halfLife?
): number;

Compute the time-decayed effective confidence of a semantic fact.

Uses an exponential decay anchored on lastReinforced (or extractedAt as a fallback when lastReinforced is missing on facts created before the V1 bug fix in addFact):

effective = confidence × 0.5 ^ (elapsedDays / halfLife)

Output is clamped to [0, fact.confidence]. The upper clamp is defensive against clock skew producing a negative elapsed; the lower clamp guards against numerical underflow.

Parameters​

fact​

Pick<SemanticFact, "confidence" | "lastReinforced" | "extractedAt">

Semantic fact with confidence, optional lastReinforced, and extractedAt.

now?​

number

Reference time as a unix-ms timestamp. Defaults to Date.now().

halfLife?​

number

Half-life in days. Defaults to DEFAULT_HYGIENE_CONFIG.confidenceDecay.halfLife (180).

Returns​

number

Effective confidence in [0, fact.confidence].


encodeEpisode()​

function encodeEpisode(
ref,
episode,
maxEpisodes
): Promise<{
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
consolidated: boolean;
content: string;
context: {
precedingTopic?: string;
sessionId: string;
};
durability: "persistent" | "permanent";
encodedAt: string;
id: string;
occurredAtTurn: number;
significance: number;
stale: boolean;
subject: string;
}>;

Encode a new episode into episodic memory.

Generates a unique ID and sets encodedAt to the current time. When the store reaches maxEpisodes, the oldest consolidated episode is evicted first; if none are consolidated, the oldest unconsolidated episode is evicted instead.

Parameters​

ref​

EpRef

episode​

EncodeEpisodeInput

maxEpisodes​

number

Returns​

Promise<{ category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; consolidated: boolean; content: string; context: { precedingTopic?: string; sessionId: string; }; durability: "persistent" | "permanent"; encodedAt: string; id: string; occurredAtTurn: number; significance: number; stale: boolean; subject: string; }>


episodeToMemoryItem()​

function episodeToMemoryItem(episode): MemoryItem;

Convert an episode to the unified MemoryItem shape.

Parameters​

episode​
category​

| "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"

consolidated​

boolean

content​

string

context​

{ precedingTopic?: string; sessionId: string; }

context.precedingTopic?​

string

context.sessionId​

string

durability​

"persistent" | "permanent"

encodedAt​

string

id​

string

occurredAtTurn​

number

significance​

number

stale​

boolean

subject​

string

Returns​

MemoryItem


evictWorkingMemory()​

function evictWorkingMemory(ref, id): Promise<boolean>;

Remove an entry by ID. Explicit eviction overrides pin status. Returns true if the entry was found and removed, false otherwise.

Parameters​

ref​

WmRef

id​

string

Returns​

Promise<boolean>


exactPhraseMatches()​

function exactPhraseMatches(
query,
candidates,
includedIds
): object[];

Stage 1.5: scan non-pre-ranked items for literal phrase matches.

Catches the "exact identifier in a low-score memory" failure mode. Returns up to EXACT_PHRASE_CAP items not already in included.

Parameters​

query​

string

candidates​

object[]

includedIds​

Set<string>

Returns​

object[]


extractExactPhrases()​

function extractExactPhrases(query): string[];

Extract contiguous phrases of EXACT_PHRASE_MIN_WORDS+ words from the query.

Whitespace splits only — no tokenisation tricks. Phrases overlap; a 5-word query produces (5-3)+(5-4)+(5-5) = 3 phrases at min-len 3.

Parameters​

query​

string

Returns​

string[]


formatWorkingMemoryEntries()​

function formatWorkingMemoryEntries(ref): string;

Format current working memory entries as a numbered list for LLM context. Returns empty string if there are no entries.

Format: - (pinned) The user prefers TypeScript

Entries are ordered by salience (most relevant first). Salience scores are intentionally omitted — they're an internal eviction mechanism, not a confidence signal, and risk being over-interpreted by the consuming LLM.

Use this when injecting memory into a generator's context: slot. For a ready-made slot function, see workingMemoryContextFormatter.

Parameters​

ref​

WmRef

Returns​

string


graphExpandCandidates()​

function graphExpandCandidates(
edges,
query,
alreadyIncluded,
opts?
): MemoryItem[];

Build relation candidates connected to entities named in query.

Focal nodes are derived from the query: each edge endpoint (a canonical subject string) whose value appears as a whitespace-delimited token in the lowercased query, plus any multi-word edge endpoint that appears verbatim as an extracted exact phrase. The ego graph around each focal node is collected; its edges become relation MemoryItems, excluding any whose id is already in alreadyIncluded. Capped at GRAPH_EXPAND_CAP.

Returns [] when edges is empty or no endpoint matches the query, so the relations-disabled path is unchanged.

Parameters​

edges​

object[]

query​

string

alreadyIncluded​

Set<string>

opts?​

GraphExpandOptions

Returns​

MemoryItem[]


intrinsicEpisodicScore()​

function intrinsicEpisodicScore(episode, currentTurn): number;

Intrinsic score for an episode (no query component).

significance × exp(-(currentTurn - occurredAtTurn) / RECENCY_HALF_LIFE). Significant + recent floats up; ancient episodes decay smoothly.

Parameters​

episode​
category​

| "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"

consolidated​

boolean

content​

string

context​

{ precedingTopic?: string; sessionId: string; }

context.precedingTopic?​

string

context.sessionId​

string

durability​

"persistent" | "permanent"

encodedAt​

string

id​

string

occurredAtTurn​

number

significance​

number

stale​

boolean

subject​

string

currentTurn​

number

Returns​

number


intrinsicSemanticScore()​

function intrinsicSemanticScore(
fact,
now?,
halfLife?
): number;

Intrinsic score for a semantic fact (no query component).

effectiveConfidence(fact) × (0.5 + reinforcementCount/10). Stable, well-reinforced AND recently-reinforced facts float up. The fact's confidence is decayed by time-since-last-reinforcement (see effectiveConfidence) before being combined with the reinforcement normaliser, so the same raw confidence ranks lower as the fact ages.

Parameters​

fact​

The semantic fact to score.

category​

| "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"

confidence​

number

content​

string

extractedAt​

string

id​

string

lastReinforced?​

string

reinforcementCount​

number

sourceEpisodeIds​

string[]

subject​

string

now?​

number

Optional reference time (unix ms) for decay computation — default Date.now(). Forwarded to effectiveConfidence.

halfLife?​

number | false

Optional half-life override (days). Default 180 via DEFAULT_HYGIENE_CONFIG. Pass an explicit value to match a configured hygiene profile, or false to skip decay entirely — useful for custom strategies that mirror hygiene: false callers.

Returns​

number


markEpisodesConsolidated()​

function markEpisodesConsolidated(ref, episodeIds): Promise<void>;

Mark episodes as consolidated (promoted to semantic memory). No-op for episode IDs that don't exist in the store.

Parameters​

ref​

EpRef

episodeIds​

string[]

Returns​

Promise<void>


markStale()​

function markStale(
ref,
now,
staleDays
): Promise<string[]>;

Flip stale: true on permanent episodes that have been silent longer than staleDays. Persistent episodes are ignored (the janitor culls them via cullByTTL instead). Idempotent: episodes already marked stale are not re-touched. Returns the IDs newly flagged.

Parameters​

ref​

EpRef

now​

number

staleDays​

number

Returns​

Promise<string[]>


memorySystemCapture()​

function memorySystemCapture(config): any;

Assembles the full capture pipeline: observe → reflect → tick. When semantic is configured, adds consolidation and prune as .sideChain() steps. Digest regeneration is appended to the consolidation and prune chains (see withDigestRegenerate) rather than scheduled per-turn, matching the "consolidation completion + sourceSignature delta" trigger. A per-turn run was structurally redundant — the digest's own staleness guard already no-ops when sources haven't drifted — and widened the failure surface of a background-only chain into the user-visible turn.

Parameters​

config​

MemorySystemBlocksConfig

Returns​

any


memorySystemConsolidate()​

function memorySystemConsolidate(config): SequencerDefinition<any, any, undefined, undefined>;

Assembles the consolidation sequencer: guard → generate → persist. Generate and persist are gated behind the guard's triggered flag so the LLM call is skipped entirely when consolidation isn't needed.

Parameters​

config​

MemorySystemBlocksConfig

Returns​

SequencerDefinition<any, any, undefined, undefined>


memorySystemJanitor()​

function memorySystemJanitor(config): BlockDefinition<ZodAny, ZodTypeAny, any, void>;

Create the memory janitor block.

Runs every configured hygiene pass:

  1. Decays semantic-fact confidence at read time (here we cull facts whose effective confidence has fallen below cullFloor).
  2. Culls persistent episodes past their turn / wall-time TTL.
  3. Marks permanent episodes that have gone silent past permanentStaleDays (never culls them).

Records what it touched on the session-scoped janitor resource so operators can inspect the most recent run.

No outputSchema and no return value — pure state mutation. Composed downstream via .tap() or .sideChain().

Parameters​

config​

MemorySystemBlocksConfig & object

Returns​

BlockDefinition<ZodAny, ZodTypeAny, any, void>


memorySystemObserve()​

function memorySystemObserve(config, readWindow?): BlockDefinition<ZodAny, ZodObject<{
items: ZodArray<ZodObject<{
category: ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>;
content: ZodString;
durability: ZodEnum<["transient", "session", "persistent", "permanent"]>;
importance: ZodNumber;
subject: ZodDefault<ZodString>;
}, "strip", ZodTypeAny, {
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
importance: number;
subject: string;
}, {
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
importance: number;
subject?: string;
}>, "many">;
}, "strip", ZodTypeAny, {
items: object[];
}, {
items: object[];
}>, unknown, {
items: object[];
}>;

Creates the unified observer generator.

Reads new items from ctx.session.items since lastProcessedIndex watermark. One LLM call per turn. Returns classified items with durability and category.

readWindow replaces how the observer finds its window. Capture with an evaluator passes one that reads the window it already computed, so the observer sees exactly the text the evaluator judged. Omit it for the observer's own read (readObserveWindow).

Parameters​

config​

MemorySystemBlocksConfig

readWindow?​

(input, ctx) => string | undefined

Returns​

BlockDefinition<ZodAny, ZodObject<{ items: ZodArray<ZodObject<{ category: ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>; content: ZodString; durability: ZodEnum<["transient", "session", "persistent", "permanent"]>; importance: ZodNumber; subject: ZodDefault<ZodString>; }, "strip", ZodTypeAny, { category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability: "transient" | "session" | "persistent" | "permanent"; importance: number; subject: string; }, { category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability: "transient" | "session" | "persistent" | "permanent"; importance: number; subject?: string; }>, "many">; }, "strip", ZodTypeAny, { items: object[]; }, { items: object[]; }>, unknown, { items: object[]; }>


memorySystemPrune()​

function memorySystemPrune(config): SequencerDefinition<any, any, undefined, undefined>;

Assembles the prune sequencer: guard → generate → persist. Generate and persist are gated behind the guard's triggered flag so the LLM call is skipped entirely when the fact store is below threshold.

Parameters​

config​

MemorySystemBlocksConfig

Returns​

SequencerDefinition<any, any, undefined, undefined>


memorySystemReflect()​

function memorySystemReflect(config, readJudged?): BlockDefinition<ZodObject<{
items: ZodArray<ZodObject<{
category: ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>;
content: ZodString;
durability: ZodEnum<["transient", "session", "persistent", "permanent"]>;
importance: ZodNumber;
subject: ZodDefault<ZodString>;
}, "strip", ZodTypeAny, {
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
importance: number;
subject: string;
}, {
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
importance: number;
subject?: string;
}>, "many">;
}, "strip", ZodTypeAny, {
items: object[];
}, {
items: object[];
}>, ZodAny, {
items: object[];
}, {
episodicWrites: number;
evictedPersistent: number;
}>;

Creates the reflect handler.

Routes observer output to appropriate stores:

  • All items go to working memory
  • Persistent/permanent items above significance threshold go to episodic memory
  • Permanent facts go directly to semantic memory (direct extraction)

Parameters​

config​

MemorySystemBlocksConfig

readJudged?​

(ctx) => Pick<JudgedWindow, "boundary" | "judged">

Returns​

BlockDefinition<ZodObject<{ items: ZodArray<ZodObject<{ category: ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>; content: ZodString; durability: ZodEnum<["transient", "session", "persistent", "permanent"]>; importance: ZodNumber; subject: ZodDefault<ZodString>; }, "strip", ZodTypeAny, { category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability: "transient" | "session" | "persistent" | "permanent"; importance: number; subject: string; }, { category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability: "transient" | "session" | "persistent" | "permanent"; importance: number; subject?: string; }>, "many">; }, "strip", ZodTypeAny, { items: object[]; }, { items: object[]; }>, ZodAny, { items: object[]; }, { episodicWrites: number; evictedPersistent: number; }>


memorySystemTick()​

function memorySystemTick(config): BlockDefinition<ZodAny, ZodTypeAny, any, void>;

Creates the tick handler.

Advances the decay clock. When semantic memory is NOT configured, also checks consolidation triggers and resets counters. When semantic IS configured, counter resets are handled by the consolidation persist handler.

Parameters​

config​

MemorySystemBlocksConfig

Returns​

BlockDefinition<ZodAny, ZodTypeAny, any, void>


pinWorkingMemory()​

function pinWorkingMemory(
ref,
id,
config?
): Promise<boolean>;

Pin an entry to protect it from automatic eviction. Returns false if the entry doesn't exist or if maxPinnedSlots is reached.

Parameters​

ref​

WmRef

id​

string

config?​

WorkingMemoryHelperConfig

Returns​

Promise<boolean>


pruneGenerate()​

function pruneGenerate(config): BlockDefinition<ZodAny, ZodObject<{
merges: ZodArray<ZodObject<{
mergedContent: ZodString;
reason: ZodString;
sourceFactIds: ZodArray<ZodString, "many">;
}, "strip", ZodTypeAny, {
mergedContent: string;
reason: string;
sourceFactIds: string[];
}, {
mergedContent: string;
reason: string;
sourceFactIds: string[];
}>, "many">;
removals: ZodArray<ZodObject<{
factId: ZodString;
reason: ZodString;
}, "strip", ZodTypeAny, {
factId: string;
reason: string;
}, {
factId: string;
reason: string;
}>, "many">;
}, "strip", ZodTypeAny, {
merges: object[];
removals: object[];
}, {
merges: object[];
removals: object[];
}>, unknown, {
merges: object[];
removals: object[];
}>;

Creates the prune generator. LLM call that evaluates the full semantic fact set and identifies facts to remove (noisy/redundant) or merge (overlapping unique info).

Parameters​

config​

MemorySystemBlocksConfig

Returns​

BlockDefinition<ZodAny, ZodObject<{ merges: ZodArray<ZodObject<{ mergedContent: ZodString; reason: ZodString; sourceFactIds: ZodArray<ZodString, "many">; }, "strip", ZodTypeAny, { mergedContent: string; reason: string; sourceFactIds: string[]; }, { mergedContent: string; reason: string; sourceFactIds: string[]; }>, "many">; removals: ZodArray<ZodObject<{ factId: ZodString; reason: ZodString; }, "strip", ZodTypeAny, { factId: string; reason: string; }, { factId: string; reason: string; }>, "many">; }, "strip", ZodTypeAny, { merges: object[]; removals: object[]; }, { merges: object[]; removals: object[]; }>, unknown, { merges: object[]; removals: object[]; }>


pruneGuard()​

function pruneGuard(config): BlockDefinition<ZodAny, ZodObject<{
facts: ZodArray<ZodAny, "many">;
triggered: ZodBoolean;
}, "strip", ZodTypeAny, {
facts: any[];
triggered: boolean;
}, {
facts: any[];
triggered: boolean;
}>, any, {
facts: object[];
triggered: boolean;
}>;

Creates the prune guard handler. Checks whether the semantic fact store has grown past the prune threshold and passes all facts forward for evaluation.

Parameters​

config​

MemorySystemBlocksConfig

Returns​

BlockDefinition<ZodAny, ZodObject<{ facts: ZodArray<ZodAny, "many">; triggered: ZodBoolean; }, "strip", ZodTypeAny, { facts: any[]; triggered: boolean; }, { facts: any[]; triggered: boolean; }>, any, { facts: object[]; triggered: boolean; }>


prunePersist()​

function prunePersist(config): BlockDefinition<ZodObject<{
merges: ZodArray<ZodObject<{
mergedContent: ZodString;
reason: ZodString;
sourceFactIds: ZodArray<ZodString, "many">;
}, "strip", ZodTypeAny, {
mergedContent: string;
reason: string;
sourceFactIds: string[];
}, {
mergedContent: string;
reason: string;
sourceFactIds: string[];
}>, "many">;
removals: ZodArray<ZodObject<{
factId: ZodString;
reason: ZodString;
}, "strip", ZodTypeAny, {
factId: string;
reason: string;
}, {
factId: string;
reason: string;
}>, "many">;
}, "strip", ZodTypeAny, {
merges: object[];
removals: object[];
}, {
merges: object[];
removals: object[];
}>, ZodAny, {
merges: object[];
removals: object[];
}, {
merged: number;
removed: number;
}>;

Creates the prune persist handler. Processes removals and merges from the prune generator output.

Parameters​

config​

MemorySystemBlocksConfig

Returns​

BlockDefinition<ZodObject<{ merges: ZodArray<ZodObject<{ mergedContent: ZodString; reason: ZodString; sourceFactIds: ZodArray<ZodString, "many">; }, "strip", ZodTypeAny, { mergedContent: string; reason: string; sourceFactIds: string[]; }, { mergedContent: string; reason: string; sourceFactIds: string[]; }>, "many">; removals: ZodArray<ZodObject<{ factId: ZodString; reason: ZodString; }, "strip", ZodTypeAny, { factId: string; reason: string; }, { factId: string; reason: string; }>, "many">; }, "strip", ZodTypeAny, { merges: object[]; removals: object[]; }, { merges: object[]; removals: object[]; }>, ZodAny, { merges: object[]; removals: object[]; }, { merged: number; removed: number; }>


querySemanticFacts()​

function querySemanticFacts(
ref,
q,
limit?,
subject?
): object[];

Query semantic facts by keyword relevance (synchronous, token-overlap). For small stores (≤50), returns all facts sorted by reinforcementCount. For larger stores, filters by token overlap with the query. When subject is provided, scopes to that subject only.

Parameters​

ref​

SemRef

q​

string

limit?​

number

subject?​

string

Returns​

object[]


rankEpisodesForDigest()​

function rankEpisodesForDigest<E>(episodes, limit): E[];

Score-and-rank episodes by significance × recency. Pure; exported so tests can verify ranking independently from the guard handler.

recencyFactor is normalised against the maximum occurredAtTurn in the input set so older absolute turn numbers don't suppress the score.

Type Parameters​

E​

E extends object

Parameters​

episodes​

E[]

limit​

number

Returns​

E[]


recentEpisodes()​

function recentEpisodes(ref, limit?): object[];

Get recent episodes sorted by occurredAtTurn descending (most recent first). Optionally limit the number of results.

Parameters​

ref​

EpRef

limit?​

number

Returns​

object[]


refreshWorkingMemory()​

function refreshWorkingMemory(
ref,
id,
config?
): Promise<boolean>;

Refresh an entry: reset its lastAccessedAtTurn to the current turn and recompute its salience. Models the "access boost" in memory theory. Returns true if the entry was found, false otherwise (no-op for missing IDs).

Parameters​

ref​

WmRef

id​

string

config?​

WorkingMemoryHelperConfig

Returns​

Promise<boolean>


reinforceSemanticFact()​

function reinforceSemanticFact(
ref,
factId,
sourceEpisodeIds,
confidenceBoost?
): Promise<
| {
category: | "identity"
| "preference"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount: number;
sourceEpisodeIds: string[];
subject: string;
}
| undefined>;

Reinforce an existing fact — bump confidence and reinforcementCount, merge new source episode IDs, update lastReinforced timestamp. Returns the updated fact, or undefined if factId not found.

Parameters​

ref​

SemRef

factId​

string

sourceEpisodeIds​

string[]

confidenceBoost?​

number

Returns​

Promise< | { category: | "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; confidence: number; content: string; extractedAt: string; id: string; lastReinforced?: string; reinforcementCount: number; sourceEpisodeIds: string[]; subject: string; } | undefined>


removeSemanticFact()​

function removeSemanticFact(ref, factId): Promise<void>;

Remove a fact by ID. No-op if not found.

Parameters​

ref​

SemRef

factId​

string

Returns​

Promise<void>


resolveStrategy()​

function resolveStrategy(ref, opts): RetrievalStrategy;

Resolve a strategy reference into a concrete RetrievalStrategy.

Accepts either a built-in name (constructs and returns a fresh instance) or an already-constructed strategy object (returned as-is).

Parameters​

ref​

"llm-filter" | RetrievalStrategy

opts​

ResolveStrategyOptions

Returns​

RetrievalStrategy


semanticFacts()​

function semanticFacts(ref, subject?): object[];

Get all facts, sorted by reinforcementCount descending (most established first). When subject is provided, returns only facts about that subject.

Parameters​

ref​

SemRef

subject?​

string

Returns​

object[]


semanticToMemoryItem()​

function semanticToMemoryItem(fact): MemoryItem;

Convert a semantic fact to the unified MemoryItem shape.

Parameters​

fact​
category​

| "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"

confidence​

number

content​

string

extractedAt​

string

id​

string

lastReinforced?​

string

reinforcementCount​

number

sourceEpisodeIds​

string[]

subject​

string

Returns​

MemoryItem


system()​

function system(config): MemorySystem;

Create a unified memory system.

Composes working memory, (optionally) episodic memory, and (optionally) semantic memory into a single capture pipeline, recall helper, and context formatter.

import { system } from '@flow-state-dev/memory'

const mem = system({
model: 'gpt-6-luna',
working: { capacity: 7 },
episodic: true,
semantic: true,
})

// Use in a flow:
const pipeline = sequencer({ name: 'chat', inputSchema })
.step(chat)
.sideChain(mem.capture)

Parameters​

config​

MemorySystemConfig

Returns​

MemorySystem


topSemanticFacts()​

function topSemanticFacts(
ref,
limit,
subject?
): object[];

Top-N facts by reinforcement count (most established first). Thin wrapper over allFacts; primarily used by digest regeneration to feed the most-reinforced subset into the prompt.

Parameters​

ref​

SemRef

limit​

number

subject?​

string

Returns​

object[]


unpinWorkingMemory()​

function unpinWorkingMemory(ref, id): Promise<boolean>;

Remove pin protection from an entry. Returns true if the entry was found (regardless of prior pin state), false if not found.

Parameters​

ref​

WmRef

id​

string

Returns​

Promise<boolean>


updateSemanticFact()​

function updateSemanticFact(
ref,
factId,
newContent,
sourceEpisodeIds,
newConfidence?
): Promise<
| {
category: | "identity"
| "preference"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
confidence: number;
content: string;
extractedAt: string;
id: string;
lastReinforced?: string;
reinforcementCount: number;
sourceEpisodeIds: string[];
subject: string;
}
| undefined>;

Update an existing fact's content while preserving its identity and provenance. Used when information changes (e.g., "works at Google" → "works at Stripe"). Merges new source episode IDs, sets lastReinforced, increments reinforcementCount. Returns the updated fact, or undefined if factId not found.

Parameters​

ref​

SemRef

factId​

string

newContent​

string

sourceEpisodeIds​

string[]

newConfidence?​

number

Returns​

Promise< | { category: | "identity" | "preference" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; confidence: number; content: string; extractedAt: string; id: string; lastReinforced?: string; reinforcementCount: number; sourceEpisodeIds: string[]; subject: string; } | undefined>


workingMemoryAdd()​

function workingMemoryAdd(config?): BlockDefinition<ZodObject<{
content: ZodString;
id: ZodOptional<ZodString>;
importance: ZodNumber;
metadata: ZodOptional<ZodRecord<ZodString, ZodAny>>;
pinned: ZodOptional<ZodBoolean>;
}, "strip", ZodTypeAny, {
content: string;
id?: string;
importance: number;
metadata?: Record<string, any>;
pinned?: boolean;
}, {
content: string;
id?: string;
importance: number;
metadata?: Record<string, any>;
pinned?: boolean;
}>, ZodObject<{
addedAtTurn: ZodNumber;
category: ZodDefault<ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>>;
content: ZodString;
durability: ZodDefault<ZodEnum<["transient", "session", "persistent", "permanent"]>>;
id: ZodString;
importance: ZodNumber;
lastAccessedAtTurn: ZodNumber;
metadata: ZodOptional<ZodRecord<ZodString, ZodAny>>;
pinned: ZodBoolean;
salience: ZodNumber;
}, "strip", ZodTypeAny, {
addedAtTurn: number;
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}, {
addedAtTurn: number;
category?: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability?: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}>, {
content: string;
id?: string;
importance: number;
metadata?: Record<string, any>;
pinned?: boolean;
}, {
addedAtTurn: number;
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}>;

Handler that explicitly adds an entry to working memory. For manual control when you don't want LLM-based extraction.

Parameters​

config?​

WorkingMemoryBlockConfig

Returns​

BlockDefinition<ZodObject<{ content: ZodString; id: ZodOptional<ZodString>; importance: ZodNumber; metadata: ZodOptional<ZodRecord<ZodString, ZodAny>>; pinned: ZodOptional<ZodBoolean>; }, "strip", ZodTypeAny, { content: string; id?: string; importance: number; metadata?: Record<string, any>; pinned?: boolean; }, { content: string; id?: string; importance: number; metadata?: Record<string, any>; pinned?: boolean; }>, ZodObject<{ addedAtTurn: ZodNumber; category: ZodDefault<ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>>; content: ZodString; durability: ZodDefault<ZodEnum<["transient", "session", "persistent", "permanent"]>>; id: ZodString; importance: ZodNumber; lastAccessedAtTurn: ZodNumber; metadata: ZodOptional<ZodRecord<ZodString, ZodAny>>; pinned: ZodBoolean; salience: ZodNumber; }, "strip", ZodTypeAny, { addedAtTurn: number; category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability: "transient" | "session" | "persistent" | "permanent"; id: string; importance: number; lastAccessedAtTurn: number; metadata?: Record<string, any>; pinned: boolean; salience: number; }, { addedAtTurn: number; category?: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability?: "transient" | "session" | "persistent" | "permanent"; id: string; importance: number; lastAccessedAtTurn: number; metadata?: Record<string, any>; pinned: boolean; salience: number; }>, { content: string; id?: string; importance: number; metadata?: Record<string, any>; pinned?: boolean; }, { addedAtTurn: number; category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability: "transient" | "session" | "persistent" | "permanent"; id: string; importance: number; lastAccessedAtTurn: number; metadata?: Record<string, any>; pinned: boolean; salience: number; }>


workingMemoryCapture()​

function workingMemoryCapture(config?): SequencerDefinition<string, object[], undefined, undefined>;

Bundled sequencer: observe → remember → tick.

This is the primary block most flow authors will use. One line to add working memory capture to a pipeline:

import { workingMemoryCapture } from '@flow-state-dev/memory'

const pipeline = sequencer({ name: 'pipeline', inputSchema: chatInput })
.sideChain((input) => input.message, workingMemoryCapture({ model: 'gpt-6-luna' }))
.step(chat)

Input: z.string() — the user's message (where new facts, preferences, and goals live). Use a connector function with .sideChain() to extract the message string from your pipeline's input. Place it early in the pipeline so capture runs in the background while the generator responds.

Runs observe first (LLM extraction), then remember (persists observations), then tick advances the clock and recomputes salience on all entries.

Parameters​

config?​

WorkingMemoryCaptureConfig

Returns​

SequencerDefinition<string, object[], undefined, undefined>


workingMemoryContextFormatter()​

function workingMemoryContextFormatter(_input, ctx): string;

Ready-made context: slot for generators that need working memory.

Reads the workingMemory resource (session-scoped via its intrinsic defineResource({ scope: 'session' }) declaration) and formats it as a bullet list. Assign to the generator's context array. The generator must declare resources: { workingMemory: workingMemoryResource } under the unified resource map.

const chat = generator({
name: 'chat',
model: 'gpt-6.1-sol',
inputSchema: z.string(),
resources: { workingMemory: workingMemoryResource },
context: [workingMemoryContextFormatter],
user: (input) => input,
})

Note: the ctx parameter uses an inline structural type rather than importing BlockContext because BlockContext is not part of @flow-state-dev/core's public API. The structural type matches the subset of BlockContext that this function actually uses.

Parameters​

_input​

unknown

ctx​
resources​

{ get(name): WmRef; }

resources.get​

(name) => WmRef

Returns​

string


workingMemoryItems()​

function workingMemoryItems(ref): object[];

Get current working memory entries sorted by salience descending. Synchronous read — returns a snapshot of the current state. Ties are broken by array position (stable sort).

Parameters​

ref​

WmRef

Returns​

object[]


workingMemoryObserve()​

function workingMemoryObserve(config?): BlockDefinition<ZodString, ZodObject<{
observations: ZodArray<ZodObject<{
content: ZodString;
importance: ZodNumber;
pinned: ZodDefault<ZodBoolean>;
replaces: ZodDefault<ZodString>;
}, "strip", ZodTypeAny, {
content: string;
importance: number;
pinned: boolean;
replaces: string;
}, {
content: string;
importance: number;
pinned?: boolean;
replaces?: string;
}>, "many">;
}, "strip", ZodTypeAny, {
observations: object[];
}, {
observations: object[];
}>, string, {
observations: object[];
}>;

Generator that uses an LLM to extract memories from input text.

Input: a string — typically the user's message, since that's where new facts, preferences, and goals live. The assistant's response rarely contains novel information worth storing.

Output: structured observations (content, importance, pinned, replaces).

This block only extracts — it does not persist anything. Pair it with workingMemoryRemember to write observations into the resource, or use the bundled workingMemoryCapture sequencer which wires both together.

Parameters​

config?​

WorkingMemoryObserveConfig

Returns​

BlockDefinition<ZodString, ZodObject<{ observations: ZodArray<ZodObject<{ content: ZodString; importance: ZodNumber; pinned: ZodDefault<ZodBoolean>; replaces: ZodDefault<ZodString>; }, "strip", ZodTypeAny, { content: string; importance: number; pinned: boolean; replaces: string; }, { content: string; importance: number; pinned?: boolean; replaces?: string; }>, "many">; }, "strip", ZodTypeAny, { observations: object[]; }, { observations: object[]; }>, string, { observations: object[]; }>


workingMemoryRemember()​

function workingMemoryRemember(config?): BlockDefinition<ZodObject<{
observations: ZodArray<ZodObject<{
content: ZodString;
importance: ZodNumber;
pinned: ZodDefault<ZodBoolean>;
replaces: ZodDefault<ZodString>;
}, "strip", ZodTypeAny, {
content: string;
importance: number;
pinned: boolean;
replaces: string;
}, {
content: string;
importance: number;
pinned?: boolean;
replaces?: string;
}>, "many">;
}, "strip", ZodTypeAny, {
observations: object[];
}, {
observations: object[];
}>, ZodArray<ZodObject<{
addedAtTurn: ZodNumber;
category: ZodDefault<ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>>;
content: ZodString;
durability: ZodDefault<ZodEnum<["transient", "session", "persistent", "permanent"]>>;
id: ZodString;
importance: ZodNumber;
lastAccessedAtTurn: ZodNumber;
metadata: ZodOptional<ZodRecord<ZodString, ZodAny>>;
pinned: ZodBoolean;
salience: ZodNumber;
}, "strip", ZodTypeAny, {
addedAtTurn: number;
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}, {
addedAtTurn: number;
category?: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability?: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}>, "many">, {
observations: object[];
}, object[]>;

Handler that persists observations into the working memory resource.

Input: the structured output from workingMemoryObserve (observations array). Output: the array of entries that were successfully added.

For each observation:

  • If replaces is set, the referenced entry is evicted first (no-op if ID doesn't exist).
  • The observation is added as a new entry with auto-eviction at capacity.

Errors on individual observations are caught and skipped — partial persistence is preferred over all-or-nothing failure for a background memory system.

Parameters​

config?​

WorkingMemoryBlockConfig

Returns​

BlockDefinition<ZodObject<{ observations: ZodArray<ZodObject<{ content: ZodString; importance: ZodNumber; pinned: ZodDefault<ZodBoolean>; replaces: ZodDefault<ZodString>; }, "strip", ZodTypeAny, { content: string; importance: number; pinned: boolean; replaces: string; }, { content: string; importance: number; pinned?: boolean; replaces?: string; }>, "many">; }, "strip", ZodTypeAny, { observations: object[]; }, { observations: object[]; }>, ZodArray<ZodObject<{ addedAtTurn: ZodNumber; category: ZodDefault<ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>>; content: ZodString; durability: ZodDefault<ZodEnum<["transient", "session", "persistent", "permanent"]>>; id: ZodString; importance: ZodNumber; lastAccessedAtTurn: ZodNumber; metadata: ZodOptional<ZodRecord<ZodString, ZodAny>>; pinned: ZodBoolean; salience: ZodNumber; }, "strip", ZodTypeAny, { addedAtTurn: number; category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability: "transient" | "session" | "persistent" | "permanent"; id: string; importance: number; lastAccessedAtTurn: number; metadata?: Record<string, any>; pinned: boolean; salience: number; }, { addedAtTurn: number; category?: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability?: "transient" | "session" | "persistent" | "permanent"; id: string; importance: number; lastAccessedAtTurn: number; metadata?: Record<string, any>; pinned: boolean; salience: number; }>, "many">, { observations: object[]; }, object[]>


workingMemorySnapshot()​

function workingMemorySnapshot(): BlockDefinition<ZodAny, ZodObject<{
currentTurn: ZodNumber;
entries: ZodArray<ZodObject<{
addedAtTurn: ZodNumber;
category: ZodDefault<ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>>;
content: ZodString;
durability: ZodDefault<ZodEnum<["transient", "session", "persistent", "permanent"]>>;
id: ZodString;
importance: ZodNumber;
lastAccessedAtTurn: ZodNumber;
metadata: ZodOptional<ZodRecord<ZodString, ZodAny>>;
pinned: ZodBoolean;
salience: ZodNumber;
}, "strip", ZodTypeAny, {
addedAtTurn: number;
category: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}, {
addedAtTurn: number;
category?: | "identity"
| "event"
| "preference"
| "task"
| "relationship"
| "profession"
| "belief"
| "attribute"
| "pattern";
content: string;
durability?: "transient" | "session" | "persistent" | "permanent";
id: string;
importance: number;
lastAccessedAtTurn: number;
metadata?: Record<string, any>;
pinned: boolean;
salience: number;
}>, "many">;
}, "strip", ZodTypeAny, {
currentTurn: number;
entries: object[];
}, {
currentTurn: number;
entries: object[];
}>, any, {
currentTurn: number;
entries: object[];
}>;

Handler that returns the current working memory state: entries sorted by salience and the current turn counter.

Returns​

BlockDefinition<ZodAny, ZodObject<{ currentTurn: ZodNumber; entries: ZodArray<ZodObject<{ addedAtTurn: ZodNumber; category: ZodDefault<ZodEnum<["identity", "event", "preference", "task", "relationship", "profession", "belief", "attribute", "pattern"]>>; content: ZodString; durability: ZodDefault<ZodEnum<["transient", "session", "persistent", "permanent"]>>; id: ZodString; importance: ZodNumber; lastAccessedAtTurn: ZodNumber; metadata: ZodOptional<ZodRecord<ZodString, ZodAny>>; pinned: ZodBoolean; salience: ZodNumber; }, "strip", ZodTypeAny, { addedAtTurn: number; category: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability: "transient" | "session" | "persistent" | "permanent"; id: string; importance: number; lastAccessedAtTurn: number; metadata?: Record<string, any>; pinned: boolean; salience: number; }, { addedAtTurn: number; category?: | "identity" | "event" | "preference" | "task" | "relationship" | "profession" | "belief" | "attribute" | "pattern"; content: string; durability?: "transient" | "session" | "persistent" | "permanent"; id: string; importance: number; lastAccessedAtTurn: number; metadata?: Record<string, any>; pinned: boolean; salience: number; }>, "many">; }, "strip", ZodTypeAny, { currentTurn: number; entries: object[]; }, { currentTurn: number; entries: object[]; }>, any, { currentTurn: number; entries: object[]; }>


workingMemoryTick()​

function workingMemoryTick(config?): BlockDefinition<ZodAny, ZodTypeAny, any, void>;

Handler that advances the decay clock and recomputes salience for all entries. Use with .tap() in a sequencer — this is a side-effect with no meaningful output.

Parameters​

config?​

WorkingMemoryBlockConfig

Returns​

BlockDefinition<ZodAny, ZodTypeAny, any, void>