@sema-agent/core
Version:
Stateless, task-oriented AI agent core
362 lines (361 loc) • 21.5 kB
TypeScript
/**
* The mods kernel's closed vocabulary: tiers, seats, sides, the `next.to` allow table, the seat × tier
* table, and the ONE event table every other rule reads (which events exist, which side's bus raises
* them, and — for the ones a station raises — the failure, abort and pinned-key columns).
*
* Zero-dependency on purpose: this folder is compiled on its own into `@sema-agent/mods-kernel`, so the
* engine and the shell run the same rules. It imports nothing outside the folder.
*/
/**
* The kernel CONTRACT number — a monotonic integer, independent of the package version (the package is
* cut with core every release; this number is not). It is exported for a host that loads a kernel copy
* beside another one to compare for EQUALITY; no rule in this folder reads it, and the engine reads it in one place only
* (`loadModPackage` refuses a mod package that states another number), so two copies that differ are not detected here.
* It is raised when, and only when, one of four things changes —
* once per release, however many of them change in it:
* the chain semantics (`next`, `next.to`, origin, trace, re-entry frames, what a `$` call reaches — a method's
* chain or a callable event's host entry — what a dispatch records of its run, how answers are received and which
* seat's answer may stand over which), the registration form (`ModRegistration`, `on`, `uses` and which names a side
* takes in it), the event closed set (names and their `side`), or the failure columns (failure, abort, pinned keys,
* an event's own budget ceiling, whether `$` may call it — which keys, and how a pinned key is judged: by value since 2).
* A column that no rule of the kernel judges by is none of the four and does not raise it: admission, the chain, the failure
* law and the budget never read the table's `env` column (added without a raise in 7.69.0) — the engine alone reads it, through
* `envReach` and `seatsReachEnv`, neither exported from the package, to tell whether a leg needs an execution environment.
* What decides it is who reads the column, not whether it is optional: `budgetMs` and `call` are optional columns too, but they
* are failure columns (listed above), judged by the dispatch, and changing them raised it.
* 3: the shell's events have stations, the event-level budget and `call` columns, a `$` call of a callable event
* reaches the host's entry, the dispatch records whether its bottom started, a re-entered guard with no `.catch`
* refuses, the one side lock over `uses` and `on`, answers received as data, the seat-trust law, `prompt.mention`
* on the engine's side, and `tool.call` with the `refuse_until_run` failure answer, callable.
* 4: a station may judge what a handler hands on (the dispatch's `checkHandOn`: its sentence is the handler's violation, as a
* changed pinned key is), `tool.call` takes one member more than its own — `requestMeta`, a record of strings, judged there —
* and an admission record carries the registration's `provenance` as the host gave it and lists in `observe` only the patterns
* on which every handler it hung watches.
* 5: `classic.SubagentStart` has a station (a delegated leg's opening event).
* 6: `agent.offer` (a listed or named agent type, before the model is offered it), `agent.spawn` (a delegation the gate let
* go, before its subagent starts — every argument pinned, a refusal its only answer), `turn.complete` (a model turn ended)
* and `session.end` (a leg ended) have stations; `tool.call`'s failure column is `refuse` — a failure once the body has
* started withholds the result (under `refuse_until_run`, its column until 5, the result stood).
* 7: `session.receive` (a frame arriving for the model), `session.append` (a row entering the conversation), `session.send` (a
* message the leg sends) and `session.compact` (a compaction about to run) have stations; `agent.spawn` has a `call` column,
* and so do `session.append`, `session.send` and `session.compact` — a `$` call of each reaches the host's entry.
* 8: the closed set is the reference's 145 names (`session.identity`, `ui.view`, `prompt.change` named, not raised);
* `session.start` (a leg opened), `session.measure` (the leg's context occupancy moved), `turn.start` (a model turn began),
* `prompt.submit` (a person's input entering the leg — rewritable, droppable, refused on a failure), `classic.SessionStart` and
* `classic.SessionEnd` have stations, the two classic ones raised in the bottoms of `session.start` and `session.end`; the
* methods `session.turns`, `session.usage` and `session.version` have bottoms, and `session.messages` takes `{ agentId }`.
* 9: `prompt.submit` has a `call` column — a `$` call reaches the host's entry, an extension's input entering the leg under the
* author `extension` — and pins `author` and `extension`; a handler's frame names the event it runs on (`ModFrame.event`).
* 10: `prompt.submit` takes a third answer, `{ reply }` — the input enters and the turn it opens is answered without a model
* request — where the entrance takes one, and pins `replyable` (the entrance's word for that); its ranks are text < reply < drop.
* `classic.MessageDisplay` has a station (an assistant message's displayed text, window by window, on a top-level leg — a handler
* that fails is skipped and said, the window shows what the handlers that answered left of it; every handler's ceiling on it
* 10 s). A cancelled dispatch records its run as an answered or a failed one does: the handlers skipped before the cancel, and
* the answer the highest handler whose `next` had answered was handed, with its producer.
* The method `turn.abort` has a bottom (it ends the caller's leg's running model turn, not pausing the caller's budget). The methods `clock.after` and `clock.every` have bottoms
* and are timers (the `method` column's `timer`): `$` hands back a handle at once and each tick is one dispatch of the event
* under the registration's own `$` frame and the timer's own signal; a `$` call made after its handler settled is made under
* that same frame and the bus's lifetime (`ModBusInput.lifetime`), and is refused once the lifetime ends.
* `classic.Stop` / `classic.SubagentStop` take `{ end }`, and each seat is judged in its own pass (task, then deployment): a
* handler's `next` reaches its own seat and the engine's bottom.
* 11: `tool.call`'s failure column is `refuse_until_run` again — a handler that fails once its own `next` ran the tool's body is
* skipped and its last `next()` run's result stands — and its station takes a `{ deny }` given over what that `next` answered
* once the body ran: the call ran and its result is withheld.
* 12: `classic.TaskCreated`, `classic.TaskCompleted` and `classic.TeammateIdle` have stations (the stop events' columns and answer
* form: a task-list write a `block` undoes or fails, and a named teammate's stop point).
* 13: the closed set is 151 names (+`theme.set`, `theme.clear`, `ui.place`, `ui.cancelNotify`, `prompt.paint`, `decision.ask`);
* the eleven named surface methods have `method(true)` stations; `ui.message` and `ui.fault` have `ownerOnly` surface stations,
* `closed` (what is handed on keeps the event's members) and with `answers` (`{ props }` on `ui.message`, none on `ui.fault`).
*/
export declare const KERNEL_CONTRACT_VERSION = 13;
/** The five tiers in run order (CC names). `builtin` and `core` are the engine's own. */
export declare const MOD_TIERS: readonly ["prepend", "user", "append", "builtin", "core"];
export type ModTier = (typeof MOD_TIERS)[number];
/** The tiers a registration may stand in. */
export type ModRegistrationTier = Exclude<ModTier, "builtin" | "core">;
/** Where a registration came from: the deployment's deps or the task's spec — listed most trusted first. */
export declare const MOD_SEATS: readonly ["deployment", "task"];
export type ModSeat = (typeof MOD_SEATS)[number];
/** Which bus raises an event: the engine's, the shell's, or each its own. */
export declare const MOD_EVENT_SIDES: readonly ["engine", "surface", "both"];
export type ModEventSide = (typeof MOD_EVENT_SIDES)[number];
/** A bus is one side. */
export type ModBusSide = Exclude<ModEventSide, "both">;
/**
* What a handler's failure means for the dispatch: the station's refusal (final); skip the handler; or — on an event whose
* bottom, once started, is what stands (`agent.spawn`: the subagent is let start; `tool.call`: the tool ran) — the refusal
* while the bottom has not started and, once the handler's own `next` has started it, the handler is skipped and its last
* `next()` run's answer stands (the failure is reported beside it). A `refuse` station refuses whether or not its bottom has
* started; the dispatch's `failed` outcome says when it had.
*/
export declare const MOD_FAILURE_ANSWERS: readonly ["refuse", "skip", "refuse_until_run"];
export type ModFailureAnswer = (typeof MOD_FAILURE_ANSWERS)[number];
/** Whether a failure column refuses: the events a station judges on (or runs an effect behind) fail closed. */
export declare function failureRefuses(failure: ModFailureAnswer): boolean;
/** What a cancel does to a dispatch: end it now, give it one second, or follow the calling handler. */
export declare const MOD_ABORT_POSTURES: readonly ["immediate", "grace", "caller"];
export type ModAbortPosture = (typeof MOD_ABORT_POSTURES)[number];
/** `next.to(e, to)` from a handler in tier `from` is allowed iff `to` is in `NEXT_TO_TABLE[from]` (CC `pvt`). */
export declare const NEXT_TO_TABLE: Readonly<{
prepend: readonly ["append", "builtin", "core"];
user: readonly [];
append: readonly ["core"];
builtin: readonly [];
core: readonly [];
}>;
/** Why `next.to(e, to)` from `from` is refused, or undefined when the table allows it. */
export declare function nextToRefusal(from: ModTier, to: unknown): string | undefined;
/** Which tiers each seat may declare, and whether it must declare one (absent ⇒ the first listed). */
export declare const SEAT_TIER_TABLE: Readonly<{
deployment: Readonly<{
declared: "required";
tiers: readonly ["prepend", "user", "append"];
}>;
task: Readonly<{
declared: "optional";
tiers: readonly ["user"];
}>;
}>;
/**
* The station columns of an event a bus raises. `method` marks a `$` method (the event a `$` call raises; its chain
* bottom is the host's seat). `call` marks an event `$` may call: the call goes to the host's entry for the event,
* which runs whatever stands before it and raises it once at its own station. A row is a method, a callable event, or
* neither — never both.
*/
export interface ModStation {
readonly failure: ModFailureAnswer;
readonly abort: ModAbortPosture;
/** Keys a handler may not change when it passes `e` on through `next` — compared by value: the engine's fact handed on,
* or a copy of it (a spread, a structured clone, a JSON round trip), is not a change; a different value is. */
readonly pinned: readonly string[];
/** `timer`: the method is a timer — its `$` member hands back a cancellable handle at once, and each tick is one dispatch
* of the event (its bottom waits the interval) that runs the caller's callback when it answers; `repeats` once or on. */
readonly method?: {
readonly pausesCallerBudget: boolean;
readonly timer?: {
readonly repeats: boolean;
};
};
/** Where the station reaches the leg's execution environment: `bottom` — a method whose bottom runs on it (a registration
* that declares it in `uses.calls` makes its leg need one); `payload` — an event whose payload states what the environment
* holds, the working directory the leg stands in (a registration that subscribes to it in `uses.events` makes its leg need
* one); `face` — a tool-call event whose payload hands its handlers the environment's face, `e.env`: raised only around a
* call, so a subscription to it makes a leg need one when the leg can call a tool. */
readonly env?: "bottom" | "payload" | "face";
readonly call?: {
readonly pausesCallerBudget: boolean;
};
/** The event's own ceiling on a handler's time: every clock a handler runs under on this event (its body, its
* `.catch`, an observer) is the smaller of its own and this — a registration's budget never widens it. */
readonly budgetMs?: number;
/** Dispatched only to the plugin named in `options.owner` (omitting `owner` rejects). */
readonly ownerOnly?: true;
/** What a handler hands on carries the event's own members, none added or dropped: with `pinned`, the rest is all it changes. */
readonly closed?: true;
/** The members an answer of a handler's own (not what its `next` answered) may carry: a record of these alone; `[]` — it
* answers only what its `next` answered. Absent ⇒ the raiser's check reads it. */
readonly answers?: readonly string[];
}
/** One event: its side, and its station when a bus raises it in this version (absent ⇒ named, not raised). */
export interface ModEventRow {
readonly side: ModEventSide;
readonly station?: ModStation;
}
/**
* Every event the kernel knows: the reference's closed set of 151 names (CC 2.1.321 `hFe` (cli321.js:276613) — its 33 `classic.*` names,
* its 47 events and its 71 `$` methods). The shell's names (`ui.*`, `theme.*`, `command.*`, `config.*`, `audio.*`,
* the prompt-box events and `prompt.read` / `prompt.paint`) carry `side: "surface"`: one table serves both buses,
* and the shell's stations are its rows here, raised by the shell where their chain bottoms are. A row with a
* station is raised on its side in this version; a name with none is named, not raised, and a registration that
* selects only such names is refused.
*/
export declare const MOD_EVENT_TABLE: Readonly<{
"classic.PreToolUse": ModEventRow;
"classic.PostToolUse": ModEventRow;
"classic.PostToolUseFailure": ModEventRow;
"classic.PostToolBatch": ModEventRow;
"classic.Notification": ModEventRow;
"classic.UserPromptSubmit": ModEventRow;
"classic.UserPromptExpansion": ModEventRow;
"classic.SessionStart": ModEventRow;
"classic.SessionEnd": ModEventRow;
"classic.Stop": ModEventRow;
"classic.StopFailure": ModEventRow;
"classic.SubagentStart": ModEventRow;
"classic.SubagentStop": ModEventRow;
"classic.PreCompact": ModEventRow;
"classic.PostCompact": ModEventRow;
"classic.PreModelSwitch": ModEventRow;
"classic.PostModelSwitch": ModEventRow;
"classic.PermissionRequest": ModEventRow;
"classic.PermissionDenied": ModEventRow;
"classic.Setup": ModEventRow;
"classic.TeammateIdle": ModEventRow;
"classic.TaskCreated": ModEventRow;
"classic.TaskCompleted": ModEventRow;
"classic.Elicitation": ModEventRow;
"classic.ElicitationResult": ModEventRow;
"classic.ConfigChange": ModEventRow;
"classic.WorktreeCreate": ModEventRow;
"classic.WorktreeRemove": ModEventRow;
"classic.InstructionsLoaded": ModEventRow;
"classic.CwdChanged": ModEventRow;
"classic.FileChanged": ModEventRow;
"classic.DirectoryAdded": ModEventRow;
"classic.MessageDisplay": ModEventRow;
"tool.call": ModEventRow;
"tool.check": ModEventRow;
"ui.render": ModEventRow;
"ui.resolve": ModEventRow;
"ui.press": ModEventRow;
"ui.input": ModEventRow;
"ui.select": ModEventRow;
"ui.message": ModEventRow;
"ui.fault": ModEventRow;
"ui.scroll": ModEventRow;
"ui.focus": ModEventRow;
"agent.offer": ModEventRow;
"agent.spawn": ModEventRow;
"prompt.submit": ModEventRow;
"prompt.fill": ModEventRow;
"prompt.suggest": ModEventRow;
"prompt.edit": ModEventRow;
"prompt.change": ModEventRow;
"prompt.autocomplete": ModEventRow;
"prompt.section": ModEventRow;
"prompt.context": ModEventRow;
"prompt.attachment": ModEventRow;
"prompt.mention": ModEventRow;
"prompt.compose": ModEventRow;
"tool.describe": ModEventRow;
"command.run": ModEventRow;
"command.describe": ModEventRow;
"config.set": ModEventRow;
"config.describe": ModEventRow;
"telemetry.log": ModEventRow;
"telemetry.mark": ModEventRow;
"skill.prompt": ModEventRow;
"attribution.text": ModEventRow;
"session.start": ModEventRow;
"session.receive": ModEventRow;
"session.append": ModEventRow;
"session.send": ModEventRow;
"session.compact": ModEventRow;
"session.attach": ModEventRow;
"session.detach": ModEventRow;
"session.measure": ModEventRow;
"session.end": ModEventRow;
"plugin.register": Readonly<{
side: "both";
station: ModStation;
}>;
"turn.start": ModEventRow;
"turn.step": ModEventRow;
"turn.complete": ModEventRow;
"engine.create": ModEventRow;
"model.complete": ModEventRow;
"model.classify": ModEventRow;
"model.fork": ModEventRow;
"audio.play": ModEventRow;
"audio.speak": ModEventRow;
"mcp.call": ModEventRow;
"mcp.connect": ModEventRow;
"session.cwd": ModEventRow;
"session.root": ModEventRow;
"session.model": ModEventRow;
"session.turns": ModEventRow;
"session.id": ModEventRow;
"session.messages": ModEventRow;
"session.repo": ModEventRow;
"session.surface": ModEventRow;
"session.surfaces": ModEventRow;
"session.authorize": ModEventRow;
"session.identity": ModEventRow;
"session.usage": ModEventRow;
"session.version": ModEventRow;
"turn.abort": ModEventRow;
"prompt.read": ModEventRow;
"prompt.paint": ModEventRow;
"flag.value": ModEventRow;
"tool.list": ModEventRow;
"tool.register": ModEventRow;
"command.list": ModEventRow;
"command.register": ModEventRow;
"config.list": ModEventRow;
"agent.list": ModEventRow;
"agent.register": ModEventRow;
"theme.set": ModEventRow;
"theme.clear": ModEventRow;
"decision.ask": ModEventRow;
"ui.toast": ModEventRow;
"ui.status": ModEventRow;
"ui.log": ModEventRow;
"ui.notice": ModEventRow;
"ui.invalidate": ModEventRow;
"ui.open": ModEventRow;
"ui.close": ModEventRow;
"ui.panes": ModEventRow;
"ui.place": ModEventRow;
"ui.selection": ModEventRow;
"ui.copy": ModEventRow;
"ui.view": ModEventRow;
"ui.notify": ModEventRow;
"ui.cancelNotify": ModEventRow;
"ui.blit": ModEventRow;
"fs.read": ModEventRow;
"fs.write": ModEventRow;
"fs.list": ModEventRow;
"fs.exists": ModEventRow;
"fs.stat": ModEventRow;
"fs.ancestors": ModEventRow;
"store.get": ModEventRow;
"store.set": ModEventRow;
"store.delete": ModEventRow;
"store.keys": ModEventRow;
"state.get": ModEventRow;
"state.set": ModEventRow;
"clock.now": ModEventRow;
"clock.sleep": ModEventRow;
"clock.after": ModEventRow;
"clock.every": ModEventRow;
"http.fetch": ModEventRow;
"process.run": ModEventRow;
"process.spawn": ModEventRow;
"settings.read": ModEventRow;
"env.get": ModEventRow;
"env.set": ModEventRow;
}>;
export type ModEventName = keyof typeof MOD_EVENT_TABLE;
export declare function isModEventName(name: unknown): name is ModEventName;
/** The row's station when a bus of `side` raises it; undefined otherwise. */
export declare function stationOn(name: ModEventName, side: ModBusSide): ModStation | undefined;
/** How a registration that names `name` in `uses.calls` (a method's bottom) or `uses.events` (an event's payload) reaches the
* leg's execution environment — the table's `env` column, read by the field the name was declared in: on any leg
* (`always`), only on a leg that can call a tool (`on_call`: a tool-call event is raised around a call), or not at all. */
export declare function envReach(name: ModEventName, field: "calls" | "events"): "always" | "on_call" | undefined;
/** The events whose payload hands their handlers the environment's face (`e.env`), read off the table's `env` column. */
export declare const MOD_EVENTS_HANDING_ENV: readonly ModEventName[];
/** Whether a bus of `side` reads `name` at all (its own side or both). */
export declare function readOnSide(name: ModEventName, side: ModBusSide): boolean;
/**
* The known names a pattern selects: an exact name, or `<prefix>.*` for every name under the prefix.
* A pattern that selects no known name is refused (a typo is not an empty declaration).
*/
export declare function expandModPattern(pattern: unknown): {
readonly names: readonly ModEventName[];
} | {
readonly refusal: string;
};
/**
* The names a pattern selects on a bus of `side` — the ONE side lock, read alike by `uses.events`, `uses.calls` and
* `on()`: an exact name the other side's bus reads (neither this side nor `both`) is refused (it is that bus's name, never
* usable here); a `<prefix>.*` pattern selects the names under the prefix this side reads and must select one. A name
* of this side that no station raises in this version is selected all the same (a forward declaration).
*/
export declare function expandOnSide(pattern: unknown, side: ModBusSide): {
readonly names: readonly ModEventName[];
} | {
readonly refusal: string;
};
/** A safe one-word description of a host value for a sentence (never calls the value's own toString). */
export declare function describe(value: unknown): string;