@ai-matrx/applets 0.2.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +130 -0
- package/LICENSE +21 -0
- package/README.md +37 -0
- package/dist/context-Dz3PWsJd.d.cts +193 -0
- package/dist/context-Dz3PWsJd.d.ts +193 -0
- package/dist/frame.cjs +977 -0
- package/dist/frame.cjs.map +1 -0
- package/dist/frame.d.cts +42 -0
- package/dist/frame.d.ts +42 -0
- package/dist/frame.js +958 -0
- package/dist/frame.js.map +1 -0
- package/dist/host.cjs +664 -0
- package/dist/host.cjs.map +1 -0
- package/dist/host.d.cts +128 -0
- package/dist/host.d.ts +128 -0
- package/dist/host.js +641 -0
- package/dist/host.js.map +1 -0
- package/dist/index.cjs +66 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +200 -0
- package/dist/index.d.ts +200 -0
- package/dist/index.js +43 -0
- package/dist/index.js.map +1 -0
- package/dist/platform.cjs +699 -0
- package/dist/platform.cjs.map +1 -0
- package/dist/platform.d.cts +135 -0
- package/dist/platform.d.ts +135 -0
- package/dist/platform.js +680 -0
- package/dist/platform.js.map +1 -0
- package/dist/react.cjs +880 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +178 -0
- package/dist/react.d.ts +178 -0
- package/dist/react.js +854 -0
- package/dist/react.js.map +1 -0
- package/package.json +128 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/host/index.ts","../src/types.ts","../src/host/memory.ts"],"sourcesContent":["/**\n * `@ai-matrx/applets/host` — hosts of the doorway (CONTRACTS §1).\n *\n * 0.1.0 ships the in-memory host: real port behavior over plain data, for\n * tests, development, and hosts that wrap it. It says so (`kind: \"memory\"`).\n */\nexport {\n createMemoryHost,\n type MemoryCall,\n type MemoryControl,\n type MemoryHost,\n type MemoryHostSpec,\n type MemoryMandateSpec,\n type MemoryRunRequest,\n type MemorySurfaceSpec,\n type MemoryTableSpec,\n type MemoryWrite,\n} from \"./memory\";\nexport type { AppletHost, AppletChannel, EventMessage } from \"../types\";\n","/**\n * The Applets contract types (CONTRACTS v2 §0, §1, §3, §4, §6, §8).\n *\n * One owner per type. Types another package owns are RE-EXPORTED from it,\n * never redefined; types whose owner has not exported them yet are written\n * here structurally, each naming its owner and contract section, and are\n * replaced by a re-export the release the owner ships them.\n *\n * Framework-free: no React, no runtime imports. Every import below is a type.\n */\nimport type { EntityRefWithWords, Uuid as RecordsUuid } from \"@ai-matrx/records\";\nimport type { IntelligencePort as AgentsIntelligencePort } from \"@ai-matrx/agents/intelligence\";\nimport type { ActionResult, SurfacePort as AlchemySurfacePort } from \"@ai-matrx/alchemy/actions\";\nimport type { ScopeSpec } from \"@ai-matrx/code-runtime\";\nimport type { DataPort, DataSource, WhereClause } from \"@ai-matrx/records/data\";\nimport type { RecordsError } from \"@ai-matrx/records\";\n\n// ─── §0 — owned elsewhere, re-exported ─────────────────────────────────────\n\n/** `@ai-matrx/records` — a UUID string. */\nexport type Uuid = RecordsUuid;\n\n/** `@ai-matrx/records` (AP-3) — every link everywhere reads as `EntityRef[]` (`EntityRefWithWords`). */\nexport type EntityRef = EntityRefWithWords;\n\n/** `@ai-matrx/agents/intelligence` (AP-1). */\nexport type {\n RunRef,\n ServedInput,\n RunEvent,\n KindEnvelope,\n MandateDescription,\n RunRequest,\n RunResult,\n RunListing,\n SoftMandateSpec,\n} from \"@ai-matrx/agents/intelligence\";\n\n/** `@ai-matrx/alchemy/actions` (AP-2). */\nexport type {\n ActionDeclaration,\n ActionInfo,\n ActionContext,\n ActionCaller,\n ActionPolicy,\n ActionRuns,\n} from \"@ai-matrx/alchemy/actions\";\n\n/** `@ai-matrx/code-runtime` (AP-5). */\nexport type { ScopeSpec, CompileResult, Finding } from \"@ai-matrx/code-runtime\";\n\n/**\n * `@ai-matrx/content-ir` — a registered kind slug. content-ir types it as a\n * plain string and exports no named alias; this is that string.\n */\nexport type KindRef = string;\n\n// ─── §0 — owned here ───────────────────────────────────────────────────────\n\n/**\n * The system's own sentence. Superset of `RecordsError` in the sense of the\n * contract: `code` + the store's `message`, plus `retryable`.\n */\nexport interface AppletError {\n code: string;\n message: string;\n retryable: boolean;\n diagnostic?: string;\n}\n\n/** Never throws: every port call and every hook write answers one of these. */\nexport type Result<T> = { ok: true; data: T } | { ok: false; error: AppletError };\n\nexport type Status = \"idle\" | \"loading\" | \"ready\" | \"saving\" | \"error\";\n\n// ─── §0/§4 — owned by @ai-matrx/records (AP-3), re-exported ──────────────\n//\n// AP-3 owns Column, Row, Values, Filter, Query, Page and DataPort (CONTRACTS\n// §0 and §4); `@ai-matrx/records/data` exports them. The frame sees only the\n// port (`DataPort`, no `subscribe`); `HostDataPort` is the host's producer\n// (amendment 2.2) and never crosses the channel.\n\nexport type {\n Column,\n Row,\n Values,\n Query,\n Page,\n DataPort,\n HostDataPort,\n RowsEvent,\n DataSource,\n DataEvents,\n WhereClause,\n WhereOp,\n Lane,\n} from \"@ai-matrx/records/data\";\n\n/** CONTRACTS §4 one `where` clause — records' `WhereClause`. */\nexport type Filter = WhereClause;\n\n/** One source an Applet declared (CONTRACTS §2 `useSources`, §4 `sources()`) — records' `DataSource`. */\nexport type SourceInfo = DataSource;\n\n/** A refusal in the store's words (`RecordsError`) — what a DataPort answers. */\nexport type { RecordsError, RecordsResult } from \"@ai-matrx/records\";\n\n// ─── §3 / §6 — the ports as the host exposes them ──────────────────────────\n\n/**\n * CONTRACTS §3 `IntelligencePort` (owner `@ai-matrx/agents`, AP-1) as a host\n * port: the agents package's port minus its in-process `events` listener —\n * across the doorway, run events arrive on the host's `run:<requestId>`\n * stream instead (no port takes a function).\n */\nexport type IntelligencePort = Omit<AgentsIntelligencePort, \"events\">;\n\n/** CONTRACTS §6 `SurfacePort` (owner `@ai-matrx/alchemy`, AP-2). Events: `value:<name>`. */\nexport type SurfacePort = AlchemySurfacePort;\n\n/**\n * The payload of the `actions` event stream: a `runs: \"page\"` Action routed to\n * the frame (CONTRACTS §6). The frame answers with `surface.completeAction`.\n * `by` is a superset field so the handler's `ActionContext` is truthful.\n */\nexport interface PageActionEvent {\n action: string;\n input: unknown;\n runId: string;\n by?: \"person\" | \"agent\" | \"applet\" | \"automation\";\n}\n\n/** The stream page-Action runs arrive on. */\nexport const PAGE_ACTION_STREAM = \"actions\";\n/** The stream a host announces route changes on (payload: `NavLocation`). */\nexport const NAV_STREAM = \"nav\";\n\nexport const rowsStream = (alias: string): string => `rows:${alias}`;\nexport const runStream = (requestId: string): string => `run:${requestId}`;\nexport const valueStream = (name: string): string => `value:${name}`;\n\n/** Re-exported so hosts can type completeAction answers without importing alchemy. */\nexport type ActionAnswer<T = unknown> = ActionResult<T>;\n\n// ─── §8 — the Applet record ────────────────────────────────────────────────\n\nexport interface AppletPage {\n path: string;\n title: string;\n file: string;\n parent?: string;\n}\n\nexport interface AppletMandate {\n alias: string;\n key: string;\n}\n\nexport type AppletSource =\n | { alias: string; table_id: Uuid; organization_id: Uuid }\n | { alias: string; entity: string };\n\n/** CONTRACTS §8 `AppletRecord` (owner `@ai-matrx/applets`, AP-0). */\nexport interface AppletRecord {\n id: Uuid;\n version: number;\n organizationId: Uuid;\n slug: string;\n published: boolean;\n files: Record<string, string>;\n entry: string;\n scope: ScopeSpec;\n pages: AppletPage[];\n mandates: AppletMandate[];\n sources: AppletSource[];\n parentId: Uuid | null;\n /** `applets/<id>` */\n surfaceName: string;\n}\n\n// ─── §1 — the doorway ──────────────────────────────────────────────────────\n\nexport interface Viewer {\n userId: Uuid | null;\n organizationIds: Uuid[];\n activeOrganizationId: Uuid | null;\n guest: boolean;\n}\n\nexport interface NavLocation {\n path: string[];\n params: Record<string, string>;\n}\n\nexport interface KindComponentSource {\n files: Record<string, string>;\n entry: string;\n}\n\n/**\n * CONTRACTS §1 `AppletHost`. Every call is an async request with JSON in and\n * JSON out (kind envelopes allowed), scoped to ONE mounted Applet.\n */\nexport interface AppletHost {\n viewer(): Promise<Viewer>;\n record(): Promise<AppletRecord>;\n child(appletId: Uuid): Promise<{ hostId: string }>;\n kinds: {\n definition(slug: string): Promise<Result<unknown>>;\n component(slug: string, platform: string): Promise<Result<KindComponentSource | null>>;\n };\n pages: { definition(pageId: Uuid): Promise<Result<unknown>> };\n data: DataPort;\n intelligence: IntelligencePort;\n surface: SurfacePort;\n nav: { go(to: string): Promise<void>; current(): Promise<NavLocation> };\n events: {\n on(stream: string, filter: unknown): Promise<{ subscriptionId: string }>;\n off(subscriptionId: string): Promise<void>;\n };\n reportError(err: AppletError & { where: string }): Promise<void>;\n}\n\n/** What the frame receives for each event (CONTRACTS §1). */\nexport interface EventMessage {\n subscriptionId: string;\n payload: unknown;\n}\n\n/**\n * The frame's side of the doorway: the contract's `AppletHost` plus the two\n * things §1 says the CHANNEL supplies — receiving `{ subscriptionId, payload }`\n * messages, and addressing a child host by the `hostId` that `child()` answered.\n * An in-page host implements these in memory; a sandbox host maps them onto a\n * message channel. Neither is a port: nothing here crosses the doorway as data.\n */\nexport interface AppletChannel extends AppletHost {\n readonly hostId: string;\n /** Subscribe to every event message for this host. Returns an unsubscribe. */\n receive(listener: (message: EventMessage) => void): () => void;\n /** The scoped host for a `hostId` that `child()` answered. */\n forHost(hostId: string): AppletChannel | null;\n}\n\n// ─── helpers every half uses ───────────────────────────────────────────────\n\nexport function ok<T>(data: T): Result<T> {\n return { ok: true, data };\n}\n\nexport function fail<T = never>(code: string, message: string, retryable = false, diagnostic?: string): Result<T> {\n const error: AppletError = { code, message, retryable };\n if (diagnostic !== undefined) error.diagnostic = diagnostic;\n return { ok: false, error };\n}\n\n/**\n * A DataPort refusal (`RecordsError`) as the §0 `AppletError`: the store's code\n * and sentence verbatim, `retryable` true only where a second try could change\n * the answer (the call never reached the store, or ran out of time).\n */\nexport function fromRecordsError(error: RecordsError): AppletError {\n const out: AppletError = { code: error.code, message: error.message, retryable: error.code === \"unreachable\" || error.code === \"timed_out\" };\n if (error.diagnostic !== undefined) out.diagnostic = error.diagnostic;\n return out;\n}\n\n/** Any thrown value → an `AppletError`, keeping a system sentence when there is one. */\nexport function toAppletError(err: unknown, code = \"internal\"): AppletError {\n if (err && typeof err === \"object\") {\n const o = err as Record<string, unknown>;\n if (typeof o.code === \"string\" && typeof o.message === \"string\") {\n const out: AppletError = { code: o.code, message: o.message, retryable: o.retryable === true };\n if (typeof o.diagnostic === \"string\") out.diagnostic = o.diagnostic;\n return out;\n }\n if (err instanceof Error) return { code, message: err.message, retryable: false };\n }\n return { code, message: String(err), retryable: false };\n}\n","/**\n * `createMemoryHost(spec)` — an in-memory `AppletHost` (CONTRACTS §1) for tests,\n * development and hosts that wrap it. Every port is real behavior over plain\n * data: rows per alias with versions and stale-write refusal, a job runner that\n * emits `RunEvent`s, surface values and Actions with page-Action routing.\n *\n * It ANNOUNCES ITSELF: `kind: \"memory\"` is on every host it makes, so a screen\n * or a guard can refuse it outside tests. It never talks to a network.\n */\nimport type {\n ActionContext,\n ActionDeclaration,\n ActionInfo,\n AppletChannel,\n AppletError,\n AppletRecord,\n Column,\n DataPort,\n EventMessage,\n HostDataPort,\n KindComponentSource,\n NavLocation,\n PageActionEvent,\n Query,\n RecordsError,\n RecordsResult,\n Result,\n Row,\n RowsEvent,\n RunEvent,\n RunRef,\n ServedInput,\n SourceInfo,\n Uuid,\n Values,\n Viewer,\n} from \"../types\";\nimport type { RecordsErrorCode } from \"@ai-matrx/records\";\nimport { fail, NAV_STREAM, ok, PAGE_ACTION_STREAM, runStream, toAppletError, valueStream } from \"../types\";\n\n// ─── spec ─────────────────────────────────────────────────────────────────\n\nexport type MemoryWrite =\n | { op: \"create\"; values: Values }\n | { op: \"update\"; id: Uuid; patch: Values; baseVersion: number }\n | { op: \"archive\"; id: Uuid }\n | { op: \"restore\"; id: Uuid };\n\nexport interface MemoryTableSpec {\n label?: string;\n kind?: \"table\" | \"entity\";\n columns: Column[];\n /** Seed rows. `_id` is minted when absent; `_version` starts at 1. */\n rows?: Values[];\n canCreate?: boolean;\n canUpdate?: boolean;\n /** The organization new rows are stamped with (default: the record's). */\n organizationId?: Uuid;\n /** Refuse a write in the store's own words (return null to allow). */\n refuse?: (write: MemoryWrite) => RecordsError | null;\n}\n\nexport interface MemoryRunRequest {\n variables: Record<string, unknown>;\n userInput?: string;\n}\n\nexport interface MemoryMandateSpec {\n label: string;\n goal: string;\n outputKind?: string | null;\n inputs?: ServedInput[];\n holder?: \"agent\" | \"workflow\";\n /**\n * The run as a list of events. A `needs_input` step pauses the run; after\n * `answer(values)` the remaining steps continue (the answer is passed to\n * `afterAnswer` when given, which then supplies the rest).\n */\n script: (req: MemoryRunRequest) => RunEvent[];\n afterAnswer?: (req: MemoryRunRequest, values: Record<string, unknown>) => RunEvent[];\n}\n\nexport interface MemorySurfaceSpec {\n values?: Record<string, unknown>;\n actions?: ActionDeclaration[];\n /** `runs: \"server\"` handlers by target name. */\n serverActions?: Record<string, (input: unknown, ctx: ActionContext) => unknown>;\n}\n\nexport interface MemoryHostSpec {\n record: AppletRecord;\n viewer?: Partial<Viewer>;\n /** Tables by the alias the record declares. */\n tables?: Record<string, MemoryTableSpec>;\n /**\n * A real host DataPort (e.g. records' `createTableDataPort`) in place of\n * `tables`: the memory host then serves its data and turns its `subscribe`\n * into the `rows:<alias>` streams exactly as a real host does.\n */\n data?: HostDataPort;\n /** Mandates by KEY (the record maps aliases to keys). */\n mandates?: Record<string, MemoryMandateSpec>;\n surface?: MemorySurfaceSpec;\n kinds?: Record<string, { definition?: unknown; component?: KindComponentSource }>;\n dataPages?: Record<Uuid, unknown>;\n /** Nested Applets by id (`child(appletId)`). */\n children?: Record<Uuid, MemoryHostSpec>;\n /** The initial route (default \"/\"). */\n path?: string;\n /** Delay every answer by this many ms (default 0, still asynchronous). */\n latencyMs?: number;\n}\n\nexport interface MemoryCall {\n hostId: string;\n port: string;\n method: string;\n args: unknown[];\n}\n\nexport interface MemoryControl {\n /** Every port call, in order (for \"one request per key\" checks). */\n readonly calls: MemoryCall[];\n /** Every `reportError` call. */\n readonly errors: (AppletError & { where: string })[];\n /** The host's data port with its producer (amendment 2.2) — never handed to the frame. */\n readonly dataPort: HostDataPort;\n /** The live rows of an alias (archived ones included, flagged `_archived`). */\n rows(alias: string): Row[];\n /** A write by ANOTHER session: bumps the version and emits `rows:<alias>`. */\n externalUpdate(alias: string, id: Uuid, patch: Values): Row;\n externalCreate(alias: string, values: Values): Row;\n /** Emit any event to this host's subscribers. */\n emit(stream: string, payload: unknown): void;\n location(): NavLocation;\n}\n\nexport interface MemoryHost extends AppletChannel {\n readonly kind: \"memory\";\n readonly control: MemoryControl;\n}\n\n// ─── shared world (one per root host) ─────────────────────────────────────\n\nconst CHAIN: unique symbol = Symbol(\"applets.memory.chain\");\nconst SURFACE_NAME: unique symbol = Symbol(\"applets.memory.surfaceName\");\n\ninterface ChainLink {\n decl: ActionDeclaration;\n owner: InternalHost;\n}\n\n/** The memory host plus its private chain hooks (never part of the public type). */\ninterface InternalHost extends MemoryHost {\n [CHAIN]: () => ChainLink[];\n [SURFACE_NAME]: string;\n}\n\ninterface World {\n hosts: Map<string, InternalHost>;\n location: NavLocation;\n nextId: number;\n calls: MemoryCall[];\n errors: (AppletError & { where: string })[];\n latencyMs: number;\n pendingActions: Map<string, (result: Result<unknown>) => void>;\n}\n\nfunction mintId(world: World, prefix: string): string {\n world.nextId += 1;\n return `${prefix}-${world.nextId.toString(36).padStart(4, \"0\")}`;\n}\n\nfunction parsePath(to: string): NavLocation {\n const [pathPart = \"\", queryPart = \"\"] = to.split(\"?\");\n const path = pathPart.split(\"/\").filter(Boolean);\n const params: Record<string, string> = {};\n for (const pair of queryPart.split(\"&\").filter(Boolean)) {\n const [k = \"\", v = \"\"] = pair.split(\"=\");\n params[decodeURIComponent(k)] = decodeURIComponent(v);\n }\n return { path, params };\n}\n\nconst clone = <T>(value: T): T => (value === undefined ? value : (JSON.parse(JSON.stringify(value)) as T));\n\n// ─── rows ─────────────────────────────────────────────────────────────────\n\ninterface StoredRow {\n row: Row;\n archived: boolean;\n}\n\nfunction matches(row: Row, q: Query): boolean {\n for (const w of q.where ?? []) {\n const v = row[w.column];\n switch (w.op) {\n case \"eq\":\n if (v !== w.value) return false;\n break;\n case \"neq\":\n if (v === w.value) return false;\n break;\n case \"lt\":\n if (!((v as number) < (w.value as number))) return false;\n break;\n case \"lte\":\n if (!((v as number) <= (w.value as number))) return false;\n break;\n case \"gt\":\n if (!((v as number) > (w.value as number))) return false;\n break;\n case \"gte\":\n if (!((v as number) >= (w.value as number))) return false;\n break;\n case \"contains\":\n if (!String(v ?? \"\").toLowerCase().includes(String(w.value ?? \"\").toLowerCase())) return false;\n break;\n case \"in\":\n if (!Array.isArray(w.value) || !w.value.includes(v)) return false;\n break;\n case \"empty\":\n if (!(v === null || v === undefined || v === \"\")) return false;\n break;\n }\n }\n if (q.search) {\n const needle = q.search.toLowerCase();\n const hit = Object.entries(row).some(([k, v]) => !k.startsWith(\"_\") && typeof v === \"string\" && v.toLowerCase().includes(needle));\n if (!hit) return false;\n }\n return true;\n}\n\nfunction compare(a: unknown, b: unknown): number {\n if (a === b) return 0;\n if (a === null || a === undefined) return 1;\n if (b === null || b === undefined) return -1;\n return a < b ? -1 : 1;\n}\n\n// ─── the host ─────────────────────────────────────────────────────────────\n\n/** Create the root in-memory host for one Applet record. */\nexport function createMemoryHost(spec: MemoryHostSpec): MemoryHost {\n const world: World = {\n hosts: new Map(),\n location: parsePath(spec.path ?? \"/\"),\n nextId: 0,\n calls: [],\n errors: [],\n latencyMs: spec.latencyMs ?? 0,\n pendingActions: new Map(),\n };\n return buildHost(world, spec, \"memory:root\", null);\n}\n\nfunction buildHost(world: World, spec: MemoryHostSpec, hostId: string, parent: InternalHost | null): InternalHost {\n const record = spec.record;\n const listeners = new Set<(message: EventMessage) => void>();\n const subscriptions = new Map<string, string>(); // subscriptionId → stream\n const tables = new Map<string, { spec: MemoryTableSpec; rows: StoredRow[] }>();\n const values = new Map<string, unknown>(Object.entries(spec.surface?.values ?? {}));\n const runs = new Map<string, { ref: RunRef; startedAt: string; status: string; text: string; envelope: RunEvent | null; rest: RunEvent[]; req: MemoryRunRequest; key: string }>();\n let mounted: { mountId: string; name: string; parent: string | null } | null = null;\n\n for (const [alias, t] of Object.entries(spec.tables ?? {})) {\n const rows: StoredRow[] = (t.rows ?? []).map((values) => ({\n archived: false,\n row: {\n ...clone(values),\n _id: typeof values._id === \"string\" ? values._id : mintId(world, \"row\"),\n _version: typeof values._version === \"number\" ? values._version : 1,\n _organization_id: t.organizationId ?? record.organizationId,\n },\n }));\n tables.set(alias, { spec: t, rows });\n }\n\n const wait = (): Promise<void> => new Promise((resolve) => setTimeout(resolve, world.latencyMs));\n const log = (port: string, method: string, args: unknown[]): void => {\n world.calls.push({ hostId, port, method, args: clone(args) });\n };\n const emit = (stream: string, payload: unknown): void => {\n for (const [subscriptionId, s] of subscriptions) {\n if (s !== stream) continue;\n const message: EventMessage = { subscriptionId, payload: clone(payload) };\n for (const l of listeners) l(message);\n }\n };\n\n const refuse = <T,>(code: RecordsErrorCode, message: string, diagnostic?: string): RecordsResult<T> => ({\n ok: false,\n error: diagnostic === undefined ? { code, message } : { code, message, diagnostic },\n });\n const answer = <T,>(data: T): RecordsResult<T> => ({ ok: true, data });\n const table = (alias: string): RecordsResult<{ spec: MemoryTableSpec; rows: StoredRow[] }> => {\n const t = tables.get(alias);\n if (!t) return refuse(\"not_found\", `This Applet declares no source named \"${alias}\".`);\n return answer(t);\n };\n // The producer of `rows:<alias>` (records' HostDataPort.subscribe): every write bumps it.\n const dataListeners = new Map<string, Set<(event: RowsEvent) => void>>();\n const bump = (alias: string, event: RowsEvent): void => {\n setTimeout(() => {\n for (const l of [...(dataListeners.get(`rows:${alias}`) ?? [])]) l(clone(event));\n }, 0);\n };\n const findRow = (rows: StoredRow[], id: Uuid): StoredRow | undefined => rows.find((r) => r.row._id === id);\n\n // ── data ──\n const memoryData: HostDataPort = {\n subscribe(event, listener) {\n let set = dataListeners.get(event);\n if (!set) {\n set = new Set();\n dataListeners.set(event, set);\n }\n set.add(listener);\n const held = set;\n return () => {\n held.delete(listener);\n };\n },\n async sources() {\n log(\"data\", \"sources\", []);\n await wait();\n const out: SourceInfo[] = [...tables.entries()].map(([alias, t]) => ({\n alias,\n label: t.spec.label ?? alias,\n kind: t.spec.kind ?? \"table\",\n canCreate: t.spec.canCreate ?? true,\n canUpdate: t.spec.canUpdate ?? true,\n }));\n return answer(out);\n },\n async columns(alias) {\n log(\"data\", \"columns\", [alias]);\n await wait();\n const t = table(alias);\n return t.ok ? answer(clone(t.data.spec.columns)) : t;\n },\n async list(alias, q, cursor) {\n log(\"data\", \"list\", [alias, q, cursor]);\n await wait();\n const t = table(alias);\n if (!t.ok) return t;\n let rows = t.data.rows.filter((r) => !r.archived).map((r) => r.row).filter((r) => matches(r, q));\n for (const s of [...(q.sort ?? [])].reverse()) {\n const dir = s.direction === \"desc\" ? -1 : 1;\n rows = [...rows].sort((a, b) => dir * compare(a[s.column], b[s.column]));\n }\n const start = cursor ? rows.findIndex((r) => r._id === cursor) + 1 : 0;\n if (cursor && start === 0) return refuse(\"invalid_argument\", \"That page cursor is not from this list.\");\n const size = q.pageSize ?? 50;\n const page = rows.slice(start, start + size);\n const last = page[page.length - 1];\n return answer({ rows: clone(page), total: rows.length, cursor: start + size < rows.length && last ? last._id : null });\n },\n async get(alias, id) {\n log(\"data\", \"get\", [alias, id]);\n await wait();\n const t = table(alias);\n if (!t.ok) return t;\n const r = findRow(t.data.rows, id);\n return answer(r && !r.archived ? clone(r.row) : null);\n },\n async create(alias, values) {\n log(\"data\", \"create\", [alias, values]);\n await wait();\n const t = table(alias);\n if (!t.ok) return t;\n if (t.data.spec.canCreate === false) return refuse(\"door\", `New records cannot be added to ${t.data.spec.label ?? alias} here.`);\n const refusal = t.data.spec.refuse?.({ op: \"create\", values });\n if (refusal) return { ok: false, error: refusal };\n const row: Row = {\n ...clone(values),\n _id: mintId(world, \"row\"),\n _version: 1,\n _organization_id: t.data.spec.organizationId ?? record.organizationId,\n };\n t.data.rows.unshift({ row, archived: false });\n bump(alias, { ids: [row._id] });\n return answer(clone(row));\n },\n async update(alias, id, patch, baseVersion) {\n log(\"data\", \"update\", [alias, id, patch, baseVersion]);\n await wait();\n const t = table(alias);\n if (!t.ok) return t;\n if (t.data.spec.canUpdate === false) return refuse(\"door\", `${t.data.spec.label ?? alias} is read-only here.`);\n const stored = findRow(t.data.rows, id);\n if (!stored || stored.archived) return refuse(\"not_found\", \"This record is not here any more.\");\n if (stored.row._version !== baseVersion) {\n return refuse(\n \"stale_write\",\n \"Someone else changed this record after you opened it. Your change was not saved.\",\n `base ${baseVersion}, current ${stored.row._version}`,\n );\n }\n const refusal = t.data.spec.refuse?.({ op: \"update\", id, patch, baseVersion });\n if (refusal) return { ok: false, error: refusal };\n stored.row = { ...stored.row, ...clone(patch), _id: id, _version: stored.row._version + 1 };\n bump(alias, { ids: [id] });\n return answer(clone(stored.row));\n },\n async archive(alias, id) {\n log(\"data\", \"archive\", [alias, id]);\n await wait();\n const t = table(alias);\n if (!t.ok) return t;\n const stored = findRow(t.data.rows, id);\n if (!stored) return refuse(\"not_found\", \"This record is not here any more.\");\n const refusal = t.data.spec.refuse?.({ op: \"archive\", id });\n if (refusal) return { ok: false, error: refusal };\n stored.archived = true;\n stored.row = { ...stored.row, _version: stored.row._version + 1 };\n bump(alias, { ids: [id] });\n return answer(undefined);\n },\n async restore(alias, id) {\n log(\"data\", \"restore\", [alias, id]);\n await wait();\n const t = table(alias);\n if (!t.ok) return t;\n const stored = findRow(t.data.rows, id);\n if (!stored) return refuse(\"not_found\", \"This record is not here any more.\");\n const refusal = t.data.spec.refuse?.({ op: \"restore\", id });\n if (refusal) return { ok: false, error: refusal };\n stored.archived = false;\n stored.row = { ...stored.row, _version: stored.row._version + 1 };\n bump(alias, { ids: [id] });\n return answer(undefined);\n },\n };\n\n const dataPort: HostDataPort = spec.data ?? memoryData;\n /** What the frame is handed: the port's eight calls, never its producer. */\n const data: DataPort = {\n sources: () => dataPort.sources(),\n columns: (alias) => dataPort.columns(alias),\n list: (alias, q, cursor) => dataPort.list(alias, q, cursor),\n get: (alias, id) => dataPort.get(alias, id),\n create: (alias, values) => dataPort.create(alias, values),\n update: (alias, id, patch, baseVersion) => dataPort.update(alias, id, patch, baseVersion),\n archive: (alias, id) => dataPort.archive(alias, id),\n restore: (alias, id) => dataPort.restore(alias, id),\n };\n const rowsUnsubscribe = new Map<string, () => void>(); // subscriptionId → the port listener\n\n // ── intelligence ──\n const playRun = (requestId: string): void => {\n const run = runs.get(requestId);\n if (!run) return;\n const step = (): void => {\n const event = run.rest.shift();\n if (!event) {\n if (run.status === \"running\") {\n run.status = \"done\";\n emit(runStream(requestId), { type: \"status\", status: \"done\" } satisfies RunEvent);\n }\n return;\n }\n if (event.type === \"text\") run.text += event.delta;\n if (event.type === \"status\") run.status = event.status;\n if (event.type === \"result\") {\n run.envelope = event;\n run.status = \"done\";\n }\n if (event.type === \"error\") run.status = \"error\";\n if (event.type === \"needs_input\") run.status = \"needs_input\";\n emit(runStream(requestId), event);\n if (event.type === \"needs_input\" || event.type === \"result\" || event.type === \"error\") return;\n setTimeout(step, 0);\n };\n setTimeout(step, world.latencyMs);\n };\n\n const intelligence: MemoryHost[\"intelligence\"] = {\n async describe(key) {\n log(\"intelligence\", \"describe\", [key]);\n await wait();\n const m = spec.mandates?.[key];\n if (!m) return fail(\"mandate_not_found\", `No job named \"${key}\" exists.`);\n return ok({\n key,\n label: m.label,\n goal: m.goal,\n outputKind: m.outputKind ?? null,\n inputs: clone(m.inputs ?? []),\n holder: { type: m.holder ?? \"agent\" },\n });\n },\n async run(req) {\n log(\"intelligence\", \"run\", [req]);\n await wait();\n const m = spec.mandates?.[req.key];\n if (!m) return fail(\"mandate_not_found\", `No job named \"${req.key}\" exists.`);\n const requestId = mintId(world, \"req\");\n const ref: RunRef = { requestId, conversationId: mintId(world, \"conv\"), mandateKey: req.key };\n const runReq: MemoryRunRequest = { variables: clone(req.variables ?? {}) };\n if (req.userInput !== undefined) runReq.userInput = req.userInput;\n runs.set(requestId, {\n ref,\n startedAt: new Date().toISOString(),\n status: \"running\",\n text: \"\",\n envelope: null,\n rest: m.script(runReq),\n req: runReq,\n key: req.key,\n });\n playRun(requestId);\n return ok(ref);\n },\n async result(ref) {\n log(\"intelligence\", \"result\", [ref]);\n await wait();\n const run = runs.get(ref.requestId);\n if (!run) return fail(\"run_not_found\", \"That run is not here.\");\n const envelope = run.envelope && run.envelope.type === \"result\" ? run.envelope.envelope : null;\n return ok({ envelope: clone(envelope), text: run.text, status: run.status });\n },\n async answer(ref, answers) {\n log(\"intelligence\", \"answer\", [ref, answers]);\n await wait();\n const run = runs.get(ref.requestId);\n if (!run) return fail(\"run_not_found\", \"That run is not here.\");\n if (run.status !== \"needs_input\") return fail(\"not_waiting\", \"This run is not waiting for an answer.\");\n const m = spec.mandates?.[run.key];\n if (m?.afterAnswer) run.rest = m.afterAnswer(run.req, clone(answers));\n run.status = \"running\";\n playRun(ref.requestId);\n return ok(undefined);\n },\n async rejoin(ref) {\n log(\"intelligence\", \"rejoin\", [ref]);\n await wait();\n return runs.has(ref.requestId) ? ok(undefined) : fail(\"run_not_found\", \"That run is not here.\");\n },\n async listRuns(key) {\n log(\"intelligence\", \"listRuns\", [key]);\n await wait();\n const out = [...runs.values()]\n .filter((r) => r.key === key)\n .map((r) => ({ ref: clone(r.ref), startedAt: r.startedAt, status: r.status }))\n .reverse();\n return ok(out);\n },\n async createSoft(s) {\n log(\"intelligence\", \"createSoft\", [s]);\n await wait();\n if (spec.mandates?.[s.key]) return fail(\"already_exists\", `A job named \"${s.key}\" already exists.`);\n spec.mandates = {\n ...(spec.mandates ?? {}),\n [s.key]: { label: s.label, goal: s.goal, outputKind: s.outputKind ?? null, script: () => [] },\n };\n return ok({ key: s.key });\n },\n };\n\n // ── surface ──\n const ownActions = (): ActionDeclaration[] => spec.surface?.actions ?? [];\n const toInfo = (a: ActionDeclaration, declaredOn: string): ActionInfo => {\n const info: ActionInfo = {\n name: a.name,\n category: a.category ?? \"applet\",\n label: a.label,\n description: a.description,\n runs: a.runs,\n policy: a.policy,\n triggeredBy: [...a.triggeredBy],\n declaredOn,\n };\n if (a.input !== undefined) info.input = a.input;\n if (a.output !== undefined) info.output = a.output;\n if (a.target !== undefined) info.target = a.target;\n if (a.updatesValue !== undefined) info.updatesValue = a.updatesValue;\n return info;\n };\n /** Own + inherited, a child winning by name. */\n const chain = (): ChainLink[] => {\n const out = new Map<string, ChainLink>();\n for (const d of ownActions()) out.set(d.name, { decl: d, owner: self });\n if (parent) {\n for (const link of parent[CHAIN]()) if (!out.has(link.decl.name)) out.set(link.decl.name, link);\n }\n return [...out.values()];\n };\n\n const surface: MemoryHost[\"surface\"] = {\n async mount(name, parentName) {\n log(\"surface\", \"mount\", [name, parentName]);\n await wait();\n mounted = { mountId: mintId(world, \"mount\"), name, parent: parentName };\n return ok({ mountId: mounted.mountId });\n },\n async unmount(mountId) {\n log(\"surface\", \"unmount\", [mountId]);\n if (mounted?.mountId === mountId) mounted = null;\n },\n async getValue(name) {\n log(\"surface\", \"getValue\", [name]);\n await wait();\n return clone(values.get(name));\n },\n async setValue(name, v) {\n log(\"surface\", \"setValue\", [name, v]);\n await wait();\n values.set(name, clone(v));\n emit(valueStream(name), v);\n },\n async listActions() {\n log(\"surface\", \"listActions\", []);\n await wait();\n return chain().map((l) => toInfo(l.decl, l.owner[SURFACE_NAME]));\n },\n async runAction(name, input, by) {\n log(\"surface\", \"runAction\", [name, input, by]);\n await wait();\n const link = chain().find((l) => l.decl.name === name);\n if (!link) return fail(\"action_not_found\", `This page has no action named \"${name}\".`);\n const { decl, owner } = link;\n if (!decl.triggeredBy.includes(by)) {\n return fail(\"caller_refused\", `\"${decl.label}\" cannot be started by ${by === \"person\" ? \"a person\" : `an ${by}`}.`);\n }\n if (decl.policy === \"manual\" && by !== \"person\") {\n return fail(\"caller_refused\", `Only a person can start \"${decl.label}\".`);\n }\n const viewer = await self.viewer();\n const runId = mintId(world, \"act\");\n let result: Result<unknown>;\n switch (decl.runs) {\n case \"page\": {\n result = await new Promise<Result<unknown>>((resolve) => {\n world.pendingActions.set(runId, resolve);\n const event: PageActionEvent = { action: name, input, runId, by };\n owner.control.emit(PAGE_ACTION_STREAM, event);\n });\n break;\n }\n case \"server\": {\n const handler = spec.surface?.serverActions?.[decl.target ?? name];\n if (!handler) {\n result = fail(\"not_supported\", `The server action \"${decl.target ?? name}\" is not available here.`);\n break;\n }\n try {\n result = ok(await handler(input, { runId, by, viewerId: viewer.userId }));\n } catch (err) {\n result = { ok: false, error: toAppletError(err) };\n }\n break;\n }\n case \"mandate\": {\n const key = record.mandates.find((m) => m.alias === decl.target)?.key ?? decl.target ?? \"\";\n const variables = input && typeof input === \"object\" && !Array.isArray(input) ? (input as Record<string, unknown>) : {};\n result = await intelligence.run({ key, variables, organizationId: viewer.activeOrganizationId, appletId: record.id, surfaceName: record.surfaceName });\n break;\n }\n case \"navigate\": {\n const params = input && typeof input === \"object\" ? (input as Record<string, unknown>) : {};\n const to = (decl.target ?? \"/\").replace(/\\{(\\w+)\\}/g, (_m, k: string) => encodeURIComponent(String(params[k] ?? \"\")));\n await nav.go(to);\n result = ok(to);\n break;\n }\n }\n if (result.ok && decl.updatesValue) await surface.setValue(decl.updatesValue, result.data);\n return result;\n },\n async completeAction(runId, result) {\n log(\"surface\", \"completeAction\", [runId, result]);\n const resolve = world.pendingActions.get(runId);\n world.pendingActions.delete(runId);\n resolve?.(result);\n },\n };\n\n // ── nav ──\n const nav: MemoryHost[\"nav\"] = {\n async go(to) {\n log(\"nav\", \"go\", [to]);\n world.location = parsePath(to);\n for (const h of world.hosts.values()) h.control.emit(NAV_STREAM, world.location);\n },\n async current() {\n log(\"nav\", \"current\", []);\n return clone(world.location);\n },\n };\n\n let childCount = 0;\n const self: InternalHost = {\n kind: \"memory\",\n hostId,\n [CHAIN]: chain,\n [SURFACE_NAME]: record.surfaceName,\n async viewer() {\n log(\"host\", \"viewer\", []);\n return {\n userId: spec.viewer?.userId ?? \"memory-viewer\",\n organizationIds: spec.viewer?.organizationIds ?? [record.organizationId],\n activeOrganizationId: spec.viewer?.activeOrganizationId ?? record.organizationId,\n guest: spec.viewer?.guest ?? false,\n };\n },\n async record() {\n log(\"host\", \"record\", []);\n await wait();\n return clone(record);\n },\n async child(appletId) {\n log(\"host\", \"child\", [appletId]);\n await wait();\n const childSpec = spec.children?.[appletId];\n if (!childSpec) throw new Error(`[applets/memory] no child Applet \"${appletId}\" in this memory host's spec.`);\n childCount += 1;\n const childId = `${hostId}/${appletId}#${childCount}`;\n buildHost(world, { latencyMs: world.latencyMs, ...childSpec }, childId, self);\n return { hostId: childId };\n },\n kinds: {\n async definition(slug) {\n log(\"kinds\", \"definition\", [slug]);\n const k = spec.kinds?.[slug];\n return k?.definition !== undefined ? ok(clone(k.definition)) : fail(\"kind_not_found\", `No kind named \"${slug}\".`);\n },\n async component(slug, platform) {\n log(\"kinds\", \"component\", [slug, platform]);\n return ok(clone(spec.kinds?.[slug]?.component ?? null));\n },\n },\n pages: {\n async definition(pageId) {\n log(\"pages\", \"definition\", [pageId]);\n const p = spec.dataPages?.[pageId];\n return p !== undefined ? ok(clone(p)) : fail(\"page_not_found\", \"That page is not here.\");\n },\n },\n data,\n intelligence,\n surface,\n nav,\n events: {\n async on(stream, filter) {\n log(\"events\", \"on\", [stream, filter]);\n const subscriptionId = mintId(world, \"sub\");\n subscriptions.set(subscriptionId, stream);\n if (stream.startsWith(\"rows:\")) {\n // The AppletHost turns the port's producer into the stream (amendment 2.2).\n const stop = dataPort.subscribe(stream as `rows:${string}`, (event) => {\n const message: EventMessage = { subscriptionId, payload: clone(event) };\n for (const l of listeners) l(message);\n });\n rowsUnsubscribe.set(subscriptionId, stop);\n }\n return { subscriptionId };\n },\n async off(subscriptionId) {\n log(\"events\", \"off\", [subscriptionId]);\n subscriptions.delete(subscriptionId);\n rowsUnsubscribe.get(subscriptionId)?.();\n rowsUnsubscribe.delete(subscriptionId);\n },\n },\n async reportError(err) {\n log(\"host\", \"reportError\", [err]);\n world.errors.push(clone(err));\n },\n receive(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n forHost(id) {\n return world.hosts.get(id) ?? null;\n },\n control: {\n dataPort,\n get calls() {\n return world.calls;\n },\n get errors() {\n return world.errors;\n },\n rows(alias) {\n return (tables.get(alias)?.rows ?? []).map((r) => ({ ...clone(r.row), ...(r.archived ? { _archived: true } : {}) }));\n },\n externalUpdate(alias, id, patch) {\n const stored = findRow(tables.get(alias)?.rows ?? [], id);\n if (!stored) throw new Error(`[applets/memory] no row ${id} in ${alias}`);\n stored.row = { ...stored.row, ...clone(patch), _version: stored.row._version + 1 };\n bump(alias, { ids: [id] });\n return clone(stored.row);\n },\n externalCreate(alias, values) {\n const t = tables.get(alias);\n if (!t) throw new Error(`[applets/memory] no table ${alias}`);\n const row: Row = { ...clone(values), _id: mintId(world, \"row\"), _version: 1, _organization_id: t.spec.organizationId ?? record.organizationId };\n t.rows.unshift({ row, archived: false });\n bump(alias, { ids: [row._id] });\n return clone(row);\n },\n emit,\n location() {\n return clone(world.location);\n },\n },\n };\n world.hosts.set(hostId, self);\n return self;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACqIO,IAAM,qBAAqB;AAE3B,IAAM,aAAa;AAGnB,IAAM,YAAY,CAAC,cAA8B,OAAO,SAAS;AACjE,IAAM,cAAc,CAAC,SAAyB,SAAS,IAAI;AA2G3D,SAAS,GAAM,MAAoB;AACxC,SAAO,EAAE,IAAI,MAAM,KAAK;AAC1B;AAEO,SAAS,KAAgB,MAAc,SAAiB,YAAY,OAAO,YAAgC;AAChH,QAAM,QAAqB,EAAE,MAAM,SAAS,UAAU;AACtD,MAAI,eAAe,OAAW,OAAM,aAAa;AACjD,SAAO,EAAE,IAAI,OAAO,MAAM;AAC5B;AAcO,SAAS,cAAc,KAAc,OAAO,YAAyB;AAC1E,MAAI,OAAO,OAAO,QAAQ,UAAU;AAClC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AACT;","names":["values","data"]}
|
package/dist/host.d.cts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { AppletError, Uuid, NavLocation, AppletChannel, AppletRecord, Viewer, KindComponentSource } from './index.cjs';
|
|
2
|
+
export { AppletHost, EventMessage } from './index.cjs';
|
|
3
|
+
import { HostDataPort, Row, Values, Column } from '@ai-matrx/records/data';
|
|
4
|
+
import { RecordsError } from '@ai-matrx/records';
|
|
5
|
+
import { ServedInput, RunEvent } from '@ai-matrx/agents/intelligence';
|
|
6
|
+
import { ActionDeclaration, ActionContext } from '@ai-matrx/alchemy/actions';
|
|
7
|
+
import '@ai-matrx/code-runtime';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `createMemoryHost(spec)` — an in-memory `AppletHost` (CONTRACTS §1) for tests,
|
|
11
|
+
* development and hosts that wrap it. Every port is real behavior over plain
|
|
12
|
+
* data: rows per alias with versions and stale-write refusal, a job runner that
|
|
13
|
+
* emits `RunEvent`s, surface values and Actions with page-Action routing.
|
|
14
|
+
*
|
|
15
|
+
* It ANNOUNCES ITSELF: `kind: "memory"` is on every host it makes, so a screen
|
|
16
|
+
* or a guard can refuse it outside tests. It never talks to a network.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
type MemoryWrite = {
|
|
20
|
+
op: "create";
|
|
21
|
+
values: Values;
|
|
22
|
+
} | {
|
|
23
|
+
op: "update";
|
|
24
|
+
id: Uuid;
|
|
25
|
+
patch: Values;
|
|
26
|
+
baseVersion: number;
|
|
27
|
+
} | {
|
|
28
|
+
op: "archive";
|
|
29
|
+
id: Uuid;
|
|
30
|
+
} | {
|
|
31
|
+
op: "restore";
|
|
32
|
+
id: Uuid;
|
|
33
|
+
};
|
|
34
|
+
interface MemoryTableSpec {
|
|
35
|
+
label?: string;
|
|
36
|
+
kind?: "table" | "entity";
|
|
37
|
+
columns: Column[];
|
|
38
|
+
/** Seed rows. `_id` is minted when absent; `_version` starts at 1. */
|
|
39
|
+
rows?: Values[];
|
|
40
|
+
canCreate?: boolean;
|
|
41
|
+
canUpdate?: boolean;
|
|
42
|
+
/** The organization new rows are stamped with (default: the record's). */
|
|
43
|
+
organizationId?: Uuid;
|
|
44
|
+
/** Refuse a write in the store's own words (return null to allow). */
|
|
45
|
+
refuse?: (write: MemoryWrite) => RecordsError | null;
|
|
46
|
+
}
|
|
47
|
+
interface MemoryRunRequest {
|
|
48
|
+
variables: Record<string, unknown>;
|
|
49
|
+
userInput?: string;
|
|
50
|
+
}
|
|
51
|
+
interface MemoryMandateSpec {
|
|
52
|
+
label: string;
|
|
53
|
+
goal: string;
|
|
54
|
+
outputKind?: string | null;
|
|
55
|
+
inputs?: ServedInput[];
|
|
56
|
+
holder?: "agent" | "workflow";
|
|
57
|
+
/**
|
|
58
|
+
* The run as a list of events. A `needs_input` step pauses the run; after
|
|
59
|
+
* `answer(values)` the remaining steps continue (the answer is passed to
|
|
60
|
+
* `afterAnswer` when given, which then supplies the rest).
|
|
61
|
+
*/
|
|
62
|
+
script: (req: MemoryRunRequest) => RunEvent[];
|
|
63
|
+
afterAnswer?: (req: MemoryRunRequest, values: Record<string, unknown>) => RunEvent[];
|
|
64
|
+
}
|
|
65
|
+
interface MemorySurfaceSpec {
|
|
66
|
+
values?: Record<string, unknown>;
|
|
67
|
+
actions?: ActionDeclaration[];
|
|
68
|
+
/** `runs: "server"` handlers by target name. */
|
|
69
|
+
serverActions?: Record<string, (input: unknown, ctx: ActionContext) => unknown>;
|
|
70
|
+
}
|
|
71
|
+
interface MemoryHostSpec {
|
|
72
|
+
record: AppletRecord;
|
|
73
|
+
viewer?: Partial<Viewer>;
|
|
74
|
+
/** Tables by the alias the record declares. */
|
|
75
|
+
tables?: Record<string, MemoryTableSpec>;
|
|
76
|
+
/**
|
|
77
|
+
* A real host DataPort (e.g. records' `createTableDataPort`) in place of
|
|
78
|
+
* `tables`: the memory host then serves its data and turns its `subscribe`
|
|
79
|
+
* into the `rows:<alias>` streams exactly as a real host does.
|
|
80
|
+
*/
|
|
81
|
+
data?: HostDataPort;
|
|
82
|
+
/** Mandates by KEY (the record maps aliases to keys). */
|
|
83
|
+
mandates?: Record<string, MemoryMandateSpec>;
|
|
84
|
+
surface?: MemorySurfaceSpec;
|
|
85
|
+
kinds?: Record<string, {
|
|
86
|
+
definition?: unknown;
|
|
87
|
+
component?: KindComponentSource;
|
|
88
|
+
}>;
|
|
89
|
+
dataPages?: Record<Uuid, unknown>;
|
|
90
|
+
/** Nested Applets by id (`child(appletId)`). */
|
|
91
|
+
children?: Record<Uuid, MemoryHostSpec>;
|
|
92
|
+
/** The initial route (default "/"). */
|
|
93
|
+
path?: string;
|
|
94
|
+
/** Delay every answer by this many ms (default 0, still asynchronous). */
|
|
95
|
+
latencyMs?: number;
|
|
96
|
+
}
|
|
97
|
+
interface MemoryCall {
|
|
98
|
+
hostId: string;
|
|
99
|
+
port: string;
|
|
100
|
+
method: string;
|
|
101
|
+
args: unknown[];
|
|
102
|
+
}
|
|
103
|
+
interface MemoryControl {
|
|
104
|
+
/** Every port call, in order (for "one request per key" checks). */
|
|
105
|
+
readonly calls: MemoryCall[];
|
|
106
|
+
/** Every `reportError` call. */
|
|
107
|
+
readonly errors: (AppletError & {
|
|
108
|
+
where: string;
|
|
109
|
+
})[];
|
|
110
|
+
/** The host's data port with its producer (amendment 2.2) — never handed to the frame. */
|
|
111
|
+
readonly dataPort: HostDataPort;
|
|
112
|
+
/** The live rows of an alias (archived ones included, flagged `_archived`). */
|
|
113
|
+
rows(alias: string): Row[];
|
|
114
|
+
/** A write by ANOTHER session: bumps the version and emits `rows:<alias>`. */
|
|
115
|
+
externalUpdate(alias: string, id: Uuid, patch: Values): Row;
|
|
116
|
+
externalCreate(alias: string, values: Values): Row;
|
|
117
|
+
/** Emit any event to this host's subscribers. */
|
|
118
|
+
emit(stream: string, payload: unknown): void;
|
|
119
|
+
location(): NavLocation;
|
|
120
|
+
}
|
|
121
|
+
interface MemoryHost extends AppletChannel {
|
|
122
|
+
readonly kind: "memory";
|
|
123
|
+
readonly control: MemoryControl;
|
|
124
|
+
}
|
|
125
|
+
/** Create the root in-memory host for one Applet record. */
|
|
126
|
+
declare function createMemoryHost(spec: MemoryHostSpec): MemoryHost;
|
|
127
|
+
|
|
128
|
+
export { AppletChannel, type MemoryCall, type MemoryControl, type MemoryHost, type MemoryHostSpec, type MemoryMandateSpec, type MemoryRunRequest, type MemorySurfaceSpec, type MemoryTableSpec, type MemoryWrite, createMemoryHost };
|
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { AppletError, Uuid, NavLocation, AppletChannel, AppletRecord, Viewer, KindComponentSource } from './index.js';
|
|
2
|
+
export { AppletHost, EventMessage } from './index.js';
|
|
3
|
+
import { HostDataPort, Row, Values, Column } from '@ai-matrx/records/data';
|
|
4
|
+
import { RecordsError } from '@ai-matrx/records';
|
|
5
|
+
import { ServedInput, RunEvent } from '@ai-matrx/agents/intelligence';
|
|
6
|
+
import { ActionDeclaration, ActionContext } from '@ai-matrx/alchemy/actions';
|
|
7
|
+
import '@ai-matrx/code-runtime';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* `createMemoryHost(spec)` — an in-memory `AppletHost` (CONTRACTS §1) for tests,
|
|
11
|
+
* development and hosts that wrap it. Every port is real behavior over plain
|
|
12
|
+
* data: rows per alias with versions and stale-write refusal, a job runner that
|
|
13
|
+
* emits `RunEvent`s, surface values and Actions with page-Action routing.
|
|
14
|
+
*
|
|
15
|
+
* It ANNOUNCES ITSELF: `kind: "memory"` is on every host it makes, so a screen
|
|
16
|
+
* or a guard can refuse it outside tests. It never talks to a network.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
type MemoryWrite = {
|
|
20
|
+
op: "create";
|
|
21
|
+
values: Values;
|
|
22
|
+
} | {
|
|
23
|
+
op: "update";
|
|
24
|
+
id: Uuid;
|
|
25
|
+
patch: Values;
|
|
26
|
+
baseVersion: number;
|
|
27
|
+
} | {
|
|
28
|
+
op: "archive";
|
|
29
|
+
id: Uuid;
|
|
30
|
+
} | {
|
|
31
|
+
op: "restore";
|
|
32
|
+
id: Uuid;
|
|
33
|
+
};
|
|
34
|
+
interface MemoryTableSpec {
|
|
35
|
+
label?: string;
|
|
36
|
+
kind?: "table" | "entity";
|
|
37
|
+
columns: Column[];
|
|
38
|
+
/** Seed rows. `_id` is minted when absent; `_version` starts at 1. */
|
|
39
|
+
rows?: Values[];
|
|
40
|
+
canCreate?: boolean;
|
|
41
|
+
canUpdate?: boolean;
|
|
42
|
+
/** The organization new rows are stamped with (default: the record's). */
|
|
43
|
+
organizationId?: Uuid;
|
|
44
|
+
/** Refuse a write in the store's own words (return null to allow). */
|
|
45
|
+
refuse?: (write: MemoryWrite) => RecordsError | null;
|
|
46
|
+
}
|
|
47
|
+
interface MemoryRunRequest {
|
|
48
|
+
variables: Record<string, unknown>;
|
|
49
|
+
userInput?: string;
|
|
50
|
+
}
|
|
51
|
+
interface MemoryMandateSpec {
|
|
52
|
+
label: string;
|
|
53
|
+
goal: string;
|
|
54
|
+
outputKind?: string | null;
|
|
55
|
+
inputs?: ServedInput[];
|
|
56
|
+
holder?: "agent" | "workflow";
|
|
57
|
+
/**
|
|
58
|
+
* The run as a list of events. A `needs_input` step pauses the run; after
|
|
59
|
+
* `answer(values)` the remaining steps continue (the answer is passed to
|
|
60
|
+
* `afterAnswer` when given, which then supplies the rest).
|
|
61
|
+
*/
|
|
62
|
+
script: (req: MemoryRunRequest) => RunEvent[];
|
|
63
|
+
afterAnswer?: (req: MemoryRunRequest, values: Record<string, unknown>) => RunEvent[];
|
|
64
|
+
}
|
|
65
|
+
interface MemorySurfaceSpec {
|
|
66
|
+
values?: Record<string, unknown>;
|
|
67
|
+
actions?: ActionDeclaration[];
|
|
68
|
+
/** `runs: "server"` handlers by target name. */
|
|
69
|
+
serverActions?: Record<string, (input: unknown, ctx: ActionContext) => unknown>;
|
|
70
|
+
}
|
|
71
|
+
interface MemoryHostSpec {
|
|
72
|
+
record: AppletRecord;
|
|
73
|
+
viewer?: Partial<Viewer>;
|
|
74
|
+
/** Tables by the alias the record declares. */
|
|
75
|
+
tables?: Record<string, MemoryTableSpec>;
|
|
76
|
+
/**
|
|
77
|
+
* A real host DataPort (e.g. records' `createTableDataPort`) in place of
|
|
78
|
+
* `tables`: the memory host then serves its data and turns its `subscribe`
|
|
79
|
+
* into the `rows:<alias>` streams exactly as a real host does.
|
|
80
|
+
*/
|
|
81
|
+
data?: HostDataPort;
|
|
82
|
+
/** Mandates by KEY (the record maps aliases to keys). */
|
|
83
|
+
mandates?: Record<string, MemoryMandateSpec>;
|
|
84
|
+
surface?: MemorySurfaceSpec;
|
|
85
|
+
kinds?: Record<string, {
|
|
86
|
+
definition?: unknown;
|
|
87
|
+
component?: KindComponentSource;
|
|
88
|
+
}>;
|
|
89
|
+
dataPages?: Record<Uuid, unknown>;
|
|
90
|
+
/** Nested Applets by id (`child(appletId)`). */
|
|
91
|
+
children?: Record<Uuid, MemoryHostSpec>;
|
|
92
|
+
/** The initial route (default "/"). */
|
|
93
|
+
path?: string;
|
|
94
|
+
/** Delay every answer by this many ms (default 0, still asynchronous). */
|
|
95
|
+
latencyMs?: number;
|
|
96
|
+
}
|
|
97
|
+
interface MemoryCall {
|
|
98
|
+
hostId: string;
|
|
99
|
+
port: string;
|
|
100
|
+
method: string;
|
|
101
|
+
args: unknown[];
|
|
102
|
+
}
|
|
103
|
+
interface MemoryControl {
|
|
104
|
+
/** Every port call, in order (for "one request per key" checks). */
|
|
105
|
+
readonly calls: MemoryCall[];
|
|
106
|
+
/** Every `reportError` call. */
|
|
107
|
+
readonly errors: (AppletError & {
|
|
108
|
+
where: string;
|
|
109
|
+
})[];
|
|
110
|
+
/** The host's data port with its producer (amendment 2.2) — never handed to the frame. */
|
|
111
|
+
readonly dataPort: HostDataPort;
|
|
112
|
+
/** The live rows of an alias (archived ones included, flagged `_archived`). */
|
|
113
|
+
rows(alias: string): Row[];
|
|
114
|
+
/** A write by ANOTHER session: bumps the version and emits `rows:<alias>`. */
|
|
115
|
+
externalUpdate(alias: string, id: Uuid, patch: Values): Row;
|
|
116
|
+
externalCreate(alias: string, values: Values): Row;
|
|
117
|
+
/** Emit any event to this host's subscribers. */
|
|
118
|
+
emit(stream: string, payload: unknown): void;
|
|
119
|
+
location(): NavLocation;
|
|
120
|
+
}
|
|
121
|
+
interface MemoryHost extends AppletChannel {
|
|
122
|
+
readonly kind: "memory";
|
|
123
|
+
readonly control: MemoryControl;
|
|
124
|
+
}
|
|
125
|
+
/** Create the root in-memory host for one Applet record. */
|
|
126
|
+
declare function createMemoryHost(spec: MemoryHostSpec): MemoryHost;
|
|
127
|
+
|
|
128
|
+
export { AppletChannel, type MemoryCall, type MemoryControl, type MemoryHost, type MemoryHostSpec, type MemoryMandateSpec, type MemoryRunRequest, type MemorySurfaceSpec, type MemoryTableSpec, type MemoryWrite, createMemoryHost };
|