UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

167 lines (166 loc) • 13.6 kB
import type { ToolSpec } from "../core/types.js"; import { type DamagedRowVerdict } from "../core/row-shape.js"; import type { TaskHookFacts } from "../core/mods/teammate-stations.js"; /** * design/119 — the structured task-list tool family: `TaskCreate` / `TaskGet` / * `TaskUpdate` / `TaskList`. The upgrade path over TodoWrite: individual tasks with stable ids, * status transitions, dependencies (blocks/blockedBy), an optional owner, and free metadata — instead * of TodoWrite's replace-the-whole-list. The two families are MUTUALLY EXCLUSIVE and * this one is the DEFAULT — TodoWrite mounts only when the task list is explicitly off (the reference * shape: TodoWrite isEnabled = !taskList; see `scenarios/full-body.ts`). * * State default: like TodoWrite, the default store lives in this factory's closure — FRESH per task * and torn down with it; nothing durable, no deps, no egress (the model's own scratch, projected to * observers only through each call's tool result / `details`). Descriptions follow the reference * (product-specific lines — teammate assignment, spinner/UI wording — trimmed or generalized). * * design/147 §6 D2 (shared team task list): pass a {@link TaskListStore} to share ONE * task list across several agents — the reference's team coordination artifact ("Check the task list * periodically. Create new tasks when work should be divided. Mark tasks resolved when complete.") * is a task-list file under the team directory; the sema equivalent is this storage seam. A * deployment mounts the SAME store instance into each teammate's tool bundle (same session = same * trust domain — the list is model scratch either way, sharing adds no egress). The `owner` field's * teammate-assignment semantics (trimmed in the 198 port) come back through this seam. */ /** A task's status words (closed; a stored entry's `status` is read against it). */ export declare const TASK_LIST_STATUSES: readonly ["pending", "in_progress", "completed"]; export interface TaskListItem { id: string; subject: string; description: string; activeForm?: string; owner?: string; status: (typeof TASK_LIST_STATUSES)[number]; blocks: string[]; blockedBy: string[]; metadata?: Record<string, unknown>; } /** An entry of a task list that does not read as {@link TASK_LIST_ITEM_ROW_SHAPE}: the id the list files it under and its verdict. * {@link TaskListStore.list} answers it in place of the item; it counts as open (it still blocks what depends on it). */ export interface DamagedTaskListItem { readonly id: string; readonly rowVerdict: DamagedRowVerdict; } /** One entry of {@link TaskListStore.list}: an item, or a damaged entry (narrow with `"rowVerdict" in entry`). */ export type TaskListEntry = TaskListItem | DamagedTaskListItem; /** The refusal code of a task entry that does not read (`get`, an update of it, an edge to it) or a write whose item does not. */ export declare const TASK_LIST_ROW_MALFORMED_CODE = "task_list.row_malformed"; /** Typed task-list store error so callers branch on `code`. */ export declare class TaskListStoreError extends Error { readonly code: typeof TASK_LIST_ROW_MALFORMED_CODE; constructor(code: typeof TASK_LIST_ROW_MALFORMED_CODE, message: string); } /** * THE TASK ENTRY'S MEMBER-SHAPE TABLE (`rowShapeReader`, row-shape.ts). An entry has no row predicate of its own — it is filed under * its id in the list (`tasks[id]`), and the list document's own shape is its store's container judgment. `members` is what the * tools read: the id (equal to the key it is filed under), subject, description, status word, the optional active form and owner, * the dependency lists — whose ABSENCE reads as no dependencies (`[]`, in a read and a write alike) and which, present, are lists of * task ids — and the metadata ({@link jsonMetadataProblem}). Exit `list-damaged`: a listing answers such an entry by its id, it * counts as open, `get` and every update of it refuse in {@link TASK_LIST_ROW_MALFORMED_CODE}, and deletion by its id goes on. */ export declare const TASK_LIST_ITEM_ROW_SHAPE: import("../core/row-shape.js").RowShapeReader<TaskListItem>; /** * A stored entry as every reader reads it: the item (absent dependency lists read as `[]`), or the refusal * ({@link TASK_LIST_ROW_MALFORMED_CODE}) of one that does not read, told to `disclose` first. A store's `get` goes through this. */ export declare function readStoredTaskListItem(raw: unknown, id: string, disclose?: (sentence: string) => void): TaskListItem; /** One stored entry as a listing answers it: the item, or — an entry that does not read — its id and verdict (told to `disclose`). */ export declare function listStoredTaskListEntry(raw: unknown, id: string, disclose?: (sentence: string) => void): TaskListEntry; /** A write's item held to {@link TASK_LIST_ITEM_ROW_SHAPE} (its metadata refused first by {@link assertJsonMetadata}): the item to * store — absent dependency lists stored as `[]` — or the refusal before anything is written. A dependency list that is present * and not a list of ids is refused. */ export declare function admitTaskListItem(item: TaskListItem, id: string): TaskListItem; /** * design/147 §6 D2 — the task-list persistence seam (storage-tier abstraction, same family as * `RosterStore`/checkpoint store: core bundles a memory implementation; a deployment plugs pg/file * behind the same interface and hands ONE instance to every teammate's tool bundle). * * Contract: * - Methods MAY be async (a pg-backed store is); the bundled memory store is synchronous. * - Each single method call must be atomic in the store. Multi-step read-modify-write sequences * (update, delete-with-pruning) are serialized PER STORE by the tools themselves within this * process ({@link createTaskListTools} keeps a per-store promise chain) — a store shared across * PROCESSES additionally needs its own transactional guarantees for those sequences, which is the * deployment's half (documented, not solved here; CC's file-backed team list has the same window). * - `allocateId` is store-owned so concurrent teammates never mint colliding ids, and the * high-water mark is MONOTONIC ACROSS REOPENS for any backend that outlives one wrapper * instance: a restart/reconnect must never re-mint an id the backend has already handed out * (the conformance suite's durable tier pins exactly this — a counter that resets while the * rows survive makes every receipt lie and every subsequent update miss). The one reset is * `drop`, which erases the rows with the counter, so no receipt survives to point at a re-minted id. * - Value semantics: `get`/`list` return detached copies; `set` stores a detached copy. Callers * mutate their copy and write it back — a live-reference store would alias already-emitted events. * - ENTRY SHAPE ({@link TASK_LIST_ITEM_ROW_SHAPE}, the one reading every backend makes): `set` stores the item the table admits — * absent dependency lists stored as `[]`, a present one that is not a list of ids refused — or refuses it * ({@link TASK_LIST_ROW_MALFORMED_CODE}) before anything is written. A stored entry that does not read (another writer's, an * earlier release's) is `list`ed as a {@link DamagedTaskListItem} — its id and verdict — in its place, and `get` of it refuses in * the same code; `delete` removes it by its id. The tools count such an entry as open, so it keeps blocking what depends on it. * - RB-274: `list` is ordered by ID — {@link compareTaskIds}: numeric ids ascending by value, any other id after them, in UTF-16 code unit order — * not by write order. The tool lane always allocates before it sets, so the two coincide there — but a store shared with an * OUTSIDE writer (a real CC instance on the same directory) can set an id out of order, and then the backends disagreed. * Ordering is part of the contract, not each backend's incidental iteration order: every bundled backend sorts with * `compareTaskIds` (the file store's key order is not the contract's order for an id that is not a canonical integer), and a * store twin sorts with it too (it is a package-root export). * * @contract task_list.partition_is_root_session — a deployment that mounts a TaskListStore per session keys it by the * delegation tree's ROOT session: every child of the tree (spawned live, or revived by a host verb after a durable park) * reads the one list the leader reads; in-engine children share by construction, a per-call or per-reviver store is the divergence. */ export interface TaskListStore { get(id: string): TaskListItem | undefined | Promise<TaskListItem | undefined>; set(id: string, item: TaskListItem): void | Promise<void>; delete(id: string): boolean | Promise<boolean>; list(): TaskListEntry[] | Promise<TaskListEntry[]>; allocateId(): string | Promise<string>; /** the transaction boundary for adapters whose backend outlives one wrapper * instance (pg, shared files): when present, the tools run EVERY read-modify-write sequence * inside `mutate` and the adapter supplies sequence-level atomicity (a DB transaction, an * advisory lock keyed on the backend — not on this object). Absent ⇒ the tools fall back to the * in-process per-store promise chain, which is exactly right for the bundled memory store (its * backend IS this object) and wrong for anything shared wider — implement `mutate` there. */ mutate?<T>(fn: (tx: TaskListStore) => Promise<T>): Promise<T>; /** * Erase the whole list — every entry, a damaged one included, and the id high-water: the next `allocateId` answers `"1"`, as on a * list never written. The session-tree cascade's leg for the list a deployment mounted under a session's id * (`task_list.partition_is_root_session`; {@link import("../core/retention.js").RETENTION_CASCADE}): the ids it reserved belonged to * that session's tree, which goes with it. Idempotent (an empty list stays empty); a store fault throws. OPTIONAL: absent ⇒ this * store's lists outlive the sessions they were mounted for, and the deployment owns that gap. */ drop?(): void | Promise<void>; } /** the clone policy behind the detached-copy contract: metadata must be JSON-shaped * (structuredClone would accept — and SHARE — SharedArrayBuffer backing memory, and throws opaquely * on functions/proxies; the tool lane is always JSON, so this guards DIRECT store users). The answer form: * `undefined` = JSON-shaped, else the refusal's sentence naming the first member that is not. */ export declare function jsonMetadataProblem(value: unknown, path?: string): string | undefined; /** {@link jsonMetadataProblem} as the write-time refusal (a store twin calls it before persisting). */ export declare function assertJsonMetadata(value: unknown, path?: string): void; /** * RB-274 / #4411 — the contract's `list` order: a TOTAL order over every string (it answers 0 only for the same string, and * it is antisymmetric and transitive), the same in every locale and runtime, so the listing is stable across repeated calls * and across hosts. In the order of the rules: * 1. an id of ASCII digits only ("numeric") comes before any other id (CC's own task order puts its numbered tasks first); * 2. numeric ids ascend by DECIMAL VALUE, read from the digits, not through a number — leading zeros dropped, the shorter * digit string first, equal lengths by UTF-16 code unit — so it is exact for an id of any length; * 3. numeric ids of one value (`7`, `007`, `0007`) are told apart by their whole text in UTF-16 code unit order (the one * with more leading zeros first); * 4. every other id comes after the numeric ones, by UTF-16 code unit order of the whole string — never by the locale's * collation, which differs between hosts and answers 0 for two different strings that are canonically equivalent * (NFC / NFD) or differ only by an ignorable character. */ export declare function compareTaskIds(a: string, b: string): number; /** The bundled in-memory {@link TaskListStore} — detached copies both ways (see interface contract). */ export declare function createMemoryTaskListStore(): TaskListStore; /** * The tasks `owner` holds in progress in the task list the leg's task tools read — the first of `tools` that is a family's * `TaskUpdate` and is `mounted` on the leg (a leg that cannot update a task holds none it could complete): its entries that read, * `in_progress` and owned by `owner`, in the list's order. No such tool ⇒ none. A store fault rejects (the caller says it). */ export declare function heldInProgress(tools: readonly ToolSpec[] | undefined, mounted: (name: string) => boolean, owner: string): Promise<TaskHookFacts[]>; /** Build the four task-list tools sharing one task list. Mount all four together. * No `store` ⇒ a fresh private in-memory list (the design/119 per-run scratch shape, unchanged). * With `store` ⇒ the shared team task list (design/147 §6 D2) — mount the same instance everywhere. * On a Runner's leg the family raises the leg's task events (`ctx.taskStations`, teammate-stations.ts): `TaskCreate` raises * `classic.TaskCreated` once its row landed — a `block` removes the row and the call fails with the reason — and `TaskUpdate` * raises `classic.TaskCompleted` before it marks a task completed — a `block` fails the update, nothing applied. */ export declare function createTaskListTools(store?: TaskListStore): ToolSpec[];