Reintent

@reintent/core

Reintent core (0008 §2): host-neutral.

Nothing here knows about slides, screens, wardrobes or layouts, and nothing here is a visual primitive.

kernel/   elements, contexts, a pure realizer with a trace and skipping; knows no choices
choices/  Choices as data, their layers, the cascade
intent/   judge, generate, useChoose, useGenerate, useLoaded; Resolve, Preview, Switch, Reconsider
runtime/  the intent, the layers it keeps, recorded handlers

This entry is what writing an intent and writing a host use, and the types in their signatures (0024). What the realizer, the libraries and the tools use is in @reintent/core/internal.

Essentials

Hooks

  • useChoose: Reads a choice's value in this evaluation.
  • useChoiceStatus: Reads a choice's value with where it came from and its status.

Components

  • <World>: A boundary that says how the choices below it settle, and what happens when they cannot.
  • <Branch>: Reads a choice once and evaluates the case it took.

APIs

  • choices: The possibilities of a choice, with their weights.
  • generate: An open choice whose candidates System Two writes.
  • createIntent: Makes the intent that holds a program and its choices, and runs it.

Kernel

HostElements

Defined in: packages/core/src/kernel/jsx.ts

The host kinds an intent can write as lowercase tags (<tonePicker tone={tone} />), and their props: what the host draws. Empty here; an application adds its kinds. In Reintent's JSX these are its intrinsic elements; in React's JSX, @reintent/react adds them to React's (docs/design/0016 §2.1).

Extended by


Child

type Child = 
  | IntentElement
  | ForeignElement
  | Rendered
  | boolean
  | null
  | undefined
  | Child[];

Defined in: packages/core/src/kernel/jsx.ts


Component

type Component<P> = (props) => Child;

Defined in: packages/core/src/kernel/jsx.ts

A component: a function of its props.

Type Parameters

Type ParameterDefault type
Pany

Parameters

ParameterType
propsP

Returns

Child


ForeignElement

type ForeignElement = object;

Defined in: packages/core/src/kernel/jsx.ts

An element another JSX runtime built as data: React's (and Preact's in compat). The kernel reads it as its own (asElement), so an intent can be written in that runtime's JSX: its components are components, its Fragment is a Fragment, and a lowercase tag (<div>, <reply>) is a host node of that kind (docs/design/0016 §2.1).

Properties

PropertyModifierType
keyreadonlystring | null
propsreadonlyunknown
typereadonlyunknown

HostData

type HostData = 
  | null
  | boolean
  | number
  | string
  | HostData[]
  | {
[key: string]: HostData;
};

Defined in: packages/core/src/kernel/jsx.ts

JSON values carried in realized host props.


HostNode

type HostNode = object;

Defined in: packages/core/src/kernel/jsx.ts

A node only the host understands: a kind and its props, children already expanded.

Properties

PropertyModifierType
$$hostreadonlytrue
childrenreadonlyRendered[]
kindreadonlystring
propsreadonlyRecord<string, HostData>

IntentContext

type IntentContext<C> = object;

Defined in: packages/core/src/kernel/context.ts

Type Parameters

Type Parameter
C

Properties

PropertyModifierTypeDescription
axesreadonlyRecord<string, (value) => number>Numeric readings of the value, by name: what a piecewise decision is piecewise on.
keyreadonly(value) => string | undefinedNames a value in traces and caches; undefined for a context that names nothing (a callback).
namereadonlystring-
namesreadonly"evaluation" | "anywhere"Where it names the reads: 'evaluation', only when the evaluation is handed it (provide); 'anywhere', given by a Provider in the tree too.
ProviderreadonlyComponent<{ children?: Child; value: C; }>-

IntentElement

type IntentElement = object;

Defined in: packages/core/src/kernel/jsx.ts

Properties

PropertyModifierType
$$elementreadonlytrue
keyreadonlystring | undefined
propsreadonlyRecord<string, any>
typereadonlyComponent | typeof Fragment

Provide

type Provide = [IntentContext<any>, unknown][];

Defined in: packages/core/src/kernel/render.ts


Realizer

type Realizer = (tree, inputs, provide) => object;

Defined in: packages/core/src/kernel/render.ts

One evaluation, nothing skipped: the kernel's (renderOnce), or another realizer's.

Parameters

ParameterType
treeChild
inputsunknown
provideProvide

Returns

object

NameType
picksPick[]
resultResult

Rendered

type Rendered = HostNode | string | number;

Defined in: packages/core/src/kernel/jsx.ts


Fragment

const Fragment: typeof Fragment;

Defined in: packages/core/src/kernel/jsx.ts


childrenOf()

function childrenOf(children): Child[];

Defined in: packages/core/src/kernel/jsx.ts

Children as a flat list (the way components usually want them).

Parameters

ParameterType
childrenChild

Returns

Child[]


createContext()

function createContext<C>(name, opts?): IntentContext<C>;

Defined in: packages/core/src/kernel/context.ts

A context: what an intent is read in (a screen, a thread, a display mode). Its axes are numbers read off it, which a decision can be piecewise on. Provide one with intent.realize([[ctx, value]]) (or createIntent({ provide })), or <ctx.Provider value> in the tree.

Its key (by default the value's id, else its JSON) names what a read was read in: each read's ctx, the questions' where, the stamps of @reintent/lib/stamps; and, for a context handed to the evaluation, the cache of evaluations. By default only a context handed to the evaluation names the reads, with the value in scope at each; one only a <ctx.Provider> in the tree gives is part of the program and names nothing (0047 §3). names: 'anywhere' lets a Provider in the tree name them too: a program that shows one card on two screens.

Naming is not tracking. A read under a Provider that names nothing still depends on the value it reads: the value is part of the program, so when it changes the program or a choice it follows changed, and the parts that read it are evaluated again. A judge's stamp never holds a context: what a judge reads of one, the read hands it in uses.

Type Parameters

Type Parameter
C

Parameters

ParameterType
namestring
opts{ axes?: Record<string, (value) => number>; key?: (value) => string | undefined; names?: "evaluation" | "anywhere"; }
opts.axes?Record<string, (value) => number>
opts.key?(value) => string | undefined
opts.names?"evaluation" | "anywhere"

Returns

IntentContext<C>

Examples

import {
  choices,
  createContext,
  createIntent,
  host,
  useChoose,
  useContext,
} from '@reintent/core';

type Thread = { id: string; hoursLeft: number };
const ThreadCtx = createContext<Thread>('Thread', {
  axes: { hoursLeft: (t) => t.hoursLeft },
});

function Reply() {
  const { hoursLeft } = useContext(ThreadCtx);
  const send = useChoose(choices('now', 'tomorrow'), {
    of: 'reply',
    name: 'send',
    defaultValue: hoursLeft < 12 ? 'now' : 'tomorrow',
  });
  return host('reply', { send });
}

const intent = createIntent({ program: <Reply /> });
const read = (t: Thread) => intent.realize([[ThreadCtx, t]]).reads[0];
console.log(read({ id: 't1', hoursLeft: 3 }).value); // → 'now'
console.log(read({ id: 't2', hoursLeft: 48 }).ctx); // → { Thread: 't2' }

A context the program gives itself names nothing: it is part of the program.

import {
  choices,
  createContext,
  createIntent,
  host,
  useChoose,
  useContext,
} from '@reintent/core';

const Screen = createContext<{ id: string; width: number }>('Screen');
const Column = createContext<{ id: string; left: boolean }>('Column');

function Note() {
  const { left } = useContext(Column);
  const size = useChoose(choices('small', 'large'), {
    of: left ? 'left' : 'right',
    name: 'size',
    defaultValue: 'small',
  });
  return host('note', { size });
}

const intent = createIntent({
  program: (
    <Column.Provider value={{ id: 'c1', left: true }}>
      <Note />
    </Column.Provider>
  ),
});
const [note] = intent.realize([[Screen, { id: 'phone', width: 390 }]]).reads;
console.log(note.ctx); // → { Screen: 'phone' }

h()

function h(
   type, 
   props, 
   ...children
): IntentElement;

Defined in: packages/core/src/kernel/jsx.ts

Parameters

ParameterType
typetypeof Fragment | Component<any>
propsRecord<string, any> | null
...childrenChild[]

Returns

IntentElement

Example

import { createIntent, h, host } from '@reintent/core';

// What JSX compiles to: the same element, without a JSX runtime.
function Card(p: { title: string }) {
  return host('card', { title: p.title });
}

const intent = createIntent({ program: h(Card, { title: 'Hello' }) }); // <Card title="Hello" />
console.log(intent.realize().tree);
// → { '$$host': true, kind: 'card', props: { title: 'Hello' }, children: [] }

host()

function host<K>(kind, props?): IntentElement;

Defined in: packages/core/src/kernel/jsx.ts

A host node. Its children (elements or nodes) are expanded by the kernel before the host sees them. A kind declared in HostElements takes the props declared there; any other, any props.

Type Parameters

Type Parameter
K extends string

Parameters

ParameterType
kindK
props?K extends never ? HostElements[K] & object : Record<string, any>

Returns

IntentElement

Example

import { createIntent, host, type HostNode } from '@reintent/core';

// Host nodes are what λ is made of: a kind and props that only the host understands.
function Card(p: { title: string }) {
  return host('card', {
    title: p.title,
    children: [<Title text={p.title} />, host('divider')],
  });
}
function Title(p: { text: string }) {
  return host('text', { text: p.text, size: 'large' });
}

const intent = createIntent({ program: <Card title="Hello" /> });
const card = intent.realize().tree as HostNode;
console.log(card.kind, card.props.title); // → 'card' 'Hello'
console.log(card.children.map((c) => (c as HostNode).kind)); // → [ 'text', 'divider' ]

isHostNode()

function isHostNode(x): x is HostNode;

Defined in: packages/core/src/kernel/jsx.ts

Reintent core (0008 §2): host-neutral. Nothing here knows about slides, screens, wardrobes or layouts, and nothing here is a visual primitive.

kernel/ elements, contexts, a pure realizer with a trace and skipping; knows no choices choices/ Choices as data, their layers, the cascade intent/ judge, generate, useChoose, useGenerate, useLoaded; Resolve, Preview, Switch, Reconsider runtime/ the intent, the layers it keeps, recorded handlers

This entry is what writing an intent and writing a host use, and the types in their signatures (0024). What the realizer, the libraries and the tools use is in @reintent/core/internal.

Parameters

ParameterType
xunknown

Returns

x is HostNode


useCompute()

function useCompute<P, T>(
   key, 
   fn, 
   props
): T;

Defined in: packages/core/src/kernel/scope.ts

Evaluate a named pure subcomputation in the current handler scope and return its typed value. The key is unique within this component call. The kernel can reuse independent calls when choices change; hooks in the subcomputation belong to realization, not host execution.

Type Parameters

Type Parameter
P extends Record<string, unknown>
T

Parameters

ParameterType
keystring
fn(props) => T
propsP

Returns

T

Example

import {
  choices,
  createIntent,
  host,
  useChoose,
  useCompute,
  type HostNode,
} from '@reintent/core';

function Offset(p: { id: string }) {
  const n = useChoose(choices(1, 2), { of: p.id, name: 'offset', defaultValue: 1 });
  return { value: n };
}
function Program() {
  const first = useCompute('first', Offset, { id: 'a' });
  const second = useCompute('second', Offset, { id: 'b' });
  return host('sum', { value: first.value + second.value });
}
const root = createIntent({ program: <Program /> });
const output = root.realize().tree as HostNode;
console.log(output.props.value); // → 2

useContext()

Call Signature

function useContext<C>(context): C;

Defined in: packages/core/src/kernel/scope.ts

The value of a context in scope, or the part select picks of it. A pick of Inputs is recorded: on new inputs the root picks again and compares with isEqual (structural by default), the way useSyncExternalStore's withSelector does.

Type Parameters
Type Parameter
C
Parameters
ParameterType
contextIntentContext<C>
Returns

C

Example
import {
  createContext,
  createIntent,
  host,
  useContext,
  type HostNode,
} from '@reintent/core';

const Screen = createContext<{ id: string; width: number; dark: boolean }>('Screen');

function Deck() {
  // The whole value, or only the part a component goes on.
  const { id } = useContext(Screen);
  const narrow = useContext(Screen, (s) => s.width < 600);
  return host('deck', { screen: id, narrow });
}

const intent = createIntent({ program: <Deck /> });
const deck = intent.realize([[Screen, { id: 'phone', width: 390, dark: true }]])
  .tree as HostNode;
console.log(deck.props); // → { screen: 'phone', narrow: true }

Call Signature

function useContext<C, V>(
   context, 
   select, 
   isEqual?
): V;

Defined in: packages/core/src/kernel/scope.ts

The value of a context in scope, or the part select picks of it. A pick of Inputs is recorded: on new inputs the root picks again and compares with isEqual (structural by default), the way useSyncExternalStore's withSelector does.

Type Parameters
Type Parameter
C
V
Parameters
ParameterType
contextIntentContext<C>
select(value) => V
isEqual?(a, b) => boolean
Returns

V

Choices

Actor

type Actor = typeof ACTORS[number];

Defined in: packages/core/src/choices/cascade.ts

Who changes a choice or an intent (the principles, Loop): Code, the program a developer wrote; a Model, weighing the possibilities (System One) or writing new ones and new programs (System Two); a Human, deciding and confirming. System One and System Two are two ways a Model works, not two Actors.

Example

import { actorOf, type Actor } from '@reintent/core';
const who: Actor = actorOf('belief')!;
console.log(who); // → 'model'

ChoiceDecl

type ChoiceDecl = object;

Defined in: packages/core/src/choices/declare.ts

A choice, declared (0015 §3.1).

Properties

PropertyModifierTypeDescription
about?readonlyJsonFor libraries and screens (labels, words): passed to the read as about, never read here.
applies?readonlyConditionWhen it applies; otherwise it is not read at all.
default?readonlystringThe tag while unsure. None: the prior's likeliest, else the first.
forbid?readonlyreadonly object[]Possibilities out of K while when holds.
given?readonlyreadonly string[]The entity's choices to know first: System One reads them; useEntity reads them first.
judge?readonlystringThe question System One is asked. None: not judged.
kindsreadonly| readonly string[] | { [tag: string]: object; }K: tags, or tag → data (the value is then { kind: tag, …data }).
or?readonlyobjectAn open tail: one possibility more, whose value System Two writes.
or.instructionreadonlystring-
or.kind?readonlystring-
or.type?readonlyTailType-
prior?readonlyobjectCode's prior, by tag; the tags it does not name share what is left. None: equal, saying nothing.

ChoiceFamily

type ChoiceFamily<T, D> = (of?) => ChoiceRef<T, D> & object;

Defined in: packages/core/src/choices/declare.ts

A family: a declared choice without an instance. Called with an of it is a handle; read as it is (useChoose(Bear.style)), its of is the nearest <Bear>'s, or the singleton's (0015 §4).

Type Declaration

NameTypeDescription
$choice?objectTypes only: the value and the declaration.
$choice.declD-
$choice.valueT-

Type Parameters

Type ParameterDefault type
Tunknown
D extends ChoiceDeclChoiceDecl

ChoiceRef

type ChoiceRef<T, D> = Id & object;

Defined in: packages/core/src/choices/declare.ts

A handle on a declared choice: its identity { of, name } (and key), typed by its value and its declaration. It is an Id, so whatever takes an identity takes it; JSON.stringify gives the identity alone.

Type Declaration

NameTypeDescription
$choice?objectTypes only: the value and the declaration.
$choice.declD-
$choice.valueT-
keystringkeyOf(id): 'man#hat'.

Type Parameters

Type ParameterDefault type
Tunknown
D extends ChoiceDeclChoiceDecl

Choices

type Choices<T> = readonly Possibility<T>[];

Defined in: packages/core/src/choices/choices.ts

Type Parameters

Type Parameter
T

Condition

type Condition = object;

Defined in: packages/core/src/choices/declare.ts

{ field: [tags] }: the field is one of these; { '!field': [tags] }: it is none of them. All must hold.

Index Signature

[field: string]: readonly string[]

Constraint

type Constraint = 
  | {
  not: readonly string[];
}
  | {
  only: readonly string[];
};

Defined in: packages/core/src/choices/layers.ts

Hard: possibilities ruled out, or the only ones left (by tag).


Decided

type Decided<T> = T | Piecewise<T>;

Defined in: packages/core/src/choices/layers.ts

A decision: one value, or one per segment of a context's axis (0008 §7).

Type Parameters

Type ParameterDefault type
Tunknown

DecisionOrigin

type DecisionOrigin = object;

Defined in: packages/core/src/choices/layers.ts

Where a person's decision came from. Display/history metadata; not a choice input.

Example

import { choices, createIntent, host, useChoose } from '@reintent/core';
const Hat = () =>
  host('hat', {
    size: useChoose(choices('usual', 'big'), {
      of: 'man',
      name: 'hat',
      defaultValue: 'usual',
    }),
  });
const intent = createIntent({ program: <Hat /> });
const id = { of: 'man', name: 'hat' };
intent.decide(id, 'big', { said: 'make the hat big', via: 'code' });
console.log(intent.explain(id).read?.origin); // → { said: 'make the hat big', via: 'code' }
intent.history.undo();
console.log(intent.explain(id).decision); // → undefined

Properties

PropertyModifierTypeDescription
gesture?readonlystringThe host gesture that caused the decision, such as click or drag.
said?readonlystringThe original sentence, kept verbatim.
via?readonlyActorThe Actor who read it as this decision: Code, a Model, or the Human themselves.

FieldDecl

type FieldDecl = ChoiceDecl | FixedDecl;

Defined in: packages/core/src/choices/declare.ts

One field of an entity: a choice, or a part that is not one.


Fields

type Fields = object;

Defined in: packages/core/src/choices/declare.ts

An entity's fields, by name: its declaration.

Index Signature

[field: string]: FieldDecl

FixedDecl

type FixedDecl = object;

Defined in: packages/core/src/choices/declare.ts

A part that is not a choice: it has an identity and data, and no K.

Properties

PropertyModifierType
fixedreadonlyJson

GivenOf

type GivenOf<D> = 
  | D extends object ? Str<G> : never
  | D extends object ? Unbang<Str<keyof A>> : never
  | D extends object ? F extends object ? Unbang<Str<keyof W>> : never : never;

Defined in: packages/core/src/choices/declare.ts

The fields a declared choice depends on: given, and what its conditions name.

Type Parameters

Type Parameter
D

Id

type Id = object;

Defined in: packages/core/src/choices/layers.ts

A choice's identity (0008 §3, provisional): the entity it is about, and its name.

Properties

PropertyModifierType
namereadonlystring
ofreadonlystring

Json

type Json = 
  | null
  | boolean
  | number
  | string
  | readonly Json[]
  | {
[k: string]: Json;
};

Defined in: packages/core/src/choices/declare.ts

What a declaration is made of: JSON, nothing else.


Layers

type Layers = object;

Defined in: packages/core/src/choices/layers.ts

Properties

PropertyModifierTypeDescription
choicesreadonlyReadonly<Record<string, ChoiceRecord>>-
factsreadonlyreadonly string[]What was said of the whole (0008 §9): every input stamp System One answers under carries it.
generatedreadonlyReadonly<Record<string, readonly GeneratedRecord[]>>What System Two generated, by identity and stamp; newest first.
namedreadonlyReadonly<Record<string, NameRecord>>-
program?readonlystringThe program's name (an accepted proposal's): what its history says it is; no handler is given it.
unloadedreadonlyreadonly string[]Entities whose content is held elsewhere and not loaded here (a collaborator's page).

Measured

type Measured = object;

Defined in: packages/core/src/choices/layers.ts

A host's measurements of a choice's possibilities in one context, by tag, with what they were made on (stamp: the host's own key, such as the content, the screen and the fonts).

Properties

PropertyModifierTypeDescription
byreadonlyReadonly<Record<string, Measurement>>-
epoch?readonlynumberThe evaluation the measured read came from (the intent's at() then). A measurement from an evaluation older than the one already kept is refused: a late result does not overwrite a newer fact (0065 §5).
stampreadonlystring-

Measurement

type Measurement = object;

Defined in: packages/core/src/choices/layers.ts

What a host measured of one possibility in one context (0065 §3). Two kinds of thing, kept apart because they sit at different heights in the cascade:

  • Evidence the host can verify there, above a judgment: whether it fits (feasible), and a score, a weight relative to the others measured with it (the best 1; 0, like not fitting, rules it out). facts are the numbers it was decided on (text size in px, characters per line…), for an explanation, System One's prompt or an escalation; the cascade does not read them.
  • Code's taste there, below a judgment (prior): how much Code prefers it on this screen, a weight relative to the others. It multiplies code's prior and, as a prior is, is replaced by a judgment where one speaks; it never rules out (0065 §6, §9).

Properties

PropertyModifierType
facts?readonlyReadonly<Record<string, number>>
feasiblereadonlyboolean
prior?readonlynumber
score?readonlynumber

Otherwise

type Otherwise = "default" | "ask" | "switch" | "best" | "escalate";

Defined in: packages/core/src/choices/cascade.ts

How an unresolved choice is handled (0006 Level 2).


Piecewise

type Piecewise<T> = object;

Defined in: packages/core/src/choices/layers.ts

Defined segment by segment along one axis of a context ('Screen.ratio'): lo ≤ x < hi.

Type Parameters

Type Parameter
T

Properties

PropertyType
$axisstring
segmentsSegment<T>[]

Preference

type Preference = object;

Defined in: packages/core/src/choices/layers.ts

Soft: a possibility's weight multiplied (0007 R2: preferences only weigh).

Properties

PropertyModifierType
factorreadonlynumber
towardreadonlystring

Segment

type Segment<T> = object;

Defined in: packages/core/src/choices/layers.ts

Type Parameters

Type Parameter
T

Properties

PropertyType
hi?number | null
lo?number | null
valueT | undefined

Source

type Source = 
  | "preview"
  | "decision"
  | "constraint"
  | "belief"
  | "generated"
  | "prior"
  | "preference"
  | "measured"
  | "drawn"
  | "default"
  | "unknown";

Defined in: packages/core/src/choices/cascade.ts


Status

type Status = "decided" | "resolved" | "unresolved" | "unknown";

Defined in: packages/core/src/choices/cascade.ts


Tagged

type Tagged<T> = T extends string ? T : T extends object ? K | T : T;

Defined in: packages/core/src/choices/declare.ts

What a person may decide for a handle: its tag, or its value.

Type Parameters

Type Parameter
T

TailType

type TailType = "string" | "number" | "boolean" | "json";

Defined in: packages/core/src/choices/declare.ts

The type of what System Two writes for an open tail.


ValueOf

type ValueOf<D> = 
  | D extends object ? Str<K> : D extends object ? { [k in Str<keyof R>]: { kind: k } & R[k] }[Str<keyof R>] : never
  | D extends object ? object : never;

Defined in: packages/core/src/choices/declare.ts

What reading a declared choice gives: a tag, a tag with its data, or the open tail's value.

Type Parameters

Type Parameter
D

Weights

type Weights = Record<string, number>;

Defined in: packages/core/src/choices/choices.ts

Weights by tag: what System One answers, and what a trace shows.


ACTORS

const ACTORS: readonly ["code", "model", "human"];

Defined in: packages/core/src/choices/cascade.ts

The Actors, in the principles' order.


BEYOND

const BEYOND: "$beyond" = '$beyond';

Defined in: packages/core/src/choices/choices.ts

The share of a judgment outside K (β; design note 0115): every K a judge is asked about carries it, so System One can answer that none of the possibilities is what was asked for. It is never a value, and no possibility, decision or candidate may use its tag. When β is K's likeliest, or near it (from the World's minBeyond, within its minMargin), the choice is unresolved: 'unmet', cause: 'judged', for a <World onUnresolved> or the intent to hand to System Two.

Example

import { BEYOND } from '@reintent/core';
const answer = { waves: 0.1, rings: 0.2, [BEYOND]: 0.7 };
console.log(Object.keys(answer)); // → [ 'waves', 'rings', '$beyond' ]

actorOf()

function actorOf(source): "code" | "model" | "human" | undefined;

Defined in: packages/core/src/choices/cascade.ts

The Actor who wrote a value read from a layer: a person's decision, constraint or preference is Human's; a belief and a generated possibility are a Model's; a prior, a measurement and a default are Code's. A preview and an unknown read have none.

Parameters

ParameterType
sourceSource

Returns

"code" | "model" | "human" | undefined

Example

import { actorOf } from '@reintent/core';
console.log(actorOf('decision'), actorOf('prior'), actorOf('preview')); // → 'human' 'code' undefined

isPiecewise()

function isPiecewise(v): v is Piecewise<unknown>;

Defined in: packages/core/src/choices/layers.ts

Parameters

ParameterType
vunknown

Returns

v is Piecewise<unknown>


keyOf()

function keyOf(id): string;

Defined in: packages/core/src/choices/layers.ts

An identity as a string, for maps (g0#fit): Layers.choices, <World as>, a world's choices. Made so it can be read back: the name is everything after the last #, so a name may not be empty or have a # in it, and an entity (an instance chain, d/m) may not be empty. Anything else throws, so a key always splits back into the identity it was made from.

Parameters

ParameterType
idId

Returns

string

Example

import { keyOf } from '@reintent/core';

console.log(keyOf({ of: 'gallery/g0', name: 'fit' })); // → 'gallery/g0#fit'
try {
  keyOf({ of: 'man', name: 'hat#size' });
} catch (e) {
  console.log((e as Error).message);
  // → "a choice's name cannot have '#' in it (man, hat#size): its key would not read back"
}

reduceMeasured()

function reduceMeasured(by): object;

Defined in: packages/core/src/choices/layers.ts

Code's Reduce of a host's measurements (0065 §1): a possibility that does not fit, or scored 0, is ruled out (not); how well each does weighs it (weights, a factor, as a preference does); Code's taste for each in this context is a factor on the prior (priors), below a judgment.

Parameters

ParameterType
byReadonly<Record<string, Measurement>>

Returns

object

NameType
notstring[]
priorsPreference[]
weightsPreference[]

Example

import { reduceMeasured } from '@reintent/core';

const { not, weights, priors } = reduceMeasured({
  cols3: { feasible: false },
  cols2: { feasible: true, score: 0.4 },
  cols1: { feasible: true, score: 1, prior: 0.5 },
});
console.log(not); // → [ 'cols3' ]
console.log(weights); // → [ { toward: 'cols2', factor: 0.4 }, { toward: 'cols1', factor: 1 } ]
console.log(priors); // → [ { toward: 'cols1', factor: 0.5 } ]

state()

function state<T>(x): Choices<T>;

Defined in: packages/core/src/choices/choices.ts

The determined state δ_x: one possibility, weight 1.

Type Parameters

Type Parameter
T

Parameters

ParameterType
xT

Returns

Choices<T>

Example

import { state } from '@reintent/core';

const grid = state({ kind: 'grid', columns: 3 });
console.log(grid); // → [ { value: { kind: 'grid', columns: 3 }, weight: 1 } ]

tagOf()

function tagOf(v): string;

Defined in: packages/core/src/choices/choices.ts

A possibility's tag: a string, the kind of a tagged value, or its JSON.

Parameters

ParameterType
vunknown

Returns

string

Intent

Ask

type Ask = Exclude<Actor, "code">;

Defined in: packages/core/src/intent/hooks.ts

Who answers a choice, in the order asked (0033 §2): a Model with the question, then a Human. Any Actor but Code.


BranchProps

type BranchProps<T> = Omit<ChooseOptions<T>, "about"> & object;

Defined in: packages/core/src/intent/handlers.ts

Type Declaration

NameTypeDescription
about?unknown-
cases{ [K in T extends string ? T : T extends { kind: infer K } ? K & string : never]: Exclude<Child, (args: any[]) => unknown> | ((value: Extract<T, K | { kind: K }>) => Child) }One case per possibility: what it evaluates to, or a function of the collapsed value.
on| Choices<T> | Generation<T> | Judged<T>-

Type Parameters

Type Parameter
T extends Tagged

CatalogContract

type CatalogContract = object;

Defined in: packages/core/src/intent/scope.ts

A host catalog's contract as the intent layer names it: HostCatalog, from exportCatalog (0043 §3). The runtime checks a program System Two wrote against it (0055 §5).

Properties

PropertyModifierType
catalogreadonlystring
kindsreadonlyReadonly<Record<string, unknown>>
versionreadonlynumber

ChoiceRead

type ChoiceRead = object;

Defined in: packages/core/src/intent/trace.ts

Properties

PropertyTypeDescription
about?unknownWhat the component says about the choice, for libraries (labels, words); never read here.
ask?trueUnresolved, and a person is to be asked.
beyond?numberSystem One judged that none of K is what was asked for: its share outside K (BEYOND).
ctxRecord<string, string>The contexts it was read in, by name: { Screen: 'phone-p' }.
describe?Readonly<Record<string, string>>-
entity?stringThe entity it was read through, by its handle (card.tone): that entity's name (0015).
generation?ModelRequestThe request that supplies this open choice; also used by regeneration.
hypothetical?trueRead inside a preview (<Preview>, intent.preview): nobody is asked about it, and it does not escalate.
idId-
keystringkeyOf(id): for maps and comparisons.
kindsreadonly unknown[]The possibilities, as the program lists them.
measured?trueWhat the host measured where it was read ruled a possibility out or weighed one (0065).
namestringThe choice's name (what a constraint on a class of choices is about).
named?trueSettled by a constraint on its name, not on itself.
openbooleanWhether there is anything to choose here (not a determined state).
origin?DecisionOriginThe stored decision's sentence and interpreter, even while that decision is waiting.
otherwiseOtherwiseHow it is handled while unresolved (inside a preview, never 'ask' or 'escalate').
question?stringFor a judged choice: the question, and what System One reads.
sample?objectRead in a sampling <World id sample> (0089): its id, with replacement or not, and what a draw would draw from here. A draw (intent.draw) draws for every such read nobody decided.
sample.fromWeights-
sample.replaceboolean-
sample.worldstring-
shape?ShapeFor a judged choice: the possibilities' shape and what each means, as System One is told (0116).
sourceSource-
stale?true-
statusStatus-
type"choice"-
unfit?trueWhat the host measured here rules out everything a person left: it was set aside (0065 §7).
uses?Record<string, unknown>-
valueunknownWhat the evaluation went on.
waiting?unknown[]-

ChoiceStatus

type ChoiceStatus<T> = object;

Defined in: packages/core/src/intent/hooks.ts

What useChoiceStatus gives: the value, and where it came from in this evaluation.

Type Parameters

Type Parameter
T

Properties

PropertyTypeDescription
beyond?numberβ (0115): System One's share outside K (BEYOND), when its answer gave any.
cause?"measured" | "judged"While unresolved with none that fits: what ruled everything out ('measured': the host); while unmet with no person's value: System One judged none of K is what was asked for ('judged', 0115).
confidence?numberHow decisive System One's answer was, when its answer says (0116 §4).
idIdWhich choice was read: a family's instance as this read found it. Hand it on to a button or a callback (action.decide(s.id, v)); it does not look for a scope again (0092 §4).
measured?trueWhat the host measured where it was read weighed it (0065).
reason?ReasonWhile unresolved: why it cannot settle (0046 §5).
sourceSource-
stale?true-
statusStatus-
unfit?trueWhat the host measured here rules out everything a person left (0065 §7).
valueT-
waiting?unknown[]-

ComponentContract

type ComponentContract = object;

Defined in: packages/core/src/intent/scope.ts

A component's data props contract (0059): JSON for the model, pure parsing before execution.

Properties

PropertyModifierTypeDescription
parsereadonly(props) => Record<string, unknown>Checks data props and fills defaults; throws on invalid data. JSX children are separate.
propsreadonlyReadonly<Record<string, unknown>>-

Declared

type Declared = 
  | ChoiceRef<any, any>
| ChoiceFamily<any, any>;

Defined in: packages/core/src/intent/declared.ts

A handle (Bear.style('me')) or a family read in its scope (Bear.style).


DeclaredArgs

type DeclaredArgs<R> = [GivenOf<Decl<R>>] extends [never] ? [DeclaredOptions<Val<R>>] : [DeclaredOptions<Val<R>> & object];

Defined in: packages/core/src/intent/declared.ts

The options a handle's read takes: given is required when its declaration depends on something.

Type Parameters

Type Parameter
R

DeclaredOptions

type DeclaredOptions<T> = Omit<ChooseOptions<T>, "of" | "name" | "about" | "defaultValue"> & object;

Defined in: packages/core/src/intent/declared.ts

How a declared choice is read here: the read's own options, and what it depends on.

Type Declaration

NameTypeDescription
defaultValue?T | T extends object ? K : neverOverrides the declaration's default here: a value or a tag (a default that moves with the inputs).
uses?Record<string, unknown>What System One reads besides given (another entity's choice, a prop).

Type Parameters

Type ParameterDefault type
Tunknown

EachTarget

type EachTarget<T> = 
  | string
  | Id
  | Declared
  | ChooseOptions<T> & object;

Defined in: packages/core/src/intent/handlers.ts

What each enumerates: one choice, by its identity, its key, a handle, or a read.

Type Parameters

Type ParameterDefault type
Tunknown

Entity

type Entity<N, F> = {
<P>(component): Component<P & object>;
  decl: F;
  fixed: { readonly [k in FixedKeys<F>]: F[k] extends FixedDecl ? F[k]["fixed"] : never };
  name: N;
  Provider: Component<{
     children?: Child;
     id?: string;
  }>;
  toJSON: F;
} & { readonly [k in ChoiceKeys<F>]: F[k] extends ChoiceDecl ? ChoiceFamily<ValueOf<F[k]>, F[k]> : never };

Defined in: packages/core/src/intent/declared.ts

An entity: its declaration, a family per choice (bear.style), and its components. Called with a component, it gives the component with its scope: an optional id prop names the instance (and is the element's key). The default is the entity name, relative to its enclosing entity. A single name extends that address (d/me); a leading / selects an address from the Intent root (/me). <bear.Provider id> gives several components one.

Type Parameters

Type Parameter
N extends string
F extends Fields

EntityValue

type EntityValue<F> = { readonly [k in keyof F as F[k] extends { applies: object } ? never : k]: F[k] extends { fixed: infer X } ? X : ChoiceRead<F[k]> } & { readonly [k in keyof F as F[k] extends { applies: object } ? k : never]?: Exclude<ChoiceRead<F[k]>, undefined> };

Defined in: packages/core/src/intent/declared.ts

What useEntity gives: the fixed parts, and the choices that apply (those that may not, optional).

Type Parameters

Type Parameter
F extends Fields

Generation

type Generation<T> = object;

Defined in: packages/core/src/intent/hooks.ts

A request for System Two to supply values in the program's type.

Type Parameters

Type Parameter
T

Properties

PropertyModifierType
$generatereadonlytrue
check?readonly(value) => string[]
instructionreadonlystring
nreadonlynumber
uses?readonlyRecord<string, unknown>

Imports

type Imports = Readonly<Record<string, Component<any>>>;

Defined in: packages/core/src/intent/scope.ts

The intent components a draft may import, by name (0057 §2.2): the abstractions there are. A draft need not use them; a rule (use/<Name>) says when it must.


ModelRequest

type ModelRequest = object;

Defined in: packages/core/src/intent/trace.ts

Properties

PropertyTypeDescription
describe?Readonly<Record<string, string>>For judge: what each possibility means, by tag (0116 §3).
effectEffect-
facts?readonly string[]-
idId-
input?unknownThe root's input it is asked under (0045 §3), when the intent has one.
keystring-
kinds?string[]For judge: the possibilities' tags.
n?numberFor generate: candidate count (default 1). One value for 1, an array for more.
promptstringThe question (judge) or the instruction (generate).
shape?ShapeFor judge: the possibilities' shape (0116 §2); without it, they are alternatives.
stampstringThe input stamp the answer is for.
type"request"-
uses?Record<string, unknown>-

OnUnresolved

type OnUnresolved = 
  | Strategy
  | { readonly [R in Reason]?: Strategy }
  | ((u) => Strategy);

Defined in: packages/core/src/intent/scope.ts

One strategy for every reason, one per reason (the others 'forward'), or a pure function.


ReadOf

type ReadOf<R> = Decl<R> extends object ? Val<R> | undefined : Val<R>;

Defined in: packages/core/src/intent/declared.ts

What a handle's read gives: undefined where the declaration says it may not apply.

Type Parameters

Type Parameter
R

Reason

type Reason = "unsure" | "none" | "unmet";

Defined in: packages/core/src/intent/scope.ts

Why a choice cannot settle (0033 §3.2): not sure enough, nothing left, or a value K does not hold: one a person said, or, cause: 'judged', what System One judged none of K is (0115).


Reprogram

type Reprogram = Step & ReprogramOptions & object;

Defined in: packages/core/src/intent/scope.ts

reprogram({ goal }): System Two proposes the next program for what the <World> holds.

Type Declaration

NameType
$step"reprogram"

Reprogrammable

type Reprogrammable<P> = Component<P> & object;

Defined in: packages/core/src/intent/reprogrammable.ts

A reprogrammable component: an intent component, with its id.

Type Declaration

NameType
contract?ComponentContract
idstring

Type Parameters

Type Parameter
P

ReprogramOptions

type ReprogramOptions<M> = object;

Defined in: packages/core/src/intent/scope.ts

What a reprogramming may use and must keep (0055 §3, 0057): how many drafts System Two may write, the host elements each may use (elements, checked against λ), the intent components it may import (imports), and the rules it is checked by. Unset, the next one out's; the intent's last (createIntent({ elements, reprogram: { attempts, imports, rules } })).

Type Parameters

Type ParameterDefault type
M extends ImportsImports

Properties

PropertyModifierTypeDescription
attempts?readonlynumber-
catalog?readonlyCatalogContractDeprecated Renamed elements (0057 §2.2).
elements?readonlyCatalogContract-
imports?readonlyM-
rules?readonlyRules<keyof M & string>-

Rules

type Rules<Names> = object & { readonly [K in `use/${Names}`]?: Severity };

Defined in: packages/core/src/intent/scope.ts

The rules a draft is checked by (0057 §3), each a mechanical check: keep-decisions, the draft drops no decision a person made that the program reads now; use/<Name>, the draft draws the import Name. Names are the imports' names, so a rule for one not imported does not compile.

Type Declaration

NameType
keep-decisions?Severity

Type Parameters

Type ParameterDefault type
Names extends stringstring

Severity

type Severity = "error" | "warn" | "off";

Defined in: packages/core/src/intent/scope.ts

How much a rule counts, as ESLint has it (0057 §3): 'error' refuses the draft, 'warn' reports.


Shape

type Shape = "ordered" | "whether";

Defined in: packages/core/src/intent/trace.ts

The shape of a choice's possibilities, which a judge request carries (0116 §2). 'ordered': they are levels, in the order listed. 'whether': they are true and false, a proposition and its negation. Without a shape they are alternatives.


StatusOf

type StatusOf<R> = Decl<R> extends object ? ChoiceStatus<Val<R>> | undefined : ChoiceStatus<Val<R>>;

Defined in: packages/core/src/intent/declared.ts

What useChoiceStatus gives for a handle: undefined where the declaration says it may not apply.

Type Parameters

Type Parameter
R

Step

type Step = object;

Defined in: packages/core/src/intent/scope.ts

A step a <World> takes for a choice that cannot settle (0046 §2), once each, in order: rejudge({ goal }) asks System One again with the goal as a hint, regenerate() asks System Two for fresh candidates, reprogram({ goal }) has System Two propose the next program for what the World holds.

Properties

PropertyModifierType
$stepreadonly"rejudge" | "regenerate" | "reprogram"
goal?readonlystring

Strategy

type Strategy = 
  | "fallback"
  | "forward"
  | Step
  | readonly (Step | "fallback")[];

Defined in: packages/core/src/intent/scope.ts

What a <World> does with a choice that cannot settle: use its default ('fallback'), leave it to the next <World> out ('forward'), or take steps, one or several in order, ending in 'fallback' to settle for the default once they are taken.


Unresolved

type Unresolved = object;

Defined in: packages/core/src/intent/trace.ts

A choice that cannot settle, reported for someone to handle (0033 §3.2, 0046 §5): by the <World> whose onUnresolved reprograms it, or, when nothing around it handles it, by the root for the host (intent.onUnresolved).

Properties

PropertyTypeDescription
allowreadonly Action[]-
beyond?numberFor cause: 'judged': System One's share outside K (BEYOND, 0115).
boundary?stringThat boundary's id: the part of the program a reprogram may change.
cause?"measured" | "judged"For 'unmet' System One judged (no wanted): 'judged'; for 'none' the host measured: 'measured'.
dist?Weights-
goal?stringThe <World> (or <Reconsider>) that caught it: its goal and what it allows; none at the root.
idId-
keystring-
reasonReason-
reprogram?ReprogramOptionsIts reprogram step's options, when it gives any (0055 §3): over the intent's.
tried?readonly Action[]What the boundaries inside it tried before letting it through (0004 §4).
type"escalate"-
wanted?unknownFor 'unmet': what the person said, which K does not hold.

UnresolvedChoice

type UnresolvedChoice = object;

Defined in: packages/core/src/intent/scope.ts

What onUnresolved is given in its function form: the choice and why it cannot settle.

Properties

PropertyModifierTypeDescription
beyond?readonlynumberFor cause: 'judged': System One's share outside K (BEYOND).
cause?readonly"measured" | "judged"Where it comes from, when not a person: for 'none', the host's measurement ruled everything out ('measured', 0065 §7); for 'unmet', System One judged none of K is what was asked for ('judged', 0115).
dist?readonlyWeights-
idreadonlyId-
keyreadonlystring-
reasonreadonlyReason-
wanted?readonlyunknown-

WorldProps

type WorldProps<T> = object;

Defined in: packages/core/src/intent/handlers.ts

Type Parameters

Type ParameterDefault type
Tunknown

Properties

PropertyTypeDescription
as?Record<string, Decided>Hypotheses by key (keyOf(id)): the subtree as it would be under them, written nowhere.
children?Child | ((value) => Child)The subtree; with each={target} that says its possibilities, a function of its value.
each?true | EachTarget<T>Enumerate: every open choice the subtree reads (true), or only target, one path per possibility. λ holds a worlds node of world paths (props.at, props.p).
id?stringThe name of the part of the program this World holds; needed to reprogram it.
max?numberAt most this many paths for each (default 16); a choice that would go past it collapses.
minBeyond?numberFrom how much System One's share outside K (β) goes to System Two when it is not K's likeliest but the likeliest does not lead it by minMargin (0115 §4.4; default 0.3). β that is the likeliest always goes.
minMargin?numberHow sure is sure enough: the likeliest is taken when it leads the next by this much.
onUnresolved?OnUnresolvedWhat to do with a choice below that cannot settle (0046 §2).
sample?| true | { replace?: boolean; }Collapse by sampling (0089): each draw (intent.draw(id), action.draw(id)) draws, for every choice read in this World that nobody decided, a value from its distribution, and records it; the choice takes the value its last draw took. With replacement by default; { replace: false } leaves out what that choice drew this round. Needs an id, which a draw names. Until a choice is drawn, the World's other policy holds.

Switch

const Switch: <T>(p) => IntentElement = Branch;

Defined in: packages/core/src/intent/handlers.ts

Pattern matching (0033 §3.1): reads the choice once and evaluates the case it took. λ holds a branch host node with the tag it took, the kinds there are, and that case. Inside <World each>, the choice is enumerated, and each case is a path of its own.

Type Parameters

Type Parameter
T extends Tagged

Parameters

ParameterType
pBranchProps<T>

Returns

IntentElement

Example

import { Branch, choices, createIntent, host, type HostNode } from '@reintent/core';

// A choice of subtree: λ holds a branch node with the case the choice collapsed to.
function Gallery(p: { id: string }) {
  return (
    <Branch
      on={choices('grid', 'list')}
      of={p.id}
      name="view"
      defaultValue="list"
      cases={{ grid: host('grid', { columns: 3 }), list: host('list') }}
    />
  );
}

const intent = createIntent({ program: <Gallery id="g1" /> });
const branch = intent.realize().tree as HostNode;
console.log(branch.kind, branch.props.chosen); // → 'branch' 'list'

intent.decide({ of: 'g1', name: 'view' }, 'grid');
const chosen = (intent.realize().tree as HostNode).children[0] as HostNode;
console.log(chosen.kind, chosen.props); // → 'grid' { columns: 3 }

Deprecated

Renamed <Branch> (0046 §6).


entity()

function entity<N, F>(name, fields): Entity<N, F>;

Defined in: packages/core/src/intent/declared.ts

An entity's choices, declared once, as data. Checked when built (every error at once). Each choice field is a family: read as it is, useChoose(man.hat) takes its of from the nearest instance (none: the singleton, 'man'); man.hat('m1') names one. Called with a component, the entity gives it its scope: const Man = man((p) => …), then <Man id="m1" />. Relative ids extend the enclosing entity path. <Man id="/m1" /> always reads m1#hat; its handle is man.hat('m1'). Omitting the id uses the entity name as a relative segment.

Type Parameters

Type Parameter
N extends string
F extends Fields

Parameters

ParameterType
nameN
fieldsF

Returns

Entity<N, F>

Example

import { createIntent, entity, host, useChoose } from '@reintent/core';

const man = entity('man', {
  hat: {
    kinds: { usual: { hatScale: 1 }, big: { hatScale: 1.45 } },
    default: 'big',
    judge: 'How big is the hat?',
  },
  outline: { fixed: 'a man in a bowler hat' },
});

// A component of the entity: it reads `man`, and writes no id.
const Man = man(() => host('man', { hat: useChoose(man.hat).hatScale }));

// The singleton (man#hat), and m2#hat.
const intent = createIntent({ program: [<Man />, <Man id="m2" />] });
intent.decide(man.hat('m2'), 'usual');
console.log(intent.realize().reads.map((r) => `${r.key}=${(r.value as any).kind}`));
// → [ 'man#hat=big', 'm2#hat=usual' ]
console.log(man.fixed.outline); // → 'a man in a bowler hat'

// A declaration that does not hold is not built.
try {
  entity('man', { hat: { kinds: ['usual'], default: 'huge' } });
} catch (e) {
  console.log((e as Error).message); // → "entity man: hat: default 'huge' is not one of its kinds"
}

judge()

function judge<T>(
   question, 
   c, 
   opts?
): Judged<T>;

Defined in: packages/core/src/intent/hooks.ts

A plain function: a request that System One weigh c, reading uses (its input stamp).

Type Parameters

Type Parameter
T

Parameters

ParameterType
questionstring
cChoices<T> | Generation<T>
opts{ uses?: Record<string, unknown>; }
opts.uses?Record<string, unknown>

Returns

Judged<T>

Deprecated

Write the question on the choice: useChoose(c, { question, ask: ['model'], uses }) (0046 §4).

Example

import { choices, createIntent, host, judge, useChoose } from '@reintent/core';

function Reply(p: { id: string }) {
  // judge only describes the request; useChoose is where it is read, and sent when shown.
  const tone = useChoose(
    judge('Which tone suits this reply?', choices('formal', 'warm')),
    {
      of: p.id,
      name: 'tone',
      defaultValue: 'warm',
    },
  );
  return host('reply', { tone });
}

// System One: here a function; in an app, a model call.
const intent = createIntent({
  program: <Reply id="r1" />,
  model: { judge: () => ({ formal: 0.8, warm: 0.2 }) },
});
const connection = intent.connect({ commit() {} }); // accept the tree before sending requests
const [tone] = intent.realize().reads;
console.log(tone.value, tone.source); // → 'formal' 'belief'
connection.disconnect();

Preview()

function Preview(p): IntentElement;

Defined in: packages/core/src/intent/handlers.ts

Parameters

ParameterType
p{ at: Record<string, Decided>; children?: Child; }
p.atRecord<string, Decided>
p.children?Child

Returns

IntentElement

Deprecated

Use <World as={…}> (0046 §6).

Evaluates a subtree under hypotheses keyed by choice identity (keyOf(id)): a value, or one per segment of a context's axis. A nested preview adds its hypotheses to the outer one's. A preview changes no choice, asks nobody and escalates nothing; it uses the answers already there. A choice in it that is not sure enough takes its defaultValue (or the likeliest) and stays unresolved; its read is marked hypothetical.

Examples

import { choices, createIntent, host, Preview, useChoose } from '@reintent/core';

function Reply(p: { id: string }) {
  const tone = useChoose(choices('formal', 'warm'), {
    of: p.id,
    name: 'tone',
    defaultValue: 'warm',
  });
  return host('reply', { tone });
}

// The reply as it is, and as it would be: a preview writes nothing, sends nothing.
const intent = createIntent({
  program: (
    <>
      <Reply id="r1" />
      <Preview at={{ 'r1#tone': 'formal' }}>
        <Reply id="r1" />
      </Preview>
    </>
  ),
});
const [now, would] = intent.realize().reads;
console.log(now.value, now.source); // → 'warm' 'default'
console.log(would.value, would.source); // → 'formal' 'preview'
import {
  choices,
  createIntent,
  host,
  Preview,
  Reconsider,
  Resolve,
  useChoose,
} from '@reintent/core';

// Only a formal reply has a sign-off to choose, and nobody has said which.
function Reply(p: { id: string }) {
  const tone = useChoose(choices('formal', 'warm'), {
    of: p.id,
    name: 'tone',
    defaultValue: 'warm',
  });
  const signoff =
    tone === 'formal'
      ? useChoose(choices('regards', 'sincerely'), {
          of: p.id,
          name: 'signoff',
          defaultValue: 'regards',
        })
      : undefined;
  return host('reply', { tone, signoff });
}

const intent = createIntent({
  program: (
    <Reconsider goal="a reply the client will not find cold" allow={['ask']}>
      <Resolve otherwise="escalate">
        <Reply id="r1" />
        <Preview at={{ 'r1#tone': 'formal' }}>
          <Reply id="r1" />
        </Preview>
      </Resolve>
    </Reconsider>
  ),
});
intent.decide({ of: 'r1', name: 'tone' }, 'warm');
const r = intent.realize();
// Only the preview reads the sign-off: it takes its default, and nobody is asked.
const signoff = r.reads.find((x) => x.name === 'signoff')!;
console.log(signoff.value, signoff.status, signoff.hypothetical); // → 'regards' 'unresolved' true
console.log(r.escalations.length, intent.questions().length); // → 0 0

Reconsider()

function Reconsider(p): IntentElement;

Defined in: packages/core/src/intent/handlers.ts

Parameters

ParameterType
p{ allow?: readonly Action[]; children?: Child; goal?: string; id?: string; }
p.allow?readonly Action[]
p.children?Child
p.goal?string
p.id?string

Returns

IntentElement

Deprecated

Use <World id onUnresolved={reprogram({ goal })}>; asking a person is the choice's ask (0046 §6).

The escalate handler. Catches escalations thrown below it, reports each (with its goal and what it allows, for the intent to act on, cheapest first), and evaluates the subtree again quietly: unresolved choices fall back as otherwise: 'default' would, so the subtree shows meanwhile. With nothing allowed, or every step taken, it lets the escalation through to the next one out, with what it tried. id names the part of the program it holds: a reprogram changes that part only, so allowing reprogram needs an id (0004 §4).

Example

import { choices, createIntent, host, Reconsider, useChoose } from '@reintent/core';

// Unsure which tone, and told not to guess: the choice escalates.
function Reply(p: { id: string }) {
  const tone = useChoose(choices('formal', 'warm'), {
    of: p.id,
    name: 'tone',
    defaultValue: 'warm',
    otherwise: 'escalate',
  });
  return host('reply', { tone });
}

const intent = createIntent({
  program: (
    <Reconsider goal="a reply the client will not find cold" allow={['ask']}>
      <Reply id="r1" />
    </Reconsider>
  ),
});
const r = intent.realize();
console.log(r.escalations.map((e) => [e.key, e.reason])); // → [ [ 'r1#tone', 'unsure' ] ]
console.log(r.reads[0].value); // → 'warm'

regenerate()

function regenerate(): Step;

Defined in: packages/core/src/intent/handlers.ts

A step for <World onUnresolved>: System Two writes a generated choice's candidates again.

Returns

Step


rejudge()

function rejudge(o?): Step;

Defined in: packages/core/src/intent/handlers.ts

A step for <World onUnresolved>: System One is asked the choice's question again, with the goal as a hint, and its answer takes the place of the last one (0046 §2). It weighs the K there is, so it is skipped for 'unmet'.

Parameters

ParameterType
o{ goal?: string; }
o.goal?string

Returns

Step


reprogram()

function reprogram<M>(o?): Reprogram;

Defined in: packages/core/src/intent/handlers.ts

A strategy for <World onUnresolved>: System Two proposes the next program for what the World holds, and a person confirms it (0033 §3, 0046 §2). The World needs an id, the name the program finds that part by. A draft may use the host elements and the intent components in imports, and is checked by rules (0057). The intent tries each draft in that part, against elements, and asks again with the problems, up to attempts drafts (0055 §3, §4); unset, the intent's.

Type Parameters

Type ParameterDefault type
M extends Readonly<Record<string, Component<any>>>Readonly<Record<string, Component<any>>>

Parameters

ParameterType
oobject & ReprogramOptions<M>

Returns

Reprogram

Example

import { choices, createIntent, host, reprogram, useChoose, World } from '@reintent/core';

function Card() {
  const tone = useChoose(choices('warm', 'formal'), { of: 'card', name: 'tone' });
  return host('card', { tone });
}

// Every tone ruled out: nothing in K fits, and the card is to be reprogrammed.
const intent = createIntent({
  program: (
    <World
      id="card"
      onUnresolved={{ none: reprogram({ goal: 'A card the family will sign' }) }}
    >
      <Card />
    </World>
  ),
});
intent.constrain({ of: 'card', name: 'tone' }, { not: ['warm', 'formal'] });
const [u] = intent.realize().unresolved;
console.log(u.reason, u.boundary, u.allow); // → 'none' 'card' [ 'reprogram' ]

reprogrammable()

function reprogrammable<P, M>(
   id, 
   initial, 
   opts?
): Reprogrammable<P>;

Defined in: packages/core/src/intent/reprogrammable.ts

Declares an intent component System Two may reprogram by its id (0056 §6). It draws the version the intent holds for id (initial until a proposal for it is accepted), in a <World id> whose onUnresolved is the one given here. Each intent has its own versions: two intents with this component reprogram it apart. An id is one in a program, as a custom element's name is; declaring it again replaces the declaration (a module loaded again while developing).

A draft for it is an intent component that takes the same props (0057 §2): it reads choices and composes the intent components in imports and the host elements, and rules check it, with names typed from imports (use/Scene). intent.reprogram({ at: id }) asks for one; the request's imports are what the host gives loadProgram as modules.

Type Parameters

Type ParameterDefault type
P extends object-
M extends Readonly<Record<string, Component<any>>>Readonly<Record<string, Component<any>>>

Parameters

ParameterTypeDescription
idstring-
initialComponent<P> & object-
opts{ attempts?: number; elements?: CatalogContract; imports?: M; onUnresolved?: OnUnresolved; rules?: Rules<keyof M & string>; }-
opts.attempts?number-
opts.elements?CatalogContractThe host elements a draft may use: the hard boundary (0057 §2.2).
opts.imports?MThe intent components a draft may import (0057 §2.2).
opts.onUnresolved?OnUnresolvedWhat the boundary does with a choice that cannot settle in it (0046 §2).
opts.rules?Rules<keyof M & string>The rules a draft is checked by, as ESLint has them (0057 §3).

Returns

Reprogrammable<P>

Example

import { createIntent, host, reprogrammable, type HostNode } from '@reintent/core';

const Line = (p: { text: string }) => host('line', { text: p.text });
const Story = reprogrammable(
  'story',
  (p: { to: string }) => <Line text={`Hi ${p.to}`} />,
  {
    imports: { Line },
    rules: { 'use/Line': 'error' },
  },
);

const intent = createIntent({
  program: <Story to="Ann" />,
  model: {
    // System Two writes the part: a component of the same props, of the imports it is given.
    reprogram: (req) => {
      const { Line } = req.imports!;
      return {
        program: (p: { to: string }) => (
          <Line text={`Dear ${p.to}, a door over the sea`} />
        ),
        summary: 'a dream',
      };
    },
  },
});
const p = await intent.reprogram({ at: 'story', prompt: 'make it a dream' });
console.log(p.checks); // → [ { rule: 'use/Line', severity: 'error', ok: true, message: 'draws Line' } ]
intent.review(p).accept();
console.log((intent.realize().tree as HostNode).props.text);
// → 'Dear Ann, a door over the sea'

Resolve()

function Resolve(p): IntentElement;

Defined in: packages/core/src/intent/handlers.ts

Parameters

ParameterType
p{ children?: Child; minMargin?: number; otherwise?: Otherwise; }
p.children?Child
p.minMargin?number
p.otherwise?Otherwise

Returns

IntentElement

Deprecated

Use <World minMargin onUnresolved>; asking a person is the choice's ask (0046 §6).

Sets the resolution policy for choice reads in a subtree. The leading candidate supplies the value when its margin over the runner-up reaches minMargin (default 0.2); otherwise sets the fallback (default: defaultValue). Nested scopes inherit omitted settings. Inside a preview nothing is asked or escalated: see Preview.

Example

import { choices, createIntent, host, Resolve, useChoose } from '@reintent/core';

// A prior that leans, but not by much: 0.55 against 0.45.
const fits = choices([
  { value: 'keep', weight: 0.55 },
  { value: 'fill', weight: 0.45 },
]);
function Photo(p: { id: string }) {
  const fit = useChoose(fits, { of: p.id, name: 'fit', defaultValue: 'fill' });
  return host('photo', { fit });
}

const intent = createIntent({
  program: (
    <>
      <Photo id="a" />
      <Resolve minMargin={0.05}>
        <Photo id="b" />
      </Resolve>
    </>
  ),
});
const [a, b] = intent.realize().reads;
console.log(a.value, a.status); // → 'fill' 'unresolved'
console.log(b.value, b.status); // → 'keep' 'resolved'

useEntity()

Call Signature

function useEntity<F>(e, opts?): EntityValue<F>;

Defined in: packages/core/src/intent/declared.ts

Reads an entity (0015 §5.2): each choice after what it depends on (in the order declared when nothing orders them), handing each the values read before it; a choice that does not apply is not read and is left out. The fixed parts are there as declared. Options per field.

Type Parameters
Type Parameter
F extends Fields
Parameters
ParameterType
eEntity<string, F>
opts?{ readonly [k in string | number | symbol]?: DeclaredOptions<unknown> }
Returns

EntityValue<F>

Example
import { createIntent, entity, host, useEntity, type HostNode } from '@reintent/core';

const bear = entity('bear', {
  lower: { fixed: '#FFFFFF' },
  style: { kinds: ['plastic', 'toy', 'pixel'], prior: { plastic: 0.6 } },
  material: { kinds: ['none', 'fuzz'], applies: { style: ['toy', 'plastic'] } },
  pocket: {
    kinds: ['none', 'seam'],
    forbid: [
      { when: { style: ['pixel'] }, kinds: ['seam'], why: 'a pixel bear is a screen' },
    ],
  },
});

const BearView = bear(() => host('softoy', useEntity(bear)));

const intent = createIntent({ program: <BearView id="me" /> });
console.log((intent.realize().tree as HostNode).props);
// → { lower: '#FFFFFF', style: 'plastic', material: 'none', pocket: 'none' }

// A pixel bear has no material to read, and no pocket but 'none'.
intent.decide(bear.style('me'), 'pixel');
console.log(intent.realize().reads.map((r) => `${r.name}=${r.value}`));
// → [ 'style=pixel', 'pocket=none' ]

Call Signature

function useEntity<F>(
   e, 
   of, 
   opts?
): EntityValue<F>;

Defined in: packages/core/src/intent/declared.ts

An instance named here rather than by its scope.

Type Parameters
Type Parameter
F extends Fields
Parameters
ParameterType
eEntity<string, F>
ofstring
opts?{ readonly [k in string | number | symbol]?: DeclaredOptions<unknown> }
Returns

EntityValue<F>


useGenerate()

function useGenerate<V>(opts): Generated<V>;

Defined in: packages/core/src/intent/hooks.ts

One-candidate sugar for useChoiceStatus(generate(instruction), { of, name }). The value participates in the choice cascade, so a person can decide it or preview another.

What System Two generated for this identity and these inputs (0004 generate): the result for exactly these uses, or pending (a request is reported). Going back to earlier inputs finds what was generated for them, without asking again. check says why a result does not do (empty: it does), and then it is pending too.

Type Parameters

Type Parameter
V

Parameters

ParameterType
opts{ check?: (value) => string[]; instruction: string; name: string; of: string; uses?: Record<string, unknown>; }
opts.check?(value) => string[]
opts.instructionstring
opts.namestring
opts.ofstring
opts.uses?Record<string, unknown>

Returns

Generated<V>

Example

import { createIntent, host, useGenerate, type HostNode } from '@reintent/core';

function Caption(p: { id: string; tone: string }) {
  const caption = useGenerate<string>({
    of: p.id,
    name: 'caption',
    instruction: 'Write a caption in this tone',
    uses: { tone: p.tone },
  });
  return host('text', { text: caption.value ?? '…' });
}

// System Two: here a function; in an app, a model call. Kept for these `uses`.
const intent = createIntent({
  program: <Caption id="c1" tone="warm" />,
  model: { generate: async (r) => `a ${(r.uses as any).tone} caption` },
});
const text = () => (intent.realize().tree as HostNode).props.text;

console.log(text()); // → '…'
const connection = intent.connect({ commit() {} }); // the host accepts the draft
await new Promise((resolve) => setTimeout(resolve)); // the answer comes back
console.log(text()); // → 'a warm caption'
connection.disconnect();

useInput()

function useInput<T>(): T;

Defined in: packages/core/src/intent/input.ts

The root's input: what createIntent({ input }) or intent.setInput gave, the same object a function root gets as its props. undefined when the intent has none.

Type Parameters

Type ParameterDefault type
Tunknown

Returns

T

Example

import { createIntent, host, useInput } from '@reintent/core';

function Greeting() {
  const { to } = useInput<{ to: string }>();
  return host('p', { children: `Hi ${to}!` });
}

const intent = createIntent({ program: <Greeting />, input: { to: 'Ann' } });
console.log(intent.realize().tree); // → { '$$host': true, kind: 'p', props: {}, children: [ 'Hi Ann!' ] }
intent.setInput({ to: 'Bo' });
console.log(intent.realize().tree); // → { '$$host': true, kind: 'p', props: {}, children: [ 'Hi Bo!' ] }
intent.dispose();

useLoaded()

function useLoaded(of): boolean;

Defined in: packages/core/src/intent/hooks.ts

Whether the entity is loaded here: false when it is held elsewhere (a collaborator's page, intent.unload).

Parameters

ParameterType
ofstring

Returns

boolean


Runtime

ContentRejected

Defined in: packages/core/src/runtime/content.ts

A tree a host was not given, for its slots (0045 §5): errors says each, as data.

Extends

  • Error

Constructors

Constructor
new ContentRejected(errors): ContentRejected;

Defined in: packages/core/src/runtime/content.ts

Parameters
ParameterType
errorsCatalogError[]
Returns

ContentRejected

Overrides
Error.constructor

Properties

PropertyModifierType
errorsreadonlyCatalogError[]

IntentDisposed

Defined in: packages/core/src/runtime/root.ts

What a disposed intent throws when it is used.

Extends

  • Error

Constructors

Constructor
new IntentDisposed(): IntentDisposed;

Defined in: packages/core/src/runtime/root.ts

Returns

IntentDisposed

Overrides
Error.constructor

InvalidInput

Defined in: packages/core/src/runtime/root.ts

A root input that is not data (0045 §3): errors says where and what, as data.

Extends

  • TypeError

Constructors

Constructor
new InvalidInput(errors): InvalidInput;

Defined in: packages/core/src/runtime/root.ts

Parameters
ParameterType
errorsobject[]
Returns

InvalidInput

Overrides
TypeError.constructor

Properties

PropertyModifierType
errorsreadonlyobject[]

MissingRecording

Defined in: packages/core/src/runtime/recordings.ts

Extends

  • Error

Constructors

Constructor
new MissingRecording(
   effect, 
   id, 
   stamp?
): MissingRecording;

Defined in: packages/core/src/runtime/recordings.ts

Parameters
ParameterType
effect"judge" | "reprogram" | "generate"
idstring
stamp?string
Returns

MissingRecording

Overrides
Error.constructor

Properties

PropertyModifierType
effectreadonly"judge" | "reprogram" | "generate"
idreadonlystring
stamp?readonlystring

ProgramRefused

Defined in: packages/core/src/runtime/root.ts

A program System Two wrote that is refused (0055 §4), with every reason, sentences a model reads: thrown by a host that cannot load the text (loadProgram), and by a reprogramming whose last draft the intent refused. Thrown by model.reprogram, it is one draft refused, and the intent asks again while it has attempts left.

Extends

  • Error

Constructors

Constructor
new ProgramRefused(reasons): ProgramRefused;

Defined in: packages/core/src/runtime/root.ts

Parameters
ParameterType
reasonsreadonly string[]
Returns

ProgramRefused

Overrides
Error.constructor

Properties

PropertyModifierType
reasonsreadonlyreadonly string[]

ProgramRejected

Defined in: packages/core/src/runtime/root.ts

A program a proposal would put in place that does not run on the root's input (0045 §3.1): the proposal is not accepted, and the program stays as it was. errors says why, as data.

Extends

  • Error

Constructors

Constructor
new ProgramRejected(
   id, 
   cause, 
   errors?
): ProgramRejected;

Defined in: packages/core/src/runtime/root.ts

Parameters
ParameterType
idstring
causeunknown
errors?object[]
Returns

ProgramRejected

Overrides
Error.constructor

Properties

PropertyModifierType
errorsreadonlyobject[]

CatalogError

type CatalogError = object;

Defined in: packages/core/src/runtime/catalog.ts

One thing wrong, as data and as a sentence (message) a model can act on.

Properties

PropertyTypeDescription
actual?HostData-
codestring-
expected?string-
messagestring-
node?stringFor an event: the pointer, in the frame's tree, of the prop that offered it.
pathstringJSON Pointer into what was checked: the catalog (/kinds/button/about), the tree (/0/children/1/props/label), or the event a host sent (/value/size, /control/args).
stageCatalogStage-

CatalogEvent

type CatalogEvent = 
  | CatalogSend
  | {
  oneOf: CatalogSend[];
} & object;

Defined in: packages/core/src/runtime/catalog.ts

An event of a kind: one send, or an action and a control (oneOf), one of which the node holds; optional when a node may leave the prop out.

Type Declaration

NameType
optional?true

CatalogKind

type CatalogKind = object;

Defined in: packages/core/src/runtime/catalog.ts

A kind of a catalog: what it is (about, for a model and a person), its data props (an object schema), its children (none; text: strings and numbers; nodes: host nodes and text) and the props that are events.

Properties

PropertyType
aboutstring
children?"none" | "text" | "nodes"
events?object
props?CatalogSchema

CatalogSchema

type CatalogSchema = object;

Defined in: packages/core/src/runtime/catalog.ts

The JSON Schema subset a catalog's props and event values are written in (0043 §3): type, enum, const, properties, required, additionalProperties: false, items, minItems, maxItems, minimum, maximum, minLength, maxLength, anyOf, description, default. A union is anyOf: a value holds when one branch takes it, the first one that does, as Zod reads a union.

Properties

PropertyType
additionalProperties?false
anyOf?CatalogSchema[]
const?HostData
default?HostData
description?string
enum?HostData[]
items?CatalogSchema
maximum?number
maxItems?number
maxLength?number
minimum?number
minItems?number
minLength?number
properties?object
required?string[]
type?"string" | "number" | "integer" | "boolean" | "null" | "object" | "array"

CatalogSend

type CatalogSend = 
  | {
  action: {
     value?: CatalogSchema;
  };
}
  | {
  control: {
     args?: CatalogSchema;
     optional?: true;
  };
};

Defined in: packages/core/src/runtime/catalog.ts

What a node sends back on an event: a HostAction (value: the value the host gives a decide without one), or an application control (args: what the host gives it when the node does not fix them; optional when the host may give none).


CatalogStage

type CatalogStage = "define" | "export" | "catalog" | "normalize" | "validate" | "event";

Defined in: packages/core/src/runtime/catalog.ts

Where a catalog check failed.


Check

type Check = object;

Defined in: packages/core/src/runtime/rules.ts

One rule's result on a draft: on the proposal, and, an error that fails, the draft's problem.

Properties

PropertyModifierType
messagereadonlystring
okreadonlyboolean
rulereadonlystring
severityreadonly"error" | "warn"

ChoiceObservation

type ChoiceObservation = object;

Defined in: packages/core/src/runtime/observation.ts

A choice an evaluation read: which one, the value it used, where that came from, whether it settled.

Properties

PropertyModifierTypeDescription
ask?readonlytrueWaiting for a person to answer.
idreadonlyId-
keyreadonlystring-
kindsreadonlyreadonly unknown[]The possibilities.
namereadonlystring-
question?readonlystringWhat a person is asked.
sourcereadonlySourceThe layer it came from: a person's decision, System One's belief, the default…
statusreadonlyStatus-
valuereadonlyunknownThe value this evaluation used.

Commit

type Commit = object;

Defined in: packages/core/src/runtime/store.ts

One step of the history (intent.history.entries): what it says it did, and the state a person committed before and after it. Read-only: the history changes only by committing, undoing and redoing.

Example

import { choices, createIntent, host, useChoose, type Commit } from '@reintent/core';

const Hat = () =>
  host('hat', { size: useChoose(choices('usual', 'big'), { of: 'man', name: 'hat' }) });
const intent = createIntent({ program: <Hat /> });
intent.decide({ of: 'man', name: 'hat' }, 'big');
const [step]: readonly Commit[] = intent.history.entries;
console.log(step.after.choices['man#hat'].decision?.value); // → 'big'

Properties

PropertyModifierType
afterreadonlyCommitted
beforereadonlyCommitted
notereadonlystring

Committed

type Committed = object;

Defined in: packages/core/src/runtime/store.ts

What a person committed: the part of the state history restores (read-only).

Properties

PropertyModifierType
choicesreadonlyReadonly<Record<string, Pick<ChoiceRecord, "decision" | "constraints" | "preferences" | "drawn">>>
factsreadonlyreadonly string[]
namedreadonlyReadonly<Record<string, NameRecord>>
programreadonlyProgram | undefined

Content

type Content = HostNode & object;

Defined in: packages/core/src/runtime/content.ts

A logical slot's node: what slot(name) gives, in the root's input.

Type Declaration

NameType
kindtypeof CONTENT_KIND
propsobject
props.slotstring

ControlRef

type ControlRef = object;

Defined in: packages/core/src/runtime/catalog.ts

A control as a node carries it: its name, and the args when the node fixes them.

Properties

PropertyType
args?HostData
namestring

DecisionFor

type DecisionFor<I> = I extends ChoiceRef<infer T, any> ? Decided<Tagged<T>> : Decided;

Defined in: packages/core/src/runtime/store.ts

What may be decided for an identity: anything, or for a handle, one of its tags or values.

Type Parameters

Type Parameter
I

EventCheck

type EventCheck = 
  | {
  action: HostAction;
  control?: undefined;
  errors: [];
  offer: EventOffer;
}
  | {
  action?: undefined;
  control: ControlRef;
  errors: [];
  offer: EventOffer;
}
  | {
  action?: undefined;
  control?: undefined;
  errors: CatalogError[];
  offer?: undefined;
};

Defined in: packages/core/src/runtime/catalog.ts

A host's event, checked: what to carry out, and the offer it answers.


EventOffer

type EventOffer = object & 
  | {
  action: HostAction;
  args?: undefined;
  control?: undefined;
  optional?: undefined;
  value?: CatalogSchema;
}
  | {
  action?: undefined;
  args?: CatalogSchema;
  control: ControlRef;
  optional?: true;
  value?: undefined;
};

Defined in: packages/core/src/runtime/catalog.ts

An event a node of a frame offers, by the prop it is in.

Type Declaration

NameTypeDescription
eventstring-
kindstring-
pathstringJSON Pointer of the prop in the frame's tree.

FrameCheck

type FrameCheck = object;

Defined in: packages/core/src/runtime/catalog.ts

A frame as checked: the normalized tree a host draws and acknowledges, and what it offers.

Properties

PropertyTypeDescription
errorsCatalogError[]-
kindsstring[]The kinds the tree uses, once each.
offersEventOffer[]-
tree?Rendered | Rendered[] | nullThe tree with the catalog's defaults filled in; the one to send. undefined when errors.

HandleReprogram

type HandleReprogram = object;

Defined in: packages/core/src/runtime/handle.ts

What a handle's reprogram asks: 0055's request, without the contexts a remote side has not got. at names the part: a <World id> in the program's tree, or a reprogrammable component's id.

Properties

PropertyType
at?string
attempts?number
prompt?string

HandleState

type HandleState<I> = object;

Defined in: packages/core/src/runtime/handle.ts

An intent's state as a handle has seen it: data, the same object until the intent changes.

Type Parameters

Type ParameterDefault type
Iunknown

Properties

PropertyModifierTypeDescription
atreadonlynumberThe change it is at: it only grows. A receipt's at is this or earlier.
historyreadonlyobject-
history.canRedoreadonlyboolean-
history.canUndoreadonlyboolean-
history.notesreadonlyreadonly string[]Each commit's note, oldest first.
inputreadonlyI | undefinedThe root's input (0045 §3).
layersreadonlyLayersThe choices' layers: what a person decided and said, what the models answered.
pendingreadonlyreadonly RequestState[]The model requests not completed when the intent last changed.
revisionreadonlynumber-
versionreadonlystringThe program's version (intent.version): a proposal is accepted only on the one it was written on.

HandleTx

type HandleTx = Omit<Tx, "program">;

Defined in: packages/core/src/runtime/handle.ts

What a handle's transaction may write (commit, review(p).accept): a person's decisions and sentences, never a program. Every argument is data, so a remote handle sends the steps.


HostAction

type HostAction = 
  | {
  $$action: "decide";
  id: ActionId;
  origin?: DecisionOrigin;
  value?: HostData;
}
  | {
  $$action: "forget";
  id: ActionId;
}
  | {
  $$action: "constrain";
  constraint:   | {
     not: string[];
   }
     | {
     only: string[];
   };
  target: ActionTarget;
}
  | {
  $$action: "unconstrain";
  target: ActionTarget;
}
  | {
  $$action: "prefer";
  factor?: number;
  target: ActionTarget;
  toward: string;
}
  | {
  $$action: "tell" | "untell";
  fact: string;
}
  | {
  $$action: "draw";
  world: string;
};

Defined in: packages/core/src/runtime/host.ts

A person's operation, represented as data from its creation, never as a callable closure.


HostCatalog

type HostCatalog = object;

Defined in: packages/core/src/runtime/catalog.ts

A host catalog, as exported (exportCatalog in @reintent/catalog): JSON.

Properties

PropertyType
catalogstring
kindsobject
versionnumber

HostConnection

type HostConnection = object;

Defined in: packages/core/src/runtime/host.ts

One host attachment; disconnect does not destroy its shared intent.

Methods

disconnect()
disconnect(): void;

Defined in: packages/core/src/runtime/host.ts

Returns

void

update()
update(provide): void;

Defined in: packages/core/src/runtime/host.ts

Parameters
ParameterType
provideProvide
Returns

void


HostEvent

type HostEvent = 
  | {
  action: HostAction;
  control?: undefined;
  value?: HostData;
}
  | {
  action?: undefined;
  control: ControlRef;
  value?: undefined;
};

Defined in: packages/core/src/runtime/catalog.ts

What a host sends back: an action (with the value it gives), or a control.


HostMessage

type HostMessage = object;

Defined in: packages/core/src/runtime/host.ts

Versioned host transport envelope. JSON and structured clone use the same data.

Properties

PropertyType
protocol"reintent.host"
treeRendered | Rendered[] | null
version1

Intent

type Intent<I> = ReturnType<typeof createIntent>;

Defined in: packages/core/src/runtime/root.ts

An intent (createIntent): I is its root input, a root component's props.

Type Parameters

Type ParameterDefault type
Iunknown

IntentHandle

type IntentHandle<I> = object;

Defined in: packages/core/src/runtime/handle.ts

What an application's code holds to act on an intent (0056 §2): handleOf(intent) here, remoteHandle(transport) (@reintent/lib/remote) for an intent elsewhere. Writes are asynchronous on both; reading is the snapshot, and subscribe says when it may have changed.

Type Parameters

Type ParameterDefault type
Iunknown

Properties

PropertyModifierType
historyreadonlyobject
history.redopublicPromise<Receipt>
history.undopublicPromise<Receipt>

Methods

close()
close(): void;

Defined in: packages/core/src/runtime/handle.ts

This handle notifies no more, and what it is asked after this is closed. The intent stays.

Returns

void

commit()
commit(note, fn): Promise<Receipt>;

Defined in: packages/core/src/runtime/handle.ts

Several writes as one step of the history, with note for it (intent.commit): one sentence said in place of another is one step, and one undo takes it back.

Parameters
ParameterType
notestring
fn(tx) => void
Returns

Promise<Receipt>

constrain()
constrain(target, c): Promise<Receipt>;

Defined in: packages/core/src/runtime/handle.ts

Parameters
ParameterType
targetTarget
cConstraint
Returns

Promise<Receipt>

decide()
decide(
   id, 
   value, 
   origin?
): Promise<Receipt>;

Defined in: packages/core/src/runtime/handle.ts

Parameters
ParameterType
idId
valueunknown
origin?DecisionOrigin
Returns

Promise<Receipt>

draw()
draw(world): Promise<Receipt>;

Defined in: packages/core/src/runtime/handle.ts

One more draw of the sampling <World id={world} sample> (0089).

Parameters
ParameterType
worldstring
Returns

Promise<Receipt>

forget()
forget(id): Promise<Receipt>;

Defined in: packages/core/src/runtime/handle.ts

Parameters
ParameterType
idId
Returns

Promise<Receipt>

onProposal()
onProposal(fn): () => void;

Defined in: packages/core/src/runtime/handle.ts

Called with each proposal the intent makes from now on, whoever asked. Returns the unsubscribe.

Parameters
ParameterType
fn(p) => void
Returns

() => void

prefer()
prefer(
   target, 
   toward, 
   factor?
): Promise<Receipt>;

Defined in: packages/core/src/runtime/handle.ts

Weighs toward up by factor (6 when not given) in every choice target names.

Parameters
ParameterType
targetTarget
towardstring
factor?number
Returns

Promise<Receipt>

rejectAll()
rejectAll(id): Promise<Receipt>;

Defined in: packages/core/src/runtime/handle.ts

Says that none of the possibilities fits id (intent.rejectAll).

Parameters
ParameterType
idId
Returns

Promise<Receipt>

reprogram()
reprogram(req?): Promise<ProposalView>;

Defined in: packages/core/src/runtime/handle.ts

Asks System Two to reprogram (0055): resolves to the proposal, rejects with ProgramRefused when every draft was refused, as intent.reprogram does.

Parameters
ParameterType
req?HandleReprogram
Returns

Promise<ProposalView>

review()
review(p): object;

Defined in: packages/core/src/runtime/handle.ts

Accepts or rejects a proposal by its id. accept(migrate) writes what migrate writes in the same step as the program (intent.review(p).accept(migrate)).

Parameters
ParameterType
pProposalView
Returns

object

NameType
accept()(migrate?) => Promise<Receipt>
reject()() => Promise<Receipt>
setInput()
setInput(input): Promise<Receipt>;

Defined in: packages/core/src/runtime/handle.ts

Changes the root's input (0045 §3). A remote side may not allow it (not-allowed).

Parameters
ParameterType
inputI
Returns

Promise<Receipt>

snapshot()
snapshot(): HandleState<I>;

Defined in: packages/core/src/runtime/handle.ts

The state as this handle has seen it: the same object until it changes.

Returns

HandleState<I>

subscribe()
subscribe(fn): () => void;

Defined in: packages/core/src/runtime/handle.ts

Called when the snapshot may have changed. Returns the unsubscribe.

Parameters
ParameterType
fn() => void
Returns

() => void

tell()
tell(fact): Promise<Receipt>;

Defined in: packages/core/src/runtime/handle.ts

Parameters
ParameterType
factstring
Returns

Promise<Receipt>

unconstrain()
unconstrain(target): Promise<Receipt>;

Defined in: packages/core/src/runtime/handle.ts

Parameters
ParameterType
targetTarget
Returns

Promise<Receipt>

untell()
untell(fact): Promise<Receipt>;

Defined in: packages/core/src/runtime/handle.ts

Parameters
ParameterType
factstring
Returns

Promise<Receipt>


IntentHost

type IntentHost = object;

Defined in: packages/core/src/runtime/host.ts

Where an intent's trees are committed, with what each evaluation read and could not settle (0060 §6). A commit is one way (0060 §3): the requests of what was committed are sent as it returns, without waiting for the host to draw it. A commit that throws disconnects this host. Acknowledgements, frame numbers and flow control belong to a transport's own protocol.

Properties

PropertyTypeDescription
content?booleanThe host draws host content (0045 §5): a slot's node, with content of its own for the slots the root's input declares. Without it, a tree that holds a slot is not committed.

Methods

commit()
commit(tree, observed): void;

Defined in: packages/core/src/runtime/host.ts

Parameters
ParameterType
treeRendered | Rendered[] | null
observedObservation
Returns

void

dispose()?
optional dispose(): void;

Defined in: packages/core/src/runtime/host.ts

Returns

void

onError()?
optional onError(error): void;

Defined in: packages/core/src/runtime/host.ts

Called with the error when a commit throws; the connection is closed by then.

Parameters
ParameterType
errorunknown
Returns

void


IntentOptions

type IntentOptions<I> = object;

Defined in: packages/core/src/runtime/root.ts

Type Parameters

Type ParameterDefault type
Iunknown

Properties

PropertyTypeDescription
catalog?HostCatalogDeprecated Renamed elements (0057 §2.2).
elements?HostCatalogThe host elements a program System Two wrote may use (0057 §2.2), a catalog's contract (exportCatalog, 0043 §3): λ is checked against them before it is proposed and when it is accepted (0055 §5). A reprogram({ elements }) step, a reprogrammable component, or intent.reprogram({ elements }), gives others for its part.
input?NoInfer<I>The root's input (0045 §3): data, which a root component gets as its props and any component reads with useInput(). setInput changes it; it is not the program, nor in its history. TypeScript holds it to a root component's props.
layers?Partial<Layers>Layers saved from another intent (intent.layers, as JSON): it starts on them, with no history.
model?ModelThe Model: System One answers judge, System Two generate and reprogram (recorded(…) in tests and examples).
program?Child | Component<I>The program: the version of the intent it realizes now. An element, or a root component, which is called with input as its props. setProgram gives it one later.
programName?stringThe program's name: what its history and versions say it is (no handler is given it).
provide?ProvideContexts every evaluation has (a context passed to realize comes after them).
realizer?RealizerWho evaluates the program: the kernel (default), or another realizer (@reintent/react).
reprogram?objectThe defaults of a reprogramming (0055 §3, 0057): attempts, how many drafts System Two may write before it fails (default 1); imports, the intent components a draft may import; rules, as ESLint has them. A reprogram(…) step, a reprogrammable component, or intent.reprogram, says otherwise for its own: rules merge by name, the nearest last.
reprogram.attempts?number-
reprogram.imports?Imports-
reprogram.rules?Rules-
strict?booleanThrow a failed request (a missing recording) instead of marking it failed: for tests.

Judgment

type Judgment = object;

Defined in: packages/core/src/runtime/root.ts

System One's answer with how decisive it was (0116 §4): confidence from 0 (spread evenly) to 1 (all on one). A judge may answer with the weights alone.

Properties

PropertyType
confidence?number
weightsWeights

Model

type Model = object;

Defined in: packages/core/src/runtime/root.ts

The model behind an intent: System One answers judge, System Two generate and reprogram.

Properties

PropertyTypeDescription
generate?(r, call) => unknownOne value (n = 1), or an array of n values (n > 1), synchronously or as a promise.
judge?(r, call) => | Weights | Judgment | Promise<Weights | Judgment>-
reprogram?(r) => | ProposalDraft | Promise<ProposalDraft>-

ModelCall

type ModelCall = object;

Defined in: packages/core/src/runtime/root.ts

One call of a model's judge or generate. signal aborts once no shown evaluation needs the request any more (the input changed, the program was replaced, every view went away): pass it on to fetch or an SDK to stop the work. A call that rejects once aborted is as if never made; an answer that still comes is kept under the stamp it was asked with, like any other.

Properties

PropertyModifierType
signalreadonlyAbortSignal

Observation

type Observation = object;

Defined in: packages/core/src/runtime/observation.ts

What a host reads of one evaluation.

Properties

PropertyModifierType
readsreadonlyreadonly ChoiceObservation[]
unresolvedreadonlyreadonly UnresolvedObservation[]

PossibleWorld

type PossibleWorld = object;

Defined in: packages/core/src/runtime/root.ts

A possible world: how the world would be under these choices, which nobody has made.

Properties

PropertyTypeDescription
choicesRecord<string, string>The choices that make it, by key: a possibility's tag each, in the order they were read.
pnumberTheir joint probability: the product of each one's weight, given the choices before it.
partial?trueA choice it enumerates, or one read before it (what it may depend on), is missing its judge answer; its probability uses available beliefs/priors.
preview() => RealizationThe intent realized under these choices, as intent.preview would (on demand: nothing runs until asked).

Proposal

type Proposal = ProposalDraft & object;

Defined in: packages/core/src/runtime/root.ts

Type Declaration

NameTypeDescription
basestringThe program version it was written against: accepting it on another fails.
baseRevisionnumberThat version's place in the history (intent.revision then), for a person to read.
checks?readonly Check[]Each rule in effect, as the draft was checked by it when it was tried (0057 §3): an 'error' passed, a 'warn' may not have.
idstring-
input?unknownThe root's input it was written under (0045 §3.1). Accepting it runs the program on the input there is then: review(p).inputChanged says whether that is another one.
part?truescope is a reprogrammable component's id, and program its next version (0056 §7).
prompt?string-
realization?RealizationWhat it realized when the intent tried it, before it was proposed: what a person looks at.
scope?stringThe <Reconsider id> whose part program replaces; none: the whole program.
why?Unresolved-

ProposalDraft

type ProposalDraft = object;

Defined in: packages/core/src/runtime/root.ts

What a reprogram handler answers: a program, and what it says it did. text, the program's text when a model wrote one, comes back in refused and, once accepted, as the part's scope.text.

Properties

PropertyType
name?string
programRootProgram
summarystring
text?string

ProposalFailure

type ProposalFailure = object;

Defined in: packages/core/src/runtime/root.ts

A reprogramming the intent asked by itself that failed (0055 §4): what it was asked for (why, the <World>'s scope), the error, and, when System Two's drafts were refused, every reason.

Properties

PropertyType
errorError
reasons?readonly string[]
scope?string
why?Unresolved

ProposalView

type ProposalView = object;

Defined in: packages/core/src/runtime/handle.ts

A proposal as data (0056 §2): what of a Proposal crosses a wire. The program stays with the intent; review finds it again by id. tree is λ as the proposal was tried, encoded as a host's data (encodeHostTree): what a person looks at before accepting.

Properties

PropertyModifierTypeDescription
basereadonlystringThe program version it was written on.
baseRevisionreadonlynumber-
checks?readonlyreadonly Check[]Each rule in effect, as the draft was checked by it (0057 §3).
idreadonlystring-
input?readonlyunknownThe root's input it was written under.
name?readonlystring-
part?readonlytruescope is a reprogrammable component's id (0056 §6).
prompt?readonlystring-
scope?readonlystringThe boundary whose part it replaces; none: the whole program.
summaryreadonlystring-
text?readonlystring-
tree?readonlyHostData-

Question

type Question = object;

Defined in: packages/core/src/runtime/root.ts

Properties

PropertyTypeDescription
dist?Weights-
idId-
keystring-
kindsunknown[]-
namestring-
partial?trueIts judge answer, or one read before it, is missing in a context it is asked in.
wherestring[]The contexts it is asked in, as their keys joined.

Realization

type Realization = Result & object;

Defined in: packages/core/src/runtime/root.ts

Type Declaration

NameTypeDescription
escalationsUnresolved[]Deprecated Renamed unresolved (0046 §5).
readsChoiceRead[]-
requestsModelRequest[]-
unresolvedUnresolved[]The choices this evaluation could not settle, reported for someone to handle (0046 §5).
unsettled?truerealize stopped before nothing more was written: what was sent kept writing (a chain of answers each asking for the next) past its limit. Evaluated again, it goes on.

Receipt

type Receipt = 
  | {
  at: number;
  ok: true;
}
  | {
  code: "refused" | "not-allowed" | "unknown-proposal" | "closed";
  message: string;
  ok: false;
};

Defined in: packages/core/src/runtime/handle.ts

What a write gives back. at is the change the handle had seen once the step was taken: its snapshot is at least there. refused: the intent did not take the step (an invalid value, a proposal written on another version, a program that fails its trial). not-allowed: the side that holds the intent does not let a remote handle do this. unknown-proposal: the proposal is not there to accept (accepted, rejected, or the side that held it started again). closed: the handle is closed, or the intent disposed.


Recording

type Recording = object;

Defined in: packages/core/src/runtime/recordings.ts

Properties

PropertyTypeDescription
answerunknown-
effect"judge" | "generate" | "reprogram"-
goal?stringFor a rejudge: the goal it was asked under.
idstringThe choice's key (man#hat); for reprogram, the prompt or the escalation's key.
stamp?stringThe input stamp it answers; omitted: any.

ReprogramRequest

type ReprogramRequest = object;

Defined in: packages/core/src/runtime/root.ts

Properties

PropertyTypeDescription
attemptnumberWhich draft this is, from 1, of a reprogramming's attempts (0055 §4).
catalog?HostCatalogDeprecated Renamed elements (0057): the same value.
elements?HostCatalogThe host elements each draft may use, when there are some: λ is checked against them (0057 §2.2).
imports?ImportsThe intent components a draft may import (0057 §2.2), what the host gives loadProgram as modules. Each is the component wrapped once, so a trial knows it drew it (use/<Name>).
importSchemas?Readonly<Record<string, Readonly<Record<string, unknown>>>>Data props schemas of the declared imports (0059), by name; absent for untyped components.
input?unknownThe root's input it is asked under (0045 §3.1), when the intent has one.
prompt?string-
refused?objectWhy the intent refused the draft before this one, sentences for the model to read, and that draft (none when the host threw ProgramRefused before it had one).
refused.draft?ProposalDraft-
refused.problemsreadonly string[]-
revisionnumber-
rules?Readonly<Record<string, "error" | "warn">>The rules in effect and how much each counts (0057 §3), for the prompt: none 'off'.
scope?objectFor a <Reconsider id>'s reprogram: the part it may reprogram, and what that part holds now. The answer's program is then what the part holds instead; the rest stays as it is.
scope.boundarystring-
scope.part?trueThe part is a reprogrammable component (0056 §7): the draft's program is then a component of the props it is given.
scope.programChild-
scope.propsSchema?Readonly<Record<string, unknown>>The original component's data props schema (0059), kept across replacements.
scope.text?stringThe part's text, when a draft that wrote it gave one (ProposalDraft.text), for the prompt.
versionstringThe program version it is asked of (intent.version).
why?UnresolvedThe escalation that asks for it (a <Reconsider> that allows reprogram, or the intent).

RootProgram

type RootProgram = Child | Component<any>;

Defined in: packages/core/src/runtime/root.ts

A program: an element (<Card to="Ann" />), or a root component, called with the root's input as its props (0045 §3).


Target

type Target = 
  | Id
  | {
  name: string;
  of?: undefined;
};

Defined in: packages/core/src/runtime/store.ts

A choice by identity, or a class of choices by name.


Tx

type Tx = object;

Defined in: packages/core/src/runtime/store.ts

Methods

constrain()
constrain(target, c): void;

Defined in: packages/core/src/runtime/store.ts

Parameters
ParameterType
targetTarget
cConstraint
Returns

void

decide()
decide<I>(
   id, 
   value, 
   origin?
): void;

Defined in: packages/core/src/runtime/store.ts

Type Parameters
Type Parameter
I extends Id
Parameters
ParameterType
idI
valueDecisionFor<I>
origin?DecisionOrigin
Returns

void

draw()
draw(world, seed): void;

Defined in: packages/core/src/runtime/store.ts

One more draw of the sampling <World id={world} sample>, with this seed (0089): what each choice read there and decided by nobody takes is recorded (drawn). Only an Intent's commit can draw: it evaluates the program to know what is read there.

Parameters
ParameterType
worldstring
seednumber
Returns

void

drawn()
drawn(id, draw): void;

Defined in: packages/core/src/runtime/store.ts

Record what a draw took for a choice (0089 §3): the Intent's draw writes it.

Parameters
ParameterType
idId
drawDrawn
Returns

void

forget()
forget(id): void;

Defined in: packages/core/src/runtime/store.ts

Parameters
ParameterType
idId
Returns

void

prefer()
prefer(
   target, 
   toward, 
   factor?
): void;

Defined in: packages/core/src/runtime/store.ts

Weighs toward up by factor (6 when not given) in every choice target names.

Parameters
ParameterType
targetTarget
towardstring
factor?number
Returns

void

program()
program(
   element, 
   note?, 
   parts?
): void;

Defined in: packages/core/src/runtime/store.ts

A new version of the program. parts, the version of each reprogrammable component (0056 §7), replaces the program's when it is given; it is kept when it is not.

Parameters
ParameterType
elementChild
note?string
parts?Readonly<Record<string, Component<any>>>
Returns

void

tell()
tell(fact): void;

Defined in: packages/core/src/runtime/store.ts

Parameters
ParameterType
factstring
Returns

void

unconstrain()
unconstrain(target): void;

Defined in: packages/core/src/runtime/store.ts

Parameters
ParameterType
targetTarget
Returns

void

unprefer()
unprefer(target): void;

Defined in: packages/core/src/runtime/store.ts

Parameters
ParameterType
targetTarget
Returns

void

untell()
untell(fact): void;

Defined in: packages/core/src/runtime/store.ts

Parameters
ParameterType
factstring
Returns

void


UnresolvedObservation

type UnresolvedObservation = object;

Defined in: packages/core/src/runtime/observation.ts

A choice an evaluation could not settle: why, and what the World that holds it may do.

Properties

PropertyModifierTypeDescription
allowreadonlyreadonly Action[]The steps that World allows.
beyond?readonlynumberFor cause: 'judged': System One's share outside K (BEYOND).
cause?readonly"measured" | "judged"For an 'unmet' System One judged: 'judged' (0115).
goal?readonlystringThe goal of the World that holds it.
idreadonlyId-
keyreadonlystring-
reasonreadonlyReason-
tried?readonlyreadonly Action[]The steps tried inside it before it came out.

action

const action: object;

Defined in: packages/core/src/runtime/host.ts

Describe an operation for a host to return to intent.act. Families resolve to the nearest entity instance when constructed during evaluation. action.with adds decision provenance without attaching methods to the transported data.

Type Declaration

NameTypeDescription
constrain()(target, constraint) => HostAction-
decide()(id, ...value) => HostAction-
draw()(world) => HostActionDraw again in the sampling <World id={world} sample> (0089): a button that opens a door, deals a card.
forget()(id) => HostAction-
prefer()( target, toward, factor? ) => HostAction-
tell()(fact) => HostAction-
unconstrain()(target) => HostAction-
untell()(fact) => HostAction-
with()(input, origin) => HostActionCopy a decision action with additional origin metadata. Other operations have no decision origin.

Example

import { action, createIntent } from '@reintent/core';
const intent = createIntent();
const pick = action.with(action.decide({ of: 'card', name: 'tone' }, 'quiet'), {
  gesture: 'click',
  via: 'human',
});
intent.act(structuredClone(pick));
console.log(intent.layers.choices['card#tone'].decision);
// → { value: 'quiet', gesture: 'click', via: 'human' }
intent.dispose();

actionSchema()

function actionSchema(reads): Record<string, unknown>;

Defined in: packages/core/src/runtime/host.ts

The actions a model may take now, as a JSON Schema (2020-12): one case for each choice read in a realization, with the possibilities it was read with, plus telling and taking back a fact. What does not apply was not read, so it is not offered; a possibility a constraint or forbid ruled out is not either. Give it to a model as a tool's input schema (constrained decoding where the API has it); what comes back still goes through intent.act, and checkAction(x, reads) says when a value is not one of those possibilities.

Parameters

ParameterType
readsreadonly ChoiceRead[]

Returns

Record<string, unknown>

Example

import { actionSchema, choices, createIntent, host, useChoose } from '@reintent/core';

function Card() {
  const tone = useChoose(choices('warm', 'formal'), {
    of: 'card',
    name: 'tone',
    defaultValue: 'warm',
  });
  return host('card', { tone });
}

const intent = createIntent({ program: <Card /> });
const schema = actionSchema(intent.realize().reads) as {
  oneOf: { properties: Record<string, any> }[];
};
const decide = schema.oneOf[0].properties;
console.log(decide.$$action, decide.value); // → { const: 'decide' } { enum: [ 'warm', 'formal' ] }
intent.dispose();

checkAction()

function checkAction(value, reads?): string[];

Defined in: packages/core/src/runtime/host.ts

Diagnose incoming action data without executing getters or accepting callable actions. An empty list means the action can be dispatched. Whether a decided value is one of the choice's possibilities is checked only against the reads given (a realization's, intent.realize().reads): a choice read there takes one of the possibilities it was read with. A choice not read there, or no reads given, is not checked: a decision outside K waits until it is one (the cascade).

Parameters

ParameterType
valueunknown
reads?readonly ChoiceRead[]

Returns

string[]

Example

import { action, checkAction } from '@reintent/core';
console.log(checkAction(action.tell('Use a quiet tone'))); // → []

checkCatalog()

function checkCatalog(catalog): CatalogError[];

Defined in: packages/core/src/runtime/catalog.ts

Everything wrong with a catalog contract: its shape, the kind names, the schemas (only the subset), the defaults (each valid against its schema). Empty when it holds. A native host reading the JSON checks it the same way.

Parameters

ParameterType
catalogunknown

Returns

CatalogError[]

Example

import { checkCatalog } from '@reintent/core';

const errors = checkCatalog({
  catalog: 'card',
  version: 1,
  kinds: { Card: { about: '' } },
});
console.log(errors.map((e) => e.code)); // → [ 'kind-name', 'about' ]
console.log(errors[1].message); // → '/kinds/Card/about: a sentence for a model and a person, given ""'

checkEvent()

function checkEvent(
   frame, 
   event, 
   options?
): EventCheck;

Defined in: packages/core/src/runtime/catalog.ts

Check what a host sends back against the frame it was drawn from (0043 §6, 0036 §2): an action one of the frame's nodes offered (compared as data; the origin a host adds is kept, not compared), with a value its event allows; or a control a node offered, with args its event allows. What the host gives is normalized, then validated, so the action carries its defaults. Returns the action to carry out, its value bound, or the control; or the errors, each with the event's own path (/value, /control/args) and the offering prop's pointer as node.

It knows no frame identity: which frame an event answers, and that only the latest one may be answered (0043 §6 step 4, 0036), is the session's to decide when it passes frame.

With reads, the reads of the realization the frame was drawn from (intent.realize().reads), a decided value is also checked against the possibilities its choice was read with (checkAction(x, reads)): the schema says what a host may send, K what the intent can take.

Parameters

ParameterType
frameFrameCheck
eventHostEvent
options{ reads?: readonly ChoiceRead[]; }
options.reads?readonly ChoiceRead[]

Returns

EventCheck

Example

import {
  action,
  checkEvent,
  checkFrame,
  createIntent,
  host,
  type HostCatalog,
} from '@reintent/core';

const catalog: HostCatalog = {
  catalog: 'card',
  version: 1,
  kinds: {
    picker: {
      about: 'buttons to pick a tone',
      events: { pick: { action: { value: { enum: ['warm', 'formal'] } } } },
    },
  },
};
const tone = { of: 'card', name: 'tone' };
const intent = createIntent({ program: host('picker', { pick: action.decide(tone) }) });
const frame = checkFrame(catalog, intent.realize().tree);

console.log(checkEvent(frame, { action: action.decide(tone), value: 'formal' }).action);
// → { '$$action': 'decide', id: { of: 'card', name: 'tone' }, value: 'formal' }
console.log(
  checkEvent(frame, { action: action.decide(tone), value: 'loud' }).errors[0].message,
);
// → '/value: one of "warm", "formal", given "loud"'
console.log(checkEvent(frame, { action: action.forget(tone) }).errors[0].code); // → 'not-offered'

// With the reads: the picker allows 'warm' and 'formal', and the choice is read with both.
const reads = intent.realize().reads;
console.log(
  checkEvent(frame, { action: action.decide(tone), value: 'formal' }, { reads }).errors,
);
// → []
intent.dispose();

checkFrame()

function checkFrame(
   catalog, 
   tree, 
   options?
): FrameCheck;

Defined in: packages/core/src/runtime/catalog.ts

The frame step (0043 §6) for a tree a host is to draw: fill the catalog's defaults (normalize), check every node (its kind in the catalog, in the host's kinds and in the program's requires when given; props, children and events by the catalog), and collect the events the frame offers. Send tree, the normalized one, and keep offers for checkEvent.

Parameters

ParameterTypeDescription
catalogHostCatalog-
treeRendered | Rendered[] | null-
options{ content?: { slots: readonly string[]; }; kinds?: Iterable<string, any, any>; requires?: Iterable<string, any, any>; }-
options.content?{ slots: readonly string[]; }Host content (0045 §5): given when the host supports it, with the slots the root's input declares (slotsOf(intent.input)). Without it, a slot's node is refused.
options.content.slotsreadonly string[]-
options.kinds?Iterable<string, any, any>-
options.requires?Iterable<string, any, any>-

Returns

FrameCheck

Example

import { action, checkFrame, createIntent, host, type HostCatalog } from '@reintent/core';

const catalog: HostCatalog = {
  catalog: 'card',
  version: 1,
  kinds: {
    button: {
      about: 'a button a person presses',
      props: {
        type: 'object',
        properties: {
          label: { type: 'string' },
          disabled: { type: 'boolean', default: false },
        },
        required: ['label'],
        additionalProperties: false,
      },
      events: { press: { action: {} } },
    },
  },
};

const intent = createIntent({
  program: host('button', {
    label: 'Formal',
    press: action.decide({ of: 'card', name: 'tone' }, 'formal'),
  }),
});
const frame = checkFrame(catalog, intent.realize().tree, { kinds: ['button'] });
console.log(
  frame.errors,
  (frame.tree as unknown as { props: { disabled: boolean } }).props.disabled,
); // → [] false
console.log(frame.offers.map((o) => o.path)); // → [ '/props/press' ]

const wrong = createIntent({
  program: host('button', { label: 3, press: action.tell('go') }),
});
console.log(checkFrame(catalog, wrong.realize().tree).errors.map((e) => e.message));
// → [ 'button.label: a string, given 3' ]
intent.dispose();
wrong.dispose();

decodeHostAction()

function decodeHostAction(value): HostAction;

Defined in: packages/core/src/runtime/host.ts

Validate an incoming action before dispatch; also used for actions embedded in host props.

Parameters

ParameterType
valueunknown

Returns

HostAction


decodeHostTree()

function decodeHostTree(message): Rendered | Rendered[] | null;

Defined in: packages/core/src/runtime/host.ts

Validate a received protocol version and tree, returning a detached copy.

Parameters

ParameterType
messageunknown

Returns

Rendered | Rendered[] | null


encodeHostTree()

function encodeHostTree(tree): HostMessage;

Defined in: packages/core/src/runtime/host.ts

Validate and copy a tree before transmitting it; rejects closures, accessors and custom objects.

Parameters

ParameterType
treeunknown

Returns

HostMessage

Example

import { createIntent, decodeHostTree, encodeHostTree, host } from '@reintent/core';
const intent = createIntent({ program: host('text', { children: 'Hello' }) });
const message = encodeHostTree(intent.realize().tree);
const tree = decodeHostTree(JSON.parse(JSON.stringify(message)));
console.log(tree); // → { '$$host': true, kind: 'text', props: {}, children: [ 'Hello' ] }
intent.dispose();

handleOf()

function handleOf<I>(intent): IntentHandle<I>;

Defined in: packages/core/src/runtime/handle.ts

The handle of an intent here (0056 §3). Each call gives a handle of its own: closing it closes only it. It calls the intent's own methods, so it writes what they write and refuses what they refuse; a step is taken before the promise is made, so the snapshot has it at once.

Type Parameters

Type Parameter
I

Parameters

ParameterType
intentIntent<I>

Returns

IntentHandle<I>

Example

import { choices, createIntent, handleOf, host, useChoose } from '@reintent/core';

const Card = () =>
  host('p', {
    children: useChoose(choices('warm', 'formal'), { of: 'card', name: 'tone' }),
  });
const handle = handleOf(createIntent({ program: <Card /> }));

const receipt = await handle.decide({ of: 'card', name: 'tone' }, 'formal');
console.log(receipt.ok); // → true
console.log(handle.snapshot().history.notes); // → [ 'card#tone = "formal"' ]
console.log((await handle.setInput(() => {})).ok); // → false

observationOf()

function observationOf(r): Observation;

Defined in: packages/core/src/runtime/observation.ts

The observation of an evaluation: its reads (a preview's supposed ones left out) and what it could not settle, each with the fields a host reads.

Parameters

ParameterType
r{ reads: readonly ChoiceRead[]; unresolved: readonly Unresolved[]; }
r.readsreadonly ChoiceRead[]
r.unresolvedreadonly Unresolved[]

Returns

Observation


recorded()

function recorded(recordings, opts?): object;

Defined in: packages/core/src/runtime/recordings.ts

Handlers that answer from recordings instead of a model: by effect and choice key, the entry with the request's stamp first, then one with no stamp. A request with no recording fails (and throws, on a strict intent).

Parameters

ParameterType
recordingsreadonly Recording[]
opts{ programs?: Record<string, RootProgram>; }
opts.programs?Record<string, RootProgram>

Returns

object

NameType
generate()(r) => unknown
judge()(r) => Weights
reprogram()(r) => ProposalDraft

Example

import { choices, createIntent, host, judge, recorded, useChoose } from '@reintent/core';

function Reply(p: { id: string }) {
  const tone = useChoose(
    judge('Which tone suits this reply?', choices('formal', 'warm')),
    {
      of: p.id,
      name: 'tone',
      defaultValue: 'warm',
    },
  );
  return host('reply', { tone });
}

// The model's answers, recorded: tests and demos run the same, without a model.
const intent = createIntent({
  program: <Reply id="r1" />,
  model: recorded([
    { effect: 'judge', id: 'r1#tone', answer: { formal: 0.9, warm: 0.1 } },
  ]),
});
const connection = intent.connect({ commit() {} }); // accept λ before requesting answers
const [tone] = intent.realize().reads;
console.log(tone.value, intent.explain(tone.id).dist); // → 'formal' { formal: 0.9, warm: 0.1 }
connection.disconnect();

slot()

function slot(name): Content;

Defined in: packages/core/src/runtime/content.ts

Declare a logical slot in the root's input (0045 §5): data, which the program places like any child, and a host fills with content of its own.

Parameters

ParameterType
namestring

Returns

Content

Example

import {
  createIntent,
  host,
  slot,
  slotsOf,
  type Content,
  type HostNode,
} from '@reintent/core';

function Card(p: { to: string; children?: Content }) {
  return host('card', { to: p.to, children: p.children });
}

const input = { to: 'Ann', children: slot('children') };
const intent = createIntent({ program: Card, input });
console.log(slotsOf(intent.input)); // → [ 'children' ]
const card = intent.realize().tree as HostNode;
console.log(card.children[0]);
// → { '$$host': true, kind: 'reintent:content', props: { slot: 'children' }, children: [] }
intent.dispose();

slotsOf()

function slotsOf(input): string[];

Defined in: packages/core/src/runtime/content.ts

The slots a root input declares, once each, in the order they are found.

Parameters

ParameterType
inputunknown

Returns

string[]

Last updated on

Edit on GitHub