UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

357 lines (356 loc) • 21.4 kB
/** * The Artifacts hosting seam: the deployment-injected `ArtifactHost` (the `RunnerDeps.artifactHost` seat), * its capability declaration, the call context the engine mints for every host call, the request / * outcome shapes, and the closed word sets the tool face is assembled from. A host declares WHAT it * supports (`capabilities()`); the engine assembles the `Artifact` tool from that declaration alone and * never inspects the implementation. `localArtifactStub` (src/tools/artifact/local-stub.ts) is the first * implementation of this interface; a server's hosting plane is the second. */ import type { AssertAllKeysHandled } from "./ask-origin.js"; import type { OwnerIdentity } from "./owner-identity.js"; /** The model-facing action words. `publish` is the default action and the one every host must declare. */ export declare const ARTIFACT_ACTIONS: readonly ["publish", "list", "read", "list_files", "read_file"]; export type ArtifactAction = (typeof ARTIFACT_ACTIONS)[number]; /** Which face the host serves. `"local-stub"` = publish-only local storage with `eval-stub://` links; * `"hosted"` = a hosting plane that mints its own URLs. Declared by the host, never detected. */ export declare const ARTIFACT_PLANES: readonly ["hosted", "local-stub"]; export type ArtifactPlane = (typeof ARTIFACT_PLANES)[number]; /** How a throw out of `publish` relates to the host's commit point. `"throw_means_uncommitted"`: every fallible * step precedes the commit, so a throw proves nothing was committed; `"uncertain"`: a throw may follow it. */ export declare const ARTIFACT_COMMIT_CERTAINTIES: readonly ["throw_means_uncommitted", "uncertain"]; export type ArtifactCommitCertainty = (typeof ARTIFACT_COMMIT_CERTAINTIES)[number]; /** The `artifact.host_error` outcome word the tool reports when the host THREW, by declaration. An aborted or * malformed answer is `"unknown"` under every declaration: the throw guarantee says nothing about those arms. */ export declare const ARTIFACT_COMMIT_THROW_OUTCOME: { readonly throw_means_uncommitted: "not_executed"; readonly uncertain: "unknown"; }; export type ThrowOutcomeTableCoversEveryCommitCertainty = AssertAllKeysHandled<Exclude<ArtifactCommitCertainty, keyof typeof ARTIFACT_COMMIT_THROW_OUTCOME>>; /** The `publishContext` word a publish carries (default `"plain"`). */ export declare const ARTIFACT_PUBLISH_CONTEXTS: readonly ["pr_review", "workshop", "whiteboard", "prototype", "plain"]; export type ArtifactPublishContext = (typeof ARTIFACT_PUBLISH_CONTEXTS)[number]; /** The `list` scope words. */ export declare const ARTIFACT_LIST_SCOPES: readonly ["mine", "shared", "all"]; export type ArtifactListScope = (typeof ARTIFACT_LIST_SCOPES)[number]; /** * The closed word sets of {@link ArtifactHostOwnership}, one per member: what a host authorizes on, read by the mount gate in * one place. Each word picks one arm of the conformance kit (no arm is skipped by declaring a word). * - `by` — `"identity"`: a page's owner record is judged against the call's `binding.identity` (any run of that identity * reaches it) — such a host declares `read`, the answer the engine judges a page on before it writes to it; `"run"`: only * what this run minted is the caller's (the local stub), which the engine knows from this run's own answers — its publishes, * and its `mine` listings (such a host lists there only what this run minted: the kit's `binding.run_mints_only`). * - `people` — `"one"`: the host serves one person (an anonymous run is one identity of its own); `"many"`: the host serves * many people, so the engine refuses every call of a run that carries no identity, and the host's own read face refuses * anonymous requests too. * - `unrecorded` — `"never"`: the host's storage cannot hold a page whose owner record names no identity (a call whose binding * names none is refused); `"possible"`: it can (pages from before owner records were kept) — nobody reads such a page. * - `sharing` — `"none"`: the host never sets the share markers (a list row's `owner: "shared"`, a read answer's * `isolatedSummary: true`); `"marked"`: it sets them on another identity's pages its own grant table shares with the caller. */ export declare const ARTIFACT_OWNERSHIP_WORDS: Readonly<{ by: readonly ["identity", "run"]; people: readonly ["one", "many"]; unrecorded: readonly ["never", "possible"]; sharing: readonly ["none", "marked"]; }>; export interface ArtifactHostOwnership { by: (typeof ARTIFACT_OWNERSHIP_WORDS.by)[number]; people: (typeof ARTIFACT_OWNERSHIP_WORDS.people)[number]; unrecorded: (typeof ARTIFACT_OWNERSHIP_WORDS.unrecorded)[number]; sharing: (typeof ARTIFACT_OWNERSHIP_WORDS.sharing)[number]; } export type OwnershipWordsCoverEveryMember = AssertAllKeysHandled<Exclude<keyof ArtifactHostOwnership, keyof typeof ARTIFACT_OWNERSHIP_WORDS>>; /** * The content-origin class of the mounted tool, derived from the declared plane: a hosted plane hands * back host-controlled bytes (URLs, titles, page content) and is classified external; the local stub * reads nothing back from outside the process. Plane-keyed, never implementation-keyed. */ export declare const ARTIFACT_PLANE_CONTENT_ORIGIN: { readonly hosted: "external"; readonly "local-stub": "local"; }; export type ContentOriginTableCoversEveryPlane = AssertAllKeysHandled<Exclude<ArtifactPlane, keyof typeof ARTIFACT_PLANE_CONTENT_ORIGIN>>; /** The host method each declared action is served by; the mount-time validator probes the method's presence. */ export declare const ARTIFACT_ACTION_HOST_METHOD: { readonly publish: "publish"; readonly list: "list"; readonly read: "read"; readonly list_files: "listFiles"; readonly read_file: "readFile"; }; export type HostMethodTableCoversEveryAction = AssertAllKeysHandled<Exclude<ArtifactAction, keyof typeof ARTIFACT_ACTION_HOST_METHOD>>; /** Whether a call of the action may run inside a parallel batch: the read family is (host reads, no host write); a * publish is not (it writes the host and the tool's path-binding state). Read by the tool's `isConcurrencySafe`. */ export declare const ARTIFACT_ACTION_CONCURRENCY_SAFE: { readonly publish: false; readonly list: true; readonly read: true; readonly list_files: true; readonly read_file: true; }; export type ConcurrencyTableCoversEveryAction = AssertAllKeysHandled<Exclude<ArtifactAction, keyof typeof ARTIFACT_ACTION_CONCURRENCY_SAFE>>; /** The typed failure words a host outcome may carry (`ok: false`). */ export declare const ARTIFACT_HOST_FAILURE_CODES: readonly ["conflict", "url_foreign", "forbidden", "payload_too_large", "not_found", "force_refused", "refused"]; export type ArtifactHostFailureCode = (typeof ARTIFACT_HOST_FAILURE_CODES)[number]; /** The tool-result `details.code` (and `tool_end.errorCode`) each host failure word is projected to. */ export declare const ARTIFACT_FAILURE_RESULT_CODE: { readonly conflict: "artifact.publish_conflict"; readonly url_foreign: "artifact.url_foreign"; readonly forbidden: "artifact.forbidden"; readonly payload_too_large: "artifact.payload_too_large"; readonly not_found: "artifact.not_found"; readonly force_refused: "artifact.force_refused"; readonly refused: "artifact.refused"; }; export type ResultCodeTableCoversEveryHostFailure = AssertAllKeysHandled<Exclude<ArtifactHostFailureCode, keyof typeof ARTIFACT_FAILURE_RESULT_CODE>>; /** The one result code that is not a host word: the host threw, timed out, or answered outside its contract. */ export declare const ARTIFACT_HOST_ERROR_CODE = "artifact.host_error"; export type ArtifactResultCode = (typeof ARTIFACT_FAILURE_RESULT_CODE)[ArtifactHostFailureCode] | typeof ARTIFACT_HOST_ERROR_CODE; /** * What a host declares at mount time. Invariants (a violation refuses the mount and announces * `config.artifact_host_invalid`): `actions` non-empty, duplicate-free, within {@link ARTIFACT_ACTIONS}, * containing `"publish"`; `plane: "local-stub"` ⇒ `actions` is exactly `["publish"]`; * `defaultVisibility` is `"private"`; both byte limits are positive finite integers; `multiFile` is a * boolean; every declared action's host method exists; `plane: "local-stub"` ⇒ `storageDir` is a non-empty * fully qualified path under its own spelling family (`C:\\…` / UNC / `/…` — read from the spelling, never from * `process.platform`); `commit` is a word of {@link ARTIFACT_COMMIT_CERTAINTIES} (no default — an undeclared * commit protocol is an invalid declaration, never read as either word); `ownership` carries each of its four members * as a word of {@link ARTIFACT_OWNERSHIP_WORDS} (absent or outside ⇒ refused, never defaulted); `ownership.by: "identity"` ⇒ * `actions` contains `"read"` (the engine judges whose a page is before it writes to it, and only a read answers that); * `libraries`, when present, is an array of at most 32 entries, each an `https:` `url` (no * whitespace or control character, no user name or password, at most 2 048 characters, no two that a browser fetches as one — * a `#fragment` is not fetched), an `sri` of one or more space-separated * Subresource Integrity tokens (`sha256-` / `sha384-` / `sha512-` with the digest's exact base64 length), and a one-line `hint` * of 1 – 200 characters. */ export interface ArtifactHostCapabilities { plane: ArtifactPlane; actions: ReadonlyArray<ArtifactAction>; /** What a throw out of `publish` proves about the commit (see {@link ARTIFACT_COMMIT_CERTAINTIES}); the tool words * its host-fault result from this and from nothing else about the host. */ commit: ArtifactCommitCertainty; /** The on-disk store of a `"local-stub"` plane (required there; ignored on `"hosted"`). Contract: the store * must lie OUTSIDE every root the run may write or read (the task root, `additionalDirectories`, * `additionalReadDirectories`) — a store the model can reach through the fs tools is not a trust boundary; * the engine refuses the mount (`config.artifact_host_invalid`) when it is inside one. */ storageDir?: string; /** The only value this version mounts: a page is private until its owner shares it. */ defaultVisibility: "private"; maxFileBytes: number; maxTotalBytes: number; /** `false` ⇒ the publish arm takes one `file_path` only (`files[]` leaves the schema). */ multiFile: boolean; /** What the host authorizes on (see {@link ARTIFACT_OWNERSHIP_WORDS}); required — a host that does not say how it tells * whose a page is is not mounted. */ ownership: ArtifactHostOwnership; /** The external libraries a page on this host may load (C-R761): each by its exact `url`, with the Subresource Integrity value * the page's tag carries (`sri` — the host's fact; the engine checks only its shape) and a one-line `hint` saying what it is. * The tool's description names these and no others; absent (or empty) ⇒ the description says a page loads nothing from * elsewhere and puts everything inline. The engine enforces nothing in the page: what loads is the host's to serve. An engine * that reads this member says so by the capability word `artifact_host.libraries`; one without it ignores the member. */ libraries?: ReadonlyArray<{ url: string; sri: string; hint: string; }>; } /** * Engine-minted, per call, never a tool argument: whom a host call acts for and which conversation it belongs to. * `identity` is the run's identity (`ownerIdentityOf(spec)`): `principal` a name, or `null` — the anonymous identity, one * identity of its own and never a name such as `"default"` — and `isolationScope` only when the run works in a scope other * than its principal. What a call creates belongs to this identity: the host records it, as given, as the page's owner record. * `root` is the delegation tree's root conversation and the occupant the tree was born under (absent = not read): the page's * home for grouping — never an authorization subject, and not a lifetime anchor (deleting a conversation does not delete its * pages; a host's page store keeps its own retention). */ export interface ArtifactCallBinding { identity: OwnerIdentity; root: { sessionId: string; occupant?: string; }; } /** * Engine-minted call attribution, the authorization binding, and idempotency keys — closure-supplied, never a tool parameter. * `binding` is the authorization subject of every call ({@link ArtifactCallBinding}); a call that arrives without one (a * direct call from code that bypasses the type) is refused, never read as the anonymous identity. The two lifecycle calls, * `capabilities()` and `onMount(runId)`, act for nobody and carry no binding. `taskId` / `sessionId` / * `agentName` are audit attribution, never an authorization subject. `runId` and `attemptId` are engine-minted trusted * keys: `runId` is the same value `onMount` received; `attemptId` is one opaque value per HOST CALL — the * engine mints a fresh one for every call it makes, so two calls of a single tool invocation (the probing * `read` that establishes ownership and the `list_files` it gates, say) never arrive under one key — and it * is stable across any retry the HOST makes of that call, so a host MUST replay the first outcome for a * repeated `attemptId` (a fresh publish never mints a second page, an update never advances twice). The rule * is keyed on the value alone: a host may hold one attempt ledger for all its methods. */ export interface ArtifactCallContext { taskId: string; sessionId?: string; agentName?: string; runId: string; attemptId: string; binding: ArtifactCallBinding; } export interface ArtifactFileContent { path: string; content: Uint8Array; mediaType?: string; } export interface ArtifactPublishRequest { slug?: string; /** Update locator. Present without `baseVersion` ⇒ the host applies last-write-wins. */ url?: string; files: ReadonlyArray<ArtifactFileContent>; /** Reserved on the seam; the model face does not expose it in this version. A host MAY refuse it. */ removeFiles?: ReadonlyArray<string>; title?: string; description?: string; favicon?: string; label?: string; baseVersion?: string; force?: boolean; publishContext: ArtifactPublishContext; } /** The reference shape every publish / list / read result carries. `ownerIdentity` is the owner record the host keeps for the * page — the `binding.identity` of the call that created it, recorded as given — handed back on every answer: the ENGINE * judges it (`identityReadVerdict` against the run's identity) before the model sees anything. */ export interface ArtifactRef { url: string; slug: string; version: string; title?: string; ownerIdentity: OwnerIdentity; } export interface ArtifactListRow extends ArtifactRef { /** The host's share marker: `"shared"` = the caller reaches another identity's page through a grant the host keeps. Whether a * row is the caller's own is the engine's verdict on `ownerIdentity`, never a word of the host's. */ owner?: "shared"; updatedAt: string; } export interface ArtifactConflictSnapshot { files: ReadonlyArray<ArtifactFileContent>; title?: string; description?: string; favicon?: string; label?: string; /** The page's owner record, as on every answer (the engine withholds a snapshot it does not judge the caller's). */ ownerIdentity: OwnerIdentity; } export type ArtifactPublishOutcome = { ok: true; ref: ArtifactRef; } | { ok: false; code: "conflict"; currentVersion: string; current: ArtifactConflictSnapshot | "reread"; } | { ok: false; code: Exclude<ArtifactHostFailureCode, "conflict">; message: string; }; export type ArtifactListOutcome = { ok: true; rows: ReadonlyArray<ArtifactListRow>; truncated: boolean; } | { ok: false; code: "refused"; message: string; }; export type ArtifactReadOutcome = { ok: true; ref: ArtifactRef; content: string; isolatedSummary: boolean; } | { ok: false; code: "not_found" | "forbidden"; message: string; }; export type ArtifactFilesOutcome = { ok: true; entries: ReadonlyArray<{ path: string; bytes: number; mediaType?: string; }>; ownerIdentity: OwnerIdentity; } | { ok: false; code: "not_found" | "forbidden"; message: string; }; export type ArtifactFileOutcome = { ok: true; file: ArtifactFileContent; ownerIdentity: OwnerIdentity; } | { ok: false; code: "not_found" | "forbidden"; message: string; }; /** * The hosting seat. Atomicity contract: no half version is ever observable — a reader sees the old * complete version or the new complete version, never a mix of files / metadata / version number. * The commit itself may be uncertain from the engine's side (the answer was lost after the host * committed); the `attemptId` replay rule above is what makes a retry of that call converge. * * Ownership contract (one seat serves every person of a deployment — never "one instance, one principal"): * - `ctx.binding.identity` is each call's authorization subject. A page a call creates records it, as given, as the page's owner * record; every answer hands that record back (`ownerIdentity` on a ref, a list row, a files answer, a conflict snapshot). The * conversation `ctx.binding.root` is kept apart from the owner record; the judge reads only `principal` / `isolationScope`. * - The host's WRITE GUARD: before writing an existing page, `identityReadVerdict(the page's owner record, ctx.binding.identity)` * other than `"readable"` refuses — with `not_found`, `forbidden` or `url_foreign`, never `conflict`. A shared page is * read-only to whom it is shared with. The host's OWN read faces (a browser, an HTTP face) judge with the same function. * - The share markers (`owner: "shared"`, `isolatedSummary: true`) go only to a caller the host's grant table really grants * (a grant names a whole identity — person and scope — never a bare name); the engine cannot verify a grant table, so the * markers' truth is the host's responsibility. * - A page that is not the caller's and not shared with it is answered exactly as a url with no page: on every method the same * code and the same `message` (the url itself aside), and nothing of the page in it — no title, no version, no owner. Telling * "a page is there, not yours" from "no page there" is itself a disclosure (that the page exists). A listing's `truncated` * counts only pages the caller may see. * - A host declaring `ownership.people: "many"` refuses anonymous requests on its own read faces too. * - Storage: a record that names no identity carries NO `principal` member (a nullable column's NULL reads back as the member * absent, never as `null`, which is the anonymous identity — `encodePrincipalColumn` / `decodePrincipalColumn` are one such * encoding); `isolationScope` is never stored as `null`. A host moving from one person to many first moves its anonymous pages * to a named identity or removes them. * - The engine does not rewrite a host's words: a refusal's `message` (every code but `not_found`, whose sentence the engine * writes itself so that "not there" reads one way however it was found absent) and anything a method throws reach the model * as written — they never name a page owner's principal or isolation scope, nor anything of a page the caller may not see. * The engine holds what it can judge (owner records); it cannot hold a host that answers everyone (a listing's `truncated` * counting pages the caller may not see, a conflict's `currentVersion` of another identity's page, the host's own text). * - A page's lifetime is not tied to its home conversation: deleting a conversation, or a session retention sweep, deletes no page. */ export interface ArtifactHost { capabilities(): ArtifactHostCapabilities; /** Called at every materialization of a run (prepare and resume) with the engine-minted run id. */ onMount?(runId: string): void; publish(req: ArtifactPublishRequest, ctx: ArtifactCallContext): Promise<ArtifactPublishOutcome>; list?(req: { scope: ArtifactListScope; limit: number; }, ctx: ArtifactCallContext): Promise<ArtifactListOutcome>; read?(req: { url: string; }, ctx: ArtifactCallContext): Promise<ArtifactReadOutcome>; listFiles?(req: { url: string; }, ctx: ArtifactCallContext): Promise<ArtifactFilesOutcome>; readFile?(req: { url: string; path: string; }, ctx: ArtifactCallContext): Promise<ArtifactFileOutcome>; } export type ArtifactHostCapabilitiesVerdict = { ok: true; capabilities: ArtifactHostCapabilities; } | { ok: false; problem: string; }; /** * Read and validate a host's declaration. Every invariant of {@link ArtifactHostCapabilities} is judged * here and nowhere else; a `problem` names the first violated one in operator-facing words. */ export declare function readArtifactHostCapabilities(host: unknown): ArtifactHostCapabilitiesVerdict;