@ai-matrx/alchemy 0.12.3 → 0.14.0
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 +46 -0
- package/dist/actions.cjs.map +1 -1
- package/dist/actions.d.cts +19 -24
- package/dist/actions.d.ts +19 -24
- package/dist/actions.js.map +1 -1
- package/dist/checks.d.cts +2 -0
- package/dist/checks.d.ts +2 -0
- package/dist/core.cjs +4 -4
- package/dist/core.cjs.map +1 -1
- package/dist/core.d.cts +8 -58
- package/dist/core.d.ts +8 -58
- package/dist/core.js +4 -4
- package/dist/core.js.map +1 -1
- package/dist/declare/schema.json +3 -0
- package/dist/declare.cjs +1 -1
- package/dist/declare.cjs.map +1 -1
- package/dist/declare.d.cts +26 -1
- package/dist/declare.d.ts +26 -1
- package/dist/declare.js +1 -1
- package/dist/declare.js.map +1 -1
- package/dist/index.cjs +4 -4
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +8 -58
- package/dist/index.d.ts +8 -58
- package/dist/index.js +4 -4
- package/dist/index.js.map +1 -1
- package/dist/menu.d.cts +17 -22
- package/dist/menu.d.ts +17 -22
- package/dist/operate-document.cjs +2 -2
- package/dist/operate-document.cjs.map +1 -1
- package/dist/operate-document.d.cts +4 -42
- package/dist/operate-document.d.ts +4 -42
- package/dist/operate-document.js +2 -2
- package/dist/operate-document.js.map +1 -1
- package/dist/operate-rich-html.cjs +1 -1
- package/dist/operate-rich-html.cjs.map +1 -1
- package/dist/operate-rich-html.d.cts +3 -42
- package/dist/operate-rich-html.d.ts +3 -42
- package/dist/operate-rich-html.js +1 -1
- package/dist/operate-rich-html.js.map +1 -1
- package/dist/operate-server.cjs +1 -1
- package/dist/operate-server.cjs.map +1 -1
- package/dist/operate-server.d.cts +8 -46
- package/dist/operate-server.d.ts +8 -46
- package/dist/operate-server.js +1 -1
- package/dist/operate-server.js.map +1 -1
- package/dist/operate-xlsx.cjs +2 -2
- package/dist/operate-xlsx.cjs.map +1 -1
- package/dist/operate-xlsx.d.cts +4 -42
- package/dist/operate-xlsx.d.ts +4 -42
- package/dist/operate-xlsx.js +2 -2
- package/dist/operate-xlsx.js.map +1 -1
- package/dist/operate.cjs +4 -4
- package/dist/operate.cjs.map +1 -1
- package/dist/operate.d.cts +8 -58
- package/dist/operate.d.ts +8 -58
- package/dist/operate.js +4 -4
- package/dist/operate.js.map +1 -1
- package/dist/ports.d.cts +11 -15
- package/dist/ports.d.ts +11 -15
- package/dist/react-bar.cjs.map +1 -1
- package/dist/react-bar.d.cts +3 -1
- package/dist/react-bar.d.ts +3 -1
- package/dist/react-bar.js.map +1 -1
- package/dist/react-host.d.cts +17 -22
- package/dist/react-host.d.ts +17 -22
- package/dist/react-menu.cjs.map +1 -1
- package/dist/react-menu.d.cts +3 -1
- package/dist/react-menu.d.ts +3 -1
- package/dist/react-menu.js.map +1 -1
- package/dist/react-overflow.cjs.map +1 -1
- package/dist/react-overflow.d.cts +17 -22
- package/dist/react-overflow.d.ts +17 -22
- package/dist/react-overflow.js.map +1 -1
- package/dist/react-palette.cjs.map +1 -1
- package/dist/react-palette.d.cts +3 -1
- package/dist/react-palette.d.ts +3 -1
- package/dist/react-palette.js.map +1 -1
- package/dist/react-selection.cjs.map +1 -1
- package/dist/react-selection.d.cts +3 -1
- package/dist/react-selection.d.ts +3 -1
- package/dist/react-selection.js.map +1 -1
- package/dist/react-sheet.cjs.map +1 -1
- package/dist/react-sheet.d.cts +3 -1
- package/dist/react-sheet.d.ts +3 -1
- package/dist/react-sheet.js.map +1 -1
- package/dist/react-workspace.cjs +7 -0
- package/dist/react-workspace.cjs.map +1 -0
- package/dist/react-workspace.d.cts +441 -0
- package/dist/react-workspace.d.ts +441 -0
- package/dist/react-workspace.js +7 -0
- package/dist/react-workspace.js.map +1 -0
- package/dist/react.cjs +1 -1
- package/dist/react.cjs.map +1 -1
- package/dist/react.d.cts +2 -2
- package/dist/react.d.ts +2 -2
- package/dist/react.js +1 -1
- package/dist/react.js.map +1 -1
- package/dist/surface.cjs +1 -1
- package/dist/surface.cjs.map +1 -1
- package/dist/surface.d.cts +222 -16
- package/dist/surface.d.ts +222 -16
- package/dist/surface.js +1 -1
- package/dist/surface.js.map +1 -1
- package/package.json +14 -4
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,51 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.14.0 — 2026-10-06
|
|
4
|
+
|
|
5
|
+
ALC-18 (Live values and items):
|
|
6
|
+
|
|
7
|
+
- `/surface` live values: `liveValues` (the one store of this realm) / `createLiveValues()` — a mounted page
|
|
8
|
+
`publish`es ONE `LiveCapture` (surface name, title, route, identity, selection, sections, errors, requests),
|
|
9
|
+
descendants `contribute` sections; `read` / `outline` / `readFor(surfaceName)` / `subscribe` / `version`.
|
|
10
|
+
`mergeLiveCapture`, `liveSlotsOf` (the four declared `LiveSlot`s as views of the capture) and `liveValueOf`.
|
|
11
|
+
- `createSurfacePort({ live })`: `getValue(name)` on a value nobody set reads the mounted surface's live capture,
|
|
12
|
+
only while a page publishing THAT surface is mounted.
|
|
13
|
+
- `/surface` item sources: `itemSources` / `createItemSources()` — one source per mounted container;
|
|
14
|
+
`resolve({ containerId, level, itemId?, partId? })` answers the declared item (`InternalResolvedItem`) plus the
|
|
15
|
+
owner's opaque `host` data; a throwing source answers null and is reported.
|
|
16
|
+
- `/declare`: `TABLE_ROW_ITEM_TYPE` (`table_row`, identity `table_id` + `row_id`, levels selection / cell / column /
|
|
17
|
+
row / table); `createDeclarationRegistry({ baselineItemTypes })` gives every surface those item types unless it
|
|
18
|
+
declares its own of the same name or sets `skipBaselineItemTypes` (new declaration field). The sync writes them
|
|
19
|
+
to `ui.ui_surface_item_type` like any declared item type.
|
|
20
|
+
|
|
21
|
+
Consumer action: pass `baselineItemTypes: [TABLE_ROW_ITEM_TYPE]` to the declaration registry; publish page
|
|
22
|
+
captures through `liveValues` and resolve clicked rows through `itemSources` instead of private registries.
|
|
23
|
+
|
|
24
|
+
## 0.13.1 — 2026-10-06
|
|
25
|
+
|
|
26
|
+
`ContentTransferError`, `normalizeTransferJson`, `NormalizeTransferJsonOptions` and the `Json` / `Payload` /
|
|
27
|
+
`Column` types now come from `@ai-matrx/kit/transfer-json` (kit 0.24.0), the one copy; `@ai-matrx/alchemy/operate`
|
|
28
|
+
re-exports them unchanged. kit's `/content-transfer` entry is deleted.
|
|
29
|
+
|
|
30
|
+
Consumer action: none; install with kit >= 0.24.0.
|
|
31
|
+
|
|
32
|
+
## 0.13.0 — 2026-10-06
|
|
33
|
+
|
|
34
|
+
ALC-16: THE copy / transform / export menu and its preparation workspace moved here.
|
|
35
|
+
|
|
36
|
+
- New subpath `@ai-matrx/alchemy/react/workspace` (from design-system's removed `./content-transfer`):
|
|
37
|
+
`ContentTransferMenu`, `MatrxCopyMenu`, `ContentTransferCapabilitiesProvider`, the surface provider,
|
|
38
|
+
the workspace, `tableSchemaFormat` / `tableDataFormat`, and `AlchemyTableCopyControls` (bind it as
|
|
39
|
+
`MatrxDataTableHost.CopyControls`). `@ai-matrx/alchemy/react` re-exports it.
|
|
40
|
+
- Typed on `/operate`: `ContentTransferCapabilities.formats` takes the contract's lazy `FormatAdapter`
|
|
41
|
+
(`load()` → engine → `build(draft, options, signal)`); `ai` takes `/operate`'s `AiPreparation`.
|
|
42
|
+
- One engine per format: rich Markdown copy/HTML is print's Markdown→HTML (`rich-html`, inline skin)
|
|
43
|
+
instead of `marked` + DOMPurify; the workbook is `/operate/formats/xlsx`.
|
|
44
|
+
- `/actions`, `/menu` and `/react/*` declarations import their transfer types from
|
|
45
|
+
`@ai-matrx/alchemy/operate` (no `@ai-matrx/kit/content-transfer`).
|
|
46
|
+
- Consumer action: import menu symbols from `@ai-matrx/alchemy/react/workspace`; give each host format
|
|
47
|
+
the lazy shape (`extension`, `mime`, `modes`, `runsOn: "client"`, `load`) instead of `build(draft, signal)`.
|
|
48
|
+
|
|
3
49
|
## 0.12.3
|
|
4
50
|
|
|
5
51
|
- A write can return what it produced: `WriteHandlerResult`'s applied variant gains `result?: Json`, and the applied
|
package/dist/actions.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/actions.ts","../src/actions/click-target.ts","../src/actions/types.ts","../src/declare/sensitivity.ts","../src/declare/keys.ts","../src/actions/target.ts","../src/actions/registry.ts","../src/actions/projection.ts","../src/actions/run.ts","../src/actions/invoke.ts","../src/declare/registry.ts","../src/actions/declarations.ts","../src/actions/surface-run.ts"],"sourcesContent":["/**\n * `@ai-matrx/alchemy/actions` — the one action registry (Matrx Alchemy CONTRACT §2.4).\n * Framework-neutral: zero React, zero `@ai-matrx/agents`.\n */\nexport {\n ACTION_CATEGORIES,\n UNIVERSAL_VERBS,\n type Action,\n type ActionCategory,\n type ActionProvider,\n type ActionRegistry,\n type ActionRunContext,\n type ActionSection,\n type ActionSurface,\n type InvocationContext,\n type ClickTarget,\n type Eligibility,\n type ProjectedReads,\n type ReadOmission,\n type ResolveRestriction,\n type ResolvedAction,\n type UniversalVerb,\n} from \"./actions/types\";\nexport {\n DuplicateActionError,\n DuplicateProviderError,\n alwaysEligible,\n computeEligibility,\n createActionRegistry,\n isMenuAction,\n staticActionProvider,\n type ActionRegistryOptions,\n} from \"./actions/registry\";\nexport { createProjectedReads, projectValues, type ProjectionSource } from \"./actions/projection\";\nexport { createClickTarget, type ClickTargetInput } from \"./actions/target\";\nexport { runAction, type RunActionOptions, type RunResult } from \"./actions/run\";\nexport {\n invocableAction,\n invokeAction,\n type InvocableActionDefinition,\n type InvokeActionOptions,\n} from \"./actions/invoke\";\nexport type {\n ActionCaller,\n ActionContext,\n ActionDeclaration,\n ActionDeclaredBy,\n ActionError,\n ActionInfo,\n ActionInput,\n ActionOrigin,\n ActionPolicy,\n ActionResult,\n ActionRuns,\n ActionWriteMode,\n MandateRunRef,\n MandateRunRequest,\n ServerActionRunRequest,\n ServerActionRunResponse,\n SurfacePort,\n} from \"./actions/applet-types\";\nexport {\n ACTION_CALLERS,\n ACTION_POLICIES,\n ACTION_RUNS,\n APPLET_CATEGORY,\n DEFAULT_TRIGGERED_BY,\n clientToolToAction,\n resolveActionChain,\n surfaceActionRowToAction,\n toActionInfo,\n writeTargetToAction,\n type ActionChainLink,\n type ClientToolRow,\n type SurfaceActionRow,\n} from \"./actions/declarations\";\nexport {\n fillActionTarget,\n refuseCaller,\n runSurfaceAction,\n type RunSurfaceActionOptions,\n type SurfaceActionPorts,\n} from \"./actions/surface-run\";\n","/**\n * The click target (CONTRACT §2.4) in its own module: `/ports` references it,\n * and `/ports` must stay free of every other package (types only).\n */\nimport type { QualifiedValueKey, ResolvedItem, ResolvedSurfaceDeclaration, WriteTarget } from \"../declare/types\";\n\n/** The six universal verbs — the ONLY rows that may grey (R1 c). */\nexport const UNIVERSAL_VERBS = [\"copy\", \"cut\", \"paste\", \"undo\", \"redo\", \"find\"] as const;\nexport type UniversalVerb = (typeof UNIVERSAL_VERBS)[number];\n\n/** The transfer Payload's kinds (`actions/types.ts` asserts equality at compile time). */\nexport type PayloadKind = \"text\" | \"markdown\" | \"json\" | \"rows\" | \"registered\";\n\n/** What eligibility is computed from: everything declared at the click target. */\nexport interface ClickTarget {\n surface: { instanceId: string; surfaceName: string } | null;\n /** The resolved declaration (inheritance applied). Eligibility decides by KEY existence over it. */\n declaration: ResolvedSurfaceDeclaration | null;\n /** Declared value keys with a read path here (screen names + qualified item keys). Key existence, not population. */\n valueKeys: ReadonlySet<QualifiedValueKey>;\n /** Scope chain, most general first: [\"global\", \"<domain>\", \"<surfaceName>\"]. */\n scopeChain: readonly string[];\n /** The surface's explicit exclusions (the one override). */\n excludedActionIds: ReadonlySet<string>;\n item: ResolvedItem | null;\n level: string | null;\n /** Offsets + the live range handle, editable or not. */\n selection: {\n text: string;\n type: \"editable\" | \"non-editable\";\n start: number;\n end: number;\n /** Opaque host handle (DOM Range / element) used to restore or stream into the selection. */\n handle?: unknown;\n } | null;\n /** Payload kinds a capture of this target would produce (from declared value types/kinds). */\n payloadKinds: readonly PayloadKind[];\n /** Declared targets writable on this target right now. */\n writable: readonly WriteTarget[];\n readOnly: boolean;\n /** True when any declared value here is secret/credential or non-exportable. */\n restricted: boolean;\n organizationId: string | null;\n auth: { authenticated: boolean; admin: boolean; creator: boolean };\n /**\n * Host-owned context a provider reads to act (the rich-document source, the\n * editable field's callbacks). Opaque to the package; never crosses into the\n * model. Providers that need it narrow it themselves.\n */\n host?: unknown;\n}\n\n","/**\n * Matrx Alchemy — Actions types (CONTRACT §2.4).\n *\n * One registry of everything a person can do to a thing. Providers plug in;\n * eligibility is computed from what is declared at the click target; duplicate\n * ids are refused; an action that does not apply is ABSENT (chair ruling R1).\n *\n * Framework-neutral: zero React, zero `@ai-matrx/agents`. Icons are string KEYS\n * resolved by the host's `IconResolverPort`; labels go through `I18nPort`.\n */\nimport type { Payload, TransferOutcome } from \"@ai-matrx/kit/content-transfer\";\nimport type { Json, LiveValues } from \"../declare/types\";\nimport type { AlchemyHostPorts } from \"../ports\";\nimport type { ClickTarget, PayloadKind } from \"./click-target\";\nimport type { ActionResult } from \"./applet-types\";\n\nexport type { ClickTarget, PayloadKind } from \"./click-target\";\n\n/** PayloadKind is the transfer Payload's kind union, kept equal at compile time. */\ntype Equal<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\nconst payloadKindsAgree: Equal<PayloadKind, Payload[\"kind\"]> = true;\nvoid payloadKindsAgree;\n\nexport { UNIVERSAL_VERBS, type UniversalVerb } from \"./click-target\";\nimport type { UniversalVerb } from \"./click-target\";\n\n/**\n * Chair ruling R1: an action that does not apply or cannot run now is ABSENT.\n * Only the six universal verbs may answer \"unavailable-verb\": greyed in the\n * strip/bar, the sentence as tooltip. `requiresAuth` is NOT unavailability.\n */\nexport type Eligibility =\n | { status: \"absent\" }\n | { status: \"available\" }\n | { status: \"unavailable-verb\"; verb: UniversalVerb; sentence: string }\n /**\n * ABSENT OR HONEST (coordinator ruling 2026-09-27, admin pass): a row that cannot run here but\n * SAYS WHY (\"Unchanged from the pack\", \"Manifested surfaces are managed in code\") stays visible,\n * greyed, with its reason — the menu is the same everywhere, only availability changes. A row\n * with no reason is absent (the registry refuses an empty sentence).\n */\n | { status: \"unavailable\"; sentence: string };\n\n/** rich-document's ActionCategory, unchanged, plus the three the context menu groups by, plus \"applet\" (surface Actions). */\nexport type ActionCategory =\n | \"feedback\"\n | \"copy\"\n | \"export\"\n | \"save\"\n | \"edit\"\n | \"share\"\n | \"creator\"\n | \"app\"\n | \"listen\"\n | \"study\"\n | \"ask\"\n | \"ai\"\n | \"admin\"\n | \"clipboard\"\n | \"history\"\n | \"surface-info\"\n /** Surface Actions (Applets CONTRACTS §6): the default category of an `ActionDeclaration`. */\n | \"applet\";\n\nexport const ACTION_CATEGORIES: readonly ActionCategory[] = [\n \"feedback\",\n \"copy\",\n \"export\",\n \"save\",\n \"edit\",\n \"share\",\n \"creator\",\n \"app\",\n \"listen\",\n \"study\",\n \"ask\",\n \"ai\",\n \"admin\",\n \"clipboard\",\n \"history\",\n \"surface-info\",\n \"applet\",\n];\n\n/**\n * An optional named section inside the action's group (a grid's cell / row /\n * column). `primary` marks the thing the person clicked: every layout renders\n * it first, inline, heading kept (context-menu-v3's primary section law).\n */\nexport interface ActionSection {\n id: string;\n label: string;\n labelKey?: string;\n icon?: string;\n primary?: boolean;\n /**\n * \"group\" (default): a heading over related rows — must be in the package's\n * APPROVED_HEADINGS (@ai-matrx/alchemy/menu). \"target\": the label of the\n * thing the person clicked, supplied at run time (\"Row · Widget A\").\n */\n kind?: \"group\" | \"target\";\n}\n\n/**\n * Where an Action can be reached. \"menu\" (the default): menus, bars, palettes and sheets — it runs\n * through `run(target, ctx)`. \"invoke\": code runs it BY ID through `invokeAction` — it runs through\n * `invoke(input, ctx)`. An Action whose `surfaces` omits \"menu\" is never resolved into a menu, so it\n * needs no eligibility of its own (`invocableAction` builds one).\n */\nexport type ActionSurface = \"menu\" | \"invoke\";\n\n/** What a programmatic invocation receives: the host's ports and a capability-scoped context the caller binds. */\nexport interface InvocationContext {\n ports: AlchemyHostPorts;\n /** Opaque to the package: the capabilities the caller hands this one Action (a launcher, the acting user). */\n context: unknown;\n signal: AbortSignal;\n}\n\nexport interface Action {\n /** Globally unique. A duplicate is refused (never overwritten). */\n id: string;\n /** Where it is reachable. Default [\"menu\"]. [\"invoke\"] = programmatic only: absent from every menu. */\n surfaces?: readonly ActionSurface[];\n /** The provider that registered it — filled by the registry. */\n provider?: string;\n /** Resolved through I18nPort.t(labelKey ?? id, label). */\n label: string | ((target: ClickTarget) => string);\n labelKey?: string;\n /** Icon KEY resolved by IconResolverPort — the model stays framework-neutral. */\n icon?: string;\n /** Host styling hint for the glyph (rich-document iconColor). Renderers may ignore it. */\n iconTone?: string;\n /** Replaces `icon` while a state holds (a spinner while speaking). */\n stateIcon?(target: ClickTarget): { icon: string; spin?: boolean } | null;\n hint?: string;\n hintKey?: string;\n description?: string;\n category: ActionCategory;\n /** Which universal verb this clipboard action is (addressed by role in every layout). */\n verb?: UniversalVerb;\n order?: number;\n /** Bar layout slot. Default \"overflow\". */\n placement?: \"primary\" | \"overflow\" | \"both\";\n section?: ActionSection;\n /** A signed-out person still sees it; running goes through AuthResumePort (sign in, then resume). */\n requiresAuth?: boolean;\n /** Declared write targets this action lands through. Absent on a read-only target. */\n writes?: readonly string[];\n destructive?: boolean;\n /**\n * STARTS A NEW GROUP inside its section: the menu draws a divider above it (never as a section's\n * first row). A delete sits in its own group, last, never beside Duplicate (DATA-V2-BASICS-2).\n */\n startsGroup?: boolean;\n preserveSelection?: boolean;\n /**\n * Running it reloads rows of the menu it sits in (a \"Couldn't load. Retry\" row): the menu and its\n * open submenu stay open and show loading, then the rows or the error again. Every other run closes.\n */\n keepsMenuOpen?: boolean;\n /** Link rows navigate instead of running. */\n href?: string | ((target: ClickTarget) => string);\n eligible(target: ClickTarget): Eligibility;\n /** Toggle/pressed state: a pressed button or a checked row. */\n pressed?(target: ClickTarget): boolean;\n /** Present = the row is a checkbox (pressed is its state). */\n toggle?: boolean;\n subscribe?(onChange: () => void, target: ClickTarget): () => void;\n /**\n * The rows behind this submenu are still loading (an agent library's first\n * fetch). The row shows as loading — never absent, never silent — and its\n * `expand` resolves once they arrive.\n */\n pending?(target: ClickTarget): boolean;\n /** Submenus whose rows load on open (agent lists). */\n expand?(target: ClickTarget, signal: AbortSignal): Promise<readonly Action[]>;\n /** Shown centred when `expand` resolves empty. */\n emptyLabel?: string;\n run(target: ClickTarget, context: ActionRunContext): Promise<TransferOutcome | void> | TransferOutcome | void;\n /**\n * The typed invocation channel (programmatic Actions): input in, a never-thrown result envelope out.\n * Called only by `invokeAction`; a throw here is captured there and answered `action_failed`.\n */\n invoke?(input: unknown, context: InvocationContext): Promise<ActionResult<unknown>> | ActionResult<unknown>;\n}\n\n/** One removed read, recorded (kit content-transfer's omission shape). */\nexport interface ReadOmission {\n path: string;\n reason: \"excluded\" | \"filtered\";\n classification?: \"secret\" | \"credential\";\n}\n\n/**\n * PROJECTION BEFORE PROVIDERS. Providers never receive a raw read. Every read\n * they can make is projected first: secret and credential values, values\n * declared `exportable: false`, and values nobody declared are removed, with an\n * omission recorded. Raw reads never leave the package.\n */\nexport interface ProjectedReads {\n values(signal: AbortSignal): Promise<{ values: Record<string, Json>; omissions: readonly ReadOmission[] }>;\n item(signal: AbortSignal): Promise<{ values: Record<string, Json>; omissions: readonly ReadOmission[] } | null>;\n live(signal: AbortSignal): Promise<LiveValues>;\n}\n\n/**\n * What a running action receives. `door` (ALC-17) and `operate` (ALC-16) join\n * with their waves; until then those capabilities are absent (N8).\n */\nexport interface ActionRunContext {\n reads: ProjectedReads;\n ports: AlchemyHostPorts;\n signal: AbortSignal;\n}\n\nexport interface ActionProvider {\n id: string;\n /** T0 providers are known at mount; T1 providers load with the menu on first open. */\n tier: \"T0\" | \"T1\";\n /**\n * The ids this provider can ever yield, when known up front. Lets the\n * registry refuse a duplicate at registration instead of at first open.\n */\n declaredIds?(): readonly string[];\n actions(target: ClickTarget): readonly Action[] | Promise<readonly Action[]>;\n}\n\nexport interface ResolvedAction {\n action: Action;\n eligibility: Exclude<Eligibility, { status: \"absent\" }>;\n}\n\nexport interface ResolveRestriction {\n exclude?: readonly string[];\n categories?: readonly ActionCategory[];\n}\n\nexport interface ActionRegistry {\n /** Throws DuplicateActionError naming both providers; nothing is overwritten. */\n register(provider: ActionProvider): () => void;\n /** restrict: a host may remove ids or categories, never add ineligible ones. */\n resolve(target: ClickTarget, restrict?: ResolveRestriction): Promise<readonly ResolvedAction[]>;\n /** Registered provider ids, in registration order. */\n providers(): readonly string[];\n /**\n * One Action by id, menu-reachable or not, or null. Asks only the provider that declared the id\n * (`declaredIds`); falls back to every provider when no declaration names it. Never throws: a\n * provider that throws is captured and skipped. `target` defaults to an empty click target.\n */\n get(id: string, target?: ClickTarget): Promise<Action | null>;\n /** Change notification (a provider registered or unregistered). */\n subscribe(listener: () => void): () => void;\n}\n","/**\n * Sensitivity defaults and resolution (CONTRACT §2.1). Its own module so the\n * lightweight entries (`/actions`, the T0 React host) can project without\n * pulling the declaration registry.\n */\nimport type { DeclaredValue, Sensitivity } from \"./types\";\n\nexport const DEFAULT_SENSITIVITY: Sensitivity = Object.freeze({\n exportable: true,\n classification: \"ordinary\",\n includedByDefault: true,\n});\n\nexport function resolveSensitivity(value: Pick<DeclaredValue, \"sensitivity\">): Sensitivity {\n return {\n exportable: value.sensitivity?.exportable ?? DEFAULT_SENSITIVITY.exportable,\n classification: value.sensitivity?.classification ?? DEFAULT_SENSITIVITY.classification,\n includedByDefault: value.sensitivity?.includedByDefault ?? DEFAULT_SENSITIVITY.includedByDefault,\n };\n}\n","import type { QualifiedValueKey } from \"./types\";\n\n/** Every value, write-target, item-type and group name (the DB CHECK rule). */\nexport const DECLARATION_NAME_RE = /^[a-z][a-z0-9_]*$/;\n\n/** \"<client>/<local>\" — the surface naming convention. */\nexport const SURFACE_NAME_RE = /^[a-z][a-z0-9-]*\\/[a-z0-9-/]+$/;\n\n/** A bare screen value (`status`) or an item value (`table_row.status`). */\nexport const QUALIFIED_VALUE_KEY_RE = /^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)?$/;\n\nexport interface ParsedValueKey {\n /** \"\" for a screen-level value. */\n itemType: string;\n name: string;\n}\n\n/** Split a qualified key; null when it is not a valid bare or qualified key. */\nexport function parseQualifiedValueKey(key: string): ParsedValueKey | null {\n if (!QUALIFIED_VALUE_KEY_RE.test(key)) return null;\n const dot = key.indexOf(\".\");\n if (dot === -1) return { itemType: \"\", name: key };\n return { itemType: key.slice(0, dot), name: key.slice(dot + 1) };\n}\n\nexport function qualifyValueKey(itemType: string, name: string): QualifiedValueKey {\n return itemType ? `${itemType}.${name}` : name;\n}\n\n/** The client that owns a surface: its name prefix. */\nexport function surfaceClientOf(surfaceName: string): string {\n return surfaceName.split(\"/\")[0] ?? \"\";\n}\n","/**\n * Building a ClickTarget from what is declared at the click (CONTRACT §2.4).\n * Key existence, never value population: a value key is present when the\n * declaration gives it a read path here.\n */\nimport { resolveSensitivity } from \"../declare/sensitivity\";\nimport { qualifyValueKey } from \"../declare/keys\";\nimport type { ResolvedItem, ResolvedSurfaceDeclaration, WriteTarget } from \"../declare/types\";\nimport type { ClickTarget } from \"./types\";\n\nexport interface ClickTargetInput {\n surface?: ClickTarget[\"surface\"];\n declaration?: ResolvedSurfaceDeclaration | null;\n item?: ResolvedItem | null;\n level?: string | null;\n selection?: ClickTarget[\"selection\"];\n payloadKinds?: ClickTarget[\"payloadKinds\"];\n /** Defaults to the item's readOnly (or false). */\n readOnly?: boolean;\n /** Extra exclusions on top of the declaration's own. */\n excludedActionIds?: Iterable<string>;\n scopeChain?: readonly string[];\n organizationId?: string | null;\n auth?: Partial<ClickTarget[\"auth\"]>;\n /** Write targets the host can serve right now; defaults to every declared target for the screen/item. */\n writable?: readonly WriteTarget[];\n host?: unknown;\n}\n\nfunction domainOf(surfaceName: string): string {\n const slash = surfaceName.indexOf(\"/\");\n return slash > 0 ? surfaceName.slice(0, slash) : surfaceName;\n}\n\nexport function createClickTarget(input: ClickTargetInput = {}): ClickTarget {\n const declaration = input.declaration ?? null;\n const item = input.item ?? null;\n const valueKeys = new Set<string>();\n let restricted = false;\n const writable: WriteTarget[] = [];\n if (declaration) {\n for (const value of declaration.values) {\n valueKeys.add(value.name);\n const s = resolveSensitivity(value);\n if (s.classification !== \"ordinary\" || !s.exportable) restricted = true;\n }\n const itemType = item ? declaration.itemTypes?.find((t) => t.name === item.itemType) : undefined;\n if (itemType) {\n for (const value of itemType.values) {\n valueKeys.add(qualifyValueKey(itemType.name, value.name));\n const s = resolveSensitivity(value);\n if (s.classification !== \"ordinary\" || !s.exportable) restricted = true;\n }\n for (const t of itemType.writeTargets ?? []) writable.push(t);\n }\n for (const t of declaration.writeTargets ?? []) {\n if (!t.itemType || t.itemType === item?.itemType) writable.push(t);\n }\n }\n const readOnly = input.readOnly ?? item?.readOnly ?? false;\n const surfaceName = input.surface?.surfaceName ?? declaration?.surfaceName ?? null;\n const scopeChain = input.scopeChain ?? (surfaceName ? [\"global\", domainOf(surfaceName), surfaceName] : [\"global\"]);\n return {\n surface: input.surface ?? null,\n declaration,\n valueKeys,\n scopeChain,\n excludedActionIds: new Set(input.excludedActionIds ?? []),\n item,\n level: input.level ?? item?.level ?? null,\n selection: input.selection ?? null,\n payloadKinds: input.payloadKinds ?? [],\n writable: readOnly ? [] : (input.writable ?? writable),\n readOnly,\n restricted,\n organizationId: input.organizationId ?? null,\n auth: {\n authenticated: input.auth?.authenticated ?? false,\n admin: input.auth?.admin ?? false,\n creator: input.auth?.creator ?? false,\n },\n host: input.host,\n };\n}\n","/**\n * The one action registry (CONTRACT §2.4).\n *\n * - Duplicate ids are REFUSED, never overwritten (rich-document's registry\n * silently overwrote — R12). A duplicate known at registration throws; one\n * that only appears when a provider yields it is dropped and captured.\n * - Eligibility is one pure pass over the resolved click target, under\n * \"restrict, never relax\": a host may remove ids or categories, never add.\n * - R1: an action that does not apply is ABSENT. Only the six universal verbs\n * (category \"clipboard\") may answer `unavailable-verb`, with a sentence; any\n * other action answering it is a contract break → absent + diagnostics.\n */\nimport type { AlchemyHostPorts, Json } from \"../ports\";\nimport { createClickTarget } from \"./target\";\nimport {\n UNIVERSAL_VERBS,\n type Action,\n type ActionProvider,\n type ActionRegistry,\n type ClickTarget,\n type Eligibility,\n type ResolveRestriction,\n type ResolvedAction,\n} from \"./types\";\n\nexport class DuplicateActionError extends Error {\n readonly actionId: string;\n readonly providers: readonly [string, string];\n constructor(actionId: string, first: string, second: string) {\n super(\n first === second\n ? `Action \"${actionId}\" is yielded twice by provider \"${first}\". Ids are unique; the second was refused.`\n : `Action \"${actionId}\" is registered by provider \"${first}\" and again by \"${second}\". Ids are unique; \"${second}\"'s copy was refused.`,\n );\n this.name = \"DuplicateActionError\";\n this.actionId = actionId;\n this.providers = [first, second];\n }\n}\n\nexport class DuplicateProviderError extends Error {\n readonly providerId: string;\n constructor(providerId: string) {\n super(`Action provider \"${providerId}\" is already registered. Unregister it first; nothing was overwritten.`);\n this.name = \"DuplicateProviderError\";\n this.providerId = providerId;\n }\n}\n\nexport interface ActionRegistryOptions {\n /** `diagnostics` is required (nothing fails silently); `auth` decides whether requiresAuth actions reach a signed-out person. */\n ports: Pick<AlchemyHostPorts, \"diagnostics\" | \"auth\">;\n}\n\nconst VERBS = new Set<string>(UNIVERSAL_VERBS);\n\nfunction capture(ports: ActionRegistryOptions[\"ports\"], error: unknown, detail: Json): void {\n try {\n ports.diagnostics.capture(error, { area: \"actions\", detail });\n } catch {\n // A broken diagnostics port must never take the menu down with it.\n }\n}\n\n/**\n * Eligibility of one action at one target — the ONE pure pass (CONTRACT §1.6).\n * Exported for providers' tests; hosts call `registry.resolve`.\n */\nexport function computeEligibility(\n action: Action,\n target: ClickTarget,\n options: { restrict?: ResolveRestriction; authResumable: boolean },\n): Eligibility | { status: \"contract-break\"; reason: string } {\n const restrict = options.restrict;\n // A programmatic-only Action (surfaces without \"menu\") is never a menu row; its own `eligible` is not asked.\n if (!isMenuAction(action)) return { status: \"absent\" };\n if (target.excludedActionIds.has(action.id)) return { status: \"absent\" };\n if (restrict?.exclude?.includes(action.id)) return { status: \"absent\" };\n if (restrict?.categories && !restrict.categories.includes(action.category)) return { status: \"absent\" };\n if (action.writes && action.writes.length > 0) {\n // A read-only target offers nothing that would change the record.\n if (target.readOnly) return { status: \"absent\" };\n const writable = new Set(target.writable.map((w) => w.name));\n if (!action.writes.some((name) => writable.has(name))) return { status: \"absent\" };\n }\n if (action.requiresAuth && !target.auth.authenticated && !options.authResumable) {\n // Sign-in-then-resume is the capability; without the auth port it is absent (N8).\n return { status: \"absent\" };\n }\n const own = action.eligible(target);\n if (own.status === \"unavailable\") {\n // A greyed row must say why; without a sentence it is absent.\n return own.sentence.trim() ? own : { status: \"absent\" };\n }\n if (own.status !== \"unavailable-verb\") return own;\n if (action.category !== \"clipboard\" || !VERBS.has(own.verb)) {\n return {\n status: \"contract-break\",\n reason: `Action \"${action.id}\" answered unavailable-verb but only the six universal verbs (category \"clipboard\") may grey; it is absent instead.`,\n };\n }\n if (!own.sentence.trim()) {\n return {\n status: \"contract-break\",\n reason: `Universal verb \"${action.id}\" greyed without a sentence; a greyed verb must say why.`,\n };\n }\n return own;\n}\n\n/** True unless the Action declares `surfaces` without \"menu\" (default: a menu Action). */\nexport function isMenuAction(action: Pick<Action, \"surfaces\">): boolean {\n return !action.surfaces || action.surfaces.includes(\"menu\");\n}\n\ninterface Entry {\n provider: ActionProvider;\n declared: readonly string[];\n}\n\nexport function createActionRegistry(options: ActionRegistryOptions): ActionRegistry {\n const ports = options.ports;\n const entries = new Map<string, Entry>();\n const listeners = new Set<() => void>();\n const notify = () => {\n for (const l of [...listeners]) l();\n };\n\n return {\n register(provider) {\n if (entries.has(provider.id)) throw new DuplicateProviderError(provider.id);\n const declared = provider.declaredIds?.() ?? [];\n const own = new Set<string>();\n for (const id of declared) {\n if (own.has(id)) throw new DuplicateActionError(id, provider.id, provider.id);\n own.add(id);\n for (const [otherId, other] of entries) {\n if (other.declared.includes(id)) throw new DuplicateActionError(id, otherId, provider.id);\n }\n }\n const entry: Entry = { provider, declared };\n entries.set(provider.id, entry);\n notify();\n return () => {\n if (entries.get(provider.id) === entry) {\n entries.delete(provider.id);\n notify();\n }\n };\n },\n\n async resolve(target, restrict) {\n const authResumable = Boolean(ports.auth);\n const seen = new Map<string, string>();\n const out: ResolvedAction[] = [];\n for (const [providerId, { provider }] of [...entries]) {\n let actions: readonly Action[];\n try {\n actions = await provider.actions(target);\n } catch (error) {\n capture(ports, error, { providerId, stage: \"actions\" });\n continue;\n }\n for (const raw of actions) {\n const first = seen.get(raw.id);\n if (first !== undefined) {\n capture(ports, new DuplicateActionError(raw.id, first, providerId), { actionId: raw.id });\n continue;\n }\n seen.set(raw.id, providerId);\n const action: Action = raw.provider === providerId ? raw : { ...raw, provider: providerId };\n let eligibility: ReturnType<typeof computeEligibility>;\n try {\n eligibility = computeEligibility(action, target, { restrict: restrict ?? {}, authResumable });\n } catch (error) {\n capture(ports, error, { actionId: action.id, stage: \"eligible\" });\n continue;\n }\n if (eligibility.status === \"contract-break\") {\n capture(ports, new Error(eligibility.reason), { actionId: action.id, stage: \"eligible\" });\n continue;\n }\n if (eligibility.status === \"absent\") continue;\n out.push({ action, eligibility });\n }\n }\n return out;\n },\n\n providers() {\n return [...entries.keys()];\n },\n\n async get(id, target) {\n const at = target ?? createClickTarget();\n const all = [...entries];\n const declaring = all.filter(([, e]) => e.declared.includes(id));\n // Declared ids are unique across providers (refused at registration), so at most one declares it.\n // Nobody declared it: fall back to asking every provider (T1 providers yield ids only on resolve).\n const order = declaring.length > 0 ? declaring : all;\n for (const [providerId, { provider }] of order) {\n let actions: readonly Action[];\n try {\n actions = await provider.actions(at);\n } catch (error) {\n capture(ports, error, { providerId, stage: \"actions\", actionId: id });\n continue;\n }\n const found = actions.find((a) => a.id === id);\n if (found) return found.provider === providerId ? found : { ...found, provider: providerId };\n }\n return null;\n },\n\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n\n/** A provider over a fixed list; its ids are declared up front so duplicates fail at registration. */\nexport function staticActionProvider(\n id: string,\n actions: readonly Action[],\n tier: ActionProvider[\"tier\"] = \"T0\",\n): ActionProvider {\n const list = actions.map((a) => (a.provider === id ? a : { ...a, provider: id }));\n return {\n id,\n tier,\n declaredIds: () => list.map((a) => a.id),\n actions: () => list,\n };\n}\n\n/** Always-available eligibility, for actions with no rule of their own. */\nexport const alwaysEligible = (): Eligibility => ({ status: \"available\" });\n","/**\n * PROJECTION BEFORE PROVIDERS (CONTRACT §2.4).\n *\n * The only place a raw read (`MountedSurface.readValues`,\n * `InternalResolvedItem.readValues`) is consumed on behalf of an action.\n * What leaves is projected: a value is kept only when it is DECLARED, its\n * classification is \"ordinary\" and it is exportable. Everything removed is\n * recorded as an omission, so the person and the agent can see what was held\n * back. No caller can relax this.\n */\nimport { resolveSensitivity } from \"../declare/sensitivity\";\nimport type { InternalResolvedItem, MountedSurface } from \"../declare/host\";\nimport type { DeclaredValue, Json, LiveValues, ResolvedSurfaceDeclaration } from \"../declare/types\";\nimport type { ProjectedReads, ReadOmission } from \"./types\";\n\nexport interface ProjectionSource {\n surface: MountedSurface | null;\n declaration: ResolvedSurfaceDeclaration | null;\n item: InternalResolvedItem | null;\n}\n\nfunction toJson(value: unknown): Json | undefined {\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") return undefined;\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"bigint\") return value.toString();\n if (value instanceof Date) return value.toISOString();\n if (Array.isArray(value)) return value.map((v) => toJson(v) ?? null);\n if (typeof value === \"object\") {\n const out: { [key: string]: Json } = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n const j = toJson(v);\n if (j !== undefined) out[k] = j;\n }\n return out;\n }\n return undefined;\n}\n\n/** Keep declared, ordinary, exportable values; record every removal. */\nexport function projectValues(\n raw: Record<string, unknown>,\n declared: readonly Pick<DeclaredValue, \"name\" | \"sensitivity\">[],\n pathPrefix = \"\",\n): { values: Record<string, Json>; omissions: ReadOmission[] } {\n const byName = new Map(declared.map((d) => [d.name, d]));\n const values: Record<string, Json> = {};\n const omissions: ReadOmission[] = [];\n for (const [name, value] of Object.entries(raw)) {\n const path = pathPrefix ? `${pathPrefix}.${name}` : name;\n const decl = byName.get(name);\n if (!decl) {\n omissions.push({ path, reason: \"filtered\" });\n continue;\n }\n const sensitivity = resolveSensitivity(decl);\n if (sensitivity.classification !== \"ordinary\") {\n omissions.push({ path, reason: \"excluded\", classification: sensitivity.classification });\n continue;\n }\n if (!sensitivity.exportable) {\n omissions.push({ path, reason: \"excluded\" });\n continue;\n }\n const json = toJson(value);\n if (json === undefined) continue;\n values[name] = json;\n }\n return { values, omissions };\n}\n\nexport function createProjectedReads(source: ProjectionSource): ProjectedReads {\n return {\n async values(signal) {\n if (!source.surface || !source.declaration) return { values: {}, omissions: [] };\n const raw = await source.surface.readValues(signal);\n const screenValues = source.declaration.values;\n return projectValues(raw, screenValues);\n },\n async item(signal) {\n const item = source.item;\n if (!item || !source.declaration) return null;\n const type = source.declaration.itemTypes?.find((t) => t.name === item.itemType);\n if (!type) return { values: {}, omissions: [{ path: item.itemType, reason: \"filtered\" }] };\n const raw = await item.readValues(signal);\n return projectValues(raw, type.values, item.itemType);\n },\n async live(signal): Promise<LiveValues> {\n if (!source.surface?.readLive) return {};\n return source.surface.readLive(signal);\n },\n };\n}\n","/**\n * The one run path (T1e). Every layout runs an action through here, so the\n * sign-in-then-resume rule, projection and failure capture live once.\n */\nimport type { TransferOutcome } from \"@ai-matrx/kit/content-transfer\";\nimport type { AlchemyHostPorts } from \"../ports\";\nimport { createProjectedReads, type ProjectionSource } from \"./projection\";\nimport type { Action, ClickTarget } from \"./types\";\n\nexport interface RunActionOptions {\n ports: AlchemyHostPorts;\n /** Raw sources; projected before the action sees them. */\n source?: ProjectionSource;\n /** Stable fingerprint of the content, for sign-in-then-resume. */\n contentFingerprint?: string;\n signal?: AbortSignal;\n}\n\nexport type RunResult =\n | { status: \"ran\"; outcome: TransferOutcome | void }\n | { status: \"auth-pending\" }\n | { status: \"failed\"; error: unknown };\n\nexport async function runAction(action: Action, target: ClickTarget, options: RunActionOptions): Promise<RunResult> {\n const { ports } = options;\n if (action.requiresAuth && !target.auth.authenticated) {\n if (!ports.auth) {\n // Unreachable through resolve (the action is absent without the port); guard direct callers.\n ports.diagnostics.capture(new Error(`requiresAuth action \"${action.id}\" ran signed out with no auth port`), {\n area: \"actions\",\n detail: { actionId: action.id },\n });\n return { status: \"failed\", error: new Error(\"sign-in unavailable\") };\n }\n ports.auth.signInThenResume({ actionId: action.id, contentFingerprint: options.contentFingerprint ?? action.id });\n return { status: \"auth-pending\" };\n }\n const reads = createProjectedReads(options.source ?? { surface: null, declaration: target.declaration, item: null });\n const signal = options.signal ?? new AbortController().signal;\n try {\n const outcome = await action.run(target, { reads, ports, signal });\n return { status: \"ran\", outcome };\n } catch (error) {\n ports.diagnostics.capture(error, { area: \"actions\", detail: { actionId: action.id, stage: \"run\" } });\n const label = typeof action.label === \"string\" ? action.label : action.id;\n ports.notify?.error(`${label} did not finish.`, \"Try again; if it keeps failing, report it from the feedback button.\");\n return { status: \"failed\", error };\n }\n}\n","/**\n * The one programmatic runner. Menu Actions run through `runAction(action, target)`; code that\n * names an Action BY ID (a kind component's `runAction(key, input)`, an accepted assist chip)\n * runs it here, on the same registry. It never throws: every outcome is an `ActionResult`.\n *\n * Refusals, by code:\n * - `not_registered` — no provider yields that id.\n * - `not_invocable` — the Action exists but has no `invoke` channel (a menu-only Action).\n * - `lookup_failed` — the registry itself threw while finding it (captured).\n * - `action_failed` — `invoke` threw or answered something that is not an envelope (captured + announced once\n * through `notify.error`; the caller never announces it again).\n */\nimport type { AlchemyHostPorts } from \"../ports\";\nimport type { ActionResult } from \"./applet-types\";\nimport type { Action, ActionRegistry, ActionSurface, Eligibility, InvocationContext } from \"./types\";\n\nexport interface InvokeActionOptions {\n ports: AlchemyHostPorts;\n /** The capability-scoped context this one Action receives (opaque to the package). */\n context?: unknown;\n signal?: AbortSignal;\n}\n\nfunction refused(code: string, message: string, retryable: boolean): { ok: false; error: { code: string; message: string; retryable: boolean } } {\n return { ok: false, error: { code, message, retryable } };\n}\n\nfunction isEnvelope(value: unknown): value is ActionResult<unknown> {\n if (!value || typeof value !== \"object\") return false;\n const v = value as { ok?: unknown; error?: unknown };\n if (v.ok === true) return true;\n return v.ok === false && !!v.error && typeof (v.error as { message?: unknown }).message === \"string\";\n}\n\nfunction capture(ports: AlchemyHostPorts, error: unknown, detail: Record<string, string>): void {\n try {\n ports.diagnostics.capture(error, { area: \"actions\", detail });\n } catch {\n // A broken diagnostics port never turns a refusal into a throw.\n }\n}\n\nexport async function invokeAction<T = unknown>(\n registry: Pick<ActionRegistry, \"get\">,\n id: string,\n input: unknown,\n options: InvokeActionOptions,\n): Promise<ActionResult<T>> {\n const { ports } = options;\n let action: Action | null;\n try {\n action = await registry.get(id);\n } catch (error) {\n capture(ports, error, { actionId: id, stage: \"get\" });\n return refused(\"lookup_failed\", `Couldn't look up \"${id}\".`, true);\n }\n if (!action) return refused(\"not_registered\", `No action registered for \"${id}\".`, false);\n if (!action.invoke) return refused(\"not_invocable\", `\"${id}\" runs only from a menu, not by id.`, false);\n const context: InvocationContext = {\n ports,\n context: options.context,\n signal: options.signal ?? new AbortController().signal,\n };\n const label = typeof action.label === \"string\" ? action.label : id;\n // `action_failed` is always captured AND announced once here, so a caller never announces it again.\n const failed = (error: unknown, message: string, retryable: boolean) => {\n capture(ports, error, { actionId: id, stage: \"invoke\" });\n try {\n ports.notify?.error(`${label} did not finish.`, \"Try again; if it keeps failing, report it from the feedback button.\");\n } catch {\n // notify is best effort.\n }\n return refused(\"action_failed\", message, retryable);\n };\n try {\n const result = await action.invoke(input, context);\n if (!isEnvelope(result)) {\n const error = new Error(`\"${id}\" answered without a result envelope ({ ok, data } | { ok: false, error }).`);\n return failed(error, error.message, false);\n }\n return result as ActionResult<T>;\n } catch (error) {\n return failed(error, error instanceof Error && error.message ? error.message : `${label} did not finish.`, true);\n }\n}\n\nexport interface InvocableActionDefinition {\n /** Globally unique; namespace it (`kind.trigger_agent`). */\n id: string;\n label: string;\n description?: string;\n category?: Action[\"category\"];\n invoke: NonNullable<Action[\"invoke\"]>;\n}\n\nconst NEVER_IN_MENUS = (): Eligibility => ({ status: \"absent\" });\n\n/**\n * A programmatic-only Action: `surfaces: [\"invoke\"]`, so no menu ever resolves it; `run` refuses\n * (only `invokeAction` reaches it). Register it like any Action, on the one registry.\n */\nexport function invocableAction(def: InvocableActionDefinition): Action {\n const surfaces: readonly ActionSurface[] = [\"invoke\"];\n return {\n id: def.id,\n label: def.label,\n ...(def.description !== undefined ? { description: def.description } : {}),\n category: def.category ?? \"app\",\n surfaces,\n eligible: NEVER_IN_MENUS,\n run() {\n throw new Error(`\"${def.id}\" runs only by id (invokeAction), never from a menu.`);\n },\n invoke: def.invoke,\n };\n}\n","/**\n * The declaration registry: inheritance, baseline injection, provenance and\n * group synthesis (CONTRACT §2.1 `DeclarationRegistry`). Ported verbatim in\n * behaviour from matrx-frontend `features/surfaces/manifests/registry.ts`\n * (ALC-14); the app now supplies its declarations and baselines.\n *\n * Guards are LOUD by design: an unknown parent, a cycle, a chain deeper than\n * the limit, a reserved or duplicate group key, a value naming an undeclared\n * group, or a reserved platform name throws on resolution — a build fails\n * instead of silently dropping values.\n */\nimport { declarationHash } from \"./hash\";\nimport type {\n DeclarationExtension,\n DeclarationIssue,\n DeclaredValue,\n ResolvedSurfaceDeclaration,\n ResolvedValue,\n Sensitivity,\n SurfaceDeclaration,\n ValueGroup,\n ValueProvenance,\n} from \"./types\";\nimport { validateDeclarations, type ValidateOptions } from \"./validate\";\n\nexport const RESERVED_GROUP_KEYS = {\n general: \"general\",\n baseline: \"baseline\",\n inheritedPrefix: \"inherited:\",\n} as const;\n\n/** Group sortOrder bands. Curated groups author 0–899; the rest is reserved. */\nexport const GENERAL_GROUP_ORDER = 850;\nexport const INHERITED_GROUP_ORDER_BASE = 9000;\nexport const BASELINE_GROUP_ORDER = 9900;\nexport const DEFAULT_MAX_INHERITANCE_DEPTH = 3;\n\nimport { DEFAULT_SENSITIVITY, resolveSensitivity } from \"./sensitivity\";\nexport { DEFAULT_SENSITIVITY, resolveSensitivity };\n\nexport type Resolved<D extends SurfaceDeclaration> = Omit<D, \"values\" | \"groups\"> & {\n values: readonly (D[\"values\"][number] & ResolvedValue)[];\n groups: readonly ValueGroup[];\n contentHash: string;\n};\n\nexport interface DeclarationRegistryOptions {\n /** Generic values injected into every declaration unless `skipBaselineValues`. */\n baselineValues?: readonly DeclaredValue[];\n /** Value names only the platform writes; a declaration claiming one is refused. */\n reservedValueNames?: readonly string[];\n /** Write-target names only the platform writes. */\n reservedWriteTargetNames?: readonly string[];\n maxInheritanceDepth?: number;\n}\n\nexport interface DeclarationRegistry<D extends SurfaceDeclaration> {\n /** Refuses a second declaration of the same surfaceName. */\n register(declaration: D): void;\n registerExtension(extension: DeclarationExtension<D>): void;\n extensions(): readonly DeclarationExtension<D>[];\n /** Declarations exactly as authored (inheritance unresolved, no baselines). */\n raw(): readonly D[];\n getRaw(surfaceName: string): D | undefined;\n /** Parent chain, ROOT FIRST. Unknown surfaces return []. */\n ancestry(surfaceName: string): string[];\n /** Direct children (declarations naming it in `inheritsFrom`), in declaration order. */\n children(surfaceName: string): string[];\n /** Inheritance + baseline + groups resolved; provenance kept. */\n all(): readonly Resolved<D>[];\n get(surfaceName: string): Resolved<D> | undefined;\n validate(options?: ValidateOptions): readonly DeclarationIssue[];\n}\n\nexport function createDeclarationRegistry<D extends SurfaceDeclaration>(\n options: DeclarationRegistryOptions = {},\n): DeclarationRegistry<D> {\n const baselineValues = options.baselineValues ?? [];\n const baselineNames = new Set(baselineValues.map((v) => v.name));\n const reservedValues = new Set(options.reservedValueNames ?? []);\n const reservedTargets = new Set(options.reservedWriteTargetNames ?? []);\n const maxDepth = options.maxInheritanceDepth ?? DEFAULT_MAX_INHERITANCE_DEPTH;\n const declarations: D[] = [];\n const index = new Map<string, D>();\n const extensionList: DeclarationExtension<D>[] = [];\n let resolvedCache: Resolved<D>[] | null = null;\n let resolvedIndex = new Map<string, Resolved<D>>();\n\n function ancestry(surfaceName: string): string[] {\n const chain: string[] = [];\n const seen = new Set<string>([surfaceName]);\n let current = index.get(surfaceName)?.inheritsFrom;\n while (current) {\n if (seen.has(current)) {\n throw new Error(\n `[surfaces] inheritsFrom CYCLE detected at \"${current}\" (from \"${surfaceName}\"). ` +\n `Fix the manifest chain: ${[...seen].join(\" → \")} → ${current}`,\n );\n }\n const parent = index.get(current);\n if (!parent) {\n throw new Error(\n `[surfaces] \"${surfaceName}\" inheritsFrom unknown surface \"${current}\" — ` +\n `the parent must be a registered declaration`,\n );\n }\n seen.add(current);\n chain.unshift(current);\n if (chain.length > maxDepth) {\n throw new Error(\n `[surfaces] inheritance chain for \"${surfaceName}\" exceeds depth ${maxDepth}: ` + chain.join(\" → \"),\n );\n }\n current = parent.inheritsFrom;\n }\n return chain;\n }\n\n function groupKeyFor(value: DeclaredValue, provenance: ValueProvenance): string {\n if (provenance.kind === \"own\" && value.group) return value.group;\n if (baselineNames.has(value.name)) return RESERVED_GROUP_KEYS.baseline;\n if (provenance.kind === \"inherited\") return `${RESERVED_GROUP_KEYS.inheritedPrefix}${provenance.from}`;\n if (provenance.kind === \"baseline\") return RESERVED_GROUP_KEYS.baseline;\n return RESERVED_GROUP_KEYS.general;\n }\n\n function resolve(declaration: D): Resolved<D> {\n const chain = ancestry(declaration.surfaceName);\n const lineage: { layer: D; from: string | null }[] = [\n ...chain.map((name) => {\n const layer = index.get(name);\n if (!layer) throw new Error(`[surfaces] missing inherited declaration \"${name}\"`);\n return { layer, from: name };\n }),\n { layer: declaration, from: null },\n ];\n\n const curatedKeys = new Set<string>();\n for (const group of declaration.groups ?? []) {\n if (\n group.key === RESERVED_GROUP_KEYS.general ||\n group.key === RESERVED_GROUP_KEYS.baseline ||\n group.key.startsWith(RESERVED_GROUP_KEYS.inheritedPrefix)\n ) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" declares reserved group key \"${group.key}\" — ` +\n `general/baseline/inherited:* are synthesized by the registry`,\n );\n }\n if (curatedKeys.has(group.key)) {\n throw new Error(`[surfaces] \"${declaration.surfaceName}\" declares duplicate group key \"${group.key}\"`);\n }\n curatedKeys.add(group.key);\n }\n for (const value of declaration.values) {\n if (reservedValues.has(value.name)) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" declares value \"${value.name}\" — that name is written by the platform; choose another name`,\n );\n }\n if (value.group && !curatedKeys.has(value.group)) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" value \"${value.name}\" references undeclared ` +\n `group \"${value.group}\" — declare it in the manifest's \\`groups\\``,\n );\n }\n }\n for (const target of declaration.writeTargets ?? []) {\n if (reservedTargets.has(target.name)) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" declares write target \"${target.name}\" — that name is written by the platform; choose another name`,\n );\n }\n }\n\n const valuesByName = new Map<string, D[\"values\"][number] & ResolvedValue>();\n const inheritedLists = new Map<string, Map<string, unknown>>();\n const coreLists: { field: string; identity(entry: unknown): string }[] = [\n { field: \"configNamespaces\", identity: (entry) => (entry as { namespace: string }).namespace },\n {\n field: \"evidenceSources\",\n identity: (entry) => `${(entry as { kind: string }).kind}:${(entry as { idValue: string }).idValue}`,\n },\n ];\n const lists = [...coreLists, ...extensionList.flatMap((extension) => extension.inheritedLists ?? [])];\n for (const { layer, from } of lineage) {\n for (const value of layer.values) {\n const provenance: ValueProvenance = from ? { kind: \"inherited\", from } : { kind: \"own\" };\n valuesByName.set(value.name, {\n ...value,\n provenance,\n groupKey: groupKeyFor(value, provenance),\n resolvedSensitivity: resolveSensitivity(value),\n });\n }\n for (const list of lists) {\n const entries = (layer as unknown as Record<string, unknown>)[list.field];\n if (!Array.isArray(entries)) continue;\n const byIdentity = inheritedLists.get(list.field) ?? new Map<string, unknown>();\n for (const entry of entries) byIdentity.set(list.identity(entry), entry);\n inheritedLists.set(list.field, byIdentity);\n }\n }\n\n if (!declaration.skipBaselineValues) {\n for (const baseline of baselineValues) {\n if (valuesByName.has(baseline.name)) continue;\n valuesByName.set(baseline.name, {\n ...baseline,\n provenance: { kind: \"baseline\" },\n groupKey: RESERVED_GROUP_KEYS.baseline,\n resolvedSensitivity: resolveSensitivity(baseline),\n } as D[\"values\"][number] & ResolvedValue);\n }\n }\n\n const usedGroupKeys = new Set(Array.from(valuesByName.values(), (value) => value.groupKey));\n const groups: ValueGroup[] = [...(declaration.groups ?? [])];\n if (usedGroupKeys.has(RESERVED_GROUP_KEYS.general)) {\n groups.push({ key: RESERVED_GROUP_KEYS.general, label: \"General\", sortOrder: GENERAL_GROUP_ORDER });\n }\n for (let i = chain.length - 1, distance = 0; i >= 0; i -= 1, distance += 1) {\n const parentName = chain[i]!;\n const key = `${RESERVED_GROUP_KEYS.inheritedPrefix}${parentName}`;\n if (!usedGroupKeys.has(key)) continue;\n const parentLabel = index.get(parentName)?.label ?? parentName;\n groups.push({\n key,\n label: `Inherited from ${parentLabel}`,\n sortOrder: INHERITED_GROUP_ORDER_BASE + distance * 10,\n });\n }\n if (usedGroupKeys.has(RESERVED_GROUP_KEYS.baseline)) {\n groups.push({ key: RESERVED_GROUP_KEYS.baseline, label: \"Generic baselines\", sortOrder: BASELINE_GROUP_ORDER });\n }\n groups.sort((a, b) => a.sortOrder - b.sortOrder);\n\n const groupOrder = new Map(groups.map((group) => [group.key, group.sortOrder] as const));\n const values = Array.from(valuesByName.values()).sort((a, b) => {\n const ga = groupOrder.get(a.groupKey) ?? GENERAL_GROUP_ORDER;\n const gb = groupOrder.get(b.groupKey) ?? GENERAL_GROUP_ORDER;\n if (ga !== gb) return ga - gb;\n return (a.sortOrder ?? 1000) - (b.sortOrder ?? 1000);\n });\n\n const merged: Record<string, unknown> = {};\n for (const [field, byIdentity] of inheritedLists) {\n if (byIdentity.size > 0) merged[field] = Array.from(byIdentity.values());\n }\n return {\n ...declaration,\n values,\n groups,\n ...merged,\n contentHash: declarationHash(declaration),\n } as Resolved<D>;\n }\n\n function resolvedAll(): Resolved<D>[] {\n if (!resolvedCache) {\n resolvedCache = declarations.map(resolve);\n resolvedIndex = new Map(resolvedCache.map((entry) => [entry.surfaceName, entry] as const));\n }\n return resolvedCache;\n }\n\n const registry: DeclarationRegistry<D> = {\n register(declaration) {\n if (index.has(declaration.surfaceName)) {\n throw new Error(`[surfaces] \"${declaration.surfaceName}\" is declared twice — one surface, one declaration`);\n }\n declarations.push(declaration);\n index.set(declaration.surfaceName, declaration);\n resolvedCache = null;\n },\n registerExtension(extension) {\n if (extensionList.some((existing) => existing.key === extension.key)) {\n throw new Error(`[surfaces] declaration extension \"${extension.key}\" is registered twice`);\n }\n extensionList.push(extension);\n resolvedCache = null;\n },\n extensions: () => extensionList,\n raw: () => declarations,\n getRaw: (surfaceName) => index.get(surfaceName),\n ancestry,\n children: (surfaceName) =>\n declarations.filter((d) => d.inheritsFrom === surfaceName).map((d) => d.surfaceName),\n all: () => resolvedAll(),\n get(surfaceName) {\n resolvedAll();\n return resolvedIndex.get(surfaceName);\n },\n validate: (validateOptions) =>\n validateDeclarations(resolvedAll() as unknown as readonly ResolvedSurfaceDeclaration[], {\n ...validateOptions,\n extensions: [...(validateOptions?.extensions ?? []), ...(extensionList as DeclarationExtension[])],\n baselineNames: validateOptions?.baselineNames ?? [...baselineNames],\n }),\n };\n return registry;\n}\n","/**\n * Every source of an Action projects onto ONE shape (Applets CONTRACTS §6):\n * a declared write target, a client tool row, a `ui.ui_surface_action` row.\n * Pure functions, zero loss (the census in `declarations.test.ts` proves every\n * source field lands). Then the chain: a child surface's Action wins by name.\n */\nimport { DEFAULT_MAX_INHERITANCE_DEPTH } from \"../declare/registry\";\nimport type { Json, WriteTarget } from \"../declare/types\";\nimport type {\n ActionCaller,\n ActionDeclaration,\n ActionDeclaredBy,\n ActionInfo,\n ActionInput,\n ActionOrigin,\n ActionPolicy,\n ActionRuns,\n ActionWriteMode,\n} from \"./applet-types\";\n\n/** Default `category` of an Action that names none. */\nexport const APPLET_CATEGORY = \"applet\";\n\n/** The DB default of `ui.ui_surface_action.triggered_by`, used where a source carries no list. */\nexport const DEFAULT_TRIGGERED_BY: readonly ActionCaller[] = [\"person\", \"agent\", \"applet\"];\n\nexport const ACTION_CALLERS: readonly ActionCaller[] = [\"person\", \"agent\", \"applet\", \"automation\"];\nexport const ACTION_RUNS: readonly ActionRuns[] = [\"page\", \"server\", \"mandate\", \"navigate\"];\nexport const ACTION_POLICIES: readonly ActionPolicy[] = [\"ask\", \"auto\", \"manual\"];\n\n/** A `ui.ui_surface_client_tool` row (live columns that carry meaning). */\nexport interface ClientToolRow {\n id?: string;\n surface_name: string;\n name: string;\n label: string;\n description: string;\n input_schema: Json;\n /** Live values: \"ui\" (applied directly) | \"draft\" (proposed for review). */\n mode: \"ui\" | \"draft\";\n declared_by?: ActionDeclaredBy;\n}\n\n/** A `ui.ui_surface_action` row. */\nexport interface SurfaceActionRow {\n id?: string;\n surface_id: string;\n surface_name: string;\n /** '' = the screen itself. */\n item_type: string;\n name: string;\n category: string;\n label: string;\n description: string;\n input: ActionInput | null;\n output: string | null;\n runs: ActionRuns;\n target: string | null;\n triggered_by: ActionCaller[];\n policy: ActionPolicy;\n updates_value: string | null;\n code_ref: string | null;\n declared_by: ActionDeclaredBy;\n sort_order: number;\n /**\n * The row's organization. A `declared_by='database'` row on a surface outside `applets/` is that\n * organization's EXTENSION and applies only to its members (`readSurfaceChain`, aidream `visible_actions`).\n */\n organization_id?: string | null;\n}\n\ntype Loose<T> = { [K in keyof T]: T[K] | undefined };\n\n/** Drop undefined keys (exactOptionalPropertyTypes: an absent field is absent, never `undefined`). */\nfunction compact<T extends object>(value: Loose<T>): T {\n return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as T;\n}\n\nconst POLICY_OF_APPLY: Record<NonNullable<WriteTarget[\"applyPolicy\"]>, ActionPolicy> = {\n manual: \"manual\",\n ask: \"ask\",\n auto: \"auto\",\n // Filed for an organization's review: never applied without someone saying yes.\n queued: \"ask\",\n};\n\n/** A declared write target → an Action that runs on the page. */\nexport function writeTargetToAction(target: WriteTarget): ActionDeclaration {\n const applyPolicy = target.applyPolicy ?? \"manual\";\n return compact<ActionDeclaration>({\n name: target.name,\n label: target.label,\n description: target.description,\n input: target.valueKind ?? { jsonSchema: target.valueType === \"document\" ? {} : { type: target.valueType } },\n runs: \"page\",\n triggeredBy: [...DEFAULT_TRIGGERED_BY],\n policy: POLICY_OF_APPLY[applyPolicy],\n updatesValue: target.updatesValue,\n mode: target.mode as ActionWriteMode,\n patchable: target.patchable,\n approvalComparison: target.approvalComparison,\n streamOps: target.streamOps ? [...target.streamOps] : undefined,\n destination: target.destination,\n groupKey: target.group,\n itemType: target.itemType,\n applyPolicy: target.applyPolicy,\n valueType: target.valueType,\n valueKind: target.valueKind,\n sortOrder: target.sortOrder,\n origin: { source: \"write-target\", declaredBy: \"code\" },\n });\n}\n\n/** A client tool row → an Action an agent runs on the page (\"draft\" tools are proposed first). */\nexport function clientToolToAction(row: ClientToolRow): ActionDeclaration {\n return compact<ActionDeclaration>({\n name: row.name,\n label: row.label,\n description: row.description,\n input: { jsonSchema: (row.input_schema ?? {}) as object },\n runs: \"page\",\n triggeredBy: [\"agent\"],\n policy: row.mode === \"draft\" ? \"ask\" : \"auto\",\n mode: row.mode,\n origin: compact<ActionOrigin>({ source: \"client-tool\", surfaceName: row.surface_name, id: row.id, declaredBy: row.declared_by }),\n });\n}\n\n/** A `ui.ui_surface_action` row → its Action. */\nexport function surfaceActionRowToAction(row: SurfaceActionRow): ActionDeclaration {\n return compact<ActionDeclaration>({\n name: row.name,\n category: row.category,\n label: row.label,\n description: row.description,\n input: row.input ?? undefined,\n output: row.output ?? undefined,\n runs: row.runs,\n target: row.target ?? undefined,\n triggeredBy: [...row.triggered_by],\n policy: row.policy,\n updatesValue: row.updates_value ?? undefined,\n itemType: row.item_type || undefined,\n sortOrder: row.sort_order,\n origin: compact<ActionOrigin>({\n source: \"surface-action\",\n surfaceName: row.surface_name,\n surfaceId: row.surface_id,\n id: row.id,\n declaredBy: row.declared_by,\n codeRef: row.code_ref ?? undefined,\n organizationId: row.organization_id ?? undefined,\n }),\n });\n}\n\n/** JSON-only view of an Action as declared on `declaredOn`. */\nexport function toActionInfo(declaration: ActionDeclaration, declaredOn: string): ActionInfo {\n return compact<ActionInfo>({\n name: declaration.name,\n category: declaration.category ?? APPLET_CATEGORY,\n label: declaration.label,\n description: declaration.description,\n runs: declaration.runs,\n policy: declaration.policy,\n triggeredBy: [...declaration.triggeredBy],\n input: declaration.input,\n output: declaration.output,\n declaredOn,\n target: declaration.target,\n updatesValue: declaration.updatesValue,\n itemType: declaration.itemType,\n source: declaration.origin?.source,\n });\n}\n\nexport interface ActionChainLink {\n surfaceName: string;\n actions: readonly ActionDeclaration[];\n}\n\n/**\n * The Actions a mount sees: its own plus every ancestor's, a child winning by\n * name. `chain` runs MOST GENERAL FIRST (root parent … the mounted surface),\n * as `DeclarationRegistry` resolves inheritance. Guards are loud, like the\n * declaration registry's: a surface twice in the chain is a cycle, more\n * ancestors than `maxDepth` throws, and one surface naming an Action twice throws.\n */\nexport function resolveActionChain(\n chain: readonly ActionChainLink[],\n options: { maxDepth?: number } = {},\n): ActionInfo[] {\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_INHERITANCE_DEPTH;\n const names = chain.map((link) => link.surfaceName);\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) {\n throw new Error(`[actions] inheritance CYCLE detected at \"${name}\". Fix the surface chain: ${names.join(\" → \")}`);\n }\n seen.add(name);\n }\n if (chain.length - 1 > maxDepth) {\n throw new Error(\n `[actions] inheritance chain for \"${names[names.length - 1]}\" exceeds depth ${maxDepth}: ${names.join(\" → \")}`,\n );\n }\n const byName = new Map<string, ActionInfo>();\n for (const link of chain) {\n const own = new Set<string>();\n for (const action of link.actions) {\n if (own.has(action.name)) {\n throw new Error(\n `[actions] surface \"${link.surfaceName}\" declares Action \"${action.name}\" twice. Names are unique; nothing was overwritten.`,\n );\n }\n own.add(action.name);\n byName.set(action.name, toActionInfo(action, link.surfaceName));\n }\n }\n return [...byName.values()];\n}\n","/**\n * THE ONE RUNNER for surface Actions (Applets CONTRACTS §6). Every caller — a\n * person's click, an agent, an applet, an automation — runs an Action through\n * here, so policy and caller rules live once.\n *\n * Policy \"ask\": a person's own click is the approval. Started by an agent, applet or automation,\n * a \"server\" run carries the policy to aidream (which answers with a proposal); every other run\n * asks the person through `ports.approvals` first, and is refused by name without that port.\n *\n * Dispatch by `runs`:\n * \"server\" → `ports.serverActions.run({ name: target, input, by, surface_name, policy })`\n * \"mandate\" → `ports.mandates.run({ alias: target, variables, by, policy })` — answers with the\n * started run's `MandateRunRef`; the result streams later on `run:<requestId>`\n * \"navigate\" → `ports.overlay.navigate(target)` with `{param}` filled from the input\n * \"page\" → `ports.pageActions.dispatch(name, input, context)`\n * A port the host did not bind means that capability is ABSENT: the run is\n * refused with a sentence, never stubbed (ports rule).\n *\n * Write targets (ALC-17): an Action projected from a declared write target (`source: \"write-target\"`)\n * goes through `ports.door.write` when a door is bound — the door applies the target's own policy\n * (manual / ask / queued / auto) and its receipt becomes the result (`applied` / `queued` → ok with\n * the receipt; refused → an error whose code is the refusal reason and whose `remedy` is the door's).\n * Without a door it dispatches to `pageActions` as before.\n *\n * Never throws: every outcome is a `Result` whose error message is the\n * system's own sentence.\n */\nimport type { AlchemyHostPorts, Json } from \"../ports\";\nimport type { WriteOp } from \"../operate/door\";\nimport type { ActionCaller, ActionContext, ActionError, ActionInfo, ActionResult } from \"./applet-types\";\n\nexport type SurfaceActionPorts = Pick<\n AlchemyHostPorts,\n \"diagnostics\" | \"serverActions\" | \"mandates\" | \"pageActions\" | \"overlay\" | \"approvals\" | \"door\"\n>;\n\nexport interface RunSurfaceActionOptions {\n runId?: string;\n viewerId?: string | null;\n signal?: AbortSignal;\n /** Which item a write-target Action writes into (by its declared identity values). */\n itemIdentity?: Record<string, string>;\n /** Text edits for a stream or patchable write target, instead of the input as the whole value. */\n ops?: readonly WriteOp[];\n}\n\nfunction fail(code: string, message: string, retryable = false, diagnostic?: string): { ok: false; error: ActionError } {\n return { ok: false, error: diagnostic ? { code, message, retryable, diagnostic } : { code, message, retryable } };\n}\n\nfunction messageOf(error: unknown): string {\n if (error instanceof Error && error.message.trim()) return error.message;\n if (typeof error === \"string\" && error.trim()) return error;\n return \"The run failed without saying why.\";\n}\n\nfunction newRunId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n return `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\n/** Fill `{param}` placeholders from the input object. Returns the names it could not fill. */\nexport function fillActionTarget(template: string, input: unknown): { value: string; missing: string[] } {\n const source = input && typeof input === \"object\" && !Array.isArray(input) ? (input as Record<string, unknown>) : {};\n const missing: string[] = [];\n const value = template.replace(/\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (_, key: string) => {\n const v = source[key];\n if (v === undefined || v === null || v === \"\" || typeof v === \"object\") {\n missing.push(key);\n return \"\";\n }\n return encodeURIComponent(String(v));\n });\n return { value, missing };\n}\n\n/** Same as fillActionTarget, without URL-encoding (a mandate alias or server action name). */\nfunction fillName(template: string, input: unknown): { value: string; missing: string[] } {\n const filled = fillActionTarget(template, input);\n return { value: decodeURIComponent(filled.value), missing: filled.missing };\n}\n\nfunction toJson(value: unknown): Json {\n if (value === undefined) return null;\n return JSON.parse(JSON.stringify(value)) as Json;\n}\n\n/**\n * Who may run this Action, under its policy. Returns the refusal, or null.\n * \"manual\" = a person only. `triggeredBy` lists every caller allowed at all.\n */\nexport function refuseCaller(info: Pick<ActionInfo, \"name\" | \"label\" | \"policy\" | \"triggeredBy\">, by: ActionCaller): ActionError | null {\n if (!info.triggeredBy.includes(by)) {\n return {\n code: \"caller_not_allowed\",\n message: `\"${info.label}\" (${info.name}) can't be started by ${CALLER_WORDS[by]}; it allows ${info.triggeredBy.join(\", \") || \"no one\"}.`,\n retryable: false,\n };\n }\n if (info.policy === \"manual\" && by !== \"person\") {\n return {\n code: \"manual_only\",\n message: `\"${info.label}\" (${info.name}) runs only when a person starts it.`,\n retryable: false,\n };\n }\n return null;\n}\n\nconst CALLER_WORDS: Record<ActionCaller, string> = {\n person: \"a person\",\n agent: \"an agent\",\n applet: \"an applet\",\n automation: \"an automation\",\n};\n\nfunction absent(info: ActionInfo, capability: string): { ok: false; error: ActionError } {\n return fail(\"capability_absent\", `\"${info.label}\" can't run here: ${capability} isn't available on this page.`);\n}\n\nexport async function runSurfaceAction(\n info: ActionInfo,\n input: unknown,\n by: ActionCaller,\n ports: SurfaceActionPorts,\n options: RunSurfaceActionOptions = {},\n): Promise<ActionResult<unknown>> {\n const refusal = refuseCaller(info, by);\n if (refusal) return { ok: false, error: refusal };\n const context: ActionContext = {\n runId: options.runId ?? newRunId(),\n by,\n viewerId: options.viewerId ?? null,\n surfaceName: info.declaredOn,\n policy: info.policy,\n };\n const capture = (error: unknown, stage: string) => {\n try {\n ports.diagnostics.capture(error, { area: \"actions\", detail: { action: info.name, runs: info.runs, stage, runId: context.runId } });\n } catch {\n // A broken diagnostics port never turns a refusal into a throw.\n }\n };\n\n try {\n if (info.source === \"write-target\" && ports.door) {\n const receipt = await ports.door.write(\n {\n surfaceName: info.declaredOn,\n target: info.name,\n ...(info.itemType ? { itemType: info.itemType } : {}),\n ...(options.itemIdentity ? { itemIdentity: options.itemIdentity } : {}),\n ...(options.ops ? { ops: options.ops } : { value: input }),\n by,\n runId: context.runId,\n },\n options.signal,\n );\n if (receipt.status === \"refused\") {\n return { ok: false, error: { code: receipt.reason, message: receipt.sentence, retryable: receipt.reason === \"failed\", remedy: receipt.remedy } };\n }\n return { ok: true, data: receipt };\n }\n if (info.policy === \"ask\" && by !== \"person\" && info.runs !== \"server\") {\n if (!ports.approvals) {\n return fail(\"needs_approval\", `\"${info.label}\" needs a person's approval, and there is no one to ask here.`);\n }\n const approved = await ports.approvals.ask({\n action: info.name,\n label: info.label,\n description: info.description,\n input: toJson(input),\n by,\n surfaceName: info.declaredOn,\n runId: context.runId,\n });\n if (!approved) return fail(\"declined\", `\"${info.label}\" was not approved, so it did not run.`);\n }\n switch (info.runs) {\n case \"server\": {\n if (!ports.serverActions) return absent(info, \"server actions\");\n const filled = fillName(info.target ?? info.name, input);\n if (filled.missing.length) return fail(\"input_missing\", `\"${info.label}\" needs ${filled.missing.join(\", \")}.`);\n const response = await ports.serverActions.run({\n name: filled.value,\n input: toJson(input),\n by,\n surface_name: info.declaredOn,\n policy: info.policy,\n });\n if (response.status === \"refused\") return fail(\"refused\", response.message);\n return { ok: true, data: response };\n }\n case \"mandate\": {\n if (!ports.mandates) return absent(info, \"running a job\");\n if (!info.target) return fail(\"target_missing\", `\"${info.label}\" names no job to run.`);\n const filled = fillName(info.target, input);\n if (filled.missing.length) return fail(\"input_missing\", `\"${info.label}\" needs ${filled.missing.join(\", \")}.`);\n const record = input && typeof input === \"object\" && !Array.isArray(input) ? (input as Record<string, unknown>) : {};\n // A generic \"run a job\" Action carries { alias, variables, userInput }; a dedicated one's input IS the variables.\n const generic = /\\{[A-Za-z_]/.test(info.target);\n const variables = generic\n ? ((record.variables && typeof record.variables === \"object\" ? toJson(record.variables) : {}) as Record<string, Json>)\n : (toJson(record) as Record<string, Json>);\n const userInput = typeof record.userInput === \"string\" ? record.userInput : undefined;\n // The Action answers with the run's identity (RunRef); its result streams on `run:<requestId>`.\n const ref = await ports.mandates.run({\n alias: filled.value,\n variables,\n ...(userInput !== undefined ? { userInput } : {}),\n by,\n policy: info.policy,\n });\n return { ok: true, data: ref };\n }\n case \"navigate\": {\n if (!ports.overlay) return absent(info, \"navigation\");\n const filled = fillActionTarget(info.target ?? \"\", input);\n if (filled.missing.length) return fail(\"input_missing\", `\"${info.label}\" needs ${filled.missing.join(\", \")}.`);\n // `{to}` is a whole route: keep its slashes.\n const to = info.target && /^\\{[A-Za-z_][A-Za-z0-9_]*\\}$/.test(info.target) ? decodeURIComponent(filled.value) : filled.value;\n if (!to) return fail(\"target_missing\", `\"${info.label}\" names no page to open.`);\n ports.overlay.navigate(to);\n return { ok: true, data: { to } };\n }\n case \"page\": {\n if (!ports.pageActions) return absent(info, \"this page's actions\");\n return await ports.pageActions.dispatch(info.name, input, context);\n }\n default: {\n const runs: never = info.runs;\n return fail(\"runs_unknown\", `\"${info.label}\" runs as \"${String(runs)}\", which nothing here knows how to run.`);\n }\n }\n } catch (error) {\n capture(error, \"run\");\n return fail(\"run_failed\", messageOf(error), true);\n }\n}\n"],"mappings":"wpBAAA,opCCOO,IAAM,gBAAkB,CAAC,OAAQ,MAAO,QAAS,OAAQ,OAAQ,MAAM,ECyDvE,IAAM,kBAA+C,CAC1D,WACA,OACA,SACA,OACA,OACA,QACA,UACA,MACA,SACA,QACA,MACA,KACA,QACA,YACA,UACA,eACA,QACF,EC3EO,IAAM,oBAAmC,OAAO,OAAO,CAC5D,WAAY,GACZ,eAAgB,WAChB,kBAAmB,EACrB,CAAC,EAEM,SAAS,mBAAmB,MAAwD,CACzF,MAAO,CACL,WAAY,MAAM,aAAa,YAAc,oBAAoB,WACjE,eAAgB,MAAM,aAAa,gBAAkB,oBAAoB,eACzE,kBAAmB,MAAM,aAAa,mBAAqB,oBAAoB,iBACjF,CACF,CCMO,SAAS,gBAAgB,SAAkB,KAAiC,CACjF,OAAO,SAAW,GAAG,QAAQ,IAAI,IAAI,GAAK,IAC5C,CCEA,SAAS,SAAS,YAA6B,CAC7C,IAAM,MAAQ,YAAY,QAAQ,GAAG,EACrC,OAAO,MAAQ,EAAI,YAAY,MAAM,EAAG,KAAK,EAAI,WACnD,CAEO,SAAS,kBAAkB,MAA0B,CAAC,EAAgB,CAC3E,IAAM,YAAc,MAAM,aAAe,KACnC,KAAO,MAAM,MAA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K,KAAK,WAAW,OAAO,QAAQ,KAAK,IAAI,CAAC,GAAG,EAE7G,IAAM,GAAK,KAAK,QAAU,+BAA+B,KAAK,KAAK,MAAM,EAAI,mBAAmB,OAAO,KAAK,EAAI,OAAO,MACvH,OAAK,IACL,MAAM,QAAQ,SAAS,EAAE,EAClB,CAAE,GAAI,GAAM,KAAM,CAAE,EAAG,CAAE,GAFhB,KAAK,iBAAkB,IAAI,KAAK,KAAK,0BAA0B,CAGjF,CACA,IAAK,OACH,OAAK,MAAM,YACJ,MAAM,MAAM,YAAY,SAAS,KAAK,KAAM,MAAO,OAAO,EADlC,OAAO,KAAM,qBAAqB,EAGnE,QAAS,CACP,IAAM,KAAc,KAAK,KACzB,OAAO,KAAK,eAAgB,IAAI,KAAK,KAAK,cAAc,OAAO,IAAI,CAAC,yCAAyC,CAC/G,CACF,CACF,OAAS,MAAO,CACd,OAAAC,SAAQ,MAAO,KAAK,EACb,KAAK,aAAc,UAAU,KAAK,EAAG,EAAI,CAClD,CACF","names":["capture","toJson","capture"]}
|
|
1
|
+
{"version":3,"sources":["../src/actions.ts","../src/actions/click-target.ts","../src/actions/types.ts","../src/declare/sensitivity.ts","../src/declare/keys.ts","../src/actions/target.ts","../src/actions/registry.ts","../src/actions/projection.ts","../src/actions/run.ts","../src/actions/invoke.ts","../src/declare/registry.ts","../src/actions/declarations.ts","../src/actions/surface-run.ts"],"sourcesContent":["/**\n * `@ai-matrx/alchemy/actions` — the one action registry (Matrx Alchemy CONTRACT §2.4).\n * Framework-neutral: zero React, zero `@ai-matrx/agents`.\n */\nexport {\n ACTION_CATEGORIES,\n UNIVERSAL_VERBS,\n type Action,\n type ActionCategory,\n type ActionProvider,\n type ActionRegistry,\n type ActionRunContext,\n type ActionSection,\n type ActionSurface,\n type InvocationContext,\n type ClickTarget,\n type Eligibility,\n type ProjectedReads,\n type ReadOmission,\n type ResolveRestriction,\n type ResolvedAction,\n type UniversalVerb,\n} from \"./actions/types\";\nexport {\n DuplicateActionError,\n DuplicateProviderError,\n alwaysEligible,\n computeEligibility,\n createActionRegistry,\n isMenuAction,\n staticActionProvider,\n type ActionRegistryOptions,\n} from \"./actions/registry\";\nexport { createProjectedReads, projectValues, type ProjectionSource } from \"./actions/projection\";\nexport { createClickTarget, type ClickTargetInput } from \"./actions/target\";\nexport { runAction, type RunActionOptions, type RunResult } from \"./actions/run\";\nexport {\n invocableAction,\n invokeAction,\n type InvocableActionDefinition,\n type InvokeActionOptions,\n} from \"./actions/invoke\";\nexport type {\n ActionCaller,\n ActionContext,\n ActionDeclaration,\n ActionDeclaredBy,\n ActionError,\n ActionInfo,\n ActionInput,\n ActionOrigin,\n ActionPolicy,\n ActionResult,\n ActionRuns,\n ActionWriteMode,\n MandateRunRef,\n MandateRunRequest,\n ServerActionRunRequest,\n ServerActionRunResponse,\n SurfacePort,\n} from \"./actions/applet-types\";\nexport {\n ACTION_CALLERS,\n ACTION_POLICIES,\n ACTION_RUNS,\n APPLET_CATEGORY,\n DEFAULT_TRIGGERED_BY,\n clientToolToAction,\n resolveActionChain,\n surfaceActionRowToAction,\n toActionInfo,\n writeTargetToAction,\n type ActionChainLink,\n type ClientToolRow,\n type SurfaceActionRow,\n} from \"./actions/declarations\";\nexport {\n fillActionTarget,\n refuseCaller,\n runSurfaceAction,\n type RunSurfaceActionOptions,\n type SurfaceActionPorts,\n} from \"./actions/surface-run\";\n","/**\n * The click target (CONTRACT §2.4) in its own module: `/ports` references it,\n * and `/ports` must stay free of every other package (types only).\n */\nimport type { QualifiedValueKey, ResolvedItem, ResolvedSurfaceDeclaration, WriteTarget } from \"../declare/types\";\n\n/** The six universal verbs — the ONLY rows that may grey (R1 c). */\nexport const UNIVERSAL_VERBS = [\"copy\", \"cut\", \"paste\", \"undo\", \"redo\", \"find\"] as const;\nexport type UniversalVerb = (typeof UNIVERSAL_VERBS)[number];\n\n/** The transfer Payload's kinds (`actions/types.ts` asserts equality at compile time). */\nexport type PayloadKind = \"text\" | \"markdown\" | \"json\" | \"rows\" | \"registered\";\n\n/** What eligibility is computed from: everything declared at the click target. */\nexport interface ClickTarget {\n surface: { instanceId: string; surfaceName: string } | null;\n /** The resolved declaration (inheritance applied). Eligibility decides by KEY existence over it. */\n declaration: ResolvedSurfaceDeclaration | null;\n /** Declared value keys with a read path here (screen names + qualified item keys). Key existence, not population. */\n valueKeys: ReadonlySet<QualifiedValueKey>;\n /** Scope chain, most general first: [\"global\", \"<domain>\", \"<surfaceName>\"]. */\n scopeChain: readonly string[];\n /** The surface's explicit exclusions (the one override). */\n excludedActionIds: ReadonlySet<string>;\n item: ResolvedItem | null;\n level: string | null;\n /** Offsets + the live range handle, editable or not. */\n selection: {\n text: string;\n type: \"editable\" | \"non-editable\";\n start: number;\n end: number;\n /** Opaque host handle (DOM Range / element) used to restore or stream into the selection. */\n handle?: unknown;\n } | null;\n /** Payload kinds a capture of this target would produce (from declared value types/kinds). */\n payloadKinds: readonly PayloadKind[];\n /** Declared targets writable on this target right now. */\n writable: readonly WriteTarget[];\n readOnly: boolean;\n /** True when any declared value here is secret/credential or non-exportable. */\n restricted: boolean;\n organizationId: string | null;\n auth: { authenticated: boolean; admin: boolean; creator: boolean };\n /**\n * Host-owned context a provider reads to act (the rich-document source, the\n * editable field's callbacks). Opaque to the package; never crosses into the\n * model. Providers that need it narrow it themselves.\n */\n host?: unknown;\n}\n\n","/**\n * Matrx Alchemy — Actions types (CONTRACT §2.4).\n *\n * One registry of everything a person can do to a thing. Providers plug in;\n * eligibility is computed from what is declared at the click target; duplicate\n * ids are refused; an action that does not apply is ABSENT (chair ruling R1).\n *\n * Framework-neutral: zero React, zero `@ai-matrx/agents`. Icons are string KEYS\n * resolved by the host's `IconResolverPort`; labels go through `I18nPort`.\n */\nimport type { Payload, TransferOutcome } from \"@ai-matrx/alchemy/operate\";\nimport type { Json, LiveValues } from \"../declare/types\";\nimport type { AlchemyHostPorts } from \"../ports\";\nimport type { ClickTarget, PayloadKind } from \"./click-target\";\nimport type { ActionResult } from \"./applet-types\";\n\nexport type { ClickTarget, PayloadKind } from \"./click-target\";\n\n/** PayloadKind is the transfer Payload's kind union, kept equal at compile time. */\ntype Equal<A, B> = [A] extends [B] ? ([B] extends [A] ? true : false) : false;\nconst payloadKindsAgree: Equal<PayloadKind, Payload[\"kind\"]> = true;\nvoid payloadKindsAgree;\n\nexport { UNIVERSAL_VERBS, type UniversalVerb } from \"./click-target\";\nimport type { UniversalVerb } from \"./click-target\";\n\n/**\n * Chair ruling R1: an action that does not apply or cannot run now is ABSENT.\n * Only the six universal verbs may answer \"unavailable-verb\": greyed in the\n * strip/bar, the sentence as tooltip. `requiresAuth` is NOT unavailability.\n */\nexport type Eligibility =\n | { status: \"absent\" }\n | { status: \"available\" }\n | { status: \"unavailable-verb\"; verb: UniversalVerb; sentence: string }\n /**\n * ABSENT OR HONEST (coordinator ruling 2026-09-27, admin pass): a row that cannot run here but\n * SAYS WHY (\"Unchanged from the pack\", \"Manifested surfaces are managed in code\") stays visible,\n * greyed, with its reason — the menu is the same everywhere, only availability changes. A row\n * with no reason is absent (the registry refuses an empty sentence).\n */\n | { status: \"unavailable\"; sentence: string };\n\n/** rich-document's ActionCategory, unchanged, plus the three the context menu groups by, plus \"applet\" (surface Actions). */\nexport type ActionCategory =\n | \"feedback\"\n | \"copy\"\n | \"export\"\n | \"save\"\n | \"edit\"\n | \"share\"\n | \"creator\"\n | \"app\"\n | \"listen\"\n | \"study\"\n | \"ask\"\n | \"ai\"\n | \"admin\"\n | \"clipboard\"\n | \"history\"\n | \"surface-info\"\n /** Surface Actions (Applets CONTRACTS §6): the default category of an `ActionDeclaration`. */\n | \"applet\";\n\nexport const ACTION_CATEGORIES: readonly ActionCategory[] = [\n \"feedback\",\n \"copy\",\n \"export\",\n \"save\",\n \"edit\",\n \"share\",\n \"creator\",\n \"app\",\n \"listen\",\n \"study\",\n \"ask\",\n \"ai\",\n \"admin\",\n \"clipboard\",\n \"history\",\n \"surface-info\",\n \"applet\",\n];\n\n/**\n * An optional named section inside the action's group (a grid's cell / row /\n * column). `primary` marks the thing the person clicked: every layout renders\n * it first, inline, heading kept (context-menu-v3's primary section law).\n */\nexport interface ActionSection {\n id: string;\n label: string;\n labelKey?: string;\n icon?: string;\n primary?: boolean;\n /**\n * \"group\" (default): a heading over related rows — must be in the package's\n * APPROVED_HEADINGS (@ai-matrx/alchemy/menu). \"target\": the label of the\n * thing the person clicked, supplied at run time (\"Row · Widget A\").\n */\n kind?: \"group\" | \"target\";\n}\n\n/**\n * Where an Action can be reached. \"menu\" (the default): menus, bars, palettes and sheets — it runs\n * through `run(target, ctx)`. \"invoke\": code runs it BY ID through `invokeAction` — it runs through\n * `invoke(input, ctx)`. An Action whose `surfaces` omits \"menu\" is never resolved into a menu, so it\n * needs no eligibility of its own (`invocableAction` builds one).\n */\nexport type ActionSurface = \"menu\" | \"invoke\";\n\n/** What a programmatic invocation receives: the host's ports and a capability-scoped context the caller binds. */\nexport interface InvocationContext {\n ports: AlchemyHostPorts;\n /** Opaque to the package: the capabilities the caller hands this one Action (a launcher, the acting user). */\n context: unknown;\n signal: AbortSignal;\n}\n\nexport interface Action {\n /** Globally unique. A duplicate is refused (never overwritten). */\n id: string;\n /** Where it is reachable. Default [\"menu\"]. [\"invoke\"] = programmatic only: absent from every menu. */\n surfaces?: readonly ActionSurface[];\n /** The provider that registered it — filled by the registry. */\n provider?: string;\n /** Resolved through I18nPort.t(labelKey ?? id, label). */\n label: string | ((target: ClickTarget) => string);\n labelKey?: string;\n /** Icon KEY resolved by IconResolverPort — the model stays framework-neutral. */\n icon?: string;\n /** Host styling hint for the glyph (rich-document iconColor). Renderers may ignore it. */\n iconTone?: string;\n /** Replaces `icon` while a state holds (a spinner while speaking). */\n stateIcon?(target: ClickTarget): { icon: string; spin?: boolean } | null;\n hint?: string;\n hintKey?: string;\n description?: string;\n category: ActionCategory;\n /** Which universal verb this clipboard action is (addressed by role in every layout). */\n verb?: UniversalVerb;\n order?: number;\n /** Bar layout slot. Default \"overflow\". */\n placement?: \"primary\" | \"overflow\" | \"both\";\n section?: ActionSection;\n /** A signed-out person still sees it; running goes through AuthResumePort (sign in, then resume). */\n requiresAuth?: boolean;\n /** Declared write targets this action lands through. Absent on a read-only target. */\n writes?: readonly string[];\n destructive?: boolean;\n /**\n * STARTS A NEW GROUP inside its section: the menu draws a divider above it (never as a section's\n * first row). A delete sits in its own group, last, never beside Duplicate (DATA-V2-BASICS-2).\n */\n startsGroup?: boolean;\n preserveSelection?: boolean;\n /**\n * Running it reloads rows of the menu it sits in (a \"Couldn't load. Retry\" row): the menu and its\n * open submenu stay open and show loading, then the rows or the error again. Every other run closes.\n */\n keepsMenuOpen?: boolean;\n /** Link rows navigate instead of running. */\n href?: string | ((target: ClickTarget) => string);\n eligible(target: ClickTarget): Eligibility;\n /** Toggle/pressed state: a pressed button or a checked row. */\n pressed?(target: ClickTarget): boolean;\n /** Present = the row is a checkbox (pressed is its state). */\n toggle?: boolean;\n subscribe?(onChange: () => void, target: ClickTarget): () => void;\n /**\n * The rows behind this submenu are still loading (an agent library's first\n * fetch). The row shows as loading — never absent, never silent — and its\n * `expand` resolves once they arrive.\n */\n pending?(target: ClickTarget): boolean;\n /** Submenus whose rows load on open (agent lists). */\n expand?(target: ClickTarget, signal: AbortSignal): Promise<readonly Action[]>;\n /** Shown centred when `expand` resolves empty. */\n emptyLabel?: string;\n run(target: ClickTarget, context: ActionRunContext): Promise<TransferOutcome | void> | TransferOutcome | void;\n /**\n * The typed invocation channel (programmatic Actions): input in, a never-thrown result envelope out.\n * Called only by `invokeAction`; a throw here is captured there and answered `action_failed`.\n */\n invoke?(input: unknown, context: InvocationContext): Promise<ActionResult<unknown>> | ActionResult<unknown>;\n}\n\n/** One removed read, recorded (kit content-transfer's omission shape). */\nexport interface ReadOmission {\n path: string;\n reason: \"excluded\" | \"filtered\";\n classification?: \"secret\" | \"credential\";\n}\n\n/**\n * PROJECTION BEFORE PROVIDERS. Providers never receive a raw read. Every read\n * they can make is projected first: secret and credential values, values\n * declared `exportable: false`, and values nobody declared are removed, with an\n * omission recorded. Raw reads never leave the package.\n */\nexport interface ProjectedReads {\n values(signal: AbortSignal): Promise<{ values: Record<string, Json>; omissions: readonly ReadOmission[] }>;\n item(signal: AbortSignal): Promise<{ values: Record<string, Json>; omissions: readonly ReadOmission[] } | null>;\n live(signal: AbortSignal): Promise<LiveValues>;\n}\n\n/**\n * What a running action receives. `door` (ALC-17) and `operate` (ALC-16) join\n * with their waves; until then those capabilities are absent (N8).\n */\nexport interface ActionRunContext {\n reads: ProjectedReads;\n ports: AlchemyHostPorts;\n signal: AbortSignal;\n}\n\nexport interface ActionProvider {\n id: string;\n /** T0 providers are known at mount; T1 providers load with the menu on first open. */\n tier: \"T0\" | \"T1\";\n /**\n * The ids this provider can ever yield, when known up front. Lets the\n * registry refuse a duplicate at registration instead of at first open.\n */\n declaredIds?(): readonly string[];\n actions(target: ClickTarget): readonly Action[] | Promise<readonly Action[]>;\n}\n\nexport interface ResolvedAction {\n action: Action;\n eligibility: Exclude<Eligibility, { status: \"absent\" }>;\n}\n\nexport interface ResolveRestriction {\n exclude?: readonly string[];\n categories?: readonly ActionCategory[];\n}\n\nexport interface ActionRegistry {\n /** Throws DuplicateActionError naming both providers; nothing is overwritten. */\n register(provider: ActionProvider): () => void;\n /** restrict: a host may remove ids or categories, never add ineligible ones. */\n resolve(target: ClickTarget, restrict?: ResolveRestriction): Promise<readonly ResolvedAction[]>;\n /** Registered provider ids, in registration order. */\n providers(): readonly string[];\n /**\n * One Action by id, menu-reachable or not, or null. Asks only the provider that declared the id\n * (`declaredIds`); falls back to every provider when no declaration names it. Never throws: a\n * provider that throws is captured and skipped. `target` defaults to an empty click target.\n */\n get(id: string, target?: ClickTarget): Promise<Action | null>;\n /** Change notification (a provider registered or unregistered). */\n subscribe(listener: () => void): () => void;\n}\n","/**\n * Sensitivity defaults and resolution (CONTRACT §2.1). Its own module so the\n * lightweight entries (`/actions`, the T0 React host) can project without\n * pulling the declaration registry.\n */\nimport type { DeclaredValue, Sensitivity } from \"./types\";\n\nexport const DEFAULT_SENSITIVITY: Sensitivity = Object.freeze({\n exportable: true,\n classification: \"ordinary\",\n includedByDefault: true,\n});\n\nexport function resolveSensitivity(value: Pick<DeclaredValue, \"sensitivity\">): Sensitivity {\n return {\n exportable: value.sensitivity?.exportable ?? DEFAULT_SENSITIVITY.exportable,\n classification: value.sensitivity?.classification ?? DEFAULT_SENSITIVITY.classification,\n includedByDefault: value.sensitivity?.includedByDefault ?? DEFAULT_SENSITIVITY.includedByDefault,\n };\n}\n","import type { QualifiedValueKey } from \"./types\";\n\n/** Every value, write-target, item-type and group name (the DB CHECK rule). */\nexport const DECLARATION_NAME_RE = /^[a-z][a-z0-9_]*$/;\n\n/** \"<client>/<local>\" — the surface naming convention. */\nexport const SURFACE_NAME_RE = /^[a-z][a-z0-9-]*\\/[a-z0-9-/]+$/;\n\n/** A bare screen value (`status`) or an item value (`table_row.status`). */\nexport const QUALIFIED_VALUE_KEY_RE = /^[a-z][a-z0-9_]*(\\.[a-z][a-z0-9_]*)?$/;\n\nexport interface ParsedValueKey {\n /** \"\" for a screen-level value. */\n itemType: string;\n name: string;\n}\n\n/** Split a qualified key; null when it is not a valid bare or qualified key. */\nexport function parseQualifiedValueKey(key: string): ParsedValueKey | null {\n if (!QUALIFIED_VALUE_KEY_RE.test(key)) return null;\n const dot = key.indexOf(\".\");\n if (dot === -1) return { itemType: \"\", name: key };\n return { itemType: key.slice(0, dot), name: key.slice(dot + 1) };\n}\n\nexport function qualifyValueKey(itemType: string, name: string): QualifiedValueKey {\n return itemType ? `${itemType}.${name}` : name;\n}\n\n/** The client that owns a surface: its name prefix. */\nexport function surfaceClientOf(surfaceName: string): string {\n return surfaceName.split(\"/\")[0] ?? \"\";\n}\n","/**\n * Building a ClickTarget from what is declared at the click (CONTRACT §2.4).\n * Key existence, never value population: a value key is present when the\n * declaration gives it a read path here.\n */\nimport { resolveSensitivity } from \"../declare/sensitivity\";\nimport { qualifyValueKey } from \"../declare/keys\";\nimport type { ResolvedItem, ResolvedSurfaceDeclaration, WriteTarget } from \"../declare/types\";\nimport type { ClickTarget } from \"./types\";\n\nexport interface ClickTargetInput {\n surface?: ClickTarget[\"surface\"];\n declaration?: ResolvedSurfaceDeclaration | null;\n item?: ResolvedItem | null;\n level?: string | null;\n selection?: ClickTarget[\"selection\"];\n payloadKinds?: ClickTarget[\"payloadKinds\"];\n /** Defaults to the item's readOnly (or false). */\n readOnly?: boolean;\n /** Extra exclusions on top of the declaration's own. */\n excludedActionIds?: Iterable<string>;\n scopeChain?: readonly string[];\n organizationId?: string | null;\n auth?: Partial<ClickTarget[\"auth\"]>;\n /** Write targets the host can serve right now; defaults to every declared target for the screen/item. */\n writable?: readonly WriteTarget[];\n host?: unknown;\n}\n\nfunction domainOf(surfaceName: string): string {\n const slash = surfaceName.indexOf(\"/\");\n return slash > 0 ? surfaceName.slice(0, slash) : surfaceName;\n}\n\nexport function createClickTarget(input: ClickTargetInput = {}): ClickTarget {\n const declaration = input.declaration ?? null;\n const item = input.item ?? null;\n const valueKeys = new Set<string>();\n let restricted = false;\n const writable: WriteTarget[] = [];\n if (declaration) {\n for (const value of declaration.values) {\n valueKeys.add(value.name);\n const s = resolveSensitivity(value);\n if (s.classification !== \"ordinary\" || !s.exportable) restricted = true;\n }\n const itemType = item ? declaration.itemTypes?.find((t) => t.name === item.itemType) : undefined;\n if (itemType) {\n for (const value of itemType.values) {\n valueKeys.add(qualifyValueKey(itemType.name, value.name));\n const s = resolveSensitivity(value);\n if (s.classification !== \"ordinary\" || !s.exportable) restricted = true;\n }\n for (const t of itemType.writeTargets ?? []) writable.push(t);\n }\n for (const t of declaration.writeTargets ?? []) {\n if (!t.itemType || t.itemType === item?.itemType) writable.push(t);\n }\n }\n const readOnly = input.readOnly ?? item?.readOnly ?? false;\n const surfaceName = input.surface?.surfaceName ?? declaration?.surfaceName ?? null;\n const scopeChain = input.scopeChain ?? (surfaceName ? [\"global\", domainOf(surfaceName), surfaceName] : [\"global\"]);\n return {\n surface: input.surface ?? null,\n declaration,\n valueKeys,\n scopeChain,\n excludedActionIds: new Set(input.excludedActionIds ?? []),\n item,\n level: input.level ?? item?.level ?? null,\n selection: input.selection ?? null,\n payloadKinds: input.payloadKinds ?? [],\n writable: readOnly ? [] : (input.writable ?? writable),\n readOnly,\n restricted,\n organizationId: input.organizationId ?? null,\n auth: {\n authenticated: input.auth?.authenticated ?? false,\n admin: input.auth?.admin ?? false,\n creator: input.auth?.creator ?? false,\n },\n host: input.host,\n };\n}\n","/**\n * The one action registry (CONTRACT §2.4).\n *\n * - Duplicate ids are REFUSED, never overwritten (rich-document's registry\n * silently overwrote — R12). A duplicate known at registration throws; one\n * that only appears when a provider yields it is dropped and captured.\n * - Eligibility is one pure pass over the resolved click target, under\n * \"restrict, never relax\": a host may remove ids or categories, never add.\n * - R1: an action that does not apply is ABSENT. Only the six universal verbs\n * (category \"clipboard\") may answer `unavailable-verb`, with a sentence; any\n * other action answering it is a contract break → absent + diagnostics.\n */\nimport type { AlchemyHostPorts, Json } from \"../ports\";\nimport { createClickTarget } from \"./target\";\nimport {\n UNIVERSAL_VERBS,\n type Action,\n type ActionProvider,\n type ActionRegistry,\n type ClickTarget,\n type Eligibility,\n type ResolveRestriction,\n type ResolvedAction,\n} from \"./types\";\n\nexport class DuplicateActionError extends Error {\n readonly actionId: string;\n readonly providers: readonly [string, string];\n constructor(actionId: string, first: string, second: string) {\n super(\n first === second\n ? `Action \"${actionId}\" is yielded twice by provider \"${first}\". Ids are unique; the second was refused.`\n : `Action \"${actionId}\" is registered by provider \"${first}\" and again by \"${second}\". Ids are unique; \"${second}\"'s copy was refused.`,\n );\n this.name = \"DuplicateActionError\";\n this.actionId = actionId;\n this.providers = [first, second];\n }\n}\n\nexport class DuplicateProviderError extends Error {\n readonly providerId: string;\n constructor(providerId: string) {\n super(`Action provider \"${providerId}\" is already registered. Unregister it first; nothing was overwritten.`);\n this.name = \"DuplicateProviderError\";\n this.providerId = providerId;\n }\n}\n\nexport interface ActionRegistryOptions {\n /** `diagnostics` is required (nothing fails silently); `auth` decides whether requiresAuth actions reach a signed-out person. */\n ports: Pick<AlchemyHostPorts, \"diagnostics\" | \"auth\">;\n}\n\nconst VERBS = new Set<string>(UNIVERSAL_VERBS);\n\nfunction capture(ports: ActionRegistryOptions[\"ports\"], error: unknown, detail: Json): void {\n try {\n ports.diagnostics.capture(error, { area: \"actions\", detail });\n } catch {\n // A broken diagnostics port must never take the menu down with it.\n }\n}\n\n/**\n * Eligibility of one action at one target — the ONE pure pass (CONTRACT §1.6).\n * Exported for providers' tests; hosts call `registry.resolve`.\n */\nexport function computeEligibility(\n action: Action,\n target: ClickTarget,\n options: { restrict?: ResolveRestriction; authResumable: boolean },\n): Eligibility | { status: \"contract-break\"; reason: string } {\n const restrict = options.restrict;\n // A programmatic-only Action (surfaces without \"menu\") is never a menu row; its own `eligible` is not asked.\n if (!isMenuAction(action)) return { status: \"absent\" };\n if (target.excludedActionIds.has(action.id)) return { status: \"absent\" };\n if (restrict?.exclude?.includes(action.id)) return { status: \"absent\" };\n if (restrict?.categories && !restrict.categories.includes(action.category)) return { status: \"absent\" };\n if (action.writes && action.writes.length > 0) {\n // A read-only target offers nothing that would change the record.\n if (target.readOnly) return { status: \"absent\" };\n const writable = new Set(target.writable.map((w) => w.name));\n if (!action.writes.some((name) => writable.has(name))) return { status: \"absent\" };\n }\n if (action.requiresAuth && !target.auth.authenticated && !options.authResumable) {\n // Sign-in-then-resume is the capability; without the auth port it is absent (N8).\n return { status: \"absent\" };\n }\n const own = action.eligible(target);\n if (own.status === \"unavailable\") {\n // A greyed row must say why; without a sentence it is absent.\n return own.sentence.trim() ? own : { status: \"absent\" };\n }\n if (own.status !== \"unavailable-verb\") return own;\n if (action.category !== \"clipboard\" || !VERBS.has(own.verb)) {\n return {\n status: \"contract-break\",\n reason: `Action \"${action.id}\" answered unavailable-verb but only the six universal verbs (category \"clipboard\") may grey; it is absent instead.`,\n };\n }\n if (!own.sentence.trim()) {\n return {\n status: \"contract-break\",\n reason: `Universal verb \"${action.id}\" greyed without a sentence; a greyed verb must say why.`,\n };\n }\n return own;\n}\n\n/** True unless the Action declares `surfaces` without \"menu\" (default: a menu Action). */\nexport function isMenuAction(action: Pick<Action, \"surfaces\">): boolean {\n return !action.surfaces || action.surfaces.includes(\"menu\");\n}\n\ninterface Entry {\n provider: ActionProvider;\n declared: readonly string[];\n}\n\nexport function createActionRegistry(options: ActionRegistryOptions): ActionRegistry {\n const ports = options.ports;\n const entries = new Map<string, Entry>();\n const listeners = new Set<() => void>();\n const notify = () => {\n for (const l of [...listeners]) l();\n };\n\n return {\n register(provider) {\n if (entries.has(provider.id)) throw new DuplicateProviderError(provider.id);\n const declared = provider.declaredIds?.() ?? [];\n const own = new Set<string>();\n for (const id of declared) {\n if (own.has(id)) throw new DuplicateActionError(id, provider.id, provider.id);\n own.add(id);\n for (const [otherId, other] of entries) {\n if (other.declared.includes(id)) throw new DuplicateActionError(id, otherId, provider.id);\n }\n }\n const entry: Entry = { provider, declared };\n entries.set(provider.id, entry);\n notify();\n return () => {\n if (entries.get(provider.id) === entry) {\n entries.delete(provider.id);\n notify();\n }\n };\n },\n\n async resolve(target, restrict) {\n const authResumable = Boolean(ports.auth);\n const seen = new Map<string, string>();\n const out: ResolvedAction[] = [];\n for (const [providerId, { provider }] of [...entries]) {\n let actions: readonly Action[];\n try {\n actions = await provider.actions(target);\n } catch (error) {\n capture(ports, error, { providerId, stage: \"actions\" });\n continue;\n }\n for (const raw of actions) {\n const first = seen.get(raw.id);\n if (first !== undefined) {\n capture(ports, new DuplicateActionError(raw.id, first, providerId), { actionId: raw.id });\n continue;\n }\n seen.set(raw.id, providerId);\n const action: Action = raw.provider === providerId ? raw : { ...raw, provider: providerId };\n let eligibility: ReturnType<typeof computeEligibility>;\n try {\n eligibility = computeEligibility(action, target, { restrict: restrict ?? {}, authResumable });\n } catch (error) {\n capture(ports, error, { actionId: action.id, stage: \"eligible\" });\n continue;\n }\n if (eligibility.status === \"contract-break\") {\n capture(ports, new Error(eligibility.reason), { actionId: action.id, stage: \"eligible\" });\n continue;\n }\n if (eligibility.status === \"absent\") continue;\n out.push({ action, eligibility });\n }\n }\n return out;\n },\n\n providers() {\n return [...entries.keys()];\n },\n\n async get(id, target) {\n const at = target ?? createClickTarget();\n const all = [...entries];\n const declaring = all.filter(([, e]) => e.declared.includes(id));\n // Declared ids are unique across providers (refused at registration), so at most one declares it.\n // Nobody declared it: fall back to asking every provider (T1 providers yield ids only on resolve).\n const order = declaring.length > 0 ? declaring : all;\n for (const [providerId, { provider }] of order) {\n let actions: readonly Action[];\n try {\n actions = await provider.actions(at);\n } catch (error) {\n capture(ports, error, { providerId, stage: \"actions\", actionId: id });\n continue;\n }\n const found = actions.find((a) => a.id === id);\n if (found) return found.provider === providerId ? found : { ...found, provider: providerId };\n }\n return null;\n },\n\n subscribe(listener) {\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n };\n },\n };\n}\n\n/** A provider over a fixed list; its ids are declared up front so duplicates fail at registration. */\nexport function staticActionProvider(\n id: string,\n actions: readonly Action[],\n tier: ActionProvider[\"tier\"] = \"T0\",\n): ActionProvider {\n const list = actions.map((a) => (a.provider === id ? a : { ...a, provider: id }));\n return {\n id,\n tier,\n declaredIds: () => list.map((a) => a.id),\n actions: () => list,\n };\n}\n\n/** Always-available eligibility, for actions with no rule of their own. */\nexport const alwaysEligible = (): Eligibility => ({ status: \"available\" });\n","/**\n * PROJECTION BEFORE PROVIDERS (CONTRACT §2.4).\n *\n * The only place a raw read (`MountedSurface.readValues`,\n * `InternalResolvedItem.readValues`) is consumed on behalf of an action.\n * What leaves is projected: a value is kept only when it is DECLARED, its\n * classification is \"ordinary\" and it is exportable. Everything removed is\n * recorded as an omission, so the person and the agent can see what was held\n * back. No caller can relax this.\n */\nimport { resolveSensitivity } from \"../declare/sensitivity\";\nimport type { InternalResolvedItem, MountedSurface } from \"../declare/host\";\nimport type { DeclaredValue, Json, LiveValues, ResolvedSurfaceDeclaration } from \"../declare/types\";\nimport type { ProjectedReads, ReadOmission } from \"./types\";\n\nexport interface ProjectionSource {\n surface: MountedSurface | null;\n declaration: ResolvedSurfaceDeclaration | null;\n item: InternalResolvedItem | null;\n}\n\nfunction toJson(value: unknown): Json | undefined {\n if (value === undefined || typeof value === \"function\" || typeof value === \"symbol\") return undefined;\n if (value === null || typeof value === \"string\" || typeof value === \"boolean\") return value;\n if (typeof value === \"number\") return Number.isFinite(value) ? value : null;\n if (typeof value === \"bigint\") return value.toString();\n if (value instanceof Date) return value.toISOString();\n if (Array.isArray(value)) return value.map((v) => toJson(v) ?? null);\n if (typeof value === \"object\") {\n const out: { [key: string]: Json } = {};\n for (const [k, v] of Object.entries(value as Record<string, unknown>)) {\n const j = toJson(v);\n if (j !== undefined) out[k] = j;\n }\n return out;\n }\n return undefined;\n}\n\n/** Keep declared, ordinary, exportable values; record every removal. */\nexport function projectValues(\n raw: Record<string, unknown>,\n declared: readonly Pick<DeclaredValue, \"name\" | \"sensitivity\">[],\n pathPrefix = \"\",\n): { values: Record<string, Json>; omissions: ReadOmission[] } {\n const byName = new Map(declared.map((d) => [d.name, d]));\n const values: Record<string, Json> = {};\n const omissions: ReadOmission[] = [];\n for (const [name, value] of Object.entries(raw)) {\n const path = pathPrefix ? `${pathPrefix}.${name}` : name;\n const decl = byName.get(name);\n if (!decl) {\n omissions.push({ path, reason: \"filtered\" });\n continue;\n }\n const sensitivity = resolveSensitivity(decl);\n if (sensitivity.classification !== \"ordinary\") {\n omissions.push({ path, reason: \"excluded\", classification: sensitivity.classification });\n continue;\n }\n if (!sensitivity.exportable) {\n omissions.push({ path, reason: \"excluded\" });\n continue;\n }\n const json = toJson(value);\n if (json === undefined) continue;\n values[name] = json;\n }\n return { values, omissions };\n}\n\nexport function createProjectedReads(source: ProjectionSource): ProjectedReads {\n return {\n async values(signal) {\n if (!source.surface || !source.declaration) return { values: {}, omissions: [] };\n const raw = await source.surface.readValues(signal);\n const screenValues = source.declaration.values;\n return projectValues(raw, screenValues);\n },\n async item(signal) {\n const item = source.item;\n if (!item || !source.declaration) return null;\n const type = source.declaration.itemTypes?.find((t) => t.name === item.itemType);\n if (!type) return { values: {}, omissions: [{ path: item.itemType, reason: \"filtered\" }] };\n const raw = await item.readValues(signal);\n return projectValues(raw, type.values, item.itemType);\n },\n async live(signal): Promise<LiveValues> {\n if (!source.surface?.readLive) return {};\n return source.surface.readLive(signal);\n },\n };\n}\n","/**\n * The one run path (T1e). Every layout runs an action through here, so the\n * sign-in-then-resume rule, projection and failure capture live once.\n */\nimport type { TransferOutcome } from \"@ai-matrx/alchemy/operate\";\nimport type { AlchemyHostPorts } from \"../ports\";\nimport { createProjectedReads, type ProjectionSource } from \"./projection\";\nimport type { Action, ClickTarget } from \"./types\";\n\nexport interface RunActionOptions {\n ports: AlchemyHostPorts;\n /** Raw sources; projected before the action sees them. */\n source?: ProjectionSource;\n /** Stable fingerprint of the content, for sign-in-then-resume. */\n contentFingerprint?: string;\n signal?: AbortSignal;\n}\n\nexport type RunResult =\n | { status: \"ran\"; outcome: TransferOutcome | void }\n | { status: \"auth-pending\" }\n | { status: \"failed\"; error: unknown };\n\nexport async function runAction(action: Action, target: ClickTarget, options: RunActionOptions): Promise<RunResult> {\n const { ports } = options;\n if (action.requiresAuth && !target.auth.authenticated) {\n if (!ports.auth) {\n // Unreachable through resolve (the action is absent without the port); guard direct callers.\n ports.diagnostics.capture(new Error(`requiresAuth action \"${action.id}\" ran signed out with no auth port`), {\n area: \"actions\",\n detail: { actionId: action.id },\n });\n return { status: \"failed\", error: new Error(\"sign-in unavailable\") };\n }\n ports.auth.signInThenResume({ actionId: action.id, contentFingerprint: options.contentFingerprint ?? action.id });\n return { status: \"auth-pending\" };\n }\n const reads = createProjectedReads(options.source ?? { surface: null, declaration: target.declaration, item: null });\n const signal = options.signal ?? new AbortController().signal;\n try {\n const outcome = await action.run(target, { reads, ports, signal });\n return { status: \"ran\", outcome };\n } catch (error) {\n ports.diagnostics.capture(error, { area: \"actions\", detail: { actionId: action.id, stage: \"run\" } });\n const label = typeof action.label === \"string\" ? action.label : action.id;\n ports.notify?.error(`${label} did not finish.`, \"Try again; if it keeps failing, report it from the feedback button.\");\n return { status: \"failed\", error };\n }\n}\n","/**\n * The one programmatic runner. Menu Actions run through `runAction(action, target)`; code that\n * names an Action BY ID (a kind component's `runAction(key, input)`, an accepted assist chip)\n * runs it here, on the same registry. It never throws: every outcome is an `ActionResult`.\n *\n * Refusals, by code:\n * - `not_registered` — no provider yields that id.\n * - `not_invocable` — the Action exists but has no `invoke` channel (a menu-only Action).\n * - `lookup_failed` — the registry itself threw while finding it (captured).\n * - `action_failed` — `invoke` threw or answered something that is not an envelope (captured + announced once\n * through `notify.error`; the caller never announces it again).\n */\nimport type { AlchemyHostPorts } from \"../ports\";\nimport type { ActionResult } from \"./applet-types\";\nimport type { Action, ActionRegistry, ActionSurface, Eligibility, InvocationContext } from \"./types\";\n\nexport interface InvokeActionOptions {\n ports: AlchemyHostPorts;\n /** The capability-scoped context this one Action receives (opaque to the package). */\n context?: unknown;\n signal?: AbortSignal;\n}\n\nfunction refused(code: string, message: string, retryable: boolean): { ok: false; error: { code: string; message: string; retryable: boolean } } {\n return { ok: false, error: { code, message, retryable } };\n}\n\nfunction isEnvelope(value: unknown): value is ActionResult<unknown> {\n if (!value || typeof value !== \"object\") return false;\n const v = value as { ok?: unknown; error?: unknown };\n if (v.ok === true) return true;\n return v.ok === false && !!v.error && typeof (v.error as { message?: unknown }).message === \"string\";\n}\n\nfunction capture(ports: AlchemyHostPorts, error: unknown, detail: Record<string, string>): void {\n try {\n ports.diagnostics.capture(error, { area: \"actions\", detail });\n } catch {\n // A broken diagnostics port never turns a refusal into a throw.\n }\n}\n\nexport async function invokeAction<T = unknown>(\n registry: Pick<ActionRegistry, \"get\">,\n id: string,\n input: unknown,\n options: InvokeActionOptions,\n): Promise<ActionResult<T>> {\n const { ports } = options;\n let action: Action | null;\n try {\n action = await registry.get(id);\n } catch (error) {\n capture(ports, error, { actionId: id, stage: \"get\" });\n return refused(\"lookup_failed\", `Couldn't look up \"${id}\".`, true);\n }\n if (!action) return refused(\"not_registered\", `No action registered for \"${id}\".`, false);\n if (!action.invoke) return refused(\"not_invocable\", `\"${id}\" runs only from a menu, not by id.`, false);\n const context: InvocationContext = {\n ports,\n context: options.context,\n signal: options.signal ?? new AbortController().signal,\n };\n const label = typeof action.label === \"string\" ? action.label : id;\n // `action_failed` is always captured AND announced once here, so a caller never announces it again.\n const failed = (error: unknown, message: string, retryable: boolean) => {\n capture(ports, error, { actionId: id, stage: \"invoke\" });\n try {\n ports.notify?.error(`${label} did not finish.`, \"Try again; if it keeps failing, report it from the feedback button.\");\n } catch {\n // notify is best effort.\n }\n return refused(\"action_failed\", message, retryable);\n };\n try {\n const result = await action.invoke(input, context);\n if (!isEnvelope(result)) {\n const error = new Error(`\"${id}\" answered without a result envelope ({ ok, data } | { ok: false, error }).`);\n return failed(error, error.message, false);\n }\n return result as ActionResult<T>;\n } catch (error) {\n return failed(error, error instanceof Error && error.message ? error.message : `${label} did not finish.`, true);\n }\n}\n\nexport interface InvocableActionDefinition {\n /** Globally unique; namespace it (`kind.trigger_agent`). */\n id: string;\n label: string;\n description?: string;\n category?: Action[\"category\"];\n invoke: NonNullable<Action[\"invoke\"]>;\n}\n\nconst NEVER_IN_MENUS = (): Eligibility => ({ status: \"absent\" });\n\n/**\n * A programmatic-only Action: `surfaces: [\"invoke\"]`, so no menu ever resolves it; `run` refuses\n * (only `invokeAction` reaches it). Register it like any Action, on the one registry.\n */\nexport function invocableAction(def: InvocableActionDefinition): Action {\n const surfaces: readonly ActionSurface[] = [\"invoke\"];\n return {\n id: def.id,\n label: def.label,\n ...(def.description !== undefined ? { description: def.description } : {}),\n category: def.category ?? \"app\",\n surfaces,\n eligible: NEVER_IN_MENUS,\n run() {\n throw new Error(`\"${def.id}\" runs only by id (invokeAction), never from a menu.`);\n },\n invoke: def.invoke,\n };\n}\n","/**\n * The declaration registry: inheritance, baseline injection, provenance and\n * group synthesis (CONTRACT §2.1 `DeclarationRegistry`). Ported verbatim in\n * behaviour from matrx-frontend `features/surfaces/manifests/registry.ts`\n * (ALC-14); the app now supplies its declarations and baselines.\n *\n * Guards are LOUD by design: an unknown parent, a cycle, a chain deeper than\n * the limit, a reserved or duplicate group key, a value naming an undeclared\n * group, or a reserved platform name throws on resolution — a build fails\n * instead of silently dropping values.\n */\nimport { declarationHash } from \"./hash\";\nimport type {\n DeclarationExtension,\n DeclarationIssue,\n DeclaredValue,\n ItemType,\n ResolvedSurfaceDeclaration,\n ResolvedValue,\n SurfaceDeclaration,\n ValueGroup,\n ValueProvenance,\n} from \"./types\";\nimport { validateDeclarations, type ValidateOptions } from \"./validate\";\n\nexport const RESERVED_GROUP_KEYS = {\n general: \"general\",\n baseline: \"baseline\",\n inheritedPrefix: \"inherited:\",\n} as const;\n\n/** Group sortOrder bands. Curated groups author 0–899; the rest is reserved. */\nexport const GENERAL_GROUP_ORDER = 850;\nexport const INHERITED_GROUP_ORDER_BASE = 9000;\nexport const BASELINE_GROUP_ORDER = 9900;\nexport const DEFAULT_MAX_INHERITANCE_DEPTH = 3;\n\nimport { DEFAULT_SENSITIVITY, resolveSensitivity } from \"./sensitivity\";\nexport { DEFAULT_SENSITIVITY, resolveSensitivity };\n\nexport type Resolved<D extends SurfaceDeclaration> = Omit<D, \"values\" | \"groups\"> & {\n values: readonly (D[\"values\"][number] & ResolvedValue)[];\n groups: readonly ValueGroup[];\n contentHash: string;\n};\n\nexport interface DeclarationRegistryOptions {\n /** Generic values injected into every declaration unless `skipBaselineValues`. */\n baselineValues?: readonly DeclaredValue[];\n /**\n * Item types every declaration carries unless it declares one of the same name or sets\n * `skipBaselineItemTypes` (ALC-18: the canonical table row, `TABLE_ROW_ITEM_TYPE`).\n */\n baselineItemTypes?: readonly ItemType[];\n /** Value names only the platform writes; a declaration claiming one is refused. */\n reservedValueNames?: readonly string[];\n /** Write-target names only the platform writes. */\n reservedWriteTargetNames?: readonly string[];\n maxInheritanceDepth?: number;\n}\n\nexport interface DeclarationRegistry<D extends SurfaceDeclaration> {\n /** Refuses a second declaration of the same surfaceName. */\n register(declaration: D): void;\n registerExtension(extension: DeclarationExtension<D>): void;\n extensions(): readonly DeclarationExtension<D>[];\n /** Declarations exactly as authored (inheritance unresolved, no baselines). */\n raw(): readonly D[];\n getRaw(surfaceName: string): D | undefined;\n /** Parent chain, ROOT FIRST. Unknown surfaces return []. */\n ancestry(surfaceName: string): string[];\n /** Direct children (declarations naming it in `inheritsFrom`), in declaration order. */\n children(surfaceName: string): string[];\n /** Inheritance + baseline + groups resolved; provenance kept. */\n all(): readonly Resolved<D>[];\n get(surfaceName: string): Resolved<D> | undefined;\n validate(options?: ValidateOptions): readonly DeclarationIssue[];\n}\n\nexport function createDeclarationRegistry<D extends SurfaceDeclaration>(\n options: DeclarationRegistryOptions = {},\n): DeclarationRegistry<D> {\n const baselineValues = options.baselineValues ?? [];\n const baselineNames = new Set(baselineValues.map((v) => v.name));\n const baselineItemTypes = options.baselineItemTypes ?? [];\n const reservedValues = new Set(options.reservedValueNames ?? []);\n const reservedTargets = new Set(options.reservedWriteTargetNames ?? []);\n const maxDepth = options.maxInheritanceDepth ?? DEFAULT_MAX_INHERITANCE_DEPTH;\n const declarations: D[] = [];\n const index = new Map<string, D>();\n const extensionList: DeclarationExtension<D>[] = [];\n let resolvedCache: Resolved<D>[] | null = null;\n let resolvedIndex = new Map<string, Resolved<D>>();\n\n function ancestry(surfaceName: string): string[] {\n const chain: string[] = [];\n const seen = new Set<string>([surfaceName]);\n let current = index.get(surfaceName)?.inheritsFrom;\n while (current) {\n if (seen.has(current)) {\n throw new Error(\n `[surfaces] inheritsFrom CYCLE detected at \"${current}\" (from \"${surfaceName}\"). ` +\n `Fix the manifest chain: ${[...seen].join(\" → \")} → ${current}`,\n );\n }\n const parent = index.get(current);\n if (!parent) {\n throw new Error(\n `[surfaces] \"${surfaceName}\" inheritsFrom unknown surface \"${current}\" — ` +\n `the parent must be a registered declaration`,\n );\n }\n seen.add(current);\n chain.unshift(current);\n if (chain.length > maxDepth) {\n throw new Error(\n `[surfaces] inheritance chain for \"${surfaceName}\" exceeds depth ${maxDepth}: ` + chain.join(\" → \"),\n );\n }\n current = parent.inheritsFrom;\n }\n return chain;\n }\n\n function groupKeyFor(value: DeclaredValue, provenance: ValueProvenance): string {\n if (provenance.kind === \"own\" && value.group) return value.group;\n if (baselineNames.has(value.name)) return RESERVED_GROUP_KEYS.baseline;\n if (provenance.kind === \"inherited\") return `${RESERVED_GROUP_KEYS.inheritedPrefix}${provenance.from}`;\n if (provenance.kind === \"baseline\") return RESERVED_GROUP_KEYS.baseline;\n return RESERVED_GROUP_KEYS.general;\n }\n\n function resolve(declaration: D): Resolved<D> {\n const chain = ancestry(declaration.surfaceName);\n const lineage: { layer: D; from: string | null }[] = [\n ...chain.map((name) => {\n const layer = index.get(name);\n if (!layer) throw new Error(`[surfaces] missing inherited declaration \"${name}\"`);\n return { layer, from: name };\n }),\n { layer: declaration, from: null },\n ];\n\n const curatedKeys = new Set<string>();\n for (const group of declaration.groups ?? []) {\n if (\n group.key === RESERVED_GROUP_KEYS.general ||\n group.key === RESERVED_GROUP_KEYS.baseline ||\n group.key.startsWith(RESERVED_GROUP_KEYS.inheritedPrefix)\n ) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" declares reserved group key \"${group.key}\" — ` +\n `general/baseline/inherited:* are synthesized by the registry`,\n );\n }\n if (curatedKeys.has(group.key)) {\n throw new Error(`[surfaces] \"${declaration.surfaceName}\" declares duplicate group key \"${group.key}\"`);\n }\n curatedKeys.add(group.key);\n }\n for (const value of declaration.values) {\n if (reservedValues.has(value.name)) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" declares value \"${value.name}\" — that name is written by the platform; choose another name`,\n );\n }\n if (value.group && !curatedKeys.has(value.group)) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" value \"${value.name}\" references undeclared ` +\n `group \"${value.group}\" — declare it in the manifest's \\`groups\\``,\n );\n }\n }\n for (const target of declaration.writeTargets ?? []) {\n if (reservedTargets.has(target.name)) {\n throw new Error(\n `[surfaces] \"${declaration.surfaceName}\" declares write target \"${target.name}\" — that name is written by the platform; choose another name`,\n );\n }\n }\n\n const valuesByName = new Map<string, D[\"values\"][number] & ResolvedValue>();\n const inheritedLists = new Map<string, Map<string, unknown>>();\n const coreLists: { field: string; identity(entry: unknown): string }[] = [\n { field: \"configNamespaces\", identity: (entry) => (entry as { namespace: string }).namespace },\n {\n field: \"evidenceSources\",\n identity: (entry) => `${(entry as { kind: string }).kind}:${(entry as { idValue: string }).idValue}`,\n },\n ];\n const lists = [...coreLists, ...extensionList.flatMap((extension) => extension.inheritedLists ?? [])];\n for (const { layer, from } of lineage) {\n for (const value of layer.values) {\n const provenance: ValueProvenance = from ? { kind: \"inherited\", from } : { kind: \"own\" };\n valuesByName.set(value.name, {\n ...value,\n provenance,\n groupKey: groupKeyFor(value, provenance),\n resolvedSensitivity: resolveSensitivity(value),\n });\n }\n for (const list of lists) {\n const entries = (layer as unknown as Record<string, unknown>)[list.field];\n if (!Array.isArray(entries)) continue;\n const byIdentity = inheritedLists.get(list.field) ?? new Map<string, unknown>();\n for (const entry of entries) byIdentity.set(list.identity(entry), entry);\n inheritedLists.set(list.field, byIdentity);\n }\n }\n\n if (!declaration.skipBaselineValues) {\n for (const baseline of baselineValues) {\n if (valuesByName.has(baseline.name)) continue;\n valuesByName.set(baseline.name, {\n ...baseline,\n provenance: { kind: \"baseline\" },\n groupKey: RESERVED_GROUP_KEYS.baseline,\n resolvedSensitivity: resolveSensitivity(baseline),\n } as D[\"values\"][number] & ResolvedValue);\n }\n }\n\n const ownItemTypes = declaration.itemTypes ?? [];\n const itemTypes: ItemType[] = [...ownItemTypes];\n if (!declaration.skipBaselineItemTypes) {\n for (const baseline of baselineItemTypes) {\n if (!itemTypes.some((item) => item.name === baseline.name)) itemTypes.push(baseline);\n }\n }\n\n const usedGroupKeys = new Set(Array.from(valuesByName.values(), (value) => value.groupKey));\n const groups: ValueGroup[] = [...(declaration.groups ?? [])];\n if (usedGroupKeys.has(RESERVED_GROUP_KEYS.general)) {\n groups.push({ key: RESERVED_GROUP_KEYS.general, label: \"General\", sortOrder: GENERAL_GROUP_ORDER });\n }\n for (let i = chain.length - 1, distance = 0; i >= 0; i -= 1, distance += 1) {\n const parentName = chain[i]!;\n const key = `${RESERVED_GROUP_KEYS.inheritedPrefix}${parentName}`;\n if (!usedGroupKeys.has(key)) continue;\n const parentLabel = index.get(parentName)?.label ?? parentName;\n groups.push({\n key,\n label: `Inherited from ${parentLabel}`,\n sortOrder: INHERITED_GROUP_ORDER_BASE + distance * 10,\n });\n }\n if (usedGroupKeys.has(RESERVED_GROUP_KEYS.baseline)) {\n groups.push({ key: RESERVED_GROUP_KEYS.baseline, label: \"Generic baselines\", sortOrder: BASELINE_GROUP_ORDER });\n }\n groups.sort((a, b) => a.sortOrder - b.sortOrder);\n\n const groupOrder = new Map(groups.map((group) => [group.key, group.sortOrder] as const));\n const values = Array.from(valuesByName.values()).sort((a, b) => {\n const ga = groupOrder.get(a.groupKey) ?? GENERAL_GROUP_ORDER;\n const gb = groupOrder.get(b.groupKey) ?? GENERAL_GROUP_ORDER;\n if (ga !== gb) return ga - gb;\n return (a.sortOrder ?? 1000) - (b.sortOrder ?? 1000);\n });\n\n const merged: Record<string, unknown> = {};\n for (const [field, byIdentity] of inheritedLists) {\n if (byIdentity.size > 0) merged[field] = Array.from(byIdentity.values());\n }\n return {\n ...declaration,\n values,\n groups,\n ...merged,\n ...(itemTypes.length > 0 ? { itemTypes } : {}),\n contentHash: declarationHash(declaration),\n } as Resolved<D>;\n }\n\n function resolvedAll(): Resolved<D>[] {\n if (!resolvedCache) {\n resolvedCache = declarations.map(resolve);\n resolvedIndex = new Map(resolvedCache.map((entry) => [entry.surfaceName, entry] as const));\n }\n return resolvedCache;\n }\n\n const registry: DeclarationRegistry<D> = {\n register(declaration) {\n if (index.has(declaration.surfaceName)) {\n throw new Error(`[surfaces] \"${declaration.surfaceName}\" is declared twice — one surface, one declaration`);\n }\n declarations.push(declaration);\n index.set(declaration.surfaceName, declaration);\n resolvedCache = null;\n },\n registerExtension(extension) {\n if (extensionList.some((existing) => existing.key === extension.key)) {\n throw new Error(`[surfaces] declaration extension \"${extension.key}\" is registered twice`);\n }\n extensionList.push(extension);\n resolvedCache = null;\n },\n extensions: () => extensionList,\n raw: () => declarations,\n getRaw: (surfaceName) => index.get(surfaceName),\n ancestry,\n children: (surfaceName) =>\n declarations.filter((d) => d.inheritsFrom === surfaceName).map((d) => d.surfaceName),\n all: () => resolvedAll(),\n get(surfaceName) {\n resolvedAll();\n return resolvedIndex.get(surfaceName);\n },\n validate: (validateOptions) =>\n validateDeclarations(resolvedAll() as unknown as readonly ResolvedSurfaceDeclaration[], {\n ...validateOptions,\n extensions: [...(validateOptions?.extensions ?? []), ...(extensionList as DeclarationExtension[])],\n baselineNames: validateOptions?.baselineNames ?? [...baselineNames],\n }),\n };\n return registry;\n}\n","/**\n * Every source of an Action projects onto ONE shape (Applets CONTRACTS §6):\n * a declared write target, a client tool row, a `ui.ui_surface_action` row.\n * Pure functions, zero loss (the census in `declarations.test.ts` proves every\n * source field lands). Then the chain: a child surface's Action wins by name.\n */\nimport { DEFAULT_MAX_INHERITANCE_DEPTH } from \"../declare/registry\";\nimport type { Json, WriteTarget } from \"../declare/types\";\nimport type {\n ActionCaller,\n ActionDeclaration,\n ActionDeclaredBy,\n ActionInfo,\n ActionInput,\n ActionOrigin,\n ActionPolicy,\n ActionRuns,\n ActionWriteMode,\n} from \"./applet-types\";\n\n/** Default `category` of an Action that names none. */\nexport const APPLET_CATEGORY = \"applet\";\n\n/** The DB default of `ui.ui_surface_action.triggered_by`, used where a source carries no list. */\nexport const DEFAULT_TRIGGERED_BY: readonly ActionCaller[] = [\"person\", \"agent\", \"applet\"];\n\nexport const ACTION_CALLERS: readonly ActionCaller[] = [\"person\", \"agent\", \"applet\", \"automation\"];\nexport const ACTION_RUNS: readonly ActionRuns[] = [\"page\", \"server\", \"mandate\", \"navigate\"];\nexport const ACTION_POLICIES: readonly ActionPolicy[] = [\"ask\", \"auto\", \"manual\"];\n\n/** A `ui.ui_surface_client_tool` row (live columns that carry meaning). */\nexport interface ClientToolRow {\n id?: string;\n surface_name: string;\n name: string;\n label: string;\n description: string;\n input_schema: Json;\n /** Live values: \"ui\" (applied directly) | \"draft\" (proposed for review). */\n mode: \"ui\" | \"draft\";\n declared_by?: ActionDeclaredBy;\n}\n\n/** A `ui.ui_surface_action` row. */\nexport interface SurfaceActionRow {\n id?: string;\n surface_id: string;\n surface_name: string;\n /** '' = the screen itself. */\n item_type: string;\n name: string;\n category: string;\n label: string;\n description: string;\n input: ActionInput | null;\n output: string | null;\n runs: ActionRuns;\n target: string | null;\n triggered_by: ActionCaller[];\n policy: ActionPolicy;\n updates_value: string | null;\n code_ref: string | null;\n declared_by: ActionDeclaredBy;\n sort_order: number;\n /**\n * The row's organization. A `declared_by='database'` row on a surface outside `applets/` is that\n * organization's EXTENSION and applies only to its members (`readSurfaceChain`, aidream `visible_actions`).\n */\n organization_id?: string | null;\n}\n\ntype Loose<T> = { [K in keyof T]: T[K] | undefined };\n\n/** Drop undefined keys (exactOptionalPropertyTypes: an absent field is absent, never `undefined`). */\nfunction compact<T extends object>(value: Loose<T>): T {\n return Object.fromEntries(Object.entries(value).filter(([, v]) => v !== undefined)) as T;\n}\n\nconst POLICY_OF_APPLY: Record<NonNullable<WriteTarget[\"applyPolicy\"]>, ActionPolicy> = {\n manual: \"manual\",\n ask: \"ask\",\n auto: \"auto\",\n // Filed for an organization's review: never applied without someone saying yes.\n queued: \"ask\",\n};\n\n/** A declared write target → an Action that runs on the page. */\nexport function writeTargetToAction(target: WriteTarget): ActionDeclaration {\n const applyPolicy = target.applyPolicy ?? \"manual\";\n return compact<ActionDeclaration>({\n name: target.name,\n label: target.label,\n description: target.description,\n input: target.valueKind ?? { jsonSchema: target.valueType === \"document\" ? {} : { type: target.valueType } },\n runs: \"page\",\n triggeredBy: [...DEFAULT_TRIGGERED_BY],\n policy: POLICY_OF_APPLY[applyPolicy],\n updatesValue: target.updatesValue,\n mode: target.mode as ActionWriteMode,\n patchable: target.patchable,\n approvalComparison: target.approvalComparison,\n streamOps: target.streamOps ? [...target.streamOps] : undefined,\n destination: target.destination,\n groupKey: target.group,\n itemType: target.itemType,\n applyPolicy: target.applyPolicy,\n valueType: target.valueType,\n valueKind: target.valueKind,\n sortOrder: target.sortOrder,\n origin: { source: \"write-target\", declaredBy: \"code\" },\n });\n}\n\n/** A client tool row → an Action an agent runs on the page (\"draft\" tools are proposed first). */\nexport function clientToolToAction(row: ClientToolRow): ActionDeclaration {\n return compact<ActionDeclaration>({\n name: row.name,\n label: row.label,\n description: row.description,\n input: { jsonSchema: (row.input_schema ?? {}) as object },\n runs: \"page\",\n triggeredBy: [\"agent\"],\n policy: row.mode === \"draft\" ? \"ask\" : \"auto\",\n mode: row.mode,\n origin: compact<ActionOrigin>({ source: \"client-tool\", surfaceName: row.surface_name, id: row.id, declaredBy: row.declared_by }),\n });\n}\n\n/** A `ui.ui_surface_action` row → its Action. */\nexport function surfaceActionRowToAction(row: SurfaceActionRow): ActionDeclaration {\n return compact<ActionDeclaration>({\n name: row.name,\n category: row.category,\n label: row.label,\n description: row.description,\n input: row.input ?? undefined,\n output: row.output ?? undefined,\n runs: row.runs,\n target: row.target ?? undefined,\n triggeredBy: [...row.triggered_by],\n policy: row.policy,\n updatesValue: row.updates_value ?? undefined,\n itemType: row.item_type || undefined,\n sortOrder: row.sort_order,\n origin: compact<ActionOrigin>({\n source: \"surface-action\",\n surfaceName: row.surface_name,\n surfaceId: row.surface_id,\n id: row.id,\n declaredBy: row.declared_by,\n codeRef: row.code_ref ?? undefined,\n organizationId: row.organization_id ?? undefined,\n }),\n });\n}\n\n/** JSON-only view of an Action as declared on `declaredOn`. */\nexport function toActionInfo(declaration: ActionDeclaration, declaredOn: string): ActionInfo {\n return compact<ActionInfo>({\n name: declaration.name,\n category: declaration.category ?? APPLET_CATEGORY,\n label: declaration.label,\n description: declaration.description,\n runs: declaration.runs,\n policy: declaration.policy,\n triggeredBy: [...declaration.triggeredBy],\n input: declaration.input,\n output: declaration.output,\n declaredOn,\n target: declaration.target,\n updatesValue: declaration.updatesValue,\n itemType: declaration.itemType,\n source: declaration.origin?.source,\n });\n}\n\nexport interface ActionChainLink {\n surfaceName: string;\n actions: readonly ActionDeclaration[];\n}\n\n/**\n * The Actions a mount sees: its own plus every ancestor's, a child winning by\n * name. `chain` runs MOST GENERAL FIRST (root parent … the mounted surface),\n * as `DeclarationRegistry` resolves inheritance. Guards are loud, like the\n * declaration registry's: a surface twice in the chain is a cycle, more\n * ancestors than `maxDepth` throws, and one surface naming an Action twice throws.\n */\nexport function resolveActionChain(\n chain: readonly ActionChainLink[],\n options: { maxDepth?: number } = {},\n): ActionInfo[] {\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_INHERITANCE_DEPTH;\n const names = chain.map((link) => link.surfaceName);\n const seen = new Set<string>();\n for (const name of names) {\n if (seen.has(name)) {\n throw new Error(`[actions] inheritance CYCLE detected at \"${name}\". Fix the surface chain: ${names.join(\" → \")}`);\n }\n seen.add(name);\n }\n if (chain.length - 1 > maxDepth) {\n throw new Error(\n `[actions] inheritance chain for \"${names[names.length - 1]}\" exceeds depth ${maxDepth}: ${names.join(\" → \")}`,\n );\n }\n const byName = new Map<string, ActionInfo>();\n for (const link of chain) {\n const own = new Set<string>();\n for (const action of link.actions) {\n if (own.has(action.name)) {\n throw new Error(\n `[actions] surface \"${link.surfaceName}\" declares Action \"${action.name}\" twice. Names are unique; nothing was overwritten.`,\n );\n }\n own.add(action.name);\n byName.set(action.name, toActionInfo(action, link.surfaceName));\n }\n }\n return [...byName.values()];\n}\n","/**\n * THE ONE RUNNER for surface Actions (Applets CONTRACTS §6). Every caller — a\n * person's click, an agent, an applet, an automation — runs an Action through\n * here, so policy and caller rules live once.\n *\n * Policy \"ask\": a person's own click is the approval. Started by an agent, applet or automation,\n * a \"server\" run carries the policy to aidream (which answers with a proposal); every other run\n * asks the person through `ports.approvals` first, and is refused by name without that port.\n *\n * Dispatch by `runs`:\n * \"server\" → `ports.serverActions.run({ name: target, input, by, surface_name, policy })`\n * \"mandate\" → `ports.mandates.run({ alias: target, variables, by, policy })` — answers with the\n * started run's `MandateRunRef`; the result streams later on `run:<requestId>`\n * \"navigate\" → `ports.overlay.navigate(target)` with `{param}` filled from the input\n * \"page\" → `ports.pageActions.dispatch(name, input, context)`\n * A port the host did not bind means that capability is ABSENT: the run is\n * refused with a sentence, never stubbed (ports rule).\n *\n * Write targets (ALC-17): an Action projected from a declared write target (`source: \"write-target\"`)\n * goes through `ports.door.write` when a door is bound — the door applies the target's own policy\n * (manual / ask / queued / auto) and its receipt becomes the result (`applied` / `queued` → ok with\n * the receipt; refused → an error whose code is the refusal reason and whose `remedy` is the door's).\n * Without a door it dispatches to `pageActions` as before.\n *\n * Never throws: every outcome is a `Result` whose error message is the\n * system's own sentence.\n */\nimport type { AlchemyHostPorts, Json } from \"../ports\";\nimport type { WriteOp } from \"../operate/door\";\nimport type { ActionCaller, ActionContext, ActionError, ActionInfo, ActionResult } from \"./applet-types\";\n\nexport type SurfaceActionPorts = Pick<\n AlchemyHostPorts,\n \"diagnostics\" | \"serverActions\" | \"mandates\" | \"pageActions\" | \"overlay\" | \"approvals\" | \"door\"\n>;\n\nexport interface RunSurfaceActionOptions {\n runId?: string;\n viewerId?: string | null;\n signal?: AbortSignal;\n /** Which item a write-target Action writes into (by its declared identity values). */\n itemIdentity?: Record<string, string>;\n /** Text edits for a stream or patchable write target, instead of the input as the whole value. */\n ops?: readonly WriteOp[];\n}\n\nfunction fail(code: string, message: string, retryable = false, diagnostic?: string): { ok: false; error: ActionError } {\n return { ok: false, error: diagnostic ? { code, message, retryable, diagnostic } : { code, message, retryable } };\n}\n\nfunction messageOf(error: unknown): string {\n if (error instanceof Error && error.message.trim()) return error.message;\n if (typeof error === \"string\" && error.trim()) return error;\n return \"The run failed without saying why.\";\n}\n\nfunction newRunId(): string {\n const c = (globalThis as { crypto?: { randomUUID?: () => string } }).crypto;\n if (c?.randomUUID) return c.randomUUID();\n return `run-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 10)}`;\n}\n\n/** Fill `{param}` placeholders from the input object. Returns the names it could not fill. */\nexport function fillActionTarget(template: string, input: unknown): { value: string; missing: string[] } {\n const source = input && typeof input === \"object\" && !Array.isArray(input) ? (input as Record<string, unknown>) : {};\n const missing: string[] = [];\n const value = template.replace(/\\{([A-Za-z_][A-Za-z0-9_]*)\\}/g, (_, key: string) => {\n const v = source[key];\n if (v === undefined || v === null || v === \"\" || typeof v === \"object\") {\n missing.push(key);\n return \"\";\n }\n return encodeURIComponent(String(v));\n });\n return { value, missing };\n}\n\n/** Same as fillActionTarget, without URL-encoding (a mandate alias or server action name). */\nfunction fillName(template: string, input: unknown): { value: string; missing: string[] } {\n const filled = fillActionTarget(template, input);\n return { value: decodeURIComponent(filled.value), missing: filled.missing };\n}\n\nfunction toJson(value: unknown): Json {\n if (value === undefined) return null;\n return JSON.parse(JSON.stringify(value)) as Json;\n}\n\n/**\n * Who may run this Action, under its policy. Returns the refusal, or null.\n * \"manual\" = a person only. `triggeredBy` lists every caller allowed at all.\n */\nexport function refuseCaller(info: Pick<ActionInfo, \"name\" | \"label\" | \"policy\" | \"triggeredBy\">, by: ActionCaller): ActionError | null {\n if (!info.triggeredBy.includes(by)) {\n return {\n code: \"caller_not_allowed\",\n message: `\"${info.label}\" (${info.name}) can't be started by ${CALLER_WORDS[by]}; it allows ${info.triggeredBy.join(\", \") || \"no one\"}.`,\n retryable: false,\n };\n }\n if (info.policy === \"manual\" && by !== \"person\") {\n return {\n code: \"manual_only\",\n message: `\"${info.label}\" (${info.name}) runs only when a person starts it.`,\n retryable: false,\n };\n }\n return null;\n}\n\nconst CALLER_WORDS: Record<ActionCaller, string> = {\n person: \"a person\",\n agent: \"an agent\",\n applet: \"an applet\",\n automation: \"an automation\",\n};\n\nfunction absent(info: ActionInfo, capability: string): { ok: false; error: ActionError } {\n return fail(\"capability_absent\", `\"${info.label}\" can't run here: ${capability} isn't available on this page.`);\n}\n\nexport async function runSurfaceAction(\n info: ActionInfo,\n input: unknown,\n by: ActionCaller,\n ports: SurfaceActionPorts,\n options: RunSurfaceActionOptions = {},\n): Promise<ActionResult<unknown>> {\n const refusal = refuseCaller(info, by);\n if (refusal) return { ok: false, error: refusal };\n const context: ActionContext = {\n runId: options.runId ?? newRunId(),\n by,\n viewerId: options.viewerId ?? null,\n surfaceName: info.declaredOn,\n policy: info.policy,\n };\n const capture = (error: unknown, stage: string) => {\n try {\n ports.diagnostics.capture(error, { area: \"actions\", detail: { action: info.name, runs: info.runs, stage, runId: context.runId } });\n } catch {\n // A broken diagnostics port never turns a refusal into a throw.\n }\n };\n\n try {\n if (info.source === \"write-target\" && ports.door) {\n const receipt = await ports.door.write(\n {\n surfaceName: info.declaredOn,\n target: info.name,\n ...(info.itemType ? { itemType: info.itemType } : {}),\n ...(options.itemIdentity ? { itemIdentity: options.itemIdentity } : {}),\n ...(options.ops ? { ops: options.ops } : { value: input }),\n by,\n runId: context.runId,\n },\n options.signal,\n );\n if (receipt.status === \"refused\") {\n return { ok: false, error: { code: receipt.reason, message: receipt.sentence, retryable: receipt.reason === \"failed\", remedy: receipt.remedy } };\n }\n return { ok: true, data: receipt };\n }\n if (info.policy === \"ask\" && by !== \"person\" && info.runs !== \"server\") {\n if (!ports.approvals) {\n return fail(\"needs_approval\", `\"${info.label}\" needs a person's approval, and there is no one to ask here.`);\n }\n const approved = await ports.approvals.ask({\n action: info.name,\n label: info.label,\n description: info.description,\n input: toJson(input),\n by,\n surfaceName: info.declaredOn,\n runId: context.runId,\n });\n if (!approved) return fail(\"declined\", `\"${info.label}\" was not approved, so it did not run.`);\n }\n switch (info.runs) {\n case \"server\": {\n if (!ports.serverActions) return absent(info, \"server actions\");\n const filled = fillName(info.target ?? info.name, input);\n if (filled.missing.length) return fail(\"input_missing\", `\"${info.label}\" needs ${filled.missing.join(\", \")}.`);\n const response = await ports.serverActions.run({\n name: filled.value,\n input: toJson(input),\n by,\n surface_name: info.declaredOn,\n policy: info.policy,\n });\n if (response.status === \"refused\") return fail(\"refused\", response.message);\n return { ok: true, data: response };\n }\n case \"mandate\": {\n if (!ports.mandates) return absent(info, \"running a job\");\n if (!info.target) return fail(\"target_missing\", `\"${info.label}\" names no job to run.`);\n const filled = fillName(info.target, input);\n if (filled.missing.length) return fail(\"input_missing\", `\"${info.label}\" needs ${filled.missing.join(\", \")}.`);\n const record = input && typeof input === \"object\" && !Array.isArray(input) ? (input as Record<string, unknown>) : {};\n // A generic \"run a job\" Action carries { alias, variables, userInput }; a dedicated one's input IS the variables.\n const generic = /\\{[A-Za-z_]/.test(info.target);\n const variables = generic\n ? ((record.variables && typeof record.variables === \"object\" ? toJson(record.variables) : {}) as Record<string, Json>)\n : (toJson(record) as Record<string, Json>);\n const userInput = typeof record.userInput === \"string\" ? record.userInput : undefined;\n // The Action answers with the run's identity (RunRef); its result streams on `run:<requestId>`.\n const ref = await ports.mandates.run({\n alias: filled.value,\n variables,\n ...(userInput !== undefined ? { userInput } : {}),\n by,\n policy: info.policy,\n });\n return { ok: true, data: ref };\n }\n case \"navigate\": {\n if (!ports.overlay) return absent(info, \"navigation\");\n const filled = fillActionTarget(info.target ?? \"\", input);\n if (filled.missing.length) return fail(\"input_missing\", `\"${info.label}\" needs ${filled.missing.join(\", \")}.`);\n // `{to}` is a whole route: keep its slashes.\n const to = info.target && /^\\{[A-Za-z_][A-Za-z0-9_]*\\}$/.test(info.target) ? decodeURIComponent(filled.value) : filled.value;\n if (!to) return fail(\"target_missing\", `\"${info.label}\" names no page to open.`);\n ports.overlay.navigate(to);\n return { ok: true, data: { to } };\n }\n case \"page\": {\n if (!ports.pageActions) return absent(info, \"this page's actions\");\n return await ports.pageActions.dispatch(info.name, input, context);\n }\n default: {\n const runs: never = info.runs;\n return fail(\"runs_unknown\", `\"${info.label}\" runs as \"${String(runs)}\", which nothing here knows how to run.`);\n }\n }\n } catch (error) {\n capture(error, \"run\");\n return fail(\"run_failed\", messageOf(error), true);\n }\n}\n"],"mappings":"wpBAAA,opCCOO,IAAM,gBAAkB,CAAC,OAAQ,MAAO,QAAS,OAAQ,OAAQ,MAAM,ECyDvE,IAAM,kBAA+C,CAC1D,WACA,OACA,SACA,OACA,OACA,QACA,UACA,MACA,SACA,QACA,MACA,KACA,QACA,YACA,UACA,eACA,QACF,EC3EO,IAAM,oBAAmC,OAAO,OAAO,CAC5D,WAAY,GACZ,eAAgB,WAChB,kBAAmB,EACrB,CAAC,EAEM,SAAS,mBAAmB,MAAwD,CACzF,MAAO,CACL,WAAY,MAAM,aAAa,YAAc,oBAAoB,WACjE,eAAgB,MAAM,aAAa,gBAAkB,oBAAoB,eACzE,kBAAmB,MAAM,aAAa,mBAAqB,oBAAoB,iBACjF,CACF,CCMO,SAAS,gBAAgB,SAAkB,KAAiC,CACjF,OAAO,SAAW,GAAG,QAAQ,IAAI,IAAI,GAAK,IAC5C,CCEA,SAAS,SAAS,YAA6B,CAC7C,IAAM,MAAQ,YAAY,QAAQ,GAAG,EACrC,OAAO,MAAQ,EAAI,YAAY,MAAM,EAAG,KAAK,EAAI,WACnD,CAEO,SAAS,kBAAkB,MAA0B,CAAC,EAAgB,CAC3E,IAAM,YAAc,MAAM,aAAe,KACnC,KAAO,MAAM,MAAQ,KACrB,UAAY,IAAI,IAClB,WAAa,GACX,SAA0B,CAAC,EACjC,GAAI,YAAa,CACf,QAAW,SAAS,YAAY,OAAQ,CACtC,UAAU,IAAI,MAAM,IAAI,EACxB,IAAM,EAAI,mBAAmB,KAAK,GAC9B,EAAE,iBAAmB,YAAc,CAAC,EAAE,cAAY,WAAa,GACrE,CACA,IAAM,SAAW,KAAO,YAAY,WAAW,KAAM,GAAM,EAAE,OAAS,KAAK,QAAQ,EAAI,OACvF,GAAI,SAAU,CACZ,QAAW,SAAS,SAAS,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