@niscorp/moss 0.2.1 → 0.2.3
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 +14 -0
- package/DESIGN.md +10 -4
- package/DOCS.md +321 -40
- package/README.md +23 -14
- package/dist/{chunk-5S7TBULB.js → chunk-JBRD2TDQ.js} +4 -3
- package/dist/chunk-JBRD2TDQ.js.map +1 -0
- package/dist/{document-BEn2zXah.d.cts → document-Dg1BZxCz.d.cts} +7 -0
- package/dist/{document-BEn2zXah.d.ts → document-Dg1BZxCz.d.ts} +7 -0
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js.map +1 -1
- package/dist/node.cjs +1 -0
- package/dist/node.cjs.map +1 -1
- package/dist/node.d.cts +1 -1
- package/dist/node.d.ts +1 -1
- package/dist/node.js +1 -1
- package/dist/terminal/dom/server.cjs.map +1 -1
- package/dist/terminal/dom/server.js.map +1 -1
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.cts +1 -1
- package/dist/vite.d.ts +1 -1
- package/dist/vite.js +1 -1
- package/package.json +13 -13
- package/dist/chunk-5S7TBULB.js.map +0 -1
package/dist/index.d.cts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { N as NiscRuntime, S as SessionVerifier, L as LayoutVariant, P as PageManifest } from './document-
|
|
2
|
-
export { B as Bundle, C as CLOSE_INVALID_TOKEN, a as CLOSE_SHELL_FAILED, b as CLOSE_SIGNED_OUT, c as CallIntegration, d as Catalog, e as ClientMessage, f as Connection, g as Contract, D as DEFAULT_IDENTITY_IDLE_MS, h as DEFAULT_IDENTITY_MAX, i as DEFAULT_IDLE_MS, j as DEFAULT_REVALIDATE_MS, k as DocumentConfig, l as DrawnDocument, E as Emit, m as ExecuteAs, n as ExportedDocument, F as Fabric, o as FabricApply, p as FabricMessage, q as FabricSignal, r as FactIntake, s as FunctionSession, I as IdentityCache, t as IdentityCacheContext, u as IdentityRecord, v as IdentityReport, w as IntakeContext, x as IntakeResult, y as IntegrationRow, M as MOSS_SEQUENCE, z as MossServer, A as NiscApp, G as PressResult, R as RunRecord, H as RunSink, J as RunTurn, K as SNAPSHOT_ELEMENT_ID, O as ServerMessage, Q as ShellHost, T as ShellManifest, U as ShellNeed, V as ShellOpening, W as ShellReport, X as ShellSession, Y as ShellSnapshot, Z as SocketAccept, _ as SocketContext, $ as SpanClock, a0 as StorePress, a1 as Telemetry, a2 as TelemetrySpan, a3 as buildContract, a4 as callIntegrationWith, a5 as contractAsMarkdown, a6 as copyPress, a7 as createIdentityCache, a8 as createServer, a9 as createShellHost, aa as createSocket, ab as defineApp, ac as describePlacements, ad as devSession, ae as documentHeaders, af as embedSnapshot, ag as emitterOf, ah as exportDocuments, ai as filterInstalled, aj as initIntegrations, ak as integrationByKey, al as integrationOfAction, am as listAttachments, an as listIntegrations, ao as listPlacements, ap as loadIntegrationActions, aq as memoKeyOf, ar as mintDevToken, as as renderDocument, at as resolveCatalog, au as resolveCatalogForRoles, av as resolvePolicy, aw as resolvePolicyAtReach, ax as resolvePolicyForRoles, ay as resolveRoles, az as resolveVariants, aA as resolveVariantsForRoles, aB as runIntake, aC as shellNeedOf, aD as spanClock, aE as tokenFromCookie, aF as verifyVariants, aG as wearableOf, aH as wireFabric } from './document-
|
|
1
|
+
import { N as NiscRuntime, S as SessionVerifier, L as LayoutVariant, P as PageManifest } from './document-Dg1BZxCz.cjs';
|
|
2
|
+
export { B as Bundle, C as CLOSE_INVALID_TOKEN, a as CLOSE_SHELL_FAILED, b as CLOSE_SIGNED_OUT, c as CallIntegration, d as Catalog, e as ClientMessage, f as Connection, g as Contract, D as DEFAULT_IDENTITY_IDLE_MS, h as DEFAULT_IDENTITY_MAX, i as DEFAULT_IDLE_MS, j as DEFAULT_REVALIDATE_MS, k as DocumentConfig, l as DrawnDocument, E as Emit, m as ExecuteAs, n as ExportedDocument, F as Fabric, o as FabricApply, p as FabricMessage, q as FabricSignal, r as FactIntake, s as FunctionSession, I as IdentityCache, t as IdentityCacheContext, u as IdentityRecord, v as IdentityReport, w as IntakeContext, x as IntakeResult, y as IntegrationRow, M as MOSS_SEQUENCE, z as MossServer, A as NiscApp, G as PressResult, R as RunRecord, H as RunSink, J as RunTurn, K as SNAPSHOT_ELEMENT_ID, O as ServerMessage, Q as ShellHost, T as ShellManifest, U as ShellNeed, V as ShellOpening, W as ShellReport, X as ShellSession, Y as ShellSnapshot, Z as SocketAccept, _ as SocketContext, $ as SpanClock, a0 as StorePress, a1 as Telemetry, a2 as TelemetrySpan, a3 as buildContract, a4 as callIntegrationWith, a5 as contractAsMarkdown, a6 as copyPress, a7 as createIdentityCache, a8 as createServer, a9 as createShellHost, aa as createSocket, ab as defineApp, ac as describePlacements, ad as devSession, ae as documentHeaders, af as embedSnapshot, ag as emitterOf, ah as exportDocuments, ai as filterInstalled, aj as initIntegrations, ak as integrationByKey, al as integrationOfAction, am as listAttachments, an as listIntegrations, ao as listPlacements, ap as loadIntegrationActions, aq as memoKeyOf, ar as mintDevToken, as as renderDocument, at as resolveCatalog, au as resolveCatalogForRoles, av as resolvePolicy, aw as resolvePolicyAtReach, ax as resolvePolicyForRoles, ay as resolveRoles, az as resolveVariants, aA as resolveVariantsForRoles, aB as runIntake, aC as shellNeedOf, aD as spanClock, aE as tokenFromCookie, aF as verifyVariants, aG as wearableOf, aH as wireFabric } from './document-Dg1BZxCz.cjs';
|
|
3
3
|
import { Sequence } from '@niscorp/strata';
|
|
4
4
|
import { PgPool, QueryEngine, DatabaseSchema, SeedEntry, SeedMutation, WriteEvent } from '@niscorp/vex';
|
|
5
5
|
import { TideStore, Tide, Fact, Retention } from '@niscorp/tide';
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { N as NiscRuntime, S as SessionVerifier, L as LayoutVariant, P as PageManifest } from './document-
|
|
2
|
-
export { B as Bundle, C as CLOSE_INVALID_TOKEN, a as CLOSE_SHELL_FAILED, b as CLOSE_SIGNED_OUT, c as CallIntegration, d as Catalog, e as ClientMessage, f as Connection, g as Contract, D as DEFAULT_IDENTITY_IDLE_MS, h as DEFAULT_IDENTITY_MAX, i as DEFAULT_IDLE_MS, j as DEFAULT_REVALIDATE_MS, k as DocumentConfig, l as DrawnDocument, E as Emit, m as ExecuteAs, n as ExportedDocument, F as Fabric, o as FabricApply, p as FabricMessage, q as FabricSignal, r as FactIntake, s as FunctionSession, I as IdentityCache, t as IdentityCacheContext, u as IdentityRecord, v as IdentityReport, w as IntakeContext, x as IntakeResult, y as IntegrationRow, M as MOSS_SEQUENCE, z as MossServer, A as NiscApp, G as PressResult, R as RunRecord, H as RunSink, J as RunTurn, K as SNAPSHOT_ELEMENT_ID, O as ServerMessage, Q as ShellHost, T as ShellManifest, U as ShellNeed, V as ShellOpening, W as ShellReport, X as ShellSession, Y as ShellSnapshot, Z as SocketAccept, _ as SocketContext, $ as SpanClock, a0 as StorePress, a1 as Telemetry, a2 as TelemetrySpan, a3 as buildContract, a4 as callIntegrationWith, a5 as contractAsMarkdown, a6 as copyPress, a7 as createIdentityCache, a8 as createServer, a9 as createShellHost, aa as createSocket, ab as defineApp, ac as describePlacements, ad as devSession, ae as documentHeaders, af as embedSnapshot, ag as emitterOf, ah as exportDocuments, ai as filterInstalled, aj as initIntegrations, ak as integrationByKey, al as integrationOfAction, am as listAttachments, an as listIntegrations, ao as listPlacements, ap as loadIntegrationActions, aq as memoKeyOf, ar as mintDevToken, as as renderDocument, at as resolveCatalog, au as resolveCatalogForRoles, av as resolvePolicy, aw as resolvePolicyAtReach, ax as resolvePolicyForRoles, ay as resolveRoles, az as resolveVariants, aA as resolveVariantsForRoles, aB as runIntake, aC as shellNeedOf, aD as spanClock, aE as tokenFromCookie, aF as verifyVariants, aG as wearableOf, aH as wireFabric } from './document-
|
|
1
|
+
import { N as NiscRuntime, S as SessionVerifier, L as LayoutVariant, P as PageManifest } from './document-Dg1BZxCz.js';
|
|
2
|
+
export { B as Bundle, C as CLOSE_INVALID_TOKEN, a as CLOSE_SHELL_FAILED, b as CLOSE_SIGNED_OUT, c as CallIntegration, d as Catalog, e as ClientMessage, f as Connection, g as Contract, D as DEFAULT_IDENTITY_IDLE_MS, h as DEFAULT_IDENTITY_MAX, i as DEFAULT_IDLE_MS, j as DEFAULT_REVALIDATE_MS, k as DocumentConfig, l as DrawnDocument, E as Emit, m as ExecuteAs, n as ExportedDocument, F as Fabric, o as FabricApply, p as FabricMessage, q as FabricSignal, r as FactIntake, s as FunctionSession, I as IdentityCache, t as IdentityCacheContext, u as IdentityRecord, v as IdentityReport, w as IntakeContext, x as IntakeResult, y as IntegrationRow, M as MOSS_SEQUENCE, z as MossServer, A as NiscApp, G as PressResult, R as RunRecord, H as RunSink, J as RunTurn, K as SNAPSHOT_ELEMENT_ID, O as ServerMessage, Q as ShellHost, T as ShellManifest, U as ShellNeed, V as ShellOpening, W as ShellReport, X as ShellSession, Y as ShellSnapshot, Z as SocketAccept, _ as SocketContext, $ as SpanClock, a0 as StorePress, a1 as Telemetry, a2 as TelemetrySpan, a3 as buildContract, a4 as callIntegrationWith, a5 as contractAsMarkdown, a6 as copyPress, a7 as createIdentityCache, a8 as createServer, a9 as createShellHost, aa as createSocket, ab as defineApp, ac as describePlacements, ad as devSession, ae as documentHeaders, af as embedSnapshot, ag as emitterOf, ah as exportDocuments, ai as filterInstalled, aj as initIntegrations, ak as integrationByKey, al as integrationOfAction, am as listAttachments, an as listIntegrations, ao as listPlacements, ap as loadIntegrationActions, aq as memoKeyOf, ar as mintDevToken, as as renderDocument, at as resolveCatalog, au as resolveCatalogForRoles, av as resolvePolicy, aw as resolvePolicyAtReach, ax as resolvePolicyForRoles, ay as resolveRoles, az as resolveVariants, aA as resolveVariantsForRoles, aB as runIntake, aC as shellNeedOf, aD as spanClock, aE as tokenFromCookie, aF as verifyVariants, aG as wearableOf, aH as wireFabric } from './document-Dg1BZxCz.js';
|
|
3
3
|
import { Sequence } from '@niscorp/strata';
|
|
4
4
|
import { PgPool, QueryEngine, DatabaseSchema, SeedEntry, SeedMutation, WriteEvent } from '@niscorp/vex';
|
|
5
5
|
import { TideStore, Tide, Fact, Retention } from '@niscorp/tide';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/app.ts","../src/driver.ts"],"names":[],"mappings":";;;;AAkhBO,IAAM,SAAA,GAAY,CAAC,GAAA,KAA0B;;;ACtdpD,IAAM,kBAAA,GAAqB,GAAA;AAG3B,IAAM,mBAAA,GAAsB,GAAA;AAE5B,IAAM,aAAa,CAAC,MAAA,KAClB,OAAO,YAAA,GACP,MAAA,CAAO,qBACP,MAAA,CAAO,YAAA,GACP,OAAO,WAAA,GACP,MAAA,CAAO,eACP,MAAA,CAAO,QAAA,GACP,OAAO,SAAA,GACP,MAAA,CAAO,cACP,MAAA,CAAO,MAAA;AAEF,IAAM,gBAAA,GAAmB,CAAC,MAAA,KAAyC;AACxE,EAAA,MAAM,EAAE,MAAK,GAAI,MAAA;AACjB,EAAA,MAAM,GAAA,GAAM,MAAA,CAAO,GAAA,KAAQ,MAAM,KAAK,GAAA,EAAI,CAAA;AAC1C,EAAA,MAAM,SAAA,GAAY,OAAO,SAAA,IAAa,kBAAA;AAEtC,EAAA,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,IAAI,MAAA,GAAS,KAAA;AACb,EAAA,IAAI,OAAA,GAAU,KAAA;AACd,EAAA,IAAI,KAAA;AACJ,EAAA,IAAI,UAAA;AACJ,EAAA,IAAI,KAAA;AAEJ,EAAA,MAAM,QAAQ,YAA2B;AACvC,IAAA,KAAA,IAAS,KAAA,GAAQ,CAAA,EAAG,KAAA,GAAQ,mBAAA,EAAqB,SAAS,CAAA,EAAG;AAC3D,MAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,OAAA,CAAQ,EAAE,GAAA,EAAK,GAAA,IAAO,CAAA;AAChD,MAAA,IAAI,UAAA,CAAW,MA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AA;AAE3C,MAAA,MAAM,KAAA;AACN,MAAA,MAAM,UAAA;AAAA,IACR;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import type { Sequence } from '@niscorp/strata';\nimport type { ScopeBehaviors, ScopePolicy, SeedEntry, SeedMutation } from '@niscorp/vex';\nimport type { Charter } from '@niscorp/charter';\nimport type { ActionDefinition, ActionFragment, CanvasConfig, FetchFn, FunctionHandler, LayoutNode, Shell } from '@niscorp/nova';\nimport type { PhraseKeys, Phrasebook } from '@niscorp/nova/i18n';\nimport type { NiscRuntime } from './runtime';\nimport type { IdentityRecord } from './identity';\n\n// ═══════════════════════════════════════════════════════════════\n// The application, as data. Every field is an ARTIFACT — content someone\n// authored — never machinery: the server derives everything mechanical\n// from these plus a database (DESIGN.md § Derivation over\n// configuration). `assignments` stands in for the artifact library's\n// assignment table until that exists.\n// ═══════════════════════════════════════════════════════════════\n\n// Ring 2, as data: a layout VARIANT reshapes ONE action's layout for the\n// principals whose charter grants the variant id (the `layouts` section).\n// The reference direction is variant → action — an action never lists its\n// variants, so minting one is additive. Holding no variant of an action\n// means the base (the layout on the definition); holding two is incoherence\n// the server refuses at boot. A variant changes ONLY the layout — different\n// behavior (triggers, endpoints, data, input) is a different action id.\n//\n// Direction: the base is the FLOOR — the least-privileged holder's shape.\n// Variants ENRICH upward and are granted like any other capability, so\n// `extends` composes them correctly and a forgotten grant fails closed\n// (under-serves visibly). A variant that reduces is authored backwards: it\n// forces deny-it-back in every richer role, and a forgotten deny\n// over-serves silently.\nexport type LayoutVariant = { action: string; layout: LayoutNode };\n\nexport type NiscApp = {\n charter: Charter;\n // THE ASSIGNMENT MAP — one entry per principal, and the reason a resident\n // copy of the population had to exist at all: an eager `Record` cannot be\n // filled without enumerating everybody.\n //\n // OPTIONAL now. An app that declares `identity` answers this per principal,\n // asynchronously, one row at a time, and never builds the map. What remains\n // here is for apps whose assignments are AUTHORED — a handful of static\n // rungs in a demo — where a literal is the honest shape.\n assignments?: Record<string, readonly string[]>;\n // WHICH ROLE COMBINATIONS A PRINCIPAL MAY HOLD — declared, not counted.\n //\n // The two coherence gates below (`verifyCharter`'s subtractive-assigned rule,\n // `verifyVariants`' one-variant-per-action rule) never wanted principals; they\n // wanted the distinct COMBINATIONS somebody could wear. Reading them off\n // `assignments` is the only reason that map has to be eager — and enumerating\n // the population to learn that `['instructor','member']` exists is a strange\n // way to learn it.\n //\n // The charter cannot supply this. It defines roles; it does not know which of\n // them coincide on one person, because that is a fact about the application's\n // schema (staff row AND membership row), not about the grant graph.\n //\n // Absent = derived from `assignments`, which is what every app did before this\n // existed and is correct while the map is still eager.\n wearable?: readonly (readonly string[])[];\n actions: Record<string, ActionDefinition>;\n // layout variants by variant id — the `layouts` universe the charter\n // selects over (ring 2; `actions` is ring 1, `data` is ring 3)\n layouts?: Record<string, LayoutVariant>;\n behaviors?: ScopeBehaviors;\n // Per-principal SCOPE VALUES — the seam that lets an app decide what a\n // principal IS beyond its id. The server always injects `{ userId }` (the\n // principal); this hook contributes the rest — a tenant, an org, a region —\n // and the merged set is what a behavior's `to:` resolves against at execute\n // (`{ match: 'property_id', to: 'propertyId' }` needs `propertyId` here).\n //\n // Moss deliberately does NOT assume how a principal maps to those values: the\n // mapping is application knowledge (a directory, a claims table, a lookup),\n // so the app supplies it. Values are injected server-side and are\n // unreferenceable by a request — the enforcement is engine-side and unforgeable.\n //\n // VOLATILE VALUES ONLY, once `identity` below exists. A resolved identity is\n // held for a session; anything derived from the CLOCK must not be, or a\n // session opened before midnight serves yesterday's date to every query that\n // compares a DATE column against it. So this seam survives beside `identity`\n // and is asked per request — and it stays synchronous on purpose, because the\n // values that belong here are COMPUTED rather than read. A sync signature is\n // only a trap when the answer lives in rows.\n //\n // The resolved record is handed in so the computation has what it needs\n // without a lookup: the day is derived from the timezone the record already\n // carries. Merged OVER the record's own scope values.\n scope?: (principal: string | null, identity?: IdentityRecord) => Record<string, unknown>;\n // WHO A PRINCIPAL IS, resolved ONCE per session instead of asked in pieces\n // per request — the seam that replaces `scope` + `assignments` +\n // `installedIntegrations` with a single async answer.\n //\n // The three seams around this one are synchronous, and that is not a detail:\n // a hook that cannot await has exactly one implementation available to it\n // when the answer lives in rows, and that implementation is a resident map of\n // the whole population. Lyra grew eight of them across three files, and every\n // one exists to satisfy a signature rather than a decision. This is the same\n // question asked in a tense that permits the obvious answer — read the row.\n //\n // Moss OWNS the resulting cache: bounded, evicted, revalidated on\n // `sessionRevalidateMs`, and enumerable only by an operator (see identity.ts,\n // and the invariants in docs/plans/lyra-identity.md Part 6). What it will\n // never do is look inside the record. `roles` goes to charter, `installed` is\n // filtered against, `scope` is merged into the engine's scope values — all\n // pass-through. The moment moss reads `.studioId` off one of these, moss has\n // learned what a tenant is and the boundary is gone.\n //\n // Absent = the three older seams answer, exactly as before.\n //\n // `resolve` is the pre-authorisation half: roles, the invalidation tag, and\n // whatever scope the app can only establish before a policy exists (an\n // integration actor's studio; a person's tenant). `scope` and `installed`\n // name SEEDED entries moss then executes through its own engine — under the\n // policy of the charter role `as` names, with the scope values resolved so\n // far — merging each mapped object into the record. The app's model of a\n // session thereby lives in its ARTIFACTS: the entries and their reach\n // profiles, checkable like any other, with moss holding no opinion about\n // what any of it means.\n identity?: {\n // The charter role the lent reader executes AS — a role nobody wears,\n // holding exactly the verbs identity's engine reads need. Opaque here.\n as?: string;\n // ONE seam. `read` is a capability moss lends for the duration of the\n // call: it executes a SEEDED entry through moss's own engine, locked to\n // replay, under the `as` role's compiled policy, with exactly the scope\n // values the app passes — values the app itself resolved, engine-side.\n // The app composes its whole record from its one licensed pre-auth read\n // plus these; moss caches the result and never looks inside it.\n resolve: (principal: string, read: (fingerprint: string, scope: Record<string, unknown>) => Promise<unknown>) => Promise<IdentityRecord>;\n };\n // THE WORDS THIS PRINCIPAL'S SHELL WEARS — the language twin of `scope`.\n //\n // Moss renders a shell server-side and serializes its trees. Between those\n // two, every word the reader will see is present at once, so that is where a\n // language is applied: one pass over the frame (`@niscorp/nova/i18n`), source\n // phrase in, translated phrase out. Nothing downstream — the socket, the\n // delta encoder, the terminal — learns that a language exists.\n //\n // Returning undefined or an empty book is the SOURCE language, and costs\n // nothing: the pass returns the same tree object and the frame serializes to\n // the bytes it always did.\n //\n // Per PRINCIPAL, because a shell is per principal. Two people at the same\n // tenant reading different languages get two shells, which they already had.\n // Resolved once when the shell is built — a change to a principal's language\n // is a `reset`/rebuild, exactly like a change to their catalog.\n // Async and wire-bearing, for the same reason `seeds` and `inputs` are: a\n // book lives in rows, and a hook that cannot reach them holds a resident\n // copy of every language. The resolved identity rides along so the app can\n // pick the language off the record the session already established.\n phrases?: (session: { principal: string | null; identity: Record<string, unknown>; wire: FetchFn }) => Phrasebook | undefined | Promise<Phrasebook | undefined>;\n // Which keys in a tree carry prose. An app with its own display-field\n // convention (`status_display`) declares it once here. Absent = nova's\n // default prop set and no suffix rule.\n phraseKeys?: PhraseKeys;\n // WHICH INTEGRATIONS ARE LIVE FOR THIS PRINCIPAL'S TENANT.\n //\n // The charter grants `ext.desk.*` once, to every desk in the deployment. In a\n // single-tenant app that is the whole answer. In a multi-tenant one it is a\n // leak: one studio installing an integration would put it on every studio's front\n // desk, and nothing would say so.\n //\n // Moss cannot decide this — it does not know what a tenant is, deliberately,\n // for the same reason `scope` exists. So the app answers, with a list of\n // integration ids, and moss drops every `ext.*` action outside it.\n //\n // Absent = every registered integration is live for everybody, which is right\n // for an app with one tenant and wrong the moment there are two.\n // May be async, like every other per-principal seam here now.\n installedIntegrations?: (principal: string | null) => readonly string[] | Promise<readonly string[]>;\n // WHO AN INTEGRATION IS when it acts and nobody is driving.\n //\n // A webhook lands, a nightly sync runs: the integration presents its minted\n // key and names who it acts for (`x-nisc-acts-for` — a tenant in most apps,\n // and opaque to moss for the same reason `scope` is). The app answers with a\n // principal, and from there NOTHING is special: that principal's charter\n // rung compiles its policy, `scope` gives it its values, and the engine\n // stamps its writes — the integration is just another client of the same\n // closed grammar.\n //\n // Returning null refuses: an integration the tenant has not installed, a\n // tenant that does not exist, an app that has no actor for unattended work.\n // Absent = integration keys resolve to nobody and every keyed call is 403.\n // MAY BE ASYNC, and this is the first of the six per-principal seams to say\n // so. A synchronous signature cannot perform I/O, so an app answering this\n // question about rows had exactly one implementation available to it: hold\n // the rows. That is how a resident copy of the database gets built by a type\n // rather than by a decision (docs/plans/lyra-identity.md, Part 1).\n //\n // Nothing here needed it: moss resolves this inside async middleware, one\n // call per keyed request, and has awaited the session verifier beside it\n // since the beginning. A sync implementation still satisfies this — the\n // widening is the point, not a migration.\n integrationActor?: (integration: string, actsFor: string) => string | null | Promise<string | null>;\n // WHERE AN INTEGRATION MAY APPEAR — the host's half of the placement\n // contract, advertised on the discovery surface and enforced at intake.\n //\n // `attachable`: host action id → the offers, as {offered key: host data\n // path} (a member detail offering `membership_id` from `$.membershipId`).\n // Declaring an action here is declaring a seat. The KEYS are the contract —\n // advertised on discovery, what a rider receives as input and what a\n // preview call carries. The PATHS are the host's private wiring: how its\n // own strip derivation and push trigger read those values off its data —\n // a rider never sees them.\n attachable?: Record<string, Record<string, string>>;\n // `menuSlots`: hub action ids whose item lists accept placed integration\n // screens. Who owns a menu is the host's question; this list is its answer,\n // and intake refuses a placement outside it.\n menuSlots?: readonly string[];\n // THE VOCABULARY AN ADD-ON'S DECLARATIONS MAY NAME — the same posture as\n // `menuSlots`: the host names what it offers, intake refuses anything outside\n // it. Read into the intake context so a `documents`/`assistants` declaration\n // fails at registration, not in front of a person, when it names one the host\n // does not hold. moss carries the names; what a tool DOES, what a check\n // MEANS, and which region an id draws are the host's, never moss's.\n //\n // `assistantTools`: the host's closed assistant tool set, an `assistants`\n // declaration's `tools[]` is checked against it.\n assistantTools?: readonly string[];\n // `publishChecks`: the checks the host runs before publishing a document, a\n // `documents` declaration's `checks[]` is checked against it.\n publishChecks?: readonly string[];\n // `editorRegions`: region action ids the host's editor offers a document\n // beyond the bundle's own actions; a `documents` declaration's `regions`\n // values are admitted if they are one of these OR one of the bundle's actions.\n editorRegions?: readonly string[];\n // WORDS FOR THE IDS ABOVE, for the one sentence a person reads before\n // turning an integration on. Optional: without it the approval card and store tile\n // print ids, which is honest and unhelpful.\n placementNames?: Readonly<Record<string, string>>;\n // WHERE PRESS IMAGES LAND. A bundle may declare listing images\n // (meta.press); intake fetches the bytes once and hands them here, and the\n // URL this answers with is what the store serves forever after — the host's\n // blob store, its bounds, its refusals (throw, and the bundle is refused\n // whole). Optional: a deployment without one refuses any bundle that\n // declares press, which is a sentence at import rather than a hole in a\n // listing.\n storePress?: import('./integrations').StorePress;\n // the prewarmed API surface — every read and write the app serves, as\n // authored entries; seeded into the cache at boot (idempotent, protected).\n // Optional because a database may already carry its vex_cache rows.\n entries?: readonly (SeedEntry | SeedMutation)[];\n // resource name → the entity subgraph it exposes as /api/<name>/vex\n // (a bare list, or an object carrying one — an app's resource artifacts\n // pass through unmapped). The bare /api/vex (full schema) always exists.\n resources?: Record<string, readonly string[] | { entities: readonly string[] }>;\n // The shell, as data (DESIGN.md § The shell runs on the server):\n // canvases and fragments are artifacts; `inputs` is the app's ONE\n // derivation hook — per-principal boot input (nav flags, user chips),\n // merged over each canvas's static seed. Absent = no server shells.\n shell?: ShellManifest;\n // PAGES — what is drawn at a path and kept by nothing.\n //\n // `shell` above is THE APP: one durable shell per person, the thing that\n // rearranges itself around whoever holds it. A page is the other kind of\n // thing a path can lead to — a welcome, the docs, a published talk: a small\n // manifest of its own (a frame, canvases, what mounts on them), drawn for\n // whoever asks and then let go. Nothing stands behind it afterwards unless\n // what mounted can still do something (./liveness), in which case the\n // terminal gets a shell for as long as its connection lasts.\n //\n // It is the SAME machinery with the keeping taken out: the same actions, the\n // same charter deciding what exists for whom (a member's chip is an action a\n // member is granted), the same policy on every read. A page drawn for nobody\n // is the same for everybody, so it may be cached or written to a file; a page\n // drawn for somebody is theirs and is not. That is decided by who asked,\n // never by the page.\n //\n // `functions` are endpoints and serve a page's actions as they serve the\n // app's. `onSession` does not run for a page: session code is the app's.\n pages?: Record<string, PageManifest>;\n // The app's own GRAMMAR sequences (strata): migrations for documents only this\n // app defines the shape of — its component kit's props, say, rewritten on\n // every nova layout node that uses them. Pure data like every artifact here: a\n // document migration is a Prism config. moss runs them with nova's and\n // Prism's over every stored document and every submitted bundle.\n grammars?: readonly Sequence[];\n // The `fn:` escape hatch, server-side: app code running IN-PROCESS next\n // to the session's durable shell (Ray lives here). Built once per\n // session — handlers close over the session context, so keys and code\n // never reach a browser. Side-effect-free computation deploys as server\n // functions behind plain `url:` endpoints instead (/fns, later).\n functions?: (session: FunctionSession) => Record<string, FunctionHandler>;\n // Called once per living shell, with the same session, for app code that is\n // NOT an endpoint: a per-session observer, a roster, an agent watching the\n // screen. Without it such code has to ride `functions` and be registered as a\n // handler nothing calls, which is a lie about what it is.\n //\n // It runs BEFORE the shell finishes building, like `functions` — so it must\n // defer anything that touches `session.shell`. Anything it returns is\n // ignored; to release resources, subscribe to the shell and drop on dispose.\n onSession?: (session: FunctionSession) => void;\n // Where model runs go. moss produces nothing itself — an app that runs an\n // agent calls `session.recordRun` and this receives the record with the\n // session's own fields already stamped.\n //\n // No default sink. A bounded in-memory array would answer \"the last few\n // minutes, gone on restart\", which is not a question anyone asks about an\n // agent's behaviour; an app that wants that can write five lines. Unset means\n // unrecorded, which is at least honest.\n runs?: RunSink;\n // A WRITE LANDED, and the app declared its interest in advance. Each\n // reaction names the table (and optionally the op) it cares about; moss\n // routes vex's write observer to the reactions whose interest matches,\n // once per matching statement — so app code never hears about writes it\n // did not declare, and never string-matches fingerprints to find out what\n // happened. `deliver` publishes onto a principal's live durable shell over\n // the socket the shells already run — push built on the transport this\n // server owns, never a second one.\n //\n // Deliberately row-less: a reaction hears THAT a write landed (table, op,\n // how many rows, the unforgeable scope), never what it wrote. A receiver\n // that wants the data re-reads it under its own policy — rows handed to\n // imperative code would be rows outside every fence this stack builds.\n // Zero-row statements (a scope-narrowed update, a conflict-skipped\n // insert) fire no reaction: nothing changed, so there is no news.\n reactions?: readonly {\n table: string;\n op?: 'insert' | 'update' | 'delete';\n run: (\n event: { fingerprint: string; table: string; op: 'insert' | 'update' | 'delete'; count: number; scope: Record<string, unknown> },\n tools: { deliver: (principal: string, channel: string, payload?: unknown) => boolean },\n ) => void;\n }[];\n // The write-fact bridge. Vex is the choke point every write passes\n // through; when an app runs tide, each committed statement is minted into\n // it as a `{ kind: 'write' }` fact — entity, op, and the row the database\n // returned — stamped with the identity `identity(scope)` names. That\n // identity is the fact's tenancy fence: tide offers a fact only to\n // reflexes running AS the same identity, so whose write it was decides\n // who may be woken by it. Returning undefined mints nothing for that\n // write (an operator surface, a write with no tenant). `tide` is a\n // getter because the instance stands up after the server does.\n //\n // Rows travel HERE and into tide's ledger only — host plumbing on one\n // side, the identity fence on the other. They never reach `onMutation`.\n //\n // The intake is structural — hand back the tide DRIVER, so a minted fact\n // wakes the engine instead of waiting for anybody's beat.\n facts?: {\n tide: () => FactIntake | undefined;\n identity: (scope: Record<string, unknown>) => string | undefined;\n // The causality gate. A tide effect that writes back through vex\n // forwards its chain position as request headers (`x-tide-cause`,\n // `x-tide-depth`); this decides whether THAT CALLER's word is good —\n // return the hints to accept them onto the minted facts, undefined to\n // drop them. Absent = hints are always dropped, which is the safe\n // default: a forged depth could park an innocent chain, and a forged\n // cause is fabricated provenance. An app grants this to exactly the\n // principals that ARE its automation rungs.\n chain?: (scope: Record<string, unknown>, hints: { cause: string; depth: number }) => { cause: string; depth: number } | undefined;\n };\n};\n\n// The one verb the bridge needs. Both `Tide` and `TideDriver` satisfy it;\n// hand out the driver unless you have a reason to want facts that wait.\nexport type FactIntake = Pick<import('@niscorp/tide').Tide, 'ingest'>;\n\n// One turn of an exchange with a model, in order. Provider-blind and\n// library-blind on purpose: moss depends on neither an LLM client nor an agent\n// framework, so this is the shape any of them can be flattened into rather than\n// one client's message union leaking into the app server.\n//\n// A tool call and its result are two turns, the way the model saw them: the\n// assistant turn that ASKED (`calls`), then the tool turn that ANSWERED (`name`\n// + content). Nothing is aggregated into a separate call list — that is a\n// display's business, and a second copy of the same facts drifts.\nexport type RunTurn = {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string;\n // What the model asked for on this turn. `args` stays a string: providers send\n // arguments JSON-encoded, and re-encoding a parse is how a malformed call\n // stops looking malformed in the record.\n calls?: ReadonlyArray<{ name: string; args: string }>;\n // Which tool a 'tool' turn is the answer from.\n name?: string;\n};\n\n// One model run, as a row. Everything is a dimension and nothing is aggregated:\n// per person, per model, per session and per day are all group-bys over this,\n// and a tally computed on write is wrong the moment a different cut is wanted.\n//\n// Deliberately not here: cost in currency. Per-model price tables rot, tokens\n// are the honest unit, and `provider` + `model` let pricing be layered on later\n// without a migration.\nexport type RunRecord = {\n at: number;\n principal: string | null;\n shellId: string;\n // The agent's own id, and its lineage when one agent runs inside another.\n agentId: string;\n agentPath: readonly string[];\n // The app's own axis — which way in produced this run.\n label: string;\n provider: string;\n model: string;\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n // False when any step was counted rather than reported by the provider.\n // Streamed responses are not reliable about the usage frame.\n reported: boolean;\n steps: number;\n elapsedMs: number;\n // THE WHOLE EXCHANGE, turn by turn: what went out (instructions, catalogs,\n // history, the input), every tool the model called and what came back from it,\n // and the answer. This is the only honest account of \"why did it do that\", and\n // reconstructing it after the fact is impossible — the prompt is assembled\n // from live state that has since moved.\n //\n // It is also the largest thing here by far, and it carries whatever the\n // person's screen carried. A sink that persists it is storing that.\n turns?: readonly RunTurn[];\n response?: string;\n // A failed run spent tokens too. Recording only successes undercounts\n // precisely when something is going wrong.\n outcome: 'ok' | 'failed';\n};\n\n// The session is handed along so a sink can persist through the CALLER's own\n// governed wire rather than a privileged one — the row then lands under the same\n// scope as everything else and cannot be written on another principal's behalf.\n// A sink that wants a plain in-process array can ignore it.\nexport type RunSink = (record: RunRecord, session: FunctionSession) => void;\n\n// What a session's functions close over: the living shell (durable per\n// principal), who is calling, the server's own surfaces as the session,\n// the environment the server stands on, and the principal's compiled\n// scope policy — dynamic reads (agents) execute under it, so an agent\n// sees what its caller sees and is refused what its caller is refused.\nexport type FunctionSession = {\n shell: Shell;\n principal: string | null;\n roles: readonly string[];\n // The scope half of the resolved identity — the record the session was built\n // from, handed back so a function reads \"which studio am I\" off what the\n // engine already established instead of looking anybody up.\n identity: Record<string, unknown>;\n // The session's granted action ids, installs already filtered — the same\n // catalog the shell was built from, so a function and a screen cannot\n // disagree about what this person holds.\n actions: readonly string[];\n wire: FetchFn;\n runtime: NiscRuntime;\n policy: ScopePolicy;\n // Session lifecycle, as capabilities — no reserved channels, no\n // observers. A login fn GRANTS: the token goes down every connection of\n // this session as a `session` message and the terminals reconnect\n // authenticated. A sign-out fn REVOKES: under moss's own credential every\n // session the principal holds is deleted, every connection closes\n // SIGNED_OUT and the durable shell dies. The promise settles when the\n // credential is gone — await it to know; ignoring it is still safe.\n grant: (token: string) => void;\n revoke: () => Promise<void>;\n // Record one model run. `at`, `principal` and `shellId` are stamped here, so a\n // caller supplies only what it knows: which agent, which model, what was said,\n // what it cost. A no-op when the manifest declares no `runs` sink.\n recordRun: (run: Omit<RunRecord, 'at' | 'principal' | 'shellId'>) => void;\n};\n\n// A canvas seed, or CANDIDATES: with a list, the FIRST action the\n// principal holds mounts — members boot `home`, anonymous boots the lock\n// screen, and nobody configures which (ring 1 as derivation).\nexport type CanvasSeed = string | { action: string; input?: Record<string, unknown>; with?: string[] };\nexport type ShellCanvas = Omit<CanvasConfig, 'initial'> & { initial?: CanvasSeed | CanvasSeed[] };\n\nexport type ShellManifest = {\n canvases: ShellCanvas[];\n // The FRAME — the canvas arrangement, a layout of CanvasSlot markers.\n // Served to terminals verbatim; the terminal owns nothing but pixels.\n layout?: LayoutNode;\n // THE INITIAL LAYOUT STORE — what a `{ ref: id }` in the frame resolves to\n // before anything calls `setLayout`. A dynamic region embeds `{ ref: 'dock' }`\n // in `layout` above and this seeds what it draws; `shell.setLayout('dock', …)`\n // then swaps it and the change re-sends the frame. NOT `layouts` (below, on\n // NiscApp) — those are per-role variants of ACTION layouts; this seeds the\n // shell's layout STORE, mirroring nova's own `createShell({ layoutStore })`.\n layoutStore?: Record<string, LayoutNode>;\n fragments?: Record<string, ActionFragment>;\n // Per-principal canvas SEEDING — the instance twin of `inputs`. Where\n // `initial` is static data and `inputs` derives per-principal boot DATA,\n // `seeds` derives per-principal boot INSTANCES: the app computes, from the\n // session (and its own reads over the session's wire), which actions to\n // push onto which canvases. moss does nothing but call it and push, in\n // order, ring-1-filtered like every other mount — an ungranted seed simply\n // doesn't. May be async (a derivation usually reads resolved rows); seeds\n // land when it resolves, and attached terminals see them arrive.\n seeds?: (session: {\n principal: string | null;\n actions: readonly string[];\n roles: readonly string[];\n wire: FetchFn;\n }) => Promise<Record<string, CanvasSeed[]>> | Record<string, CanvasSeed[]>;\n // Component CONTRACTS for the server registry — name → { meta }. The\n // React components stay in the terminal; only their meta crosses, so\n // the layout agent's palette (meta.description / meta.propsSchema) works\n // server-side. Names listed here are registered even when no authored\n // layout mentions them (generated layouts may).\n components?: Record<string, { meta?: { description?: string; propsSchema?: unknown } }>;\n //\n // ASYNC AND WIRE-BEARING, matching `seeds`. These two are called twins a few\n // lines apart, and one was handed the governed internal wire while the other\n // was not. That asymmetry is the origin of every resident cache in this repo:\n // a hook that cannot await, asked a question about rows, has exactly one\n // implementation available to it, and that implementation is a map of\n // everybody (docs/plans/lyra-identity.md, Part 1). A synchronous\n // implementation still satisfies this — the widening is the point.\n inputs?: (session: {\n principal: string | null;\n actions: readonly string[];\n roles: readonly string[];\n // The scope values the app's own `identity` seam returned — handed straight\n // back so a shell can be composed from the record the session already\n // resolved, instead of reaching into a directory for the same four facts.\n identity: Record<string, unknown>;\n wire: FetchFn;\n }) => Record<string, Record<string, unknown>> | Promise<Record<string, Record<string, unknown>>>;\n};\n\n// A page: a shell manifest, and the path it is drawn at. `:name` segments are\n// parameters (\"/docs/:slug\"); every other segment matches itself.\nexport type PageManifest = ShellManifest & {\n path: string;\n // The canvas whose seed receives the path's parameters as input (merged over\n // `inputs`, which a page may still derive). Absent: the parameters go nowhere,\n // which is right for a path that has none.\n params?: string;\n};\n\n// Identity today, a validation seam tomorrow — and the one name an app\n// file needs besides its artifacts.\nexport const defineApp = (app: NiscApp): NiscApp => app;\n","import type { AdvanceReport, Fact, Retention, Tide } from '@niscorp/tide';\n\n// ═══════════════════════════════════════════════════════════════\n// The tide driver — wake on ingest, sleep until the next due\n// instant, and a janitor for what fell behind the couch.\n//\n// Tide reads no clocks and paces nothing; this is the thing that\n// does. Three duties:\n//\n// WAKE — every ingest (a write fact off the vex bridge, a signal,\n// a manual fire) advances the engine immediately, to quiescence:\n// a chain advances one hop per committed step, so the driver\n// loops until a step reports nothing moved. Chains stop crawling\n// at a metronome's speed and run at the store's.\n//\n// SLEEP — after quiescence, `nextDue` names the next instant\n// worth waking for (a clock occurrence, a retry backoff, a lease\n// lapse, a delayed fact) and one timer sleeps until exactly then.\n// A new ingest preempts it. No beat, no polling for work.\n//\n// JANITOR — a slow fallback wake plus retention sweep. It finds\n// nothing when nothing is broken; it exists because any durable\n// multi-worker design needs the scan that notices work committed\n// by a process that died before its own wake ran. It is how work\n// is RECOVERED, never how it moves.\n//\n// Concurrency: one drain at a time. A wake during a drain queues\n// exactly one more pass (facts landed mid-drain are caught by it);\n// the mutex is a flag pair, not a lock, because everything here is\n// one event loop.\n// ═══════════════════════════════════════════════════════════════\n\nexport type TideDriver = {\n // Delegates to tide, then wakes — the ingest edge a host should hand out\n // (the vex bridge mints through this) so a fact never waits for a beat.\n ingest: Tide['ingest'];\n fire: (reflexId: string, options: { now: number; input?: unknown; by?: string }) => Promise<Fact | undefined>;\n // Advance-to-quiescence now (idempotent, coalescing). Call after anything\n // that changes what tide would do — a reflex reload, an arm flip. The\n // promise resolves when the drain it triggered (or joined) reaches\n // quiescence, so a caller that must see the settled world — a \"run now\"\n // button whose screen re-reads — can await it; everyone else ignores it.\n wake: () => Promise<void>;\n // Stop waking, and resolve once nothing the driver started is still\n // touching the store — the drain in flight and the next-due read after it.\n // A host awaits it before closing the database under the engine.\n stop: () => Promise<void>;\n};\n\nexport type TideDriverConfig = {\n tide: Tide;\n now?: () => number;\n // The janitor's beat. Frequent enough that a lapsed lease is not lapsed\n // for long; rare enough to be a recovery scan rather than a heartbeat.\n janitorMs?: number;\n // Ledger retention, swept on the janitor's beat. Absent = never swept —\n // an honest default; how long history matters is the host's call.\n retention?: Retention;\n};\n\nconst DEFAULT_JANITOR_MS = 300_000;\n// A backstop against a step that always reports progress (which would be a\n// bug, not a workload) — generous enough that no real chain hits it.\nconst MAX_STEPS_PER_DRAIN = 10_000;\n\nconst progressOf = (report: AdvanceReport): number =>\n report.materialized +\n report.skippedOccurrences +\n report.factsMatched +\n report.runsCreated +\n report.tasksCreated +\n report.executed +\n report.reclaimed +\n report.runsSettled +\n report.parked;\n\nexport const createTideDriver = (config: TideDriverConfig): TideDriver => {\n const { tide } = config;\n const now = config.now ?? (() => Date.now());\n const janitorMs = config.janitorMs ?? DEFAULT_JANITOR_MS;\n\n let running = false;\n let queued = false;\n let stopped = false;\n let cycle: Promise<void> | undefined;\n let scheduling: Promise<void> | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const drain = async (): Promise<void> => {\n for (let steps = 0; steps < MAX_STEPS_PER_DRAIN; steps += 1) {\n const report = await tide.advance({ now: now() });\n if (progressOf(report) === 0) return;\n }\n console.error(`[moss:tide-driver] a drain exceeded ${MAX_STEPS_PER_DRAIN} steps — stopping this pass; the janitor will resume it`);\n };\n\n // Never rejects: it runs detached after every drain, and an unhandled\n // rejection there would take the host's process down with it.\n const schedule = async (): Promise<void> => {\n if (stopped) return;\n let due: number | undefined;\n try {\n due = await tide.nextDue(now());\n } catch (err) {\n // Stopping mid-read (the store closing under it) is expected, not news.\n if (!stopped) console.error('[moss:tide-driver] next due', err);\n return;\n }\n if (stopped) return;\n if (timer !== undefined) clearTimeout(timer);\n if (due === undefined) return; // nothing scheduled — the next ingest wakes us\n const delay = due - now();\n // Quiescent yet still \"due now\" means advance cannot progress it (facts\n // waiting for reflexes to load, say). Retry on the janitor's beat, not\n // in a hot loop.\n timer = setTimeout(() => void wake(), delay > 0 ? delay : janitorMs);\n timer.unref?.();\n };\n\n // A wake during a drain queues one more pass INSIDE the same cycle, and\n // every waker gets the same cycle promise — so awaiting it always means\n // \"quiescence including whatever landed while we drained\".\n const wake = (): Promise<void> => {\n if (stopped) return Promise.resolve();\n queued = true;\n if (running) return cycle ?? Promise.resolve();\n running = true;\n cycle = (async () => {\n try {\n while (queued) {\n queued = false;\n await drain();\n }\n } catch (err) {\n console.error('[moss:tide-driver]', err);\n } finally {\n running = false;\n cycle = undefined;\n scheduling = schedule();\n }\n })();\n return cycle;\n };\n\n const janitor = setInterval(() => {\n if (config.retention !== undefined) {\n void tide.sweep(now(), config.retention).catch((err) => console.error('[moss:tide-driver] sweep', err));\n }\n void wake();\n }, janitorMs);\n janitor.unref?.();\n\n return {\n ingest: async (fact, options) => {\n const stored = await tide.ingest(fact, options);\n if (stored !== undefined) void wake();\n return stored;\n },\n fire: async (reflexId, options) => {\n const fact = await tide.fire(reflexId, options);\n void wake();\n return fact;\n },\n wake,\n stop: async () => {\n stopped = true;\n clearInterval(janitor);\n if (timer !== undefined) clearTimeout(timer);\n // the drain in flight (it schedules on its way out), then that schedule\n await cycle;\n await scheduling;\n },\n };\n};\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/app.ts","../src/driver.ts"],"names":[],"mappings":";;;;AA2gBO,IAAM,SAAA,GAAY,CAAC,GAAA,KAA0B;;;AC/cpD,IAAM,kBAAA,GAAqB,GAAA;AAG3B,IAAM,mBAAA,GAAsB,GAAA;AAE5B,IAAM,aAAa,CAAC,MAAA,KAClB,OAAO,YAAA,GACP,MAAA,CAAO,qBACP,MAAA,CAAO,YAAA,GACP,OAAO,WAAA,GACP,MAAA,CAAO,eACP,MAAA,CAAO,QAAA,GACP,OAAO,SAAA,GACP,MAAA,CAAO,cACP,MAAA,CAAO,MAAA;AAEF,IAAM,gBAAA,GAAmB,CAAC,MAAA,KAAyC;A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hB,EAAA,OAAO;AAAA,IACL,MAAA,EAAQ,OAAO,IAAA,EAAM,OAAA,KAAY;AAC/B,MAAA,MAAM,MAAA,GAAS,MAAM,IAAA,CAAK,MAAA,CAAO,MAAM,OAAO,CAAA;AAC9C,MAAA,IAAI,MAAA,KAAW,MAAA,EAAW,KAAK,IAAA,EAAK;AACpC,MAAA,OAAO,MAAA;AAAA,IACT,CAAA;AAAA,IACA,IAAA,EAAM,OAAO,QAAA,EAAU,OAAA,KAAY;AACjC,MAAA,MAAM,IAAA,GAAO,MAAM,IAAA,CAAK,IAAA,CAAK,UAAU,OAAO,CAAA;AAC9C,MAAA,KAAK,IAAA,EAAK;AACV,MAAA,OAAO,IAAA;AAAA,IACT,CAAA;AAAA,IACA,IAAA;AAAA,IACA,MAAM,YAAY;AAChB,MAAA,OAAA,GAAU,IAAA;AACV,MAAA,aAAA,CAAc,OAAO,CAAA;AACrB,MAAA,IAAI,KAAA,KAAU,MAAA,EAAW,YAAA,CAAa,KAAK,CAAA;AAE3C,MAAA,MAAM,KAAA;AACN,MAAA,MAAM,UAAA;AAAA,IACR;AAAA,GACF;AACF","file":"index.js","sourcesContent":["import type { Sequence } from '@niscorp/strata';\nimport type { ScopeBehaviors, ScopePolicy, SeedEntry, SeedMutation } from '@niscorp/vex';\nimport type { Charter } from '@niscorp/charter';\nimport type { ActionDefinition, ActionFragment, CanvasConfig, FetchFn, FunctionHandler, LayoutNode, Shell } from '@niscorp/nova';\nimport type { PhraseKeys, Phrasebook } from '@niscorp/nova/i18n';\nimport type { NiscRuntime } from './runtime';\nimport type { IdentityRecord } from './identity';\n\n// ═══════════════════════════════════════════════════════════════\n// The application, as data. Every field is an ARTIFACT — content someone\n// authored — never machinery: the server derives everything mechanical\n// from these plus a database (DESIGN.md § Derivation over\n// configuration). `assignments` stands in for the artifact library's\n// assignment table until that exists.\n// ═══════════════════════════════════════════════════════════════\n\n// Ring 2, as data: a layout VARIANT reshapes ONE action's layout for the\n// principals whose charter grants the variant id (the `layouts` section).\n// The reference direction is variant → action — an action never lists its\n// variants, so minting one is additive. Holding no variant of an action\n// means the base (the layout on the definition); holding two is incoherence\n// the server refuses at boot. A variant changes ONLY the layout — different\n// behavior (triggers, endpoints, data, input) is a different action id.\n//\n// Direction: the base is the FLOOR — the least-privileged holder's shape.\n// Variants ENRICH upward and are granted like any other capability, so\n// `extends` composes them correctly and a forgotten grant fails closed\n// (under-serves visibly). A variant that reduces is authored backwards: it\n// forces deny-it-back in every richer role, and a forgotten deny\n// over-serves silently.\nexport type LayoutVariant = { action: string; layout: LayoutNode };\n\nexport type NiscApp = {\n charter: Charter;\n // THE ASSIGNMENT MAP — one entry per principal, and the reason a resident\n // copy of the population had to exist at all: an eager `Record` cannot be\n // filled without enumerating everybody.\n //\n // OPTIONAL now. An app that declares `identity` answers this per principal,\n // asynchronously, one row at a time, and never builds the map. What remains\n // here is for apps whose assignments are AUTHORED — a handful of static\n // rungs in a demo — where a literal is the honest shape.\n assignments?: Record<string, readonly string[]>;\n // WHICH ROLE COMBINATIONS A PRINCIPAL MAY HOLD — declared, not counted.\n //\n // The two coherence gates below (`verifyCharter`'s subtractive-assigned rule,\n // `verifyVariants`' one-variant-per-action rule) never wanted principals; they\n // wanted the distinct COMBINATIONS somebody could wear. Reading them off\n // `assignments` is the only reason that map has to be eager — and enumerating\n // the population to learn that `['instructor','member']` exists is a strange\n // way to learn it.\n //\n // The charter cannot supply this. It defines roles; it does not know which of\n // them coincide on one person, because that is a fact about the application's\n // schema (staff row AND membership row), not about the grant graph.\n //\n // Absent = derived from `assignments`, which is what every app did before this\n // existed and is correct while the map is still eager.\n wearable?: readonly (readonly string[])[];\n actions: Record<string, ActionDefinition>;\n // layout variants by variant id — the `layouts` universe the charter\n // selects over (ring 2; `actions` is ring 1, `data` is ring 3)\n layouts?: Record<string, LayoutVariant>;\n behaviors?: ScopeBehaviors;\n // Per-principal SCOPE VALUES — the seam that lets an app decide what a\n // principal IS beyond its id. The server always injects `{ userId }` (the\n // principal); this hook contributes the rest — a tenant, an org, a region —\n // and the merged set is what a behavior's `to:` resolves against at execute\n // (`{ match: 'property_id', to: 'propertyId' }` needs `propertyId` here).\n //\n // Moss deliberately does NOT assume how a principal maps to those values: the\n // mapping is application knowledge (a directory, a claims table, a lookup),\n // so the app supplies it. Values are injected server-side and are\n // unreferenceable by a request — the enforcement is engine-side and unforgeable.\n //\n // VOLATILE VALUES ONLY, once `identity` below exists. A resolved identity is\n // held for a session; anything derived from the CLOCK must not be, or a\n // session opened before midnight serves yesterday's date to every query that\n // compares a DATE column against it. So this seam survives beside `identity`\n // and is asked per request — and it stays synchronous on purpose, because the\n // values that belong here are COMPUTED rather than read. A sync signature is\n // only a trap when the answer lives in rows.\n //\n // The resolved record is handed in so the computation has what it needs\n // without a lookup: the day is derived from the timezone the record already\n // carries. Merged OVER the record's own scope values.\n scope?: (principal: string | null, identity?: IdentityRecord) => Record<string, unknown>;\n // WHO A PRINCIPAL IS, resolved ONCE per session instead of asked in pieces\n // per request — one async answer for roles, scope and the install list\n // (`installed`: which integrations are live for this principal's tenant).\n //\n // The three seams around this one are synchronous, and that is not a detail:\n // a hook that cannot await has exactly one implementation available to it\n // when the answer lives in rows, and that implementation is a resident map of\n // the whole population. Lyra grew eight of them across three files, and every\n // one exists to satisfy a signature rather than a decision. This is the same\n // question asked in a tense that permits the obvious answer — read the row.\n //\n // Moss OWNS the resulting cache: bounded, evicted, revalidated on\n // `sessionRevalidateMs`, and enumerable only by an operator (see identity.ts,\n // and the invariants in docs/plans/lyra-identity.md Part 6). What it will\n // never do is look inside the record. `roles` goes to charter, `installed` is\n // filtered against, `scope` is merged into the engine's scope values — all\n // pass-through. The moment moss reads `.studioId` off one of these, moss has\n // learned what a tenant is and the boundary is gone.\n //\n // Absent = the three older seams answer, exactly as before.\n //\n // `resolve` is the pre-authorisation half: roles, the invalidation tag, and\n // whatever scope the app can only establish before a policy exists (an\n // integration actor's studio; a person's tenant). `scope` and `installed`\n // name SEEDED entries moss then executes through its own engine — under the\n // policy of the charter role `as` names, with the scope values resolved so\n // far — merging each mapped object into the record. The app's model of a\n // session thereby lives in its ARTIFACTS: the entries and their reach\n // profiles, checkable like any other, with moss holding no opinion about\n // what any of it means.\n identity?: {\n // The charter role the lent reader executes AS — a role nobody wears,\n // holding exactly the verbs identity's engine reads need. Opaque here.\n as?: string;\n // ONE seam. `read` is a capability moss lends for the duration of the\n // call: it executes a SEEDED entry through moss's own engine, locked to\n // replay, under the `as` role's compiled policy, with exactly the scope\n // values the app passes — values the app itself resolved, engine-side.\n // The app composes its whole record from its one licensed pre-auth read\n // plus these; moss caches the result and never looks inside it.\n resolve: (principal: string, read: (fingerprint: string, scope: Record<string, unknown>) => Promise<unknown>) => Promise<IdentityRecord>;\n };\n // THE WORDS THIS PRINCIPAL'S SHELL WEARS — the language twin of `scope`.\n //\n // Moss renders a shell server-side and serializes its trees. Between those\n // two, every word the reader will see is present at once, so that is where a\n // language is applied: one pass over the frame (`@niscorp/nova/i18n`), source\n // phrase in, translated phrase out. Nothing downstream — the socket, the\n // delta encoder, the terminal — learns that a language exists.\n //\n // Returning undefined or an empty book is the SOURCE language, and costs\n // nothing: the pass returns the same tree object and the frame serializes to\n // the bytes it always did.\n //\n // Per PRINCIPAL, because a shell is per principal. Two people at the same\n // tenant reading different languages get two shells, which they already had.\n // Resolved once when the shell is built — a change to a principal's language\n // is a `reset`/rebuild, exactly like a change to their catalog.\n // Async and wire-bearing, for the same reason `seeds` and `inputs` are: a\n // book lives in rows, and a hook that cannot reach them holds a resident\n // copy of every language. The resolved identity rides along so the app can\n // pick the language off the record the session already established.\n phrases?: (session: { principal: string | null; identity: Record<string, unknown>; wire: FetchFn }) => Phrasebook | undefined | Promise<Phrasebook | undefined>;\n // Which keys in a tree carry prose. An app with its own display-field\n // convention (`status_display`) declares it once here. Absent = nova's\n // default prop set and no suffix rule.\n phraseKeys?: PhraseKeys;\n /**\n * @deprecated Never called. Which integrations are live for a principal's\n * tenant is `installed` on the record `identity.resolve` returns; without\n * `identity`, every registered integration is live for everybody. Kept on\n * the type so a manifest that still names it compiles — and it stays: a\n * manifest that works is not broken to tidy a type.\n */\n installedIntegrations?: (principal: string | null) => readonly string[] | Promise<readonly string[]>;\n // WHO AN INTEGRATION IS when it acts and nobody is driving.\n //\n // A webhook lands, a nightly sync runs: the integration presents its minted\n // key and names who it acts for (`x-nisc-acts-for` — a tenant in most apps,\n // and opaque to moss for the same reason `scope` is). The app answers with a\n // principal, and from there NOTHING is special: that principal's charter\n // rung compiles its policy, `scope` gives it its values, and the engine\n // stamps its writes — the integration is just another client of the same\n // closed grammar.\n //\n // Returning null refuses: an integration the tenant has not installed, a\n // tenant that does not exist, an app that has no actor for unattended work.\n // Absent = integration keys resolve to nobody and every keyed call is 403.\n // MAY BE ASYNC, and this is the first of the six per-principal seams to say\n // so. A synchronous signature cannot perform I/O, so an app answering this\n // question about rows had exactly one implementation available to it: hold\n // the rows. That is how a resident copy of the database gets built by a type\n // rather than by a decision (docs/plans/lyra-identity.md, Part 1).\n //\n // Nothing here needed it: moss resolves this inside async middleware, one\n // call per keyed request, and has awaited the session verifier beside it\n // since the beginning. A sync implementation still satisfies this — the\n // widening is the point, not a migration.\n integrationActor?: (integration: string, actsFor: string) => string | null | Promise<string | null>;\n // WHERE AN INTEGRATION MAY APPEAR — the host's half of the placement\n // contract, advertised on the discovery surface and enforced at intake.\n //\n // `attachable`: host action id → the offers, as {offered key: host data\n // path} (a member detail offering `membership_id` from `$.membershipId`).\n // Declaring an action here is declaring a seat. The KEYS are the contract —\n // advertised on discovery, what a rider receives as input and what a\n // preview call carries. The PATHS are the host's private wiring: how its\n // own strip derivation and push trigger read those values off its data —\n // a rider never sees them.\n attachable?: Record<string, Record<string, string>>;\n // `menuSlots`: hub action ids whose item lists accept placed integration\n // screens. Who owns a menu is the host's question; this list is its answer,\n // and intake refuses a placement outside it.\n menuSlots?: readonly string[];\n // THE VOCABULARY AN ADD-ON'S DECLARATIONS MAY NAME — the same posture as\n // `menuSlots`: the host names what it offers, intake refuses anything outside\n // it. Read into the intake context so a `documents`/`assistants` declaration\n // fails at registration, not in front of a person, when it names one the host\n // does not hold. moss carries the names; what a tool DOES, what a check\n // MEANS, and which region an id draws are the host's, never moss's.\n //\n // `assistantTools`: the host's closed assistant tool set, an `assistants`\n // declaration's `tools[]` is checked against it.\n assistantTools?: readonly string[];\n // `publishChecks`: the checks the host runs before publishing a document, a\n // `documents` declaration's `checks[]` is checked against it.\n publishChecks?: readonly string[];\n // `editorRegions`: region action ids the host's editor offers a document\n // beyond the bundle's own actions; a `documents` declaration's `regions`\n // values are admitted if they are one of these OR one of the bundle's actions.\n editorRegions?: readonly string[];\n // WORDS FOR THE IDS ABOVE, for the one sentence a person reads before\n // turning an integration on. Optional: without it the approval card and store tile\n // print ids, which is honest and unhelpful.\n placementNames?: Readonly<Record<string, string>>;\n // WHERE PRESS IMAGES LAND. A bundle may declare listing images\n // (meta.press); intake fetches the bytes once and hands them here, and the\n // URL this answers with is what the store serves forever after — the host's\n // blob store, its bounds, its refusals (throw, and the bundle is refused\n // whole). Optional: a deployment without one refuses any bundle that\n // declares press, which is a sentence at import rather than a hole in a\n // listing.\n storePress?: import('./integrations').StorePress;\n // the prewarmed API surface — every read and write the app serves, as\n // authored entries; seeded into the cache at boot (idempotent, protected).\n // Optional because a database may already carry its vex_cache rows.\n entries?: readonly (SeedEntry | SeedMutation)[];\n // resource name → the entity subgraph it exposes as /api/<name>/vex\n // (a bare list, or an object carrying one — an app's resource artifacts\n // pass through unmapped). The bare /api/vex (full schema) always exists.\n resources?: Record<string, readonly string[] | { entities: readonly string[] }>;\n // The shell, as data (DESIGN.md § The shell runs on the server):\n // canvases and fragments are artifacts; `inputs` is the app's ONE\n // derivation hook — per-principal boot input (nav flags, user chips),\n // merged over each canvas's static seed. Absent = no server shells.\n shell?: ShellManifest;\n // PAGES — what is drawn at a path and kept by nothing.\n //\n // `shell` above is THE APP: one durable shell per person, the thing that\n // rearranges itself around whoever holds it. A page is the other kind of\n // thing a path can lead to — a welcome, the docs, a published talk: a small\n // manifest of its own (a frame, canvases, what mounts on them), drawn for\n // whoever asks and then let go. Nothing stands behind it afterwards unless\n // what mounted can still do something (./liveness), in which case the\n // terminal gets a shell for as long as its connection lasts.\n //\n // It is the SAME machinery with the keeping taken out: the same actions, the\n // same charter deciding what exists for whom (a member's chip is an action a\n // member is granted), the same policy on every read. A page drawn for nobody\n // is the same for everybody, so it may be cached or written to a file; a page\n // drawn for somebody is theirs and is not. That is decided by who asked,\n // never by the page.\n //\n // `functions` are endpoints and serve a page's actions as they serve the\n // app's. `onSession` does not run for a page: session code is the app's.\n pages?: Record<string, PageManifest>;\n // The app's own GRAMMAR sequences (strata): migrations for documents only this\n // app defines the shape of — its component kit's props, say, rewritten on\n // every nova layout node that uses them. Pure data like every artifact here: a\n // document migration is a Prism config. moss runs them with nova's and\n // Prism's over every stored document and every submitted bundle.\n grammars?: readonly Sequence[];\n // The `fn:` escape hatch, server-side: app code running IN-PROCESS next\n // to the session's durable shell (Ray lives here). Built once per\n // session — handlers close over the session context, so keys and code\n // never reach a browser. Side-effect-free computation deploys as server\n // functions behind plain `url:` endpoints instead (/fns, later).\n functions?: (session: FunctionSession) => Record<string, FunctionHandler>;\n // Called once per living shell, with the same session, for app code that is\n // NOT an endpoint: a per-session observer, a roster, an agent watching the\n // screen. Without it such code has to ride `functions` and be registered as a\n // handler nothing calls, which is a lie about what it is.\n //\n // It runs BEFORE the shell finishes building, like `functions` — so it must\n // defer anything that touches `session.shell`. Anything it returns is\n // ignored; to release resources, subscribe to the shell and drop on dispose.\n onSession?: (session: FunctionSession) => void;\n // Where model runs go. moss produces nothing itself — an app that runs an\n // agent calls `session.recordRun` and this receives the record with the\n // session's own fields already stamped.\n //\n // No default sink. A bounded in-memory array would answer \"the last few\n // minutes, gone on restart\", which is not a question anyone asks about an\n // agent's behaviour; an app that wants that can write five lines. Unset means\n // unrecorded, which is at least honest.\n runs?: RunSink;\n // A WRITE LANDED, and the app declared its interest in advance. Each\n // reaction names the table (and optionally the op) it cares about; moss\n // routes vex's write observer to the reactions whose interest matches,\n // once per matching statement — so app code never hears about writes it\n // did not declare, and never string-matches fingerprints to find out what\n // happened. `deliver` publishes onto a principal's live durable shell over\n // the socket the shells already run — push built on the transport this\n // server owns, never a second one.\n //\n // Deliberately row-less: a reaction hears THAT a write landed (table, op,\n // how many rows, the unforgeable scope), never what it wrote. A receiver\n // that wants the data re-reads it under its own policy — rows handed to\n // imperative code would be rows outside every fence this stack builds.\n // Zero-row statements (a scope-narrowed update, a conflict-skipped\n // insert) fire no reaction: nothing changed, so there is no news.\n reactions?: readonly {\n table: string;\n op?: 'insert' | 'update' | 'delete';\n run: (\n event: { fingerprint: string; table: string; op: 'insert' | 'update' | 'delete'; count: number; scope: Record<string, unknown> },\n tools: { deliver: (principal: string, channel: string, payload?: unknown) => boolean },\n ) => void;\n }[];\n // The write-fact bridge. Vex is the choke point every write passes\n // through; when an app runs tide, each committed statement is minted into\n // it as a `{ kind: 'write' }` fact — entity, op, and the row the database\n // returned — stamped with the identity `identity(scope)` names. That\n // identity is the fact's tenancy fence: tide offers a fact only to\n // reflexes running AS the same identity, so whose write it was decides\n // who may be woken by it. Returning undefined mints nothing for that\n // write (an operator surface, a write with no tenant). `tide` is a\n // getter because the instance stands up after the server does.\n //\n // Rows travel HERE and into tide's ledger only — host plumbing on one\n // side, the identity fence on the other. They never reach `onMutation`.\n //\n // The intake is structural — hand back the tide DRIVER, so a minted fact\n // wakes the engine instead of waiting for anybody's beat.\n facts?: {\n tide: () => FactIntake | undefined;\n identity: (scope: Record<string, unknown>) => string | undefined;\n // The causality gate. A tide effect that writes back through vex\n // forwards its chain position as request headers (`x-tide-cause`,\n // `x-tide-depth`); this decides whether THAT CALLER's word is good —\n // return the hints to accept them onto the minted facts, undefined to\n // drop them. Absent = hints are always dropped, which is the safe\n // default: a forged depth could park an innocent chain, and a forged\n // cause is fabricated provenance. An app grants this to exactly the\n // principals that ARE its automation rungs.\n chain?: (scope: Record<string, unknown>, hints: { cause: string; depth: number }) => { cause: string; depth: number } | undefined;\n };\n};\n\n// The one verb the bridge needs. Both `Tide` and `TideDriver` satisfy it;\n// hand out the driver unless you have a reason to want facts that wait.\nexport type FactIntake = Pick<import('@niscorp/tide').Tide, 'ingest'>;\n\n// One turn of an exchange with a model, in order. Provider-blind and\n// library-blind on purpose: moss depends on neither an LLM client nor an agent\n// framework, so this is the shape any of them can be flattened into rather than\n// one client's message union leaking into the app server.\n//\n// A tool call and its result are two turns, the way the model saw them: the\n// assistant turn that ASKED (`calls`), then the tool turn that ANSWERED (`name`\n// + content). Nothing is aggregated into a separate call list — that is a\n// display's business, and a second copy of the same facts drifts.\nexport type RunTurn = {\n role: 'system' | 'user' | 'assistant' | 'tool';\n content: string;\n // What the model asked for on this turn. `args` stays a string: providers send\n // arguments JSON-encoded, and re-encoding a parse is how a malformed call\n // stops looking malformed in the record.\n calls?: ReadonlyArray<{ name: string; args: string }>;\n // Which tool a 'tool' turn is the answer from.\n name?: string;\n};\n\n// One model run, as a row. Everything is a dimension and nothing is aggregated:\n// per person, per model, per session and per day are all group-bys over this,\n// and a tally computed on write is wrong the moment a different cut is wanted.\n//\n// Deliberately not here: cost in currency. Per-model price tables rot, tokens\n// are the honest unit, and `provider` + `model` let pricing be layered on later\n// without a migration.\nexport type RunRecord = {\n at: number;\n principal: string | null;\n shellId: string;\n // The agent's own id, and its lineage when one agent runs inside another.\n agentId: string;\n agentPath: readonly string[];\n // The app's own axis — which way in produced this run.\n label: string;\n provider: string;\n model: string;\n inputTokens: number;\n outputTokens: number;\n totalTokens: number;\n // False when any step was counted rather than reported by the provider.\n // Streamed responses are not reliable about the usage frame.\n reported: boolean;\n steps: number;\n elapsedMs: number;\n // THE WHOLE EXCHANGE, turn by turn: what went out (instructions, catalogs,\n // history, the input), every tool the model called and what came back from it,\n // and the answer. This is the only honest account of \"why did it do that\", and\n // reconstructing it after the fact is impossible — the prompt is assembled\n // from live state that has since moved.\n //\n // It is also the largest thing here by far, and it carries whatever the\n // person's screen carried. A sink that persists it is storing that.\n turns?: readonly RunTurn[];\n response?: string;\n // A failed run spent tokens too. Recording only successes undercounts\n // precisely when something is going wrong.\n outcome: 'ok' | 'failed';\n};\n\n// The session is handed along so a sink can persist through the CALLER's own\n// governed wire rather than a privileged one — the row then lands under the same\n// scope as everything else and cannot be written on another principal's behalf.\n// A sink that wants a plain in-process array can ignore it.\nexport type RunSink = (record: RunRecord, session: FunctionSession) => void;\n\n// What a session's functions close over: the living shell (durable per\n// principal), who is calling, the server's own surfaces as the session,\n// the environment the server stands on, and the principal's compiled\n// scope policy — dynamic reads (agents) execute under it, so an agent\n// sees what its caller sees and is refused what its caller is refused.\nexport type FunctionSession = {\n shell: Shell;\n principal: string | null;\n roles: readonly string[];\n // The scope half of the resolved identity — the record the session was built\n // from, handed back so a function reads \"which studio am I\" off what the\n // engine already established instead of looking anybody up.\n identity: Record<string, unknown>;\n // The session's granted action ids, installs already filtered — the same\n // catalog the shell was built from, so a function and a screen cannot\n // disagree about what this person holds.\n actions: readonly string[];\n wire: FetchFn;\n runtime: NiscRuntime;\n policy: ScopePolicy;\n // Session lifecycle, as capabilities — no reserved channels, no\n // observers. A login fn GRANTS: the token goes down every connection of\n // this session as a `session` message and the terminals reconnect\n // authenticated. A sign-out fn REVOKES: under moss's own credential every\n // session the principal holds is deleted, every connection closes\n // SIGNED_OUT and the durable shell dies. The promise settles when the\n // credential is gone — await it to know; ignoring it is still safe.\n grant: (token: string) => void;\n revoke: () => Promise<void>;\n // Record one model run. `at`, `principal` and `shellId` are stamped here, so a\n // caller supplies only what it knows: which agent, which model, what was said,\n // what it cost. A no-op when the manifest declares no `runs` sink.\n recordRun: (run: Omit<RunRecord, 'at' | 'principal' | 'shellId'>) => void;\n};\n\n// A canvas seed, or CANDIDATES: with a list, the FIRST action the\n// principal holds mounts — members boot `home`, anonymous boots the lock\n// screen, and nobody configures which (ring 1 as derivation).\nexport type CanvasSeed = string | { action: string; input?: Record<string, unknown>; with?: string[] };\nexport type ShellCanvas = Omit<CanvasConfig, 'initial'> & { initial?: CanvasSeed | CanvasSeed[] };\n\nexport type ShellManifest = {\n canvases: ShellCanvas[];\n // The FRAME — the canvas arrangement, a layout of CanvasSlot markers.\n // Served to terminals verbatim; the terminal owns nothing but pixels.\n layout?: LayoutNode;\n // THE INITIAL LAYOUT STORE — what a `{ ref: id }` in the frame resolves to\n // before anything calls `setLayout`. A dynamic region embeds `{ ref: 'dock' }`\n // in `layout` above and this seeds what it draws; `shell.setLayout('dock', …)`\n // then swaps it and the change re-sends the frame. NOT `layouts` (below, on\n // NiscApp) — those are per-role variants of ACTION layouts; this seeds the\n // shell's layout STORE, mirroring nova's own `createShell({ layoutStore })`.\n layoutStore?: Record<string, LayoutNode>;\n fragments?: Record<string, ActionFragment>;\n // Per-principal canvas SEEDING — the instance twin of `inputs`. Where\n // `initial` is static data and `inputs` derives per-principal boot DATA,\n // `seeds` derives per-principal boot INSTANCES: the app computes, from the\n // session (and its own reads over the session's wire), which actions to\n // push onto which canvases. moss does nothing but call it and push, in\n // order, ring-1-filtered like every other mount — an ungranted seed simply\n // doesn't. May be async (a derivation usually reads resolved rows); seeds\n // land when it resolves, and attached terminals see them arrive.\n seeds?: (session: {\n principal: string | null;\n actions: readonly string[];\n roles: readonly string[];\n wire: FetchFn;\n }) => Promise<Record<string, CanvasSeed[]>> | Record<string, CanvasSeed[]>;\n // Component CONTRACTS for the server registry — name → { meta }. The\n // React components stay in the terminal; only their meta crosses, so\n // the layout agent's palette (meta.description / meta.propsSchema) works\n // server-side. Names listed here are registered even when no authored\n // layout mentions them (generated layouts may).\n components?: Record<string, { meta?: { description?: string; propsSchema?: unknown } }>;\n //\n // ASYNC AND WIRE-BEARING, matching `seeds`. These two are called twins a few\n // lines apart, and one was handed the governed internal wire while the other\n // was not. That asymmetry is the origin of every resident cache in this repo:\n // a hook that cannot await, asked a question about rows, has exactly one\n // implementation available to it, and that implementation is a map of\n // everybody (docs/plans/lyra-identity.md, Part 1). A synchronous\n // implementation still satisfies this — the widening is the point.\n inputs?: (session: {\n principal: string | null;\n actions: readonly string[];\n roles: readonly string[];\n // The scope values the app's own `identity` seam returned — handed straight\n // back so a shell can be composed from the record the session already\n // resolved, instead of reaching into a directory for the same four facts.\n identity: Record<string, unknown>;\n wire: FetchFn;\n }) => Record<string, Record<string, unknown>> | Promise<Record<string, Record<string, unknown>>>;\n};\n\n// A page: a shell manifest, and the path it is drawn at. `:name` segments are\n// parameters (\"/docs/:slug\"); every other segment matches itself.\nexport type PageManifest = ShellManifest & {\n path: string;\n // The canvas whose seed receives the path's parameters as input (merged over\n // `inputs`, which a page may still derive). Absent: the parameters go nowhere,\n // which is right for a path that has none.\n params?: string;\n};\n\n// Identity today, a validation seam tomorrow — and the one name an app\n// file needs besides its artifacts.\nexport const defineApp = (app: NiscApp): NiscApp => app;\n","import type { AdvanceReport, Fact, Retention, Tide } from '@niscorp/tide';\n\n// ═══════════════════════════════════════════════════════════════\n// The tide driver — wake on ingest, sleep until the next due\n// instant, and a janitor for what fell behind the couch.\n//\n// Tide reads no clocks and paces nothing; this is the thing that\n// does. Three duties:\n//\n// WAKE — every ingest (a write fact off the vex bridge, a signal,\n// a manual fire) advances the engine immediately, to quiescence:\n// a chain advances one hop per committed step, so the driver\n// loops until a step reports nothing moved. Chains stop crawling\n// at a metronome's speed and run at the store's.\n//\n// SLEEP — after quiescence, `nextDue` names the next instant\n// worth waking for (a clock occurrence, a retry backoff, a lease\n// lapse, a delayed fact) and one timer sleeps until exactly then.\n// A new ingest preempts it. No beat, no polling for work.\n//\n// JANITOR — a slow fallback wake plus retention sweep. It finds\n// nothing when nothing is broken; it exists because any durable\n// multi-worker design needs the scan that notices work committed\n// by a process that died before its own wake ran. It is how work\n// is RECOVERED, never how it moves.\n//\n// Concurrency: one drain at a time. A wake during a drain queues\n// exactly one more pass (facts landed mid-drain are caught by it);\n// the mutex is a flag pair, not a lock, because everything here is\n// one event loop.\n// ═══════════════════════════════════════════════════════════════\n\nexport type TideDriver = {\n // Delegates to tide, then wakes — the ingest edge a host should hand out\n // (the vex bridge mints through this) so a fact never waits for a beat.\n ingest: Tide['ingest'];\n fire: (reflexId: string, options: { now: number; input?: unknown; by?: string }) => Promise<Fact | undefined>;\n // Advance-to-quiescence now (idempotent, coalescing). Call after anything\n // that changes what tide would do — a reflex reload, an arm flip. The\n // promise resolves when the drain it triggered (or joined) reaches\n // quiescence, so a caller that must see the settled world — a \"run now\"\n // button whose screen re-reads — can await it; everyone else ignores it.\n wake: () => Promise<void>;\n // Stop waking, and resolve once nothing the driver started is still\n // touching the store — the drain in flight and the next-due read after it.\n // A host awaits it before closing the database under the engine.\n stop: () => Promise<void>;\n};\n\nexport type TideDriverConfig = {\n tide: Tide;\n now?: () => number;\n // The janitor's beat. Frequent enough that a lapsed lease is not lapsed\n // for long; rare enough to be a recovery scan rather than a heartbeat.\n janitorMs?: number;\n // Ledger retention, swept on the janitor's beat. Absent = never swept —\n // an honest default; how long history matters is the host's call.\n retention?: Retention;\n};\n\nconst DEFAULT_JANITOR_MS = 300_000;\n// A backstop against a step that always reports progress (which would be a\n// bug, not a workload) — generous enough that no real chain hits it.\nconst MAX_STEPS_PER_DRAIN = 10_000;\n\nconst progressOf = (report: AdvanceReport): number =>\n report.materialized +\n report.skippedOccurrences +\n report.factsMatched +\n report.runsCreated +\n report.tasksCreated +\n report.executed +\n report.reclaimed +\n report.runsSettled +\n report.parked;\n\nexport const createTideDriver = (config: TideDriverConfig): TideDriver => {\n const { tide } = config;\n const now = config.now ?? (() => Date.now());\n const janitorMs = config.janitorMs ?? DEFAULT_JANITOR_MS;\n\n let running = false;\n let queued = false;\n let stopped = false;\n let cycle: Promise<void> | undefined;\n let scheduling: Promise<void> | undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n\n const drain = async (): Promise<void> => {\n for (let steps = 0; steps < MAX_STEPS_PER_DRAIN; steps += 1) {\n const report = await tide.advance({ now: now() });\n if (progressOf(report) === 0) return;\n }\n console.error(`[moss:tide-driver] a drain exceeded ${MAX_STEPS_PER_DRAIN} steps — stopping this pass; the janitor will resume it`);\n };\n\n // Never rejects: it runs detached after every drain, and an unhandled\n // rejection there would take the host's process down with it.\n const schedule = async (): Promise<void> => {\n if (stopped) return;\n let due: number | undefined;\n try {\n due = await tide.nextDue(now());\n } catch (err) {\n // Stopping mid-read (the store closing under it) is expected, not news.\n if (!stopped) console.error('[moss:tide-driver] next due', err);\n return;\n }\n if (stopped) return;\n if (timer !== undefined) clearTimeout(timer);\n if (due === undefined) return; // nothing scheduled — the next ingest wakes us\n const delay = due - now();\n // Quiescent yet still \"due now\" means advance cannot progress it (facts\n // waiting for reflexes to load, say). Retry on the janitor's beat, not\n // in a hot loop.\n timer = setTimeout(() => void wake(), delay > 0 ? delay : janitorMs);\n timer.unref?.();\n };\n\n // A wake during a drain queues one more pass INSIDE the same cycle, and\n // every waker gets the same cycle promise — so awaiting it always means\n // \"quiescence including whatever landed while we drained\".\n const wake = (): Promise<void> => {\n if (stopped) return Promise.resolve();\n queued = true;\n if (running) return cycle ?? Promise.resolve();\n running = true;\n cycle = (async () => {\n try {\n while (queued) {\n queued = false;\n await drain();\n }\n } catch (err) {\n console.error('[moss:tide-driver]', err);\n } finally {\n running = false;\n cycle = undefined;\n scheduling = schedule();\n }\n })();\n return cycle;\n };\n\n const janitor = setInterval(() => {\n if (config.retention !== undefined) {\n void tide.sweep(now(), config.retention).catch((err) => console.error('[moss:tide-driver] sweep', err));\n }\n void wake();\n }, janitorMs);\n janitor.unref?.();\n\n return {\n ingest: async (fact, options) => {\n const stored = await tide.ingest(fact, options);\n if (stored !== undefined) void wake();\n return stored;\n },\n fire: async (reflexId, options) => {\n const fact = await tide.fire(reflexId, options);\n void wake();\n return fact;\n },\n wake,\n stop: async () => {\n stopped = true;\n clearInterval(janitor);\n if (timer !== undefined) clearTimeout(timer);\n // the drain in flight (it schedules on its way out), then that schedule\n await cycle;\n await scheduling;\n },\n };\n};\n"]}
|
package/dist/node.cjs
CHANGED
|
@@ -3282,6 +3282,7 @@ var mountSite = (server, config) => {
|
|
|
3282
3282
|
});
|
|
3283
3283
|
server.get("*", async (c) => {
|
|
3284
3284
|
if (owned.test(c.req.path)) return c.notFound();
|
|
3285
|
+
if (path.extname(c.req.path) !== "" && c.req.path !== "/index.html" && server.page(c.req.path) === void 0) return c.notFound();
|
|
3285
3286
|
const template = await promises.readFile(path.join(dist, "index.html"), "utf8");
|
|
3286
3287
|
const page = await renderDocument({
|
|
3287
3288
|
...drawing,
|