Skip to content

bolt

bolt

Import from @norbital-ai/bolt

@norbital-ai/bolt: author declarations, small composition helpers and their types. Native services use separate entries. Terms: server code (transforms, verdicts, effects, automations, syncs, integrations) receives a ctx from these declarations; the page SDK is @norbital-ai/bolt/page; Device is what the shell running a page provides (ctx.device); a shell is the container a workspace runs in (the web shell, or a native app); a host runs a bundle and supplies its Facilities (@norbital-ai/host-api, the host contract); secrets are encrypted tenant values declared with secrets; an environment (local, staging, production, and a tenant inside one) is an operator concern, never a workspace setting.

decl

ActInput type

type ActInput<N> = N extends `${infer C}.${infer V}` ? V extends 'create' ? readonly (CreateInput<C> & {
    readonly id?: Id<C>;
})[] : V extends 'import' ? ImportInput<C> : V extends 'update' ? readonly {
    target: WriteTarget<C>;
    set: UpdateInput<C>;
}[] : V extends 'delete' ? readonly {
    target: WriteTarget<C>;
}[] : never : never;

The input of a generated model write. Always a batch: create takes insert trees, update takes { target, set } entries and delete takes { target }. A created root may carry an id its writer minted (new_id(model)), so a later act in the same map can name the row in a ref. Import takes { rows, on_conflict, on_missing?, prune?, dry_run? }: one atomic act matching rows by the model's key; dry_run runs every callback and writes nothing. Fields and child layers come from the model's write exposure, not its read output or complete storage schema. Optional/defaulted insert fields may be omitted; update patches contain only the fields being changed. An unknown verb resolves to never. Regenerate workspace names after changing declarations before inspecting this type.

@see Callable *

@see ActOutput

Example

type CreateOrders = ActInput<'orders.create'>;
type UpdateOrders = ActInput<'orders.update'>;

Source: packages/bolt/src/decl/ctx.ts:473

ActOutput type

type ActOutput<N> = N extends `${infer C}.${infer V}` ? V extends 'import' ? ImportReport<C> : V extends 'create' | 'update' | 'delete' ? null : never : never;

The output inside a successful generated write receipt: create/update/delete return null; import returns a per-row resolution report. Written ids and revisions are on the receipt's records; this type is not the whole receipt and does not imply that approval has completed.

@see ActInput *

@see Committed *

@see PendingApproval

Example

type ImportResult = ActOutput<'orders.import'>;

Source: packages/bolt/src/decl/ctx.ts:516

Actor type

type Actor = Member | {
    kind: 'envoy';
    envoy: Id<'sys_envoy'>;
    instance: Id<'sys_integration'>;
    sender: Handle;
    member: Id<'sys_user'> | null;
    linked?: Member;
} | {
    kind: 'visitor';
    app: AppName;
    visitor: string;
    anonymous?: true;
} | {
    kind: 'api_key';
    key: Id<'sys_api_key'>;
} | {
    kind: 'system';
    run: Id<'sys_run'>;
    by: {
        automation: AutomationName;
    } | {
        platform: PlatformAutomation;
    } | {
        sync: `${string}.sync.${string}`;
        instance: Id<'sys_integration'>;
    };
};

Who a request runs as, discriminated by kind: a member (with teams and admin), an envoy answering a sender on the instance it is deployed on, a public visitor of an app, an api_key, or the system running an automation, a remote sync's read or write for one instance ('<model>.sync.<sync>': the engine never sends a sync's own writes back through it), or a platform run. system is the one reserved identity of the platform's own work: an automation run or a remote sync page is it, holding the automation's or sync's policies whoever started it (who did is the run's trigger, ctx.trigger), and its actor.* operands name no member, party or team (a remote sync's carries only actor.instance), so an actor-scoped grant matches nothing (bolt check refuses an automation or sync holding one).

Source: packages/bolt/src/decl/access/actor.ts:36

ApprovalFlow type

type ApprovalFlow = {
    readonly steps: NonEmpty<{
        readonly name: string;
    } & ({
        readonly teams: NonEmpty<Id<'sys_team'>>;
        readonly users?: NonEmpty<Id<'sys_user'>>;
    } | {
        readonly teams?: NonEmpty<Id<'sys_team'>>;
        readonly users: NonEmpty<Id<'sys_user'>>;
    })>;
    readonly superseded_by?: readonly Id<'sys_team'>[];
};

Who decides a write, in step order: each step names teams, members (sys_team and sys_user ids the verdict reads at runtime, such as a record's reviewing team or assigned approver), or both, and any one of them decides it. The requester never decides their own request. Superseders may decide any step with a reason.

Members

NameTypeDescription
stepsNonEmpty<{ readonly name: string; } & ({ readonly teams: NonEmpty<Id<'sys_team'>>; readonly users?: NonEmpty<Id<'sys_user'>>; } | { readonly teams?: NonEmpty<Id<'sys_team'>>; readonly users: NonEmpty<Id<'sys_user'>>; })>
superseded_by?readonly Id<'sys_team'>[]

Source: packages/bolt/src/decl/access/policy.ts:58

ApprovalRecipient type

type ApprovalRecipient = 'requester' | 'approvers';

A model effect's approval roles: the request's 'requester' or the current step's 'approvers' (teams and users), resolved only in an approval event (ctx.event.kind === 'approval'). 'approvers' resolves at delivery against active staff, leaves out the requester, and sends nothing once the request has closed.

Source: packages/bolt/src/decl/runtime/facilities.ts:177

Attachment type

type Attachment = Omit<HostAttachment, 'id'> & {
    readonly id?: Id<'sys_file'>;
};

The transport attachment with a workspace's typed file handle.

Members

NameTypeDescription
namestring
mimestring
bytesnumber
id?Id<'sys_file'>

Source: packages/bolt/src/decl/runtime/integration.ts:42

AutomationCtx type

type AutomationCtx<S = AutomationSpec> = RunCtx<Extract<Actor, {
    kind: 'system';
}>, true, Recipient> & {
    readonly trigger: TriggerOf<S> & (S extends {
        mode: 'call';
    } ? {} : {
        readonly id: Id<'sys_run'>;
    });
} & (S extends {
    mode: 'call';
} ? {} : {
    wait: Wait;
});

run's ctx: reads (ctx.query), writes and schedules as its policies; the only place for I/O. A failed yield* ends the body: try/catch never sees it (bolt check refuses one), so recover with Effect.catch or Effect.catchTag on the yielded Effect (yield* ctx.browser.download(url, options).pipe(Effect.catch(...))). actor is the reserved system identity; trigger records who or what started the run and, for a job, its run id. Code acting for a starter checks it explicitly (trigger.kind === 'person', then their id, party or teams against the rows it touches).

Source: packages/bolt/src/decl/runtime/automation.ts:154

BodyError type

type BodyError = {
    readonly _tag: string;
};

A body's failure: every failure is tagged, and a body requires no service.

Members

NameTypeDescription
_tagstring

Source: packages/bolt/src/decl/ctx.ts:65

integrations

CalendarEvent type

type CalendarEvent = {
    readonly id: string;
    readonly summary: string | null;
    readonly description: string | null;
    readonly location: string | null;
    readonly url: string | null;
    readonly status: 'confirmed' | 'tentative' | 'cancelled';
    readonly start: CalendarTime;
    readonly end: CalendarTime;
    /** Original provider event, including attendees, recurrence and identifiers needed by authored business rules. */
    readonly source: Json;
};

One event a calendar driver pushes to a sync's read (items); the read's partition is its calendar (a sync's partitions names the text-many configuration field listing them, one cursor each). A changed calendar wakes its partition; lost history (retained: false) starts a fresh snapshot. All-day events keep their dates, timed events their instants and source zones.

Members

NameTypeDescription
idstring
summarystring | null
descriptionstring | null
locationstring | null
urlstring | null
status'confirmed' | 'tentative' | 'cancelled'
startCalendarTime
endCalendarTime
sourceJson

Original provider event, including attendees, recurrence and identifiers needed by authored business rules.

Source: packages/host-api/src/integrations.ts:649

decl

Callable type

type Callable = {
    [C in ModelName]: `${C}.${Verbs<C>}`;
}[ModelName];

Every callable: a model's generated write verb.

Source: packages/bolt/src/decl/ctx.ts:455

CarriedWrites type

type CarriedWrites = {
    readonly [N in AuthoredModelName]?: {
        readonly create?: readonly CreateSet<N>[];
        readonly update?: readonly {
            readonly target: WriteTarget<N>;
            readonly set: UpdateSet<N>;
        }[];
    };
};

Rows of other models a write callback carries into its own commit: creates, and updates naming the revision they read (a newer one is a conflict). They are the carrier's own complete logic, written straight to storage: the carrier's grant admits them, and the carried model's policies, verdicts, callbacks and effects never run for them, nor do write triggers or waits fire. Storage still holds: native constraints, foreign keys, uniqueness, locks and state rules, history and audit, all in the root write's one transaction (rolled back with it). Models never call each other implicitly: rows a person writes through a parent's layer are input, and run their own model's callbacks and effects.

Source: packages/bolt/src/decl/ctx.ts:679

Check type

type Check<E> = [E] extends [never] ? true : {
    [K in E & string]: K;
}[E & string];

true when E is never; otherwise an object type whose keys are the error messages, so tsc prints them. The generated Check<Verify> gate.

Source: packages/bolt/src/decl/verify.ts:150

Clock interface

interface Clock {
    readonly actor: Actor;
    now: Instant;
    today: PlainDate;
    tz: IanaZone;
    today_in(zone: IanaZone): PlainDate;
}

What every server body knows of its moment: who it runs as, the instant, today and the zone (today_in another zone). now and today are fixed for the invocation (a page uses clock(unit) instead). Read predicates, grant scopes included, hold literal date and instant values, never clock operators.

Members

NameTypeDescription
actorActor
nowInstant
todayPlainDate
tzIanaZone
today_in(zone: IanaZone) => PlainDate

Source: packages/bolt/src/decl/ctx.ts:359

CreateInput type

type CreateInput<M> = CreateLayer<M, M & string>;

One created row of M as a writer sends it and the policy's verdict judges it: the root's create.fields (required ones required, filled ones optional) and each declared child layer as a list of child rows (or, for a non-owned relation, existing rows to link).

Source: packages/bolt/src/decl/ctx.ts:393

CreatedRow type

type CreatedRow<M> = Omit<CreateSet<M>, SubLayer<WritePath<M, 'create'>, M & string>> & {
    readonly id: Id<M & string>;
} & ProposedChildren<M, 'create', M & string>;

A proposed create: writable values, its known id and actual child lists; generated columns wait for the commit.

Members

NameTypeDescription
idId<M & string>

Source: packages/bolt/src/decl/ctx.ts:651

CurrencyCode type

type CurrencyCode = Uppercase<string>;

An ISO 4217 currency code (SGD, USD).

Source: packages/bolt/src/decl/values.ts:34

cursor

Cursor type

type Cursor = string & {
    readonly [cursor]: true;
};

An opaque page cursor: pass a page's next back as after to read on.

Source: packages/store/src/cursor.ts:6

shell

CustomFieldView type

type CustomFieldView<F extends string = string> = (ViewCommon<F> & {
    mode: 'show';
    dense?: true;
}) | (ViewCommon<F> & {
    mode: 'edit';
    disabled: boolean;
    error?: string;
    /** The typed next value, or `null` to clear it; never a JSON round-trip. */
    on_change(next: CustomValue<F> | null): void;
});

what +renderer.svelte receives, { view: CustomFieldView<'<f>'> }, a workspace's and a built-in's (money, file, point, phone) alike. row is the record's other field values (the form's draft in edit mode), absent when a page embeds the renderer; kind the field's literal (a custom reference's shape); dense asks for one compact line (a table cell, a card); address is a point field's address sibling.

Source: packages/bolt/src/shell/runtime.ts:571

integrations

DatabaseRequest type

DatabaseRequest: Schema.Union<readonly [Schema.Struct<{
    readonly max_rows: Schema.optionalKey<Schema.Int>;
    readonly transaction: Schema.optionalKey<Schema.Literal<"serializable">>;
    readonly op: Schema.Literal<"values">;
    readonly values: Schema.$Record<Schema.NonEmptyString, Schema.Union<readonly [Schema.String, Schema.Finite, Schema.Boolean, Schema.Null]>>;
}>, Schema.Struct<{
    readonly max_rows: Schema.optionalKey<Schema.Int>;
    readonly transaction: Schema.optionalKey<Schema.Literal<"serializable">>;
    readonly op: Schema.Literal<"read">;
    readonly table: Schema.Struct<{
        readonly schema: Schema.NonEmptyString;
        readonly name: Schema.NonEmptyString;
    }>;
    readonly columns: Schema.$Array<Schema.NonEmptyString>;
    readonly where: Schema.optionalKey<Schema.$Record<Schema.NonEmptyString, Schema.Union<readonly [Schema.String, Schema.Finite, Schema.Boolean, Schema.Null]>>>;
}>, Schema.Struct<{
    readonly max_rows: Schema.optionalKey<Schema.Int>;
    readonly transaction: Schema.optionalKey<Schema.Literal<"serializable">>;
    readonly op: Schema.Literal<"call">;
    readonly procedure: Schema.Struct<{
        readonly schema: Schema.NonEmptyString;
        readonly name: Schema.NonEmptyString;
    }>;
    readonly arguments: Schema.$Record<Schema.String, Schema.Union<readonly [Schema.String, Schema.Finite, Schema.Boolean, Schema.Null]>>;
}>, Schema.Struct<{
    readonly max_rows: Schema.optionalKey<Schema.Int>;
    readonly trans…

Schema of one structured database program a guest sends through a database link (today the SQL Server shape): values, read, call, CDC metadata and pages, and insert_once. The workspace names qualified tables, projected columns, filters, decimal/date formats and its delete policy; the host compiles the native SQL. CDC pages reconcile current rows and tombstones from an inclusive LSN/sequence/operation/key cursor. insert_once takes an immutable key and fingerprint, a five-second native lock and one serializable header/child/procedure batch, and answers an exact receipt; call names a procedure with typed arguments over native RPC. Cancellation, row and byte bounds, TLS identity and network admission apply to every program.

Example

yield* ctx.request(erp, { op: 'read', table: { schema: 'accounting', name: 'products' }, columns: ['code', 'name'],
	where: { active: true }, max_rows: 100 });

Source: packages/host-api/src/integrations.ts:616

DatabaseResult type

DatabaseResult: Schema.Struct<{
    readonly rows: Schema.$Array<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>;
}>

Schema of a database link's answer: its rows as JSON column maps.

Members

NameTypeDescription
rowsSchema.$Array<Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>>

Source: packages/host-api/src/integrations.ts:619

values

Decimal type

type Decimal = string;

A decimal's exact text ('12.50').

Source: packages/store/src/values.ts:8

lang

Duration type

type Duration = `${bigint}${keyof typeof UNITS}`;

A whole duration in seconds, minutes, hours or days: the authoring grammar of schedules and clock defaults.

Source: packages/store/src/lang/vars.ts:15

decl

Eff interface

interface Eff<out A, out E = never> extends Effect.Effect<A, E> {
}

What a ctx member answers: an Effect succeeding with A and failing with its typed failures E, yield*ed in a generator body. One interface with declared variance keeps the check cost flat (G1 scale fixture).

Source: packages/bolt/src/decl/ctx.ts:63

EffectCtx type

type EffectCtx<M = ModelName> = RunCtx<Actor, false, Recipient | ApprovalRecipient> & {
    /** Approval moves have no committed change list; their frozen data is carried here. */
    readonly event: EffectEvent<M>;
};

A model effect's ctx (create.effect, update.effect, delete.effect): an automation run's facilities, as the writer whose committed write ran it (member, envoy, visitor or automation run, with that authority); an effect holds no policy of its own and its ai has no host tools. Each committed batch queues one durable run <model>.effect.<verb> in the write's own statement, retried for over an hour on a transient failure and never rate limited; a failure never undoes the write. Changes carry before, set, after and changed(...) over the root fields of the writer's output (default when held, else the first named output it holds; a writer holding no read output of the model sees its rows as stored). An effect's writes run effects one level deeper; a write that would queue one past depth 8 (LIMITS.writeDepth) is refused. ctx.notify may also address the approval's 'requester' and 'approvers'; they resolve only when ctx.event.kind === 'approval'. A write held for approval freezes its changes and writer until final approval releases them; rejection discards them. The writer sees its effect run's status and error code; an administrator also sees its input.

Members

NameTypeDescription
tzIanaZone
nowInstant
todayPlainDate
today_in(zone: IanaZone) => PlainDate
query<const R extends ReadRequestBase>(request: ReadRequest<R>) => Eff<ReadAnswer<R>, ReadFailed>

A read request: a layer map of roots (models with outputs) and the layers of the output each names, in one crossing and ONE statement, under the caller's authority: each root's policies granting that output alone filter it and its layers.

@returns An Effect containing each root's typed page or aggregate. A page's rows are only that page; follow its cursor for more.

@see ReadRequest *

@see ReadAnswer *

const { orders, commercial_settings } = yield* ctx.query({
  orders: { where: { status: { eq: 'issued' } }, fields: ['number', 'total'], limit: 100,
    lines: { where: { quantity: { gt: 0 } }, fields: ['quantity', 'net'] } },
  commercial_settings: { limit: 1 }
});
history<C extends string>(model: Is<C, ReadableName>, id: NoInfer<Id<C>>, options?: HistoryOptions<C>) => Eff<readonly Revision[], ReadFailed>

A record's revisions, oldest first, up to an instant, a revision or just before an approval request. Every committed write appends one (who, when, cause, changed fields); pruning keeps the newest 256 per record and folds the rest into a full-row anchor. Each revision keeps the schema version it was written under and is marked valid when it projects into today's schema. Reading needs the record's current output grant (history: true).

invocation_idstring
actorA
attemptnumber

1 on the first attempt.

progress(update: { ratio?: number | null; text?: string | null; }) => Eff<void>
actAct
refuseRefuse<{ field?: string; row?: number; }>

Stops the current body with an authored refusal; row and field name the input list row and field.

scheduleSchedule
notifyNotify<To>
sendSend
requestRequest
webWeb
filesFiles
browserBrowser

This run's own browser tab; it closes when the run's scope ends.

convertConvert

Markdown or HTML to a declared document format (optional host capability; absent → unavailable).

aiAi<Tools>
geoGeo
eventEffectEvent<M>

Approval moves have no committed change list; their frozen data is carried here.

Source: packages/bolt/src/decl/runtime/automation.ts:245

FileRef type

type FileRef = {
    readonly [brand]: 'FileRef';
    readonly id: Id<'sys_file'>;
    readonly name: string;
    readonly mime: string;
};

A file field's value: a handle to a stored file (id, name, MIME type), never its bytes.

Members

NameTypeDescription
idId<'sys_file'>
namestring
mimestring

Source: packages/bolt/src/decl/values.ts:25

Finding type

type Finding = {
    readonly at: number;
    readonly field?: string;
    readonly message: string;
    readonly severity: 'warn' | 'refuse';
};

A problem a file's read found: at is the record's $at (0: the file as a whole), field the column. Any refuse blocks the file (nothing is written); a warn is reported with what was imported.

Members

NameTypeDescription
atnumber
field?string
messagestring
severity'warn' | 'refuse'

Source: packages/bolt/src/decl/runtime/sync.ts:145

Health type

type Health = {
    readonly state: 'ready' | 'attention';
    readonly code?: string;
    readonly message?: string;
};

A sync's health as read reports it: attention raises the instance's status (and any automation watching it).

Members

NameTypeDescription
state'ready' | 'attention'
code?string
message?string

Source: packages/bolt/src/decl/runtime/sync.ts:77

Id type

type Id<C extends string> = string & {
    readonly [brand]: C;
};

A row id, branded by its model so an id of one model never passes for another's.

Source: packages/bolt/src/decl/values.ts:10

ImageFacts type

type ImageFacts = {
    readonly format: string;
    readonly width: number;
    readonly height: number;
    readonly sha256: string;
    readonly pdq: string;
    readonly exif: {
        readonly taken_at?: Instant;
        readonly gps?: Point;
        readonly software?: string;
        readonly make?: string;
        readonly model?: string;
    };
};

What ctx.files.image reads from an image: format, size, SHA-256, the PDQ perceptual hash and EXIF (time taken, GPS, camera).

Members

NameTypeDescription
formatstring
widthnumber
heightnumber
sha256string
pdqstring
exif{ readonly taken_at?: Instant; readonly gps?: Point; readonly software?: string; readonly make?: string; readonly model?: string; }

Source: packages/bolt/src/decl/runtime/facilities.ts:329

IndexSearch type

type IndexSearch<C> = {
    [I in IndexName<C>]: {
        readonly [P in I]: InputOf<IndexInput<C, I>>;
    };
}[IndexName<C>] | (HasSemantic<C> extends true ? {
    readonly semantic: string | {
        readonly record: Id<C & string>;
    };
} : never);

A search over one of C's search.indexes, keyed by the index with its probe input ({ colour: { lab, … } }), or over search.semantic: nearest by meaning to a text, or to a record's own embedding (the record itself left out).

Source: packages/bolt/src/decl/ctx.ts:108

InputFields type

type InputFields = {
    readonly [name: string]: InputKind;
};

A record of named input fields: a query's, action's, automation's or custom field's input shape.

Source: packages/bolt/src/decl/fields.ts:155

InputOf type

type InputOf<F> = InputOfFields<F>;

An input object derived from a map of field kinds. Required keys must be present; optional or defaulted keys may be omitted. An optional key also accepts null; a default does not itself add null to the value type. This derives a shape only: runtime decoding, defaults and business validation still execute at their boundary.

@see ValueOf

Example

type Input = InputOf<{ title: { kind: 'text' }; notes: { kind: 'text'; optional: true } }>;

Source: packages/bolt/src/decl/fields.ts:265

InstanceId type

type InstanceId<D extends string = IntegrationName> = Id<'sys_integration'> & {
    readonly [definition]: D;
};

A sys_integration id known to be an instance of definition D: what an FK pinned to D holds.

Source: packages/bolt/src/decl/names.ts:103

values

Instant type

type Instant = string;

An instant, ISO UTC text (2026-01-05T09:30:00.000Z).

Source: packages/store/src/values.ts:12

decl

Integration type

type Integration<N extends string, S> = {
    readonly name: N;
    readonly spec: S;
    readonly bodies: {
        readonly test?: Body;
        readonly webhook?: Body;
    };
};

What integration() returns: the name, the literal, and its test body as the guest calls it.

Members

NameTypeDescription
nameN
specS
bodies{ readonly test?: Body; readonly webhook?: Body; }

Source: packages/bolt/src/decl/runtime/integration.ts:518

IntegrationLiteral type

type IntegrationLiteral<N> = Omit<IntegrationSpec, 'webhook'> & {
    webhook?: Omit<WebhookSpec, 'handle'> & {
        handle?: WebhookBody<N>;
    };
    test?: TestBody<N>;
};

The literal an integration takes, with its inline test and webhook handler typed by the path-derived binding.

Members

NameTypeDescription
descriptionSchema.String
driverSchema.Union<readonly [Schema.Literals<("email" | "http" | "calendar" | "chat" | "sqlserver")[]>, Schema.Struct<{ readonly read: Schema.Literals<readonly ["cursor", "deliveries", "items"]>; readonly request: Schema.optionalKey<Schema.Literals<readonly ["http", "database"]>>; readonly call: Schema.optionalKey<Schema.Literal<"http">>; readonly credential: Schema.optionalKey<Schema.Literal<true>>; r…
configuration?Schema.optionalKey<Schema.$Record<Schema.String, Schema.Codec<import("@norbital-ai/ui").Kind, import("@norbital-ai/ui").Kind, never, never>>>

Safe settings each instance edits at run time (with history), decoded against these fields.

credential?Schema.optionalKey<Schema.$Record<Schema.String, Schema.Codec<import("@norbital-ai/ui").Kind, import("@norbital-ai/ui").Kind, never, never>>>

The secret each instance pairs with, sealed host-side and never readable (http and sqlserver only).

oauth?Schema.optionalKey<Schema.Struct<{ readonly client: Schema.String; readonly secret: Schema.String; readonly authorize: Schema.optionalKey<Schema.String>; readonly token: Schema.optionalKey<Schema.String>; readonly scopes: Schema.optionalKey<Schema.$Array<Schema.String>>; }>>

The OAuth client an oauth driver (http, calendar) grants with, by secret name; tokens are per instance. An http definition names its authorize and token endpoints too, and its requests carry the instance's token as a bearer.

http?Schema.optionalKey<Schema.Struct<{ readonly base_url: Schema.String; readonly auth: Schema.optionalKey<Schema.Union<readonly [Schema.Struct<{ readonly bearer: Schema.String; }>, Schema.Struct<{ readonly header: Schema.Struct<{ readonly name: Schema.String; readonly value: Schema.String; }>; }>, Schema.Struct<{ readonly basic: Schema.Struct<{ readonly user: Schema.String; readonly password: Schema…

http only: the base URL (a literal or a text configuration field), how requests authenticate and, with allow, the only requests an instance sends: these methods on these paths under the base ({name} one segment, a final ** any rest). Anything else is refused before its credential is read.

rate?Schema.optionalKey<Schema.String>

At most this many requests through one instance ('10/s', '600/min'): every sync read, write and ctx.request waits its turn; a 429 with Retry-After is honoured on top. Request drivers only.

webhook?Omit<WebhookSpec, 'handle'> & { handle?: WebhookBody<N>; }
test?TestBody<N>

Source: packages/bolt/src/decl/runtime/integration.ts:492

IntegrationLiteralInput type

type IntegrationLiteralInput<N extends IntegrationName, S extends IntegrationLiteral<N>> = S & NoInfer<Checked<IntegrationLiteral<N>, S, Exact<S, IntegrationFor<N, S>>>>;

An integration literal with its driver-specific checks.

Source: packages/bolt/src/decl/runtime/integration.ts:574

values

Json type

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

A JSON value. Structural, so Predicate.isObject narrows it to its object and list arms.

Source: packages/store/src/values.ts:4

lang

Kind type

type Kind = Common & ({
    readonly kind: 'text';
    readonly format?: 'email' | 'phone' | 'url' | 'zone' | 'markdown' | 'cel' | 'policy';
    readonly max?: number;
    readonly many?: true;
    /** A `markdown` text's sibling many-`file` field: pictures pasted or dropped into the text are stored there. */
    readonly images?: string;
} | ({
    readonly kind: 'int';
} & Range) | ({
    readonly kind: 'number';
} & Range) | ({
    readonly kind: 'decimal';
    readonly scale: number;
    readonly precision?: number;
} & Range) | {
    readonly kind: 'money';
    readonly currency?: string;
    readonly scale?: number;
} | {
    readonly kind: 'currency';
} | {
    readonly kind: 'bool';
} | {
    readonly kind: 'point';
} | {
    readonly kind: 'date';
    readonly precision?: DatePrecision;
} | {
    readonly kind: 'instant';
    readonly precision?: Precision;
} | {
    readonly kind: 'time';
    readonly precision?: TimePrecision;
} | {
    readonly kind: 'period';
    readonly of: 'date';
    readonly precision?: DatePrecision;
} | {
    readonly kind: 'period';
    readonly of: 'instant';
    readonly precision?: Precision;
} | {
    readonly kind: 'enum';
    readonly values: readonly string[];
    readonly many?: true;
    /** The states one value may move to; a write naming another transition is refused. */
    readonly transitions?: Readonly<Record<string, readonly string[]>>;
} | {
    readonly kind: 'state';
    readonly initial: string;
    readonly states: {
        readonly [state: string]: {
            readonly to?: readonly string[];
            readonly stamp?: string;
        };
    };
} | {
    readonly kind: 'seq';
    readonly pattern?: `${string}{${string}}${string}`;
    readonly per?: readonly string[];
    readonly start?: {
        readonly [value: string]: number;
    };
} | {
    readonly kind: 'sum';
    readonly of: `${string}.${string}`;
    readonly where?: Where;
    readonly money?: {
        readonly currency?: string;
    };
} | {
    readonly kind: 'count';
    readonly of: string;
    readonly where?: Where;
} | {
    readonly kind: 'json';
    readonly shape?: Kind;
} | {
    readonly kind: 'file';
    readonly accept: readonly `${string}/${string}`[];
    readonly max: `${bigint}${'KiB' | 'MiB' | 'GiB' | 'KB' | 'MB' | 'GB'}`;
} | {
    readonly kind: 'vector';
    readonly dim: number;
    readonly metric: 'l2' | 'cosine' | 'ip';
} | {
    readonly kind: 'custom';
    readonly of: string;
    readonly many?: true;
}
/** A relation: an id of one table, or `{ model, id }` of one of several (polymorphic). */
 | {
    readonly kind: 'ref';
    readonly to: string | readonly string[];
    readonly inverse?: string;
    readonly owned?: true;
    readonly on_delete?: 'restrict' | 'cascade' | 'set_null';
    readonly where?: Where;
} | {
    readonly kind: 'object';
    readonly fields: Fields;
    readonly rest?: Kind;
} | {
    readonly kind: 'union';
    readonly by: string;
    readonly arms: {
        readonly [tag: string]: Fields;
    };
}
/** Untagged: the first scalar arm the value decodes against. */
 | {
    readonly kind: 'union';
    readonly of: readonly ScalarKind[];
} | {
    readonly kind: 'record';
    readonly of: Kind;
});

A kind literal: every stored and input kind with its options, one arm per kind.

Source: packages/store/src/lang/kind.ts:77

decl

LayerWhere type

type LayerWhere<C, P, O = 'default'> = [PathModel<C, P>] extends [infer T] ? T extends TargetName ? WhereOver<T, P, O> : never : never;

A predicate over layer P of C's output O: only the fields that layer exposes (the root: Where<C, O>).

Source: packages/bolt/src/decl/where.ts:224

ListRow type

type ListRow<C> = Simplify<Pick<LightRow<C>, SharedField<C> & keyof LightRow<C>> & Partial<Omit<LightRow<C>, SharedField<C>>>>;

A view's list row: the caller row less its heavy fields. A native view given a model name (Table, Board, Map) reads its viewer's output, default when held, else the first named output held, so a field some declared output leaves out is optional.

Source: packages/bolt/src/decl/ctx.ts:100

MessageKey type

type MessageKey = keyof NamesPart<'messages'> & string;

A key of src/i18n/+messages.ts.

Source: packages/bolt/src/decl/ctx.ts:733

Model type

type Model<K extends string, S> = {
    readonly name: K;
    readonly spec: S;
    readonly bodies: ModelBodies;
};

What model() returns: its name, the literal, and the bodies the guest calls.

Members

NameTypeDescription
nameK
specS
bodiesModelBodies

Source: packages/bolt/src/decl/model.ts:712

ModelLiteral type

type ModelLiteral = ModelMetadata & {
    /** The stored fields, `ref` fields included. Every row also carries the system columns (see `ModelSpec.fields`). */
    fields: {
        readonly [name: string]: Exclude<FieldKind, {
            kind: 'ref';
        }> | RefField | ComputedField;
    };
    /**
     * Named rules, enforced natively on every write path: `unique` (one may be the `import_key` that enables the `import`
     * verb), `check`, `no_overlap` of a period `per` key, and `locked`. A `locked` predicate makes a matching row
     * read-only: update and delete are refused and the record page shows a lock; `except` names fields every matching lock
     * still lets through. Each takes an optional `message` (a catalogue key without placeholders) a violation refuses with,
     * naming the field when the rule has one column; changing it needs no migration. Do not repeat these in a transform.
     * @example
     * constraints: { placed: { locked: { status: { eq: 'placed' } }, except: ['notes'] } }
     */
    constraints?: Readonly<Record<string, Constraint>>;
    /**
     * Named indexes: physical (`{ on }`), text (`{ text }`, fields matched beside `record_label`), `{ semantic }` and custom
     * vector indexes (pure `vector`, `probe`, optional `rerank`; the engine computes the vector on every committed write,
     * keeps it in a hidden HNSW column, and `null` leaves a row out; a vector that needs I/O is an ordinary `vector` field
     * an automation fills, named as `vector: '<field>'`). Search one with `query({ m: { search: { <index>: input } } })`;
     * rows carry `$distance` and the output and grants still apply. Each also appears as a toolbar search mode.
     */
    indexes?: Readonly<Record<string, IndexLiteral>>;
    /**
     * A `default` read output and optional named outputs: each lists `fields` (or `'all'`) and nests one projection per
     * relation it exposes. A read names one output (`default` when absent); a policy grants outputs and filters their
     * rows, never their fields. A model without outputs still stores rows and may appear in another model's output tree.
     */
    outputs?: {
        readonly default: ReadOutput;
        readonly [output: string]: ReadOutput;
    };
    /**
     * The generated `create`: a write tree like an output's (`fields`, then one nested tree per child relation) beside
     * `filled` (the fields its `transform` fills when omitted, in the same tree), `transform` and `effect`; a relation
     * cannot be named after one of those. A layer below the root is a many-relation (the child rows) and never lists the
     * key to its parent; a non-owned child may also be an existing `{ id, revision }`, which links it.
     * @example
     * create: { fields: ['customer', 'notes'], lines: { fields: ['product', 'qty'] } }
     */
    create?: WriteVerb & {
        filled?: ColumnTree;
    };
    /** The generated `update`: the fields a writer changes in the same tree (child layers take `create`, `update`, `delete`, `link`, `unlink`), beside `transform` and `effect`. */
    update?: WriteVerb;
    /** The generated delete, its `transform` and its optional post-commit effect. */
    delete?: {
        transform?: GeneratorBody;
        effect?: GeneratorBody;
    };
};

A model literal as model() takes it: shared data derives from the native codec, trees and bodies retain their author types.

Members

NameTypeDescription
descriptionSchema.String
was?Schema.optionalKey<Schema.String>
icon?Schema.optionalKey<Schema.String>
record_label?Schema.optionalKey<Schema.String>
fields{ readonly [name: string]: Exclude<FieldKind, { kind: 'ref'; }> | RefField | ComputedField; }

The stored fields, ref fields included. Every row also carries the system columns (see ModelSpec.fields).

constraints?Readonly<Record<string, Constraint>>

Named rules, enforced natively on every write path: unique (one may be the import_key that enables the import verb), check, no_overlap of a period per key, and locked. A locked predicate makes a matching row read-only: update and delete are refused and the record page shows a lock; except names fields every matching lock still lets through. Each takes an optional message (a catalogue key without placeholders) a violation refuses with, naming the field when the rule has one column; changing it needs no migration. Do not repeat these in a transform.

constraints: { placed: { locked: { status: { eq: 'placed' } }, except: ['notes'] } }
indexes?Readonly<Record<string, IndexLiteral>>

Named indexes: physical ({ on }), text ({ text }, fields matched beside record_label), { semantic } and custom vector indexes (pure vector, probe, optional rerank; the engine computes the vector on every committed write, keeps it in a hidden HNSW column, and null leaves a row out; a vector that needs I/O is an ordinary vector field an automation fills, named as vector: '<field>'). Search one with query({ m: { search: { <index>: input } } }); rows carry $distance and the output and grants still apply. Each also appears as a toolbar search mode.

outputs?{ readonly default: ReadOutput; readonly [output: string]: ReadOutput; }

A default read output and optional named outputs: each lists fields (or 'all') and nests one projection per relation it exposes. A read names one output (default when absent); a policy grants outputs and filters their rows, never their fields. A model without outputs still stores rows and may appear in another model's output tree.

create?WriteVerb & { filled?: ColumnTree; }

The generated create: a write tree like an output's (fields, then one nested tree per child relation) beside filled (the fields its transform fills when omitted, in the same tree), transform and effect; a relation cannot be named after one of those. A layer below the root is a many-relation (the child rows) and never lists the key to its parent; a non-owned child may also be an existing { id, revision }, which links it.

create: { fields: ['customer', 'notes'], lines: { fields: ['product', 'qty'] } }
update?WriteVerb

The generated update: the fields a writer changes in the same tree (child layers take create, update, delete, link, unlink), beside transform and effect.

delete?{ transform?: GeneratorBody; effect?: GeneratorBody; }

The generated delete, its transform and its optional post-commit effect.

Source: packages/bolt/src/decl/model.ts:627

ModelLiteralInput type

type ModelLiteralInput<K, S extends ModelLiteral> = S & NoInfer<Checked<ModelLiteral, S, Exact<S, ModelFor<S>>>> & NoInfer<BodiesFor<K>>;

A model literal with its model-specific checks and callback context.

Source: packages/bolt/src/decl/model.ts:809

ModelName type

type ModelName = (keyof Exposed & string) | SystemName;

Every surface addresses models: authored ones, plus the system models.

Source: packages/bolt/src/decl/names.ts:77

Names interface

interface Names {
}

Augmented by the generated .norbital/names.ts: declare module '@norbital-ai/bolt' { interface Names { … } }.

Source: packages/bolt/src/decl/names.ts:13

Notice type

type Notice<To = Recipient> = {
    /** Plain text, stored and shown as written (also used in push and transactional email subjects); not a message key. */
    title: string;
    /** Optional plain text body, shown in the inbox, push notification, transactional email and `via` channels. */
    description?: string;
    /** Target recipients: `{ user }`, `{ team }`, `{ policy }` (and `'requester'` / `'approvers'` in approval effects). */
    to: readonly To[];
    /**
     * The channels beyond the inbox and push: `'email'` (the host's transactional mail) and active workspace-owned
     * conversation instances (runtime `sys_integration` rows with `owner: null`, wrapped with `instance_id`) that send
     * the notice to each staff recipient's matching `sys_user` handle.
     */
    via?: readonly ('email' | InstanceId<ConversationDefinition>)[];
    /** Optional files or render-at-delivery documents attached to the inbox notice and `via` channel sends. */
    attachments?: readonly NoticeAttachment[];
    /** Record opened in the workspace's record sheet (and linked from push and transactional emails); defaults to the event's record. */
    link?: RecordRef;
    /** Deduplication key (scoped per recipient for inbox/email/push), so retried business work does not repeat notices. */
    once?: string;
};

One notice passed to ctx.notify.

Every notice lands in each recipient's in-app inbox (sys_notification), live stream and web/APNs push (bolt.push). The call decides every other channel in via:

  • 'email': transactional email (bolt.mail) through the host's configured mail port to each active member with a deliverable non-placeholder sys_user.email (a direct link to link, no attachments, zero workspace configuration).
  • an active workspace-owned conversation integration (sys_integration with owner: null, including envoy-paired accounts such as WhatsApp). Each resolves the recipient's handle on sys_user (whatsapp → phone, telegram → telegram, slack → slack, discord → discord, email → email); members without that handle are skipped on that channel, and replies on an envoy-paired channel continue on that envoy thread. Channels without auto-handles (such as wechat) or external/group recipients use ctx.send. Host transactional SMS is reserved for sign-in and invitation codes, not ctx.notify; send SMS notifications via an SMS chat integration or an http integration.

Code decides wording, grouping and which events notify; approval inbox notices already exist.

Members

NameTypeDescription
titlestring

Plain text, stored and shown as written (also used in push and transactional email subjects); not a message key.

description?string

Optional plain text body, shown in the inbox, push notification, transactional email and via channels.

toreadonly To[]

Target recipients: { user }, { team }, { policy } (and 'requester' / 'approvers' in approval effects).

via?readonly ('email' | InstanceId<ConversationDefinition>)[]

The channels beyond the inbox and push: 'email' (the host's transactional mail) and active workspace-owned conversation instances (runtime sys_integration rows with owner: null, wrapped with instance_id) that send the notice to each staff recipient's matching sys_user handle.

attachments?readonly NoticeAttachment[]

Optional files or render-at-delivery documents attached to the inbox notice and via channel sends.

link?RecordRef

Record opened in the workspace's record sheet (and linked from push and transactional emails); defaults to the event's record.

once?string

Deduplication key (scoped per recipient for inbox/email/push), so retried business work does not repeat notices.

Example

{ title: 'New review job', description: `${name} is waiting on the board.`, to: [{ team: project.review_team }],
  link: { model: 'projects', id: project.id }, via: ['email', hotline.id],
  attachments: [{ document: { html }, to: 'pdf', name: 'Brief.pdf' }], once: `review:${project.id}` }

Source: packages/bolt/src/decl/runtime/facilities.ts:210

NoticeAttachment type

type NoticeAttachment = FileRef | TransientFile | {
    document: ConvertSource;
    to: ConvertTarget;
    name: string;
};

A file a notice carries: a stored file, bytes the run holds (ctx.convert.record's answer, kept by the delivery until sent), or a document converted at delivery (after the commit, retried with the delivery) from Markdown or HTML to a target +workspace.ts declares under convert.to. Delivered to the in-app inbox and via channels (not transactional notification emails).

Source: packages/bolt/src/decl/runtime/facilities.ts:184

Notify type

type Notify<To = Recipient> = (notice: Notice<To> | readonly Notice<To>[]) => Eff<{
    readonly messages: readonly Id<'sys_message'>[];
}>;

ctx.notify: queues notices, delivered after the current write commits; a notice never delays or fails the write. Automations notify under their declared policies; model effects notify as the writer, after a committed write or approval move.

Inbox notices fan out to live views and push subscriptions (bolt.push); via: ['email'] adds transactional email (bolt.mail, the host's mail transport). messages returns the sys_message ids queued for any via conversation instances (queue admission, as ctx.send's).

Example

update: { effect: function* (changes, ctx) {
	if (ctx.event.kind !== 'write') return;
	yield* ctx.notify(changes.map(({ after }) => ({ title: 'Project moved', to: [{ team: after.review_team }],
		link: { model: 'projects', id: after.id }, once: `project-moved:${after.id}` })));
} }

Source: packages/bolt/src/decl/runtime/facilities.ts:245

Page type

type Page<T> = {
    readonly rows: readonly T[];
    readonly next: Cursor | null;
};

One page of a read: its rows, and the next cursor, null on the last page.

Members

NameTypeDescription
rowsreadonly T[]
nextCursor | null

Source: packages/bolt/src/decl/ctx.ts:80

values

PlainDate type

type PlainDate = string;

A calendar day, YYYY-MM-DD.

Source: packages/store/src/values.ts:10

decl

PlainTime type

type PlainTime = string & {
    readonly [brand]: 'PlainTime';
};

A time field's value: a validated time-of-day string.

Source: packages/bolt/src/decl/values.ts:8

facilities

Point type

type Point = {
    readonly lat: number;
    readonly lng: number;
};

A point on Earth: latitude and longitude in degrees.

Members

NameTypeDescription
latnumber
lngnumber

Source: packages/host-api/src/facilities.ts:162

decl

PolicyCtx interface

interface PolicyCtx<in out M, in out V extends 'create' | 'update' | 'delete'> extends Clock {
    readonly invocation_id: string;
    readonly policies: readonly string[];
    readonly query: WorkspaceQuery['query'];
    /** The write executes directly. */
    allow(): Verdict;
    /** Refuses the whole batch; `at` names the row and a root field of it. */
    refuse: Refuse<RefuseWhere<M, V>>;
    /** The batch is held for the declared approval steps and optional superseding teams. */
    approve(flow: ApprovalFlow): Verdict;
}

What a policy's write verdict sees: who writes (actor, policies), the clock, query (read requests as the workspace, at most ten per call, whatever the batch size) and the three verdicts. It writes nothing and does no I/O; it returns allow() or approve(flow), or stops with refuse(message_key, at?).

Members

NameTypeDescription
invocation_idstring
policiesreadonly string[]
queryWorkspaceQuery['query']
allow() => Verdict

The write executes directly.

refuseRefuse<RefuseWhere<M, V>>

Refuses the whole batch; at names the row and a root field of it.

approve(flow: ApprovalFlow) => Verdict

The batch is held for the declared approval steps and optional superseding teams.

actorActor
nowInstant
todayPlainDate
tzIanaZone
today_in(zone: IanaZone) => PlainDate

Source: packages/bolt/src/decl/ctx.ts:603

PolicyName type

type PolicyName = keyof NamesPart<'policies'> & string;

The policy names (src/access_control/policy/+<name>.policy.ts).

Source: packages/bolt/src/decl/names.ts:87

ReadAnswer type

type ReadAnswer<R> = {
    readonly [C in keyof R & string]: RootAnswer<C, R>;
};

A read request's answer: per root, a page of layer rows (or its aggregate), typed from its output's named layers.

Source: packages/bolt/src/decl/ctx.ts:309

ReadRequest type

type ReadRequest<R> = R & NoInfer<Checked<ReadRequestBase, R, Exact<R, RequestSpec<R>>>>;

A read request literal, checked exactly: an unknown key, path, field or option fails to type-check (and is refused at run time). The same JSON tree serves pages, server ctx.query, policy verdicts and the agent's read tool. Each root appears once; relations nest under their parent, never as dotted keys. The caller's where, a view's prefilter and the granting policy compose per root (where ANDed, limit capped), so nothing widens the policy; one answer page is at most 4 MiB. Derive several views of one root from one read on the client. A past state is as_of on the root; a revision is history(…, { at: { revision } }).

Source: packages/bolt/src/decl/ctx.ts:260

ReadRequestBase type

type ReadRequestBase = Readonly<Record<string, ReadNodeBase>>;

The loose shape every read request satisfies: read roots mapped to their options and nested relation layers.

Source: packages/bolt/src/decl/ctx.ts:231

Recipient type

type Recipient = {
    team: Id<'sys_team'>;
} | {
    user: Id<'sys_user'>;
} | {
    policy: PolicyName;
};

Whom a notice goes to: a team's members, one member, or a policy's holders.

Source: packages/bolt/src/decl/runtime/facilities.ts:171

shell

RecordView type

type RecordView<C extends string = string> = {
    model: C;
    mode: 'update';
    record: RowFor<C>;
} | {
    model: C;
    mode: 'create';
    values: Partial<RowFor<C>>;
};

what +representation.svelte receives, { view: RecordView<'<model>'> } (ui's views pass the same shape).

Source: packages/bolt/src/shell/runtime.ts:551

decl

Row type

type Row<C, O = 'default'> = RowOf<C, O> & RowState;

A model's root row for read output O (default when omitted): its declared fields, foreign-key ids and system columns. This is a read shape, not an insert/update input and not the complete stored row. Relationship layers and a query's selected fields are reflected by ReadAnswer instead. The type does not grant access: runtime policies still filter the rows a caller can read. Names and outputs come from the workspace's generated registry. Keep it through helpers (with ValueOf<Kind> for custom values) rather than widening to JSON and re-guarding.

@see ReadAnswer *

@see ActInput

Members

NameTypeDescription
$label?string | null

An authorized relation-dependent record_label or live reference's target label; derived at read time, never copied to a field.

$sync?{ readonly [sync: string]: SyncState; }
$approval?RowApproval

Example

type Order = Row<'orders'>;
type PublicOrder = Row<'orders', 'public'>;

Source: packages/bolt/src/decl/names.ts:478

StartInput type

type StartInput<A> = A extends AutomationName ? AutomationSpecOf<A> extends {
    input: infer I;
} ? AutomationInputOf<I, false> : {
    readonly [key: string]: never;
} : never;

The input declared by an automation. Sync controls are native operations, never authored starts.

Source: packages/bolt/src/decl/runtime/facilities.ts:141

StoredRow type

type StoredRow<M> = Simplify<ColumnValues<M, WritableField<M> | keyof SystemColumns<M>>>;

A stored row as write callbacks see it (before, ctx.query): never masked, every stored field, no seq, roll-up or computed.

Source: packages/bolt/src/decl/names.ts:509

StoredTree type

type StoredTree<M, V extends 'create' | 'update'> = StoredLayer<M, V, M & string>;

The stored row of M with each child layer its V declares, as update verdicts and transforms see it (before).

Source: packages/bolt/src/decl/ctx.ts:429

SyncCtx type

type SyncCtx<D = never> = Clock & WorkspaceQuery & SyncRefusal & ([D] extends [never] ? {} : {
    readonly configuration: ConfigurationOf<D>;
} & RequestOn<D> & SendOn<D>);

What a remote sync body sees: the clock and query reads as the workspace (unscoped), the instance's configuration, request (request drivers) and send (conversation drivers). A sync body writes nothing itself: what it returns is written in one act.

Source: packages/bolt/src/decl/runtime/sync.ts:107

SyncRow type

type SyncRow<M> = SyncValues<M> & {
    readonly $id?: string;
    readonly $version?: string;
    readonly $deleted?: true;
};

One row a sync's read returns: the model's writable fields it carries (those are the synced fields; the model's other fields are local and read never touches them), plus up to three markers. $id is the other side's identity (the engine keeps the id map, so the model needs no external-id field); $version its version (updated_at, an etag, a sequence). Numeric sequences and ISO timestamps reject older versions; opaque etags only detect equality and guard conditional writes, so their adapter fetches current state rather than replaying unordered row payloads; $deleted: true deletes the row. A soft delete is an ordinary field ({ $id, active: false }). The engine's id map carries the connection; no routing field is needed.

Members

NameTypeDescription
$id?string
$version?string
$deleted?true

Source: packages/bolt/src/decl/runtime/sync.ts:71

ThemeAccent type

type ThemeAccent = ThemeAccentPreset | `#${string}`;

Brand accent preset name or 6-digit #rrggbb hex colour.

Source: packages/bolt/src/decl/theme.ts:111

ThemeAccentPreset type

type ThemeAccentPreset = (typeof THEME_ACCENTS)[number];

Named brand accent preset.

Source: packages/bolt/src/decl/theme.ts:109

ThemePalette type

type ThemePalette = (typeof THEME_PALETTES)[number];

Named surface palette preset ('warm', 'neutral', or 'crisp').

Source: packages/bolt/src/decl/theme.ts:94

ThemeRadius type

type ThemeRadius = (typeof THEME_RADII)[number];

Named workspace corner radius preset ('sharp', 'default', or 'soft').

Source: packages/bolt/src/decl/theme.ts:116

ThemeTokens type

type ThemeTokens = Partial<Record<(typeof THEME_TOKENS)[number], string>>;

A partial theme: omitted variables keep Bolt's defaults. Values are CSS colours, font stacks or a radius length.

Source: packages/bolt/src/decl/theme.ts:119

UpdateInput type

type UpdateInput<M> = UpdateLayer<M, M & string>;

The set of one updated row of M: the root's update.fields, all optional, and per declared child layer the child rows it creates, updates ({ target, set }) and deletes (and, for a non-owned relation, links or unlinks), each with that layer's update columns.

Source: packages/bolt/src/decl/ctx.ts:419

lang

Value type

type Value = Json;

A value: JSON; a decimal is its exact text.

Source: packages/store/src/lang/kind.ts:351

decl

ValueOf type

type ValueOf<K> = K extends {
    optional: true;
} ? ManyValue<K> | null : ManyValue<K>;

The runtime value type of a field-kind declaration. optional: true adds null; it does not make an object key optional. Numeric, date and id kinds retain their Bolt value types rather than accepting arbitrary wire strings.

@see InputOf

Example

type Notes = ValueOf<{ kind: 'text'; optional: true }>; // string | null

Source: packages/bolt/src/decl/fields.ts:249

Verdict class

class Verdict {
    #private;
    readonly data: VerdictData;
    private constructor();
    /** The verdict members of a verdict's ctx (the guest edge installs them on `PolicyCtx`). */
    static readonly allow: () => Verdict;
    static readonly approve: (flow: ApprovalFlow) => Verdict;
    /** The data of what a verdict returned; anything no verdict member made is an authoring error. */
    static dataOf(v: unknown): VerdictData;
}

A verdict's answer: only ctx.allow() and ctx.approve(…) make one; a plain object is never one.

Members

NameTypeDescription
#privateany
dataVerdictData

Source: packages/bolt/src/decl/access/policy.ts:114

Verify type

type Verify = {
    [M in keyof Models & string]: ModelErrors<M>;
}[keyof Models & string] | LocaleErrors;

Every cross-file declaration error in the workspace, as messages; never when there is none.

Source: packages/bolt/src/decl/verify.ts:145

Where type

type Where<C, O = 'default'> = [C] extends [infer D] ? D extends ModelName ? WhereOver<D, D, O> : never : never;

A predicate over model C read as output O: only that output's fields and layers exist.

Source: packages/bolt/src/decl/where.ts:218

WorkspaceQuery type

type WorkspaceQuery = Pick<CallerQuery, 'query'>;

Reading records as the workspace (policy verdicts, write callbacks and remote sync bodies): the same typed request as CallerQuery, answered with every stored row under no grant; its where still crosses only the layers the output declares. A file sync's body reads as the member importing or exporting instead (FileSyncCtx).

Members

NameTypeDescription
query<const R extends ReadRequestBase>(request: ReadRequest<R>) => Eff<ReadAnswer<R>, ReadFailed>

A read request: a layer map of roots (models with outputs) and the layers of the output each names, in one crossing and ONE statement, under the caller's authority: each root's policies granting that output alone filter it and its layers.

@returns An Effect containing each root's typed page or aggregate. A page's rows are only that page; follow its cursor for more.

@see ReadRequest *

@see ReadAnswer *

const { orders, commercial_settings } = yield* ctx.query({
  orders: { where: { status: { eq: 'issued' } }, fields: ['number', 'total'], limit: 100,
    lines: { where: { quantity: { gt: 0 } }, fields: ['quantity', 'net'] } },
  commercial_settings: { limit: 1 }
});

Source: packages/bolt/src/decl/ctx.ts:353

WorkspaceTheme type

type WorkspaceTheme = {
    palette?: ThemePalette;
    accent?: ThemeAccent;
    radius?: ThemeRadius;
    light?: ThemeTokens;
    dark?: ThemeTokens;
};

Workspace-wide visual theme compiled into static CSS (zero runtime flash, automatic light/dark contrast). High-level knobs (palette, accent, radius) restyle every surface and component in one declaration; light and dark token overrides layer cleanly on top when finer control is needed.

Members

NameTypeDescription
palette?ThemePalette
accent?ThemeAccent
radius?ThemeRadius
light?ThemeTokens
dark?ThemeTokens

Source: packages/bolt/src/decl/theme.ts:126

WriteCtx interface

interface WriteCtx<in out M> extends Clock, WorkspaceQuery {
    readonly invocation_id: string;
    readonly policies: readonly string[];
    readonly admin: boolean;
    /**
     * `true` when the decision that approves a held write asks again: the rows are the records as they now stand (an
     * update's `{ before: row, set: {}, after: row }`), and only the answer's `on_approved` is written, in the
     * decision's commit. A held delete's rows are still stored: the decision deletes them and writes both `with` and
     * `on_approved`. A refusal refuses the approval.
     */
    readonly approving: boolean;
    /** Refuses the whole write; `field` names the field, `row` the offending row's index in the batch received. */
    refuse: Refuse<{
        field?: WritableField<M>;
        row?: number;
    }>;
    /**
     * Workspace reads. A root with `as_of: 'act'` reads the stored rows overlaid with this act's own rows: what the
     * model will hold once the act commits.
     */
    query: WorkspaceQuery['query'];
}

What a write callback sees: the clock, the writer's policies, the workspace reads (unmasked; as_of: 'act' sees this act's rows) and refuse. A callback crosses into the host at most 10 times per call (LIMITS.crossings.write), whatever the batch size: read for the whole batch at once (yield* ctx.query({ customers: …, prices: … }) is one read), never inside a loop over the rows (bolt check refuses a read in a loop). Verdicts, effects and approval callbacks read the same way: once per dependency wave, each request counting toward the limit. It performs no writes itself: the sets it returns, and any rows it carries (with, on_approved), are written in the writer's one transaction.

Members

NameTypeDescription
invocation_idstring
policiesreadonly string[]
adminboolean
approvingboolean

true when the decision that approves a held write asks again: the rows are the records as they now stand (an update's { before: row, set: {}, after: row }), and only the answer's on_approved is written, in the decision's commit. A held delete's rows are still stored: the decision deletes them and writes both with and on_approved. A refusal refuses the approval.

refuseRefuse<{ field?: WritableField<M>; row?: number; }>

Refuses the whole write; field names the field, row the offending row's index in the batch received.

queryWorkspaceQuery['query']

Workspace reads. A root with as_of: 'act' reads the stored rows overlaid with this act's own rows: what the model will hold once the act commits.

@returns An Effect containing each root's typed page or aggregate. A page's rows are only that page; follow its cursor for more.

@see ReadRequest *

@see ReadAnswer *

const { orders, commercial_settings } = yield* ctx.query({
  orders: { where: { status: { eq: 'issued' } }, fields: ['number', 'total'], limit: 100,
    lines: { where: { quantity: { gt: 0 } }, fields: ['quantity', 'net'] } },
  commercial_settings: { limit: 1 }
});
actorActor
nowInstant
todayPlainDate
tzIanaZone
today_in(zone: IanaZone) => PlainDate

Source: packages/bolt/src/decl/ctx.ts:711

app function

function app<const S extends AppSpec>(spec: S & Checked<AppSpec, S, AppFor & Exact<S, AppFor>>): S

src/app/<a>/+app.ts: an app's title, description, icon and banner, its audience, and its pages in nav order (each +<page>.page.svelte in the folder needs an entry). An optional +session.svelte beside it mounts once for every signed-in caller the app is granted to, receives ctx like a page, stays mounted across navigation and is disposed with the signed-in client: run its device work (a position watch) with {@attach attach(...)} so disposal interrupts it. It grants no server policy. A page's browser graph may not reach server declaration roles, .env files, server-named files or server/ directories (type-only imports are fine): share browser values through src/lib/.

Kiosks: staff open them through capabilities.apps, administrators directly, external members those that admit them. Public visitors: minting is limited per IP (register); past it a page opens with a per-request identity that owns nothing. When a visitor signs in, a newcomer's account is the anonymous user; an existing account absorbs its sys_user refs (except state-locked fields) and the anonymous user is deactivated. The daily prune deletes anonymous users with no live session that no record references.

Parameters

NameTypeDescription
specS & Checked<AppSpec, S, AppFor & Exact<S, AppFor>>

Example

export default app({
	title: 'app.crm.title',
	description: 'app.crm.description',
	icon: 'lucide:handshake',
	pages: { desk: { title: 'app.crm.title', icon: 'lucide:handshake' } }
});

Source: packages/bolt/src/decl/runtime/app.ts:332

automation function

function automation<const I extends AutomationInputFields = {}, const O extends OutputKind | undefined = undefined, const M extends "job" | "call" = "job", const T extends readonly Trigger[] = readonly [], const S extends AutomationLiteral<I, O, M, T> = AutomationLiteral<I, O, M, T>>(spec: { input?: I; output?: O; mode?: M; on?: T; } & S & NoInfer<Checked<AutomationLiteral<I, O, M, T>, S, Exact<S, AutomationFor<S, AutomationLiteral<I, O, M, T>["run"]>>>>): Automation<S>

src/automation/+<a>.automation.ts: a job on a trigger, or a call (a page's request/response), executed by the reserved system identity with the declared policies (ctx.trigger records who started it), with typed input and output, retries and concurrency. run is a generator in the literal; ctx carries reads (ctx.query), act, files, AI and the other facilities. A person's permission to start a job does not grant the job that person's authority. Check ctx.trigger explicitly when business rules depend on the starter. A retried run's act answers from its earlier commit; ctx.send and external requests can repeat. Every declared automation the caller may start appears in the native Command Center Automations, with this typed input rendered by Form; a page form is optional, not required. A start queues a run and is followed by the native run status — the page does not poll or reimplement the queue.

@returns Declaration metadata with an attached run body; declaring it does not start a job.

Parameters

NameTypeDescription
spec{ input?: I; output?: O; mode?: M; on?: T; } & S & NoInfer<Checked<AutomationLiteral<I, O, M, T>, S, Exact<S, AutomationFor<S, AutomationLiteral<I, O, M, T>['run']>>>>

Input/output contracts, execution policies, trigger and generator body.

  • description: string
  • policies: NonEmpty<string>

    The policies every run holds, whoever or whatever starts it: a run executes as the reserved system identity, and who triggered it (ctx.trigger) never changes its authority.

  • retry?: { attempts: Attempts; backoff?: Duration; }

    Retries of a failed run, only for a transient failure: a refusal or a bug is final. attempts counts every run, the first included, so 1 never retries. backoff (default 10s) doubles each attempt, up to an hour, with jitter.

  • concurrency?: { max: Max; }

    At most max runs of this automation at once (1 to 64); absent, one. The rest wait queued. A host runs as many runs at once as the sum of its automations' max.

  • agent?: AgentUse

    Whether the agent may start it: confirm (default; the person confirms each start) or never.

  • input?: I
  • output?: O
  • mode?: M
  • on?: T
  • run: (input: RunInput<{ input: I; }>, ctx: AutomationCtx<{ mode: M; on: T; }>) => BodyReturn<O extends OutputKind ? ValueOf<O> : void>

Example

export default automation({
	description: 'Daily sweep of lapsed quotes.',
	on: [{ cron: '0 6 * * *' }],
	policies: ['quote_watch'],
	run: function* (_, ctx) {
		const { quotes: lapsed } = yield* ctx.query({ quotes: { where: { valid_until: { lt: ctx.today } }, limit: 50 } });
		yield* ctx.progress({ text: `${lapsed.rows.length} lapsed` });
	}
});

Source: packages/bolt/src/decl/runtime/automation.ts:292

lang

compile function

function compile<R extends Roots, M extends Mode, T extends FormulaResult>(ctx: Site<R, M>, text: string, result: T): Compiled<R, M, T> | { readonly error: string; }

Compiles text for a result kind; { error } names the syntax fault, the unknown path or the wrong type. Cached per (context, text, result).

Parameters

NameTypeDescription
ctxSite<R, M>
  • roots: R
  • numbers: M
  • read: Readers<M>

    Each result kind's reader in this mode, so a result carries its Out type.

textstring
resultT

Source: packages/store/src/lang/formula.ts:279

context function

function context<const R extends Roots, D extends Derive<R> = undefined>(roots: R, opts?: Options<"decimal", D>): FormulaContext<R, "decimal", D>
function context<const R extends Roots, M extends Mode, D extends Derive<R> = undefined>(roots: R, opts: Options<M, D> & { readonly numbers: M; }): FormulaContext<R, M, D>

A formula context: its roots (field-kind literals), numeric mode, registered CEL functions ({ signature, fn }, registerFunction) and, for derived roots, a typed derive(rows) builder.

Parameters

NameTypeDescription
rootsR
opts?Options<'decimal', D>

Source: packages/store/src/lang/formula.ts:200

decl

custom_field function

function custom_field<const Shape extends InputKind, const S extends CustomFieldLiteral<Shape>>(spec: { shape: Shape; } & S & NoInfer<Checked<CustomFieldLiteral<Shape>, S, Exact<S, Omit<CustomFieldLiteral<Shape>, "shape"> & { shape: ValidInput<Shape>; }>>>): CustomField<Shape, S>

src/data/custom_field/<f>/+custom_field.ts: a reusable structured value (shape, an input kind literal) that model fields store as { kind: 'custom', of: '<f>' }, with an optional pure validate and a +renderer.svelte beside it. It is an inline value, not an entity: use a model when identity, lifecycle, authority, history or relational queries need one. Without a renderer the value is shown and edited from its shape; a renderer (CustomFieldView) is used in table cells, board cards, forms, record fields, history diffs and pickers, and is bundled statically, so keep it light. The built-in names money, file, point and phone are reserved.

Parameters

NameTypeDescription
spec{ shape: Shape; } & S & NoInfer<Checked<CustomFieldLiteral<Shape>, S, Exact<S, Omit<CustomFieldLiteral<Shape>, 'shape'> & { shape: ValidInput<Shape>; }>>>
  • description: string
  • label?: Msg
  • search?: true

    Include the value's text in the record's text search.

  • shape: Shape
  • validate?: Validate<Shape>

Example

export default custom_field({
	description: 'A postal address.',
	shape: { kind: 'object', fields: { line1: { kind: 'text' }, postcode: { kind: 'text' } } },
	validate: (v) => (/^\d{6}$/.test(v.postcode) ? undefined : 'A postcode has six digits.')
});

Source: packages/bolt/src/decl/custom-field.ts:42

lang

evaluate function

function evaluate<R extends Roots, M extends Mode, T extends FormulaResult>(compiled: Compiled<R, M, T>, values: ValuesOf<R>): Out<T, M>

Evaluates a compiled formula; a runtime fault (a missing value, a wrong result) throws.

Parameters

NameTypeDescription
compiledCompiled<R, M, T>
  • text: string
  • result: T
  • context: Site<R, M>
  • program: ParseResult
valuesValuesOf<R>

Source: packages/store/src/lang/formula.ts:375

formula function

function formula<R extends Roots, M extends Mode>(ctx: Site<R, M>, result: FormulaResult): (text: string) => string | undefined

A value validator for stored formula text (a custom field's validate, a transform refusal): the error or undefined.

Parameters

NameTypeDescription
ctxSite<R, M>
  • roots: R
  • numbers: M
  • read: Readers<M>

    Each result kind's reader in this mode, so a result carries its Out type.

resultFormulaResult

Source: packages/store/src/lang/formula.ts:420

decl

group function

function group<const S extends GroupSpec>(spec: S & Checked<GroupSpec, S, Exact<S, Omit<GroupSpec, "default_child"> & { default_child: ChildName<GroupName>; }>>): S

src/app/<g>/+group.ts: a folder of apps shown as one entry in the nav, opening default_child. A policy's capabilities.apps naming the group reaches every app under it.

Parameters

NameTypeDescription
specS & Checked<GroupSpec, S, Exact<S, Omit<GroupSpec, 'default_child'> & { default_child: ChildName<GroupName>; }>>
  • title: Schema.String
  • icon: Schema.String
  • default_child: Schema.String
  • description?: Schema.optionalKey<Schema.String>

Example

export default group({ title: 'HR', icon: 'lucide:briefcase-business', default_child: 'people' });

Source: packages/bolt/src/decl/runtime/app.ts:352

id_of function

function id_of<C extends TargetName>(model: C): Schema.declare<Id<C>>

The schema of one model's record id: decodes a non-empty string into Id<C>.

const id = Schema.decodeUnknownSync(id_of('employee'))(params.get('employee')); // Id<'employee'>

Parameters

NameTypeDescription
modelC

Source: packages/bolt/src/decl/id.ts:21

lang

input_schema function

function input_schema(spec: Kind): KindCodec

The codec of one kind literal, memoised per spec object: many holds a list of the kind's values, optional admits null. An input's fields decode as input_schema({ kind: 'object', fields }).

Parameters

NameTypeDescription
specKind

Source: packages/store/src/lang/kind.ts:760

decl

instance_id function

function instance_id<const D extends string>(definition: Is<D, IntegrationName>, instance: { readonly id: Id<"sys_integration">; readonly integration: string; }): InstanceId<D>

Checks the definition of a read integration instance before using its id in a definition-pinned ref (ctx.send, ctx.request, a notice's via), without a cast; throws RangeError for another definition's instance.

Parameters

NameTypeDescription
definitionIs<D, IntegrationName>
instance{ readonly id: Id<'sys_integration'>; readonly integration: string; }
  • id: Id<'sys_integration'>
  • integration: string

Example

const { sys_integration } = yield* ctx.query({ sys_integration: { where: { name: { eq: 'Hotline' } }, limit: 1 } });
yield* ctx.send(instance_id('whatsapp', sys_integration.rows[0]), { to, text });

Source: packages/bolt/src/decl/runtime/integration.ts:57

integration function

function integration<const N extends IntegrationName, const S extends IntegrationLiteral<N>>(name: N, spec: IntegrationLiteralInput<N, S>): Integration<N, S>

src/integration/<name>/+integration.ts: one external system's connection: its driver, configuration, credential, OAuth client, HTTP base and auth, webhook verification and handler, and request rate, with an optional test body run when an instance is paired. Its durable instances (connections) are runtime sys_integration rows made by people or the agent; source never declares one, and a release neither provisions nor deletes them. Each row's configuration is decoded with its defaults on every write; its credential is collected masked at pairing and sealed host-side, never entering a guest or the browser. What it exchanges is declared on models: sync('<model>', '<sync>', { with: '<name>', read?, write? }) in the model's +<sync>.sync.ts. name must equal the folder name. The definition carries no provider protocol: conversation platforms are the host's providers, which a workspace cannot supply.

@returns Declaration metadata and its attached pairing-test body.

Parameters

NameTypeDescription
nameN

The integration's name: its folder.

specIntegrationLiteralInput<N, S>

Driver, configuration, credentials and the optional pairing test.

  • description: Schema.String
  • driver: Schema.Union<readonly [Schema.Literals<("email" | "http" | "calendar" | "chat" | "sqlserver")[]>, Schema.Struct<{ readonly read: Schema.Literals<readonly ["cursor", "deliveries", "items"]>; readonly request: Schema.optionalKey<Schema.Literals<readonly ["http", "database"]>>; readonly call: Schema.optionalKey<Schema.Literal<"http">>; readonly credential: Schema.optionalKey<Schema.Literal<true>>; r…
  • configuration?: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Codec<import("@norbital-ai/ui").Kind, import("@norbital-ai/ui").Kind, never, never>>>

    Safe settings each instance edits at run time (with history), decoded against these fields.

  • credential?: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Codec<import("@norbital-ai/ui").Kind, import("@norbital-ai/ui").Kind, never, never>>>

    The secret each instance pairs with, sealed host-side and never readable (http and sqlserver only).

  • oauth?: Schema.optionalKey<Schema.Struct<{ readonly client: Schema.String; readonly secret: Schema.String; readonly authorize: Schema.optionalKey<Schema.String>; readonly token: Schema.optionalKey<Schema.String>; readonly scopes: Schema.optionalKey<Schema.$Array<Schema.String>>; }>>

    The OAuth client an oauth driver (http, calendar) grants with, by secret name; tokens are per instance. An http definition names its authorize and token endpoints too, and its requests carry the instance's token as a bearer.

  • http?: Schema.optionalKey<Schema.Struct<{ readonly base_url: Schema.String; readonly auth: Schema.optionalKey<Schema.Union<readonly [Schema.Struct<{ readonly bearer: Schema.String; }>, Schema.Struct<{ readonly header: Schema.Struct<{ readonly name: Schema.String; readonly value: Schema.String; }>; }>, Schema.Struct<{ readonly basic: Schema.Struct<{ readonly user: Schema.String; readonly password: Schema…

    http only: the base URL (a literal or a text configuration field), how requests authenticate and, with allow, the only requests an instance sends: these methods on these paths under the base ({name} one segment, a final ** any rest). Anything else is refused before its credential is read.

  • rate?: Schema.optionalKey<Schema.String>

    At most this many requests through one instance ('10/s', '600/min'): every sync read, write and ctx.request waits its turn; a 429 with Retry-After is honoured on top. Request drivers only.

  • webhook?: Omit<WebhookSpec, 'handle'> & { handle?: WebhookBody<N>; }
  • test?: TestBody<N>

Example

import { integration } from '@norbital-ai/bolt';
export default integration('crm', {
	description: 'The CRM account.',
	driver: 'http',
	http: { base_url: 'https://api.crm.example', auth: { bearer: 'api_key' } },
	credential: { api_key: { kind: 'text', label: 'API key' }, signing_secret: { kind: 'text', label: 'Webhook signing secret' } },
	webhook: {
		verify: { scheme: 'standard', secret: 'signing_secret' },
		policies: ['crm_inbound'],
		handle: function* (request, ctx) {
			yield* ctx.act({ 'leads.import': { rows: [{ ref: String(request.headers['webhook-id']) }], on_conflict: 'keep' } });
			return { status: 202 };
		}
	},
	rate: '10/s',
	test: function* (ctx) {
		yield* ctx.request({ method: 'GET', path: '/me', output: { kind: 'json' } });
	}
});

Source: packages/bolt/src/decl/runtime/integration.ts:558

is_instance function

function is_instance<const D extends string>(definition: Is<D, IntegrationName>, instance: { readonly id: Id<"sys_integration">; readonly integration: string; }): instance is { readonly id: InstanceId<D>; readonly integration: D; }

Narrows a read instance and its id by its declared integration definition.

Parameters

NameTypeDescription
definitionIs<D, IntegrationName>
instance{ readonly id: Id<'sys_integration'>; readonly integration: string; }
  • id: Id<'sys_integration'>
  • integration: string

Source: packages/bolt/src/decl/runtime/integration.ts:66

mcp function

function mcp<const S extends McpBase>(spec: S & Checked<McpBase, S, Exact<S, McpSpec>>): S

src/agent/mcp/+<n>.mcp.ts: an MCP server the agent may call, its url and credentials named from +secrets.ts, and an optional tool allowlist. Reachable only through a policy's capabilities.mcp. Declare the names, merge the change to live, then an administrator's agent calls page { path, configure: { capability: 'mcp.configure', record: '<n>' } } (its path from describe_workspace { names: ['system'] }) to open the native MCP settings; each secret opens the write-only form. Its tools are offered as <n>__<tool> (in a conversation begun earlier, through run_tool); a tool name outside [A-Za-z0-9_-], a server name with a double or trailing underscore, or a pair past 64 characters is offered as its readable start and a 12-hex digest of the pair. A tool whose name a native, host or other MCP tool also takes is not offered.

Parameters

NameTypeDescription
specS & Checked<McpBase, S, Exact<S, McpSpec>>
  • description: string
  • url: string

    The secret name holding the server's streamable-HTTP URL.

  • auth?: { bearer: string; } | { oauth: { client_id: string; client_secret?: string; scopes?: readonly string[]; }; }

    A bearer token or OAuth client, by secret name.

  • tools?: readonly string[]

    An allowlist of the server's tools; absent = every tool it lists.

Example

export default mcp({ description: 'HQ tools', url: 'HQ_URL', auth: { bearer: 'HQ_TOKEN' } });

Source: packages/bolt/src/decl/runtime/agent.ts:40

messages function

function messages<const M extends { readonly [key: string]: string; }>(spec: M): M

src/i18n/+messages.ts (the base catalogue) and src/i18n/+<locale>.messages.ts: message keys to text with {name} placeholders. A locale mirrors the base's keys (checked by Verify), except native model captions (models.<model>.label|singular|fields.<field>…), which it may translate alone: the base humanizes the declared name. Every locale ships, and the viewer's choice selects one at boot; pages read it with bolt.t.

Parameters

NameTypeDescription
specM

Example

export default messages({ 'app.crm.title': 'CRM', 'jobs.assigned': 'Assigned to {name}' });

Source: packages/bolt/src/decl/runtime/app.ts:371

model function

function model<const K extends string, const S extends ModelLiteral>(name: K, spec: ModelLiteralInput<K, S>): Model<K, S>

src/data/model/<name>/+model.ts: one entity. Its storage (fields, ref fields that relate it to other models, keys, constraints, computed fields (a CEL string over its own fields) and indexes), its exposure (outputs; create, update and delete with their field trees, transforms and effects); each sync is its own +<sync>.sync.ts beside it. Every callback sits on what triggers it, inside the literal, and is typed by the model's name. Until the next sync a body does not see a field just added. Model folders may nest under other models or grouping folders; the leaf folder names the model, unique across the workspace, and must equal name; its +representation.svelte (receiving RecordView<'<name>'>) sits beside it. Declaring an exposure makes the operation available; policies still decide which callers and rows may use it. The writes are the guarded create, update, delete and, with an import_key constraint, import; a model has no named queries or actions (a computed answer is a read request plus a pure src/lib helper; a business operation is an automation, and a page's request/response to server code is a call automation). Raw SQL is privileged: native constraints and history apply, policies and callbacks do not. Native surfaces derive from this one declaration: Table and Form render the permitted columns and defaults, a declared file sync adds Import/Export/Template to the toolbar, record history is automatic, effects receive write and approval events, and a policy verdict returning ctx.approve holds the write for its flow. Pages and agents must not wire those again.

@returns Declaration metadata and attached callback bodies. Calling model does not read or write records.

Parameters

NameTypeDescription
nameK

The model's name: its leaf folder.

specModelLiteralInput<K, S>

Storage, read outputs, guarded write layers and their callbacks.

  • description: Schema.String
  • was?: Schema.optionalKey<Schema.String>
  • icon?: Schema.optionalKey<Schema.String>
  • record_label?: Schema.optionalKey<Schema.String>
  • fields: { readonly [name: string]: Exclude<FieldKind, { kind: 'ref'; }> | RefField | ComputedField; }

    The stored fields, ref fields included. Every row also carries the system columns (see ModelSpec.fields).

  • constraints?: Readonly<Record<string, Constraint>>

    Named rules, enforced natively on every write path: unique (one may be the import_key that enables the import verb), check, no_overlap of a period per key, and locked. A locked predicate makes a matching row read-only: update and delete are refused and the record page shows a lock; except names fields every matching lock still lets through. Each takes an optional message (a catalogue key without placeholders) a violation refuses with, naming the field when the rule has one column; changing it needs no migration. Do not repeat these in a transform.

    constraints: { placed: { locked: { status: { eq: 'placed' } }, except: ['notes'] } }
  • indexes?: Readonly<Record<string, IndexLiteral>>

    Named indexes: physical ({ on }), text ({ text }, fields matched beside record_label), { semantic } and custom vector indexes (pure vector, probe, optional rerank; the engine computes the vector on every committed write, keeps it in a hidden HNSW column, and null leaves a row out; a vector that needs I/O is an ordinary vector field an automation fills, named as vector: '<field>'). Search one with query({ m: { search: { <index>: input } } }); rows carry $distance and the output and grants still apply. Each also appears as a toolbar search mode.

  • outputs?: { readonly default: ReadOutput; readonly [output: string]: ReadOutput; }

    A default read output and optional named outputs: each lists fields (or 'all') and nests one projection per relation it exposes. A read names one output (default when absent); a policy grants outputs and filters their rows, never their fields. A model without outputs still stores rows and may appear in another model's output tree.

  • create?: WriteVerb & { filled?: ColumnTree; }

    The generated create: a write tree like an output's (fields, then one nested tree per child relation) beside filled (the fields its transform fills when omitted, in the same tree), transform and effect; a relation cannot be named after one of those. A layer below the root is a many-relation (the child rows) and never lists the key to its parent; a non-owned child may also be an existing { id, revision }, which links it.

    create: { fields: ['customer', 'notes'], lines: { fields: ['product', 'qty'] } }
  • update?: WriteVerb

    The generated update: the fields a writer changes in the same tree (child layers take create, update, delete, link, unlink), beside transform and effect.

  • delete?: { transform?: GeneratorBody; effect?: GeneratorBody; }

    The generated delete, its transform and its optional post-commit effect.

Example

import { model } from '@norbital-ai/bolt';
export default model('orders', {
	description: 'Customer orders.',
	record_label: 'record.number',
	fields: {
		number: { kind: 'seq', pattern: 'SO-{yyyy}-{0000}' },
		customer: { kind: 'ref', to: 'customers', inverse: 'orders' },
		notes: { kind: 'text', optional: true }
	},
	outputs: { default: { fields: 'all', customer: { fields: ['name'] } } },
	create: {
		fields: ['customer', 'notes'],
		transform: function* (changes, ctx) {
			const { customers } = yield* ctx.query({ customers: { where: { id: { in: changes.map((c) => c.after.customer) } }, fields: ['id', 'blocked'], limit: changes.length } });
			const blocked = new Set(customers.rows.filter((c) => c.blocked).map((c) => c.id));
			const row = changes.findIndex((c) => blocked.has(c.after.customer));
			if (row >= 0) return yield* ctx.refuse('errors.customer_blocked', { row, field: 'customer' });
			return changes.map((c) => c.set);
		}
	}
});

Source: packages/bolt/src/decl/model.ts:801

new_id function

function new_id<C extends TargetName>(model: C): Id<C>

A fresh uuidv7 for a row of model the caller creates: a created root carrying it can be named by a later act in the same act map, which then commits both together. A run mints the same ids on every attempt.

const loan = new_id('loans');
yield* ctx.act({ 'loans.create': [{ id: loan, amount }], 'loan_repayments.create': [{ loan, due_on }] });

Parameters

NameTypeDescription
modelC

Source: packages/bolt/src/decl/id.ts:35

policy function

function policy<const P extends PolicyBase>(spec: P & NoInfer<Checked<PolicyBase, P, Exact<P, PolicyFor<keyof Grants<P> & Grantable>>>>): P

src/access_control/policy/+<name>.policy.ts: what holders may do: per-model grants (the read outputs they read — the default and named outputs and a row filter per layer of each, and create, update and delete with the fields they admit per layer and a verdict returning allow or approve, or refusing), the automations they may start, remote syncs they may refresh and capabilities (apps, host tools, MCP servers). A model's policy guards every caller request at its access points and every layer under them; rows a write callback carries (with, on_approved, owned children) are admitted by the root write's grant, while native constraints, locks and state rules still apply. Teams, envoys and automations hold policies; rate limits per policy are declared in +workspace.ts (limits). approve(flow) is the whole approval mechanism: the write is held as a native approval request, the named step approvers decide it in the record's approval panel, and a rejection restores the checkpoint. A page needs no separate approval control. The model's verb effects receive the write and approval events. Returns the literal.

Parameters

NameTypeDescription
specP & NoInfer<Checked<PolicyBase, P, Exact<P, PolicyFor<keyof Grants<P> & Grantable>>>>
  • description: string

    What holding the policy is for, for people and the agent.

  • grants: { readonly [model: string]: object; } & VerdictSlots

    Per model, the granted outputs and their scopes and history, and the admitted model verbs.

  • capabilities?: { readonly [k: string]: readonly string[]; }

    The apps, manual starts, host tools and MCP servers holders may use; every agent skill is open to all.

Example

export default policy({
	description: 'Contractors raise variations on their own jobs.',
	grants: {
		variation_requests: {
			outputs: { default: { where: { raised_by: { eq: { var: 'actor.id' } } } } },
			create: {
				fields: ['job_assignment_id', 'title', 'amount'],
				verdict: function* (rows, ctx) {
					const { job_assignments } = yield* ctx.query({
						job_assignments: {
							where: { id: { in: rows.map((r) => r.after.job_assignment_id) } },
							fields: ['assignee_user_id', 'controller_team']
						}
					});
					const [job] = job_assignments.rows;
					const mine = job_assignments.rows.every((j) => j.assignee_user_id === ctx.actor.id);
					return mine && job !== undefined
						? ctx.approve({ steps: [{ name: 'Controller review', teams: [job.controller_team] }] })
						: yield* ctx.refuse('errors.own_jobs_only', { field: 'job_assignment_id' });
				}
			}
		}
	},
	capabilities: { apps: ['field_ops'] }
});

Source: packages/bolt/src/decl/access/policy.ts:274

secrets function

function secrets<const E extends Record<string, SecretDecl>>(spec: E & Exact<E, { [N in keyof E]: N extends Uppercase<N & string> ? SecretDecl : "error: secret names are UPPER_SNAKE"; }>): E

Declares secret names and their Settings labels in src/+secrets.ts. This is metadata, never a place for values. Administrators supply values at runtime; the host seals them in the tenant store. Refer to a declared name when configuring an integration or MCP connection rather than copying its value into source or browser code. Once the declaration is live, page { configure: { capability: 'secret.set', record: '<NAME>' } } in a web conversation opens the native write-only form; the value is never read back or sent through chat.

@returns The declaration unchanged; declaring a name neither supplies nor verifies its runtime value.

Parameters

NameTypeDescription
specE & Exact<E, { [N in keyof E]: N extends Uppercase<N & string> ? SecretDecl : 'error: secret names are UPPER_SNAKE'; }>

UPPER_SNAKE names with labels and optional help text.

Example

export default secrets({ SERVICE_TOKEN: { label: 'Service token', description: 'Pair in Settings.' } });

Source: packages/bolt/src/decl/runtime/app.ts:24

seeder function

function seeder(definition: Seeder): Seeder

seed/+seeder.ts's default export: names the bank tree a template's private rows live in.

A template's rows come from three places. Public rows (seed/public/**) ship in the release's base pack and reach every environment's provision and reset. Test rows (seed/test/**) are synthetic fixtures for the template's own bolt test, never published. Private rows live in a bank tree and reach one environment only through bolt seed. Without a seeder a template has only its public and test rows.

seed/ holds only +seeder.ts, public/ and test/: **\/<model>.json[.gz] row files (the file name is the model; a directory groups files or names a test scenario) and assets.json ([{ path, sha256, bytes, content_type }]) with its assets/** bytes; anything else is a seed-layout diagnostic. Each row carries its id and stored fields in wire form (decimals as numbers, numeric text or { "$dec" }; dates, instants and ids as text) and loads as stored. Identity rows are sys_team, sys_user (team is the id of a sys_team row of the same pack) and unnamed sys_integration instances.

bolt check loads the seeder (seed/seeder) and decodes every public and test row (seed/decode). A row value declaring $schema is a JSON Schema whose datatypes are checked (seed/datatype): a non-string format must name one of DATATYPE_SHAPES and a property naming one must have exactly its shape.

Parameters

NameTypeDescription
definitionSeeder
  • bank?: { /** The bank tree's name: its own axis, not the workspace handle. */ readonly tree: string; /** Automations queued once with the rows when they load. */ readonly start?: readonly AutomationName[]; }

    The private rows bolt seed reads, in memory, from <bank>/<tree>/rows/** (<model>.json[.gz] files) into one demo environment; a file value names a path relative to <bank>/<tree>/ unless seed/public/assets.json carries it. Private rows never enter a release, a host's disk or a template checkout.

Example

export default seeder({ bank: { tree: 'example', start: ['recompute_balances'] } });

Source: packages/bolt/src/decl/seeder.ts:43

sync function

function sync<const M extends string, const S extends string, const X extends SyncShape>(model: M, name: S, spec: X & NoInfer<Checked<SyncLiteral, X, Exact<X, SyncFor<X>>>> & NoInfer<FileSync<M, S> | RemoteSync<M, S>>): Sync<M, S, X>

src/data/model/<…>/<model>/+<sync>.sync.ts, beside its model's +model.ts: how that model's rows are exchanged with a file (with: 'file': the native Import, Download template and Export toolbar actions from its parser/read/write) or with another system through integration with (runs on every). model must be the leaf folder's name and name the file's. A file's rows enter as the member importing; a remote sync's pages are written as the reserved system identity holding its policies, never as admin. context is input, never authority; only returned source fields change. Run by ctx.sync, a native control or the sync's schedule, never by a page script.

@returns Declaration metadata and attached bodies. Calling sync does not read or write records.

Parameters

NameTypeDescription
modelM

The model's name: its leaf folder.

nameS

The sync's name: its file.

specX & NoInfer<Checked<SyncLiteral, X, Exact<X, SyncFor<X>>>> & NoInfer<FileSync<M, S> | RemoteSync<M, S>>

FileSync or RemoteSync.

  • policies?: readonly string[]
  • with: string
  • schema?: InputFields
  • context?: InputFields
  • every?: string
  • partitions?: string
  • parser?: readonly (string | { type: string; extensions: readonly string[]; parse: unknown; })[]
  • read?: unknown
  • write?: unknown

Source: packages/bolt/src/decl/runtime/sync.ts:419

workspace function

function workspace<const S extends WorkspaceBase>(spec: S & Checked<WorkspaceBase, S, Exact<S, WorkspaceFor>>): S

src/+workspace.ts, exactly one: timezone, locale, app order, workspace capabilities and rate limits per policy. Declarations are found by path and named by it; each takes one literal (model and integration first repeat their name, which must match the path), and every callback sits inside the declaration that invokes it. bolt sync (run by bolt dev on save and first by bolt check) writes their data shapes into the generated, never-edited .norbital/. text src/+workspace.ts, +secrets.ts src/data/model/<name>/+model.ts, +representation.svelte (folders may nest; the leaf names the model) src/data/custom_field/<name>/+custom_field.ts, +renderer.svelte src/access_control/policy/+<name>.policy.ts src/integration/<name>/+integration.ts, +integration.svelte src/automation/+<name>.automation.ts src/agent/+agent.md, +agent.external.md, skill/<name>/+skill.md, mcp/+<name>.mcp.ts src/app/, src/i18n/+messages.ts, src/lib/ (ordinary helpers) seed/ (public/ ships in the release, test/ serves bolt test, +seeder.ts) migrations/ (generated, editable SQL and its proofs), tests/ theme configures the look and feel of every application, the shell and public pages. Start with the high-level presets — palette ('warm' | 'neutral' | 'crisp'), accent (preset name or '#rrggbb' hex with automatic light/dark contrast foregrounds) and radius ('sharp' | 'default' | 'soft') — and layer optional light and dark token overrides on top; omitted tokens retain Bolt's defaults. Semantic tokens (surface-*, content-*, border-*, tone-*), primary/accent/brand, sidebar and chart tokens use CSS variable names without --. Fonts use installed/bundled font stacks; this declaration never downloads a font or stylesheet. Changes go through the workspace's normal preview and release.

@returns The typed declaration unchanged. Compilation validates its references against this workspace's names.

Parameters

NameTypeDescription
specS & Checked<WorkspaceBase, S, Exact<S, WorkspaceFor>>

Workspace settings; integration accounts and credentials are created at runtime.

  • theme?: WorkspaceTheme

    Shared light/dark token overrides; omitted tokens keep Bolt’s defaults. See WorkspaceTheme.

  • tz: IanaZone

    The workspace's IANA zone: today, date defaults and document numbers are read in it.

  • locale: string

    The default locale tag.

  • languages?: readonly string[]

    Languages the workspace is authored and translated into (BCP-47 tags; default ['en']). English ('en') is always the workspace basis.

  • currency?: CurrencyCode

    The default currency of money fields that name none.

  • apps?: readonly string[]

    App order in the launcher.

  • landing?: { app: string; single_app?: true; }

    On the member home route, open the preferred granted app, or optionally the only granted app of a non-admin.

  • navigation_visibility?: NavigationVisibility<string, string>
  • ai?: { embeddings?: readonly string[]; }

    Requires AI facilities and declares embedding models. Allowed chat models and monthly USD caps (workspace, default member, per policy) are runtime settings in sys_config under agent, applied at the next step; an empty allowed list permits the host catalogue, else its first model is the fallback. limits.<policy>.agent still limits rate.

  • convert?: { to: readonly ConvertTarget[]; }

    The document formats Markdown or HTML converts to (ctx.convert.document, notice attachments, a file sync's document export); the host must serve each. A declared target the host does not serve is a check warning and fails Unavailable when used.

  • csp?: { connect?: readonly `https://${string}`[]; }

    Origins pages may connect to beyond the workspace.

  • agent?: { triage?: false; }

    triage: false turns off System 1 triage of the in-app agent.

  • signup?: Signup

    Who may join without an invitation; absent, only invited members join.

  • memberships?: Memberships<string>

    Optional supplementary teams for staff, on a protected workspace model with a member ref to sys_user, a team ref to sys_team and a nullable date until (the last inclusive day in the workspace zone). Direct member writes are disallowed; an administrator or a guarded automation issues or revokes grants. Existing sessions see changes on the next request. Bundles optionally join assignments (member, role, until) to levels (role, team).

  • limits?: { readonly [policy: string]: { readonly [key: string]: unknown; }; }

    Rate limits per policy, applied to every caller holding it.

Example

export default workspace({ tz: 'Asia/Singapore', locale: 'en-SG', apps: ['crm'] });

Example

export default workspace({
  tz: 'Asia/Singapore', locale: 'en-SG',
  theme: {
    palette: 'crisp',
    accent: '#1467a6',
    radius: 'default',
    light: { 'font-sans': 'Inter, system-ui, sans-serif' }
  }
});

Source: packages/bolt/src/decl/runtime/app.ts:215