UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

264 lines (263 loc) โ€ข 18.9 kB
import type { EngineNotice } from "./engine-notice.js"; /** * Scan `text` for a high-confidence credential (CC-parity P0-2). Returns the matched pattern's stable * `label` (NEVER the matched secret value โ€” labels are safe to log/surface), or `null` when clean. * Deliberately CONSERVATIVE: only provider-prefixed keys + PEM private-key headers match, so ordinary * prose that merely mentions tokens/keys/passwords passes through untouched (false-positives are the head * risk โ€” a wrongly-rejected normal note silently breaks legitimate memory). * * ๐Ÿ”ด RB-445: this is a BEST-EFFORT tripwire for a handful of high-signal token * formats, NOT a data-loss-prevention boundary โ€” "the write gate passed" never means "the text contains * no credential". Known-through shapes (deliberate, per the false-positive stance above): connection * strings carrying passwords, `password=`/`Authorization:` header values, bare high-entropy bodies * (40-char keys, 64-hex โ€” indistinguishable from git SHAs/digests in engineering notes), and structured * tokens without a vendor prefix. A deployment needing a real DLP boundary must put its OWN scanner in * front of the store; widening candidates are evaluated per-format in the review backlog (RB-445). */ export declare function detectSecret(text: string): string | null; /** First sentence (or ~120-char head) of a note โ€” the manifest description fallback for untyped notes. */ export declare function firstSentence(text: string): string; /** The canonical, normalized shape of {@link import("./types.js").TaskSpec.memory} โ€” the ONE form every * consumer reads (prepare-task, recall, consolidation, the remember tool), so the union never narrows * downstream. `scopes` is the ordered read-side layering (first = stable prefix, last = volatile tail = * highest priority); `writeScope` is the single layer ALL writes land in (`null` = read-only, no writes). */ export interface NormalizedMemorySpec { /** Ordered, deduped, non-empty opaque scopes for read-side layered injection (list order = inject order). */ scopes: string[]; /** The single scope all writes route to (decision 3), or `null` for a read-only (inherited) layering. */ writeScope: string | null; /** Mirrors `memory.enabled` (default true) โ€” false โ‡’ the whole memory feature is off for this task. */ enabled: boolean; /** design/142 ยง1.2 โ€” present iff the task opted into the v2 scope identity contract (keys validated). */ scopeContract?: "v2"; /** * design/178 ยง3 โ€” host allowlist for UNDECLARED tools: names listed here classify `"local"` instead * of the fail-closed `"external"` default. The explicit-config channel for a deployment whose custom * tools predate the {@link import("./types.js").ToolSpec.contentOrigin} declaration; it never * overrides a tool's OWN declaration. Normalized: trimmed, deduped, empties dropped. * * NOT the channel for MCP servers (design/378). A per-name entry here keys on the MINTED name โ€” the * host has to predict the namespacing and charset normalization โ€” covers nothing a mid-task refresh * adds, and says "exempt this undeclared tool" where the fact is "this whole server is mine". * {@link import("./types.js").McpServerSpec.contentOrigin} states that fact at the entry, and being * a DECLARATION it wins over this allowlist in both directions: a declared server's tools leave this * list's reach entirely, an explicit `"external"` declaration included (that is the one way a * deployment can pin a server's tools BEYOND this exemption). This list is not retired โ€” it remains * the in-register channel for undeclared HOST tools and for a deployment not ready to touch its * server entries. */ trustedTools?: string[]; /** * design/178 ยง3 strict upgrade (`execIsExternalContent`): treat `"execution"`-class tools as * external-content sources โ€” invoking one then marks the session's memory polluted. For * high-assurance deployments; default false (the execution class is a NAMED residual channel: * write-side scans/fences compensate, and disabling memory for every shell session would disable * it for the main coding scenario). */ execIsExternalContent?: boolean; /** Per-scope origin provenance stamped by the deployment's ASSEMBLY point (a server that resolved an * operator registry entry knows what core cannot). Two-tier absence semantics (ruled 2026-08-05): * the WHOLE key absent = legacy โ€” admission classifies by the deployment-scope set exactly as * before (a `^5.12` default install must not have its single-user deployment refused by its own * upgrade); the key PRESENT but missing an entry for a scope = that scope is `"request"` * (fail-closed for the stamped form). Domain covers `writeScope` strings too. */ scopeOrigins?: Readonly<Record<string, "deployment" | "request">>; /** See {@link MemorySpecInput.capture} (design/383 ยง2.1 โ€” the session capture opt-out). */ capture?: "off"; /** See {@link MemorySpecInput.projectKey} โ€” carried verbatim; a normalized spec never invents it. */ projectKey?: MemoryProjectKey; } /** * The closed vocabulary a deployment states a MISSING project key with: the working root is not a * repository, it is a bare repository, or it could not be read. Purely descriptive โ€” the engine * branches on presence (`absent` vs `scope`), never on which word; the word rides the operator * notice so a deployment can tell "no project here" from "I could not look". */ export declare const MEMORY_PROJECT_KEY_ABSENT_REASONS: readonly ["not_git", "bare", "unreadable"]; export type MemoryProjectKeyAbsentReason = (typeof MEMORY_PROJECT_KEY_ABSENT_REASONS)[number]; /** * The assembly point's STATEMENT about this task's project identity โ€” the key it derived for the * working root, or the reason there is none. Exactly one arm is spelled. * * It is a DECLARATION, not a second way to configure memory: the layering is still `scopes` and * `writeScope`, and this key only lets the engine refuse the one misconfiguration those two cannot * express โ€” an assembler that derived a project key and then left `writeScope` to its default, so * every entry the session writes lands in the shared layer instead of the project's. */ export type MemoryProjectKey = { scope: string; absent?: never; } | { absent: MemoryProjectKeyAbsentReason; scope?: never; }; /** The memory spec accepted on `TaskSpec.memory`. RB-479-Bโ‘ก (ruled 2026-08-02): ONE form โ€” * the legacy singular `scope` field is REMOVED; `scopes` (ordered read layers) is the only spelling. * An input still carrying an own `scope` property is REFUSED by {@link normalizeMemorySpec} * (`config.memory_scope_spelling`), not quietly read as "no scopes" โ€” see the throw there. */ export type MemorySpecInput = { scopes?: ReadonlyArray<string>; writeScope?: string | null; enabled?: boolean; /** * design/142 ยง1.2 โ€” EXPLICIT opt-in to the v2 scope identity contract (`user:` / `org:` / * `proj:<tenant>/<projectId>` / `userproj:` typed keys). Absent โ‡’ every scope stays byte-identically * OPAQUE, including keys that happen to look like `user:42` (the documented legacy shape above โ€” the * contract is NEVER activated by prefix sniffing, ๅคๅฎก F1 double-confirmed). Under `"v2"`, keys * carrying a reserved prefix are validated fail-loud (`config.memory_scope_key`); unprefixed keys * remain legal opaque legacy scopes. */ scopeContract?: "v2"; /** See {@link NormalizedMemorySpec.trustedTools} โ€” design/178 ยง3 allowlist for undeclared tools. */ trustedTools?: ReadonlyArray<string>; /** See {@link NormalizedMemorySpec.execIsExternalContent} โ€” design/178 ยง3 strict upgrade. */ execIsExternalContent?: boolean; /** See {@link NormalizedMemorySpec.scopeOrigins} โ€” assembly-point provenance, additive. */ scopeOrigins?: Readonly<Record<string, "deployment" | "request">>; /** * design/383 ยง2.1 โ€” the SESSION CAPTURE OPT-OUT declaration: `"off"` = this session's content * must not enter long-term memory (the forward legs commit nothing; the session's contributions * leave the consolidation candidate set; reads stay fully mounted). SINGLE-MEMBER CLOSED SET, * deliberately with no `"on"` spelling: absence is the one capture-as-usual state, the record the * declaration mints is one-way, and a future tier is a new member โ€” never a polarity flip (the * `trust: "untrusted"` single-value-no-upgrade family's shape). Any other value โ€” `"on"`, * `"OFF"`, booleans, garbage โ€” is REFUSED loudly (`config.memory_capture_spelling`), never read * as either state (a privacy request must not be dropped by a typo, and capture must not be * switched off by one either). * * PLACEMENT LAW (why this key legally lives on TaskSpec while the memory family's other knobs are * "DEPLOYMENT seat ONLY"): that law forbids task authors WIDENING past the deployment's safety * posture (`memoryProvenance` / `memoryDelegationEvidence`). This key can only NARROW โ€” it * removes a capture that would otherwise happen and never re-enables anything โ€” the same * direction `memoryScopeAdmission`'s "can only NARROW" clause blesses. Do not move it to a * deployment seat by family pattern-matching: the DECLARER here is the session's user, which is * the whole point. * * The AUTHORITY seat is separate (design/383 ยง3): whether this principal MAY declare is * `RuntimeCaps.allowMemoryOptOut` under `RunnerDeps.memoryCapturePolicy` โ€” adjudicated at * prepare, strictly BEFORE any record lands (a denied declaration leaves zero record residue). */ capture?: "off"; /** * The assembly point's statement about this task's PROJECT IDENTITY ({@link MemoryProjectKey}). * Two things happen to it and nothing else: a `{ scope }` arm must EQUAL `writeScope` (a * read-only layering excepted), or the task refuses to start with * `config.memory_write_scope_mismatch`; an `{ absent }` arm mints one operator notice * (`memory.project_scope_absent`) naming the reason, and the layering is used as written. * * Why this rather than "derive writeScope from it": the layering is the deployment's to compose, * and a key that quietly re-pointed the write face would be a second configuration channel. What * it closes is the SILENT direction โ€” an omitted `writeScope` defaults to the LAST scope, so an * assembler that derived a project key and forgot to pin the write face writes every entry of * every project into the shared layer, and nothing says so. Absent โ‡’ the spec reads as before. * * Any other shape โ€” both arms, neither, an empty `scope`, a reason outside * {@link MEMORY_PROJECT_KEY_ABSENT_REASONS} โ€” is REFUSED loudly * (`config.memory_project_key_spelling`), never folded to "no key stated". */ projectKey?: MemoryProjectKey; }; /** * Normalize {@link import("./types.js").TaskSpec.memory} into ONE canonical * {@link NormalizedMemorySpec} (design/84 Seam A decision 1). The consumer side reads ONLY this result โ€” no * narrowing of the union anywhere downstream: * - an own `scope` property (the removed singular spelling) is a THROW, not a normalization โ€” * `config.memory_scope_spelling`, so the task fails to start instead of running memory-less. * - blank/whitespace scopes are dropped and duplicates collapsed (FIRST occurrence wins โ€” keeps the * caller's stableโ†’volatile order); list order is the inject order (stable prefix first, volatile tail last). * - `writeScope` defaults to the LAST scope (the highest-priority layer); an EXPLICIT `null` means read-only * (no `remember` tool, no consolidation); an explicit non-null string is taken as-is (it need NOT be one * of `scopes` โ€” a deployment may write a layer it does not inject, though normally it is the last scope). * โš ๏ธ Layered READ seeding (142-S4): when `scopes` comes from a registry's defaultScopes * (shared read layers), ALWAYS pin `writeScope` explicitly โ€” the last-scope default would land every * harvest in whichever shared layer happens to be listed last (a cross-tenant write surface). * - returns `undefined` when there are no usable scopes (the caller treats it like "no memory configured"). * */ export declare function normalizeMemorySpec(input: MemorySpecInput | undefined): NormalizedMemorySpec | undefined; /** Does a leg open an engine-memory session: a spec that enables memory over a deployment with a memory backend. The one * reading of prepare's memory phase, the static plan's memory seat and the leg's `memory` need of an environment. */ export declare function memoryEngineOpens(memorySpec: NormalizedMemorySpec | undefined, deps: { readonly memoryBackend?: unknown; }): boolean; /** * The operator disclosure for a declared-absent project key (`memory.project_scope_absent`, * audience `operator`): the deployment stated it could derive no project identity for this working * root, so the layering it sent is used exactly as written โ€” typically writing into a layer shared * with every other project. The notice states the deployment's own reason word and the root it was * about; whether that reading is correct is a question about how the deployment resolves working * roots, which is why nobody is judged here. One per prepared leg, at the declaration โ€” not at the * mount, because the declaration is already the fact. */ export declare function memoryProjectScopeAbsentNotice(input: { reason: MemoryProjectKeyAbsentReason; taskRoot: string; sessionId: string; writeScope: string | null; }): EngineNotice; /** Max bytes of memory injected into the prompt; larger is truncated with a marker. (CodeWhale: 100 KiB) * Exported so the inject-all de-dup seeding (prepare-task.ts) can detect truncation and NOT seed dropped * (truncated-out) note ids as "already surfaced" โ€” see the MINOR-1 audit fix there. */ export declare const MAX_MEMORY_BYTES: number; /** The wrapper-tag family the memory ADMISSION gate rejects on (`<system-reminder>` is ALWAYS * included by {@link sanitizeUntrustedText} itself). Single source (design/138 S2-C, C-F10/O-F11): * the memory write-time scan (`memory-engine/scan.ts`) detects break-out markup by diffing * `sanitizeUntrustedText(text, MEMORY_WRAPPER_TAGS)` against the raw text. * * ADMISSION half โ€” deliberately UNCHANGED at the single outer wrapper. See * {@link MEMORY_INJECTION_TAGS} for the (wider) containment half and for why the two are allowed to * differ in exactly one direction. */ export declare const MEMORY_WRAPPER_TAGS: readonly string[]; /** * The tag family the memory injection fences actually NEUTRALIZE โ€” the whole authority-envelope * census (untrusted-text.ts `ENGINE_ENVELOPES`), a deliberate SUPERSET of {@link MEMORY_WRAPPER_TAGS}. * * Two reproduced findings drove the widening: * โ‘  `<scope>` โ€” {@link composeLayeredMemoryBlock} renders a `<scope name="โ€ฆ">` SUB-ENVELOPE per * layer, but the neutralized list named only the outer wrapper, so a layer payload could close its * own `</scope>` and open a fresh `<scope name="managed">`: a forged higher-authority layer landing * at the END of the block, where this function's own contract puts the highest-priority layer. * Project-scope content is repository-controlled by our own stated posture * (the instruction frames' opening), i.e. reachable from untrusted input. * โ‘ก the SIBLING envelopes โ€” nesting a forged `<task-notification>` or `<new-diagnostics>` inside * `<user_memory>` does not make it inert: the TAG is what a model reads as harness speech, and * this payload lands in the SYSTEM PROMPT. Widening is safe precisely here because the sanitizer * runs on the PAYLOAD, before this file assembles the engine's own wrappers around it โ€” it can * never defuse our own fences. * * WHY THE ADMISSION LIST DID NOT WIDEN WITH IT (the asymmetry is the point). The write scan * (`memory-engine/scan.ts`) diffs against {@link MEMORY_WRAPPER_TAGS} and REFUSES on a difference, * and it runs on re-serialization / sync / import paths as well as on fresh writes. Widening it would * retroactively refuse ALREADY-STORED entries โ€” and `<scope>test</scope>` is a Maven POM element, so * the false-rejection is not hypothetical. The drift therefore runs in the one safe direction: * containment โЇ admission. A note the gate accepts is neutralized on the way in to the prompt; the * dangerous drift would be the reverse (admission accepting what containment does not defuse), and * that one is structurally impossible while this constant is a superset. */ export declare const MEMORY_INJECTION_TAGS: readonly string[]; /** * Wrap memory content in a `<user_memory>` block. This is the **variable tail** of the system prompt * (per-user, scoped, timestamped) โ€” the prompt assembly places it LAST (the memory tail section) so the * stable base prompt before it stays a cacheable prefix. * Truncates over-cap content with a `<truncated bytes=N>` marker (mirrors CodeWhale `as_system_block`). * Returns undefined for empty content. */ export declare function composeMemoryBlock(content: string | null | undefined, scope: string): string | undefined; /** * Compose the LAYERED inject-all memory block for multiple scopes (design/84 Seam A decision 2). One * `<user_memory>` block with a `<scope name="โ€ฆ">` subsection per scope, **in the given list order** โ€” the * caller passes stable layers FIRST (cacheable prefix) and volatile layers LAST (re-computed tail), and the * highest-priority layer is therefore at the END of the block (closest to the model's attention, matching the * single-scope tail placement). Empty layers are omitted. Each layer's content is byte-capped + fence-sanitized * exactly like {@link composeMemoryBlock} (the same A-7 escape class). Returns `undefined` when every layer is * empty (no block to inject). * * **Cache-stability guarantee (ยง5):** the subsection order is EXACTLY the caller's list order โ€” never sorted * or reordered here โ€” and the per-scope wrapper/format is fixed, so a stable layer at the front renders * byte-identically across turns (the 90/98% prefix-cache hit measured in ยง5.1/ยง5.2 depends on this). The * VOLATILE layers the caller places last are the only part that changes, so only the tail re-computes. */ export declare function composeLayeredMemoryBlock(layers: ReadonlyArray<{ scope: string; content: string | null | undefined; }>): string | undefined;