@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 handlersThis 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 Parameter | Default type |
|---|---|
P | any |
Parameters
| Parameter | Type |
|---|---|
props | P |
Returns
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
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
| Property | Modifier | Type |
|---|---|---|
$$host | readonly | true |
children | readonly | Rendered[] |
kind | readonly | string |
props | readonly | Record<string, HostData> |
IntentContext
type IntentContext<C> = object;Defined in: packages/core/src/kernel/context.ts
Type Parameters
| Type Parameter |
|---|
C |
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
axes | readonly | Record<string, (value) => number> | Numeric readings of the value, by name: what a piecewise decision is piecewise on. |
key | readonly | (value) => string | undefined | Names a value in traces and caches; undefined for a context that names nothing (a callback). |
name | readonly | string | - |
names | readonly | "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. |
Provider | readonly | Component<{ children?: Child; value: C; }> | - |
IntentElement
type IntentElement = object;Defined in: packages/core/src/kernel/jsx.ts
Properties
| Property | Modifier | Type |
|---|---|---|
$$element | readonly | true |
key | readonly | string | undefined |
props | readonly | Record<string, any> |
type | readonly | Component | 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
Returns
object
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
| Parameter | Type |
|---|---|
children | Child |
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
| Parameter | Type |
|---|---|
name | string |
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
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
Returns
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
| Parameter | Type |
|---|---|
kind | K |
props? | K extends never ? HostElements[K] & object : Record<string, any> |
Returns
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
| Parameter | Type |
|---|---|
x | unknown |
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
| Parameter | Type |
|---|---|
key | string |
fn | (props) => T |
props | P |
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); // → 2useContext()
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
| Parameter | Type |
|---|---|
context | IntentContext<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
| Parameter | Type |
|---|---|
context | IntentContext<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
| Property | Modifier | Type | Description |
|---|---|---|---|
about? | readonly | Json | For libraries and screens (labels, words): passed to the read as about, never read here. |
applies? | readonly | Condition | When it applies; otherwise it is not read at all. |
default? | readonly | string | The tag while unsure. None: the prior's likeliest, else the first. |
forbid? | readonly | readonly object[] | Possibilities out of K while when holds. |
given? | readonly | readonly string[] | The entity's choices to know first: System One reads them; useEntity reads them first. |
judge? | readonly | string | The question System One is asked. None: not judged. |
kinds | readonly | | readonly string[] | { [tag: string]: object; } | K: tags, or tag → data (the value is then { kind: tag, …data }). |
or? | readonly | object | An open tail: one possibility more, whose value System Two writes. |
or.instruction | readonly | string | - |
or.kind? | readonly | string | - |
or.type? | readonly | TailType | - |
prior? | readonly | object | Code'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
| Name | Type | Description |
|---|---|---|
$choice? | object | Types only: the value and the declaration. |
$choice.decl | D | - |
$choice.value | T | - |
Type Parameters
| Type Parameter | Default type |
|---|---|
T | unknown |
D extends ChoiceDecl | ChoiceDecl |
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
| Name | Type | Description |
|---|---|---|
$choice? | object | Types only: the value and the declaration. |
$choice.decl | D | - |
$choice.value | T | - |
key | string | keyOf(id): 'man#hat'. |
Type Parameters
| Type Parameter | Default type |
|---|---|
T | unknown |
D extends ChoiceDecl | ChoiceDecl |
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 Parameter | Default type |
|---|---|
T | unknown |
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); // → undefinedProperties
| Property | Modifier | Type | Description |
|---|---|---|---|
gesture? | readonly | string | The host gesture that caused the decision, such as click or drag. |
said? | readonly | string | The original sentence, kept verbatim. |
via? | readonly | Actor | The 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]: FieldDeclFixedDecl
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
| Property | Modifier | Type |
|---|---|---|
fixed | readonly | Json |
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
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
| Property | Modifier | Type | Description |
|---|---|---|---|
choices | readonly | Readonly<Record<string, ChoiceRecord>> | - |
facts | readonly | readonly string[] | What was said of the whole (0008 §9): every input stamp System One answers under carries it. |
generated | readonly | Readonly<Record<string, readonly GeneratedRecord[]>> | What System Two generated, by identity and stamp; newest first. |
named | readonly | Readonly<Record<string, NameRecord>> | - |
program? | readonly | string | The program's name (an accepted proposal's): what its history says it is; no handler is given it. |
unloaded | readonly | readonly 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
| Property | Modifier | Type | Description |
|---|---|---|---|
by | readonly | Readonly<Record<string, Measurement>> | - |
epoch? | readonly | number | The 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). |
stamp | readonly | string | - |
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 ascore, a weight relative to the others measured with it (the best 1; 0, like not fitting, rules it out).factsare 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
| Property | Modifier | Type |
|---|---|---|
facts? | readonly | Readonly<Record<string, number>> |
feasible | readonly | boolean |
prior? | readonly | number |
score? | readonly | number |
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
| Property | Type |
|---|---|
$axis | string |
segments | Segment<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
Segment
type Segment<T> = object;Defined in: packages/core/src/choices/layers.ts
Type Parameters
| Type Parameter |
|---|
T |
Properties
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
| Parameter | Type |
|---|---|
source | Source |
Returns
"code" | "model" | "human" | undefined
Example
import { actorOf } from '@reintent/core';
console.log(actorOf('decision'), actorOf('prior'), actorOf('preview')); // → 'human' 'code' undefinedisPiecewise()
function isPiecewise(v): v is Piecewise<unknown>;Defined in: packages/core/src/choices/layers.ts
Parameters
| Parameter | Type |
|---|---|
v | unknown |
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
| Parameter | Type |
|---|---|
id | Id |
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
| Parameter | Type |
|---|---|
by | Readonly<Record<string, Measurement>> |
Returns
object
| Name | Type |
|---|---|
not | string[] |
priors | Preference[] |
weights | Preference[] |
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
| Parameter | Type |
|---|---|
x | T |
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
| Parameter | Type |
|---|---|
v | unknown |
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
| Name | Type | Description |
|---|---|---|
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
| Property | Modifier | Type |
|---|---|---|
catalog | readonly | string |
kinds | readonly | Readonly<Record<string, unknown>> |
version | readonly | number |
ChoiceRead
type ChoiceRead = object;Defined in: packages/core/src/intent/trace.ts
Properties
| Property | Type | Description |
|---|---|---|
about? | unknown | What the component says about the choice, for libraries (labels, words); never read here. |
ask? | true | Unresolved, and a person is to be asked. |
beyond? | number | System One judged that none of K is what was asked for: its share outside K (BEYOND). |
ctx | Record<string, string> | The contexts it was read in, by name: { Screen: 'phone-p' }. |
describe? | Readonly<Record<string, string>> | - |
entity? | string | The entity it was read through, by its handle (card.tone): that entity's name (0015). |
generation? | ModelRequest | The request that supplies this open choice; also used by regeneration. |
hypothetical? | true | Read inside a preview (<Preview>, intent.preview): nobody is asked about it, and it does not escalate. |
id | Id | - |
key | string | keyOf(id): for maps and comparisons. |
kinds | readonly unknown[] | The possibilities, as the program lists them. |
measured? | true | What the host measured where it was read ruled a possibility out or weighed one (0065). |
name | string | The choice's name (what a constraint on a class of choices is about). |
named? | true | Settled by a constraint on its name, not on itself. |
open | boolean | Whether there is anything to choose here (not a determined state). |
origin? | DecisionOrigin | The stored decision's sentence and interpreter, even while that decision is waiting. |
otherwise | Otherwise | How it is handled while unresolved (inside a preview, never 'ask' or 'escalate'). |
question? | string | For a judged choice: the question, and what System One reads. |
sample? | object | Read 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.from | Weights | - |
sample.replace | boolean | - |
sample.world | string | - |
shape? | Shape | For a judged choice: the possibilities' shape and what each means, as System One is told (0116). |
source | Source | - |
stale? | true | - |
status | Status | - |
type | "choice" | - |
unfit? | true | What the host measured here rules out everything a person left: it was set aside (0065 §7). |
uses? | Record<string, unknown> | - |
value | unknown | What 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
| Property | Type | Description |
|---|---|---|
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? | number | How decisive System One's answer was, when its answer says (0116 §4). |
id | Id | Which 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? | true | What the host measured where it was read weighed it (0065). |
reason? | Reason | While unresolved: why it cannot settle (0046 §5). |
source | Source | - |
stale? | true | - |
status | Status | - |
unfit? | true | What the host measured here rules out everything a person left (0065 §7). |
value | T | - |
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
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
| Name | Type | Description |
|---|---|---|
defaultValue? | T | T extends object ? K : never | Overrides 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 Parameter | Default type |
|---|---|
T | unknown |
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 Parameter | Default type |
|---|---|
T | unknown |
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
| Property | Modifier | Type |
|---|---|---|
$generate | readonly | true |
check? | readonly | (value) => string[] |
instruction | readonly | string |
n | readonly | number |
uses? | readonly | Record<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
| Property | Type | Description |
|---|---|---|
describe? | Readonly<Record<string, string>> | For judge: what each possibility means, by tag (0116 §3). |
effect | Effect | - |
facts? | readonly string[] | - |
id | Id | - |
input? | unknown | The root's input it is asked under (0045 §3), when the intent has one. |
key | string | - |
kinds? | string[] | For judge: the possibilities' tags. |
n? | number | For generate: candidate count (default 1). One value for 1, an array for more. |
prompt | string | The question (judge) or the instruction (generate). |
shape? | Shape | For judge: the possibilities' shape (0116 §2); without it, they are alternatives. |
stamp | string | The 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
| Name | Type |
|---|---|
$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
| Name | Type |
|---|---|
contract? | ComponentContract |
id | string |
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
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
attempts? | readonly | number | - |
catalog? | readonly | CatalogContract | Deprecated Renamed elements (0057 §2.2). |
elements? | readonly | CatalogContract | - |
imports? | readonly | M | - |
rules? | readonly | Rules<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
| Name | Type |
|---|---|
keep-decisions? | Severity |
Type Parameters
| Type Parameter | Default type |
|---|---|
Names extends string | string |
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
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
| Property | Type | Description |
|---|---|---|
allow | readonly Action[] | - |
beyond? | number | For cause: 'judged': System One's share outside K (BEYOND, 0115). |
boundary? | string | That 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? | string | The <World> (or <Reconsider>) that caught it: its goal and what it allows; none at the root. |
id | Id | - |
key | string | - |
reason | Reason | - |
reprogram? | ReprogramOptions | Its 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? | unknown | For '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
| Property | Modifier | Type | Description |
|---|---|---|---|
beyond? | readonly | number | For 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? | readonly | Weights | - |
id | readonly | Id | - |
key | readonly | string | - |
reason | readonly | Reason | - |
wanted? | readonly | unknown | - |
WorldProps
type WorldProps<T> = object;Defined in: packages/core/src/intent/handlers.ts
Type Parameters
| Type Parameter | Default type |
|---|---|
T | unknown |
Properties
| Property | Type | Description |
|---|---|---|
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? | string | The name of the part of the program this World holds; needed to reprogram it. |
max? | number | At most this many paths for each (default 16); a choice that would go past it collapses. |
minBeyond? | number | From 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? | number | How sure is sure enough: the likeliest is taken when it leads the next by this much. |
onUnresolved? | OnUnresolved | What 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
| Parameter | Type |
|---|---|
p | BranchProps<T> |
Returns
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
| Parameter | Type |
|---|---|
name | N |
fields | F |
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
| Parameter | Type |
|---|---|
question | string |
c | Choices<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
| Parameter | Type |
|---|---|
p | { at: Record<string, Decided>; children?: Child; } |
p.at | Record<string, Decided> |
p.children? | Child |
Returns
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 0Reconsider()
function Reconsider(p): IntentElement;Defined in: packages/core/src/intent/handlers.ts
Parameters
| Parameter | Type |
|---|---|
p | { allow?: readonly Action[]; children?: Child; goal?: string; id?: string; } |
p.allow? | readonly Action[] |
p.children? | Child |
p.goal? | string |
p.id? | string |
Returns
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
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
| Parameter | Type |
|---|---|
o | { goal?: string; } |
o.goal? | string |
Returns
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 Parameter | Default type |
|---|---|
M extends Readonly<Record<string, Component<any>>> | Readonly<Record<string, Component<any>>> |
Parameters
| Parameter | Type |
|---|---|
o | object & ReprogramOptions<M> |
Returns
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 Parameter | Default type |
|---|---|
P extends object | - |
M extends Readonly<Record<string, Component<any>>> | Readonly<Record<string, Component<any>>> |
Parameters
| Parameter | Type | Description |
|---|---|---|
id | string | - |
initial | Component<P> & object | - |
opts | { attempts?: number; elements?: CatalogContract; imports?: M; onUnresolved?: OnUnresolved; rules?: Rules<keyof M & string>; } | - |
opts.attempts? | number | - |
opts.elements? | CatalogContract | The host elements a draft may use: the hard boundary (0057 §2.2). |
opts.imports? | M | The intent components a draft may import (0057 §2.2). |
opts.onUnresolved? | OnUnresolved | What 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
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
| Parameter | Type |
|---|---|
p | { children?: Child; minMargin?: number; otherwise?: Otherwise; } |
p.children? | Child |
p.minMargin? | number |
p.otherwise? | Otherwise |
Returns
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
| Parameter | Type |
|---|---|
e | Entity<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
| Parameter | Type |
|---|---|
e | Entity<string, F> |
of | string |
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
| Parameter | Type |
|---|---|
opts | { check?: (value) => string[]; instruction: string; name: string; of: string; uses?: Record<string, unknown>; } |
opts.check? | (value) => string[] |
opts.instruction | string |
opts.name | string |
opts.of | string |
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 Parameter | Default type |
|---|---|
T | unknown |
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
| Parameter | Type |
|---|---|
of | string |
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
| Parameter | Type |
|---|---|
errors | CatalogError[] |
Returns
Overrides
Error.constructorProperties
| Property | Modifier | Type |
|---|---|---|
errors | readonly | CatalogError[] |
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
Overrides
Error.constructorInvalidInput
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
| Parameter | Type |
|---|---|
errors | object[] |
Returns
Overrides
TypeError.constructorProperties
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
| Parameter | Type |
|---|---|
effect | "judge" | "reprogram" | "generate" |
id | string |
stamp? | string |
Returns
Overrides
Error.constructorProperties
| Property | Modifier | Type |
|---|---|---|
effect | readonly | "judge" | "reprogram" | "generate" |
id | readonly | string |
stamp? | readonly | string |
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
| Parameter | Type |
|---|---|
reasons | readonly string[] |
Returns
Overrides
Error.constructorProperties
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
| Parameter | Type |
|---|---|
id | string |
cause | unknown |
errors? | object[] |
Returns
Overrides
Error.constructorProperties
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
| Property | Type | Description |
|---|---|---|
actual? | HostData | - |
code | string | - |
expected? | string | - |
message | string | - |
node? | string | For an event: the pointer, in the frame's tree, of the prop that offered it. |
path | string | JSON 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). |
stage | CatalogStage | - |
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
| Name | Type |
|---|---|
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
| Property | Type |
|---|---|
about | string |
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
| Property | Type |
|---|---|
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
| Property | Modifier | Type |
|---|---|---|
message | readonly | string |
ok | readonly | boolean |
rule | readonly | string |
severity | readonly | "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
| Property | Modifier | Type | Description |
|---|---|---|---|
ask? | readonly | true | Waiting for a person to answer. |
id | readonly | Id | - |
key | readonly | string | - |
kinds | readonly | readonly unknown[] | The possibilities. |
name | readonly | string | - |
question? | readonly | string | What a person is asked. |
source | readonly | Source | The layer it came from: a person's decision, System One's belief, the default… |
status | readonly | Status | - |
value | readonly | unknown | The 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
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
| Property | Modifier | Type |
|---|---|---|
choices | readonly | Readonly<Record<string, Pick<ChoiceRecord, "decision" | "constraints" | "preferences" | "drawn">>> |
facts | readonly | readonly string[] |
named | readonly | Readonly<Record<string, NameRecord>> |
program | readonly | Program | 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
| Name | Type |
|---|---|
kind | typeof CONTENT_KIND |
props | object |
props.slot | string |
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
| Property | Type |
|---|---|
args? | HostData |
name | string |
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
| Name | Type | Description |
|---|---|---|
event | string | - |
kind | string | - |
path | string | JSON 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
| Property | Type | Description |
|---|---|---|
errors | CatalogError[] | - |
kinds | string[] | The kinds the tree uses, once each. |
offers | EventOffer[] | - |
tree? | Rendered | Rendered[] | null | The 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
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 Parameter | Default type |
|---|---|
I | unknown |
Properties
| Property | Modifier | Type | Description |
|---|---|---|---|
at | readonly | number | The change it is at: it only grows. A receipt's at is this or earlier. |
history | readonly | object | - |
history.canRedo | readonly | boolean | - |
history.canUndo | readonly | boolean | - |
history.notes | readonly | readonly string[] | Each commit's note, oldest first. |
input | readonly | I | undefined | The root's input (0045 §3). |
layers | readonly | Layers | The choices' layers: what a person decided and said, what the models answered. |
pending | readonly | readonly RequestState[] | The model requests not completed when the intent last changed. |
revision | readonly | number | - |
version | readonly | string | The 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
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
| Parameter | Type |
|---|---|
provide | Provide |
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
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 Parameter | Default type |
|---|---|
I | unknown |
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 Parameter | Default type |
|---|---|
I | unknown |
Properties
| Property | Modifier | Type |
|---|---|---|
history | readonly | object |
history.redo | public | Promise<Receipt> |
history.undo | public | Promise<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
| Parameter | Type |
|---|---|
note | string |
fn | (tx) => void |
Returns
Promise<Receipt>
constrain()
constrain(target, c): Promise<Receipt>;Defined in: packages/core/src/runtime/handle.ts
Parameters
| Parameter | Type |
|---|---|
target | Target |
c | Constraint |
Returns
Promise<Receipt>
decide()
decide(
id,
value,
origin?
): Promise<Receipt>;Defined in: packages/core/src/runtime/handle.ts
Parameters
| Parameter | Type |
|---|---|
id | Id |
value | unknown |
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
| Parameter | Type |
|---|---|
world | string |
Returns
Promise<Receipt>
forget()
forget(id): Promise<Receipt>;Defined in: packages/core/src/runtime/handle.ts
Parameters
| Parameter | Type |
|---|---|
id | Id |
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
| Parameter | Type |
|---|---|
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
| Parameter | Type |
|---|---|
target | Target |
toward | string |
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
| Parameter | Type |
|---|---|
id | Id |
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
| Parameter | Type |
|---|---|
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
| Parameter | Type |
|---|---|
p | ProposalView |
Returns
object
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
| Parameter | Type |
|---|---|
input | I |
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
| Parameter | Type |
|---|---|
fn | () => void |
Returns
() => void
tell()
tell(fact): Promise<Receipt>;Defined in: packages/core/src/runtime/handle.ts
Parameters
| Parameter | Type |
|---|---|
fact | string |
Returns
Promise<Receipt>
unconstrain()
unconstrain(target): Promise<Receipt>;Defined in: packages/core/src/runtime/handle.ts
Parameters
| Parameter | Type |
|---|---|
target | Target |
Returns
Promise<Receipt>
untell()
untell(fact): Promise<Receipt>;Defined in: packages/core/src/runtime/handle.ts
Parameters
| Parameter | Type |
|---|---|
fact | string |
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
Methods
commit()
commit(tree, observed): void;Defined in: packages/core/src/runtime/host.ts
Parameters
| Parameter | Type |
|---|---|
tree | Rendered | Rendered[] | null |
observed | Observation |
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
| Parameter | Type |
|---|---|
error | unknown |
Returns
void
IntentOptions
type IntentOptions<I> = object;Defined in: packages/core/src/runtime/root.ts
Type Parameters
| Type Parameter | Default type |
|---|---|
I | unknown |
Properties
| Property | Type | Description |
|---|---|---|
catalog? | HostCatalog | Deprecated Renamed elements (0057 §2.2). |
elements? | HostCatalog | The 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? | Model | The 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? | string | The program's name: what its history and versions say it is (no handler is given it). |
provide? | Provide | Contexts every evaluation has (a context passed to realize comes after them). |
realizer? | Realizer | Who evaluates the program: the kernel (default), or another realizer (@reintent/react). |
reprogram? | object | The 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? | boolean | Throw 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
| Property | Type |
|---|---|
confidence? | number |
weights | Weights |
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
| Property | Type | Description |
|---|---|---|
generate? | (r, call) => unknown | One 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
Observation
type Observation = object;Defined in: packages/core/src/runtime/observation.ts
What a host reads of one evaluation.
Properties
| Property | Modifier | Type |
|---|---|---|
reads | readonly | readonly ChoiceObservation[] |
unresolved | readonly | readonly 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
| Property | Type | Description |
|---|---|---|
choices | Record<string, string> | The choices that make it, by key: a possibility's tag each, in the order they were read. |
p | number | Their joint probability: the product of each one's weight, given the choices before it. |
partial? | true | A 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 | () => Realization | The 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
| Name | Type | Description |
|---|---|---|
base | string | The program version it was written against: accepting it on another fails. |
baseRevision | number | That 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. |
id | string | - |
input? | unknown | The 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? | true | scope is a reprogrammable component's id, and program its next version (0056 §7). |
prompt? | string | - |
realization? | Realization | What it realized when the intent tried it, before it was proposed: what a person looks at. |
scope? | string | The <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
| Property | Type |
|---|---|
name? | string |
program | RootProgram |
summary | string |
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
| Property | Type |
|---|---|
error | Error |
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
| Property | Modifier | Type | Description |
|---|---|---|---|
base | readonly | string | The program version it was written on. |
baseRevision | readonly | number | - |
checks? | readonly | readonly Check[] | Each rule in effect, as the draft was checked by it (0057 §3). |
id | readonly | string | - |
input? | readonly | unknown | The root's input it was written under. |
name? | readonly | string | - |
part? | readonly | true | scope is a reprogrammable component's id (0056 §6). |
prompt? | readonly | string | - |
scope? | readonly | string | The boundary whose part it replaces; none: the whole program. |
summary | readonly | string | - |
text? | readonly | string | - |
tree? | readonly | HostData | - |
Question
type Question = object;Defined in: packages/core/src/runtime/root.ts
Properties
| Property | Type | Description |
|---|---|---|
dist? | Weights | - |
id | Id | - |
key | string | - |
kinds | unknown[] | - |
name | string | - |
partial? | true | Its judge answer, or one read before it, is missing in a context it is asked in. |
where | string[] | 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
| Name | Type | Description |
|---|---|---|
escalations | Unresolved[] | Deprecated Renamed unresolved (0046 §5). |
reads | ChoiceRead[] | - |
requests | ModelRequest[] | - |
unresolved | Unresolved[] | The choices this evaluation could not settle, reported for someone to handle (0046 §5). |
unsettled? | true | realize 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
ReprogramRequest
type ReprogramRequest = object;Defined in: packages/core/src/runtime/root.ts
Properties
| Property | Type | Description |
|---|---|---|
attempt | number | Which draft this is, from 1, of a reprogramming's attempts (0055 §4). |
catalog? | HostCatalog | Deprecated Renamed elements (0057): the same value. |
elements? | HostCatalog | The host elements each draft may use, when there are some: λ is checked against them (0057 §2.2). |
imports? | Imports | The 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? | unknown | The root's input it is asked under (0045 §3.1), when the intent has one. |
prompt? | string | - |
refused? | object | Why 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.problems | readonly string[] | - |
revision | number | - |
rules? | Readonly<Record<string, "error" | "warn">> | The rules in effect and how much each counts (0057 §3), for the prompt: none 'off'. |
scope? | object | For 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.boundary | string | - |
scope.part? | true | The part is a reprogrammable component (0056 §7): the draft's program is then a component of the props it is given. |
scope.program | Child | - |
scope.propsSchema? | Readonly<Record<string, unknown>> | The original component's data props schema (0059), kept across replacements. |
scope.text? | string | The part's text, when a draft that wrote it gave one (ProposalDraft.text), for the prompt. |
version | string | The program version it is asked of (intent.version). |
why? | Unresolved | The 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
| Parameter | Type |
|---|---|
target | Target |
c | Constraint |
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
| Parameter | Type |
|---|---|
id | I |
value | DecisionFor<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
| Parameter | Type |
|---|---|
world | string |
seed | number |
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
Returns
void
forget()
forget(id): void;Defined in: packages/core/src/runtime/store.ts
Parameters
| Parameter | Type |
|---|---|
id | Id |
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
| Parameter | Type |
|---|---|
target | Target |
toward | string |
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
Returns
void
tell()
tell(fact): void;Defined in: packages/core/src/runtime/store.ts
Parameters
| Parameter | Type |
|---|---|
fact | string |
Returns
void
unconstrain()
unconstrain(target): void;Defined in: packages/core/src/runtime/store.ts
Parameters
| Parameter | Type |
|---|---|
target | Target |
Returns
void
unprefer()
unprefer(target): void;Defined in: packages/core/src/runtime/store.ts
Parameters
| Parameter | Type |
|---|---|
target | Target |
Returns
void
untell()
untell(fact): void;Defined in: packages/core/src/runtime/store.ts
Parameters
| Parameter | Type |
|---|---|
fact | string |
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
| Property | Modifier | Type | Description |
|---|---|---|---|
allow | readonly | readonly Action[] | The steps that World allows. |
beyond? | readonly | number | For cause: 'judged': System One's share outside K (BEYOND). |
cause? | readonly | "measured" | "judged" | For an 'unmet' System One judged: 'judged' (0115). |
goal? | readonly | string | The goal of the World that holds it. |
id | readonly | Id | - |
key | readonly | string | - |
reason | readonly | Reason | - |
tried? | readonly | readonly 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
| Name | Type | Description |
|---|---|---|
constrain() | (target, constraint) => HostAction | - |
decide() | (id, ...value) => HostAction | - |
draw() | (world) => HostAction | Draw 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) => HostAction | Copy 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
| Parameter | Type |
|---|---|
reads | readonly 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
| Parameter | Type |
|---|---|
value | unknown |
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
| Parameter | Type |
|---|---|
catalog | unknown |
Returns
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
| Parameter | Type |
|---|---|
frame | FrameCheck |
event | HostEvent |
options | { reads?: readonly ChoiceRead[]; } |
options.reads? | readonly ChoiceRead[] |
Returns
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
| Parameter | Type | Description |
|---|---|---|
catalog | HostCatalog | - |
tree | Rendered | 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.slots | readonly string[] | - |
options.kinds? | Iterable<string, any, any> | - |
options.requires? | Iterable<string, any, any> | - |
Returns
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
| Parameter | Type |
|---|---|
value | unknown |
Returns
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
| Parameter | Type |
|---|---|
message | unknown |
Returns
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
| Parameter | Type |
|---|---|
tree | unknown |
Returns
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
| Parameter | Type |
|---|---|
intent | Intent<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); // → falseobservationOf()
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
| Parameter | Type |
|---|---|
r | { reads: readonly ChoiceRead[]; unresolved: readonly Unresolved[]; } |
r.reads | readonly ChoiceRead[] |
r.unresolved | readonly Unresolved[] |
Returns
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
| Parameter | Type |
|---|---|
recordings | readonly Recording[] |
opts | { programs?: Record<string, RootProgram>; } |
opts.programs? | Record<string, RootProgram> |
Returns
object
| Name | Type |
|---|---|
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
| Parameter | Type |
|---|---|
name | string |
Returns
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
| Parameter | Type |
|---|---|
input | unknown |
Returns
string[]
Last updated on
Edit on GitHub