@orthograph/language-effect 0.0.0-stage → 0.1.0-next.1

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.
Files changed (141) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +2 -2
  3. package/dist/device.d.ts +5 -0
  4. package/dist/device.js +6 -0
  5. package/dist/index.d.ts +30 -0
  6. package/dist/index.js +25 -0
  7. package/dist/modules/access/internal/path.d.ts +3 -0
  8. package/dist/modules/access/internal/path.js +11 -0
  9. package/dist/modules/access/service.d.ts +5 -0
  10. package/dist/modules/access/service.js +111 -0
  11. package/dist/modules/access/types.d.ts +38 -0
  12. package/dist/modules/access/types.js +3 -0
  13. package/dist/modules/auth/service.d.ts +4 -0
  14. package/dist/modules/auth/service.js +19 -0
  15. package/dist/modules/auth/types.d.ts +38 -0
  16. package/dist/modules/auth/types.js +8 -0
  17. package/dist/modules/calls/internal/run.d.ts +2 -0
  18. package/dist/modules/calls/internal/run.js +28 -0
  19. package/dist/modules/calls/service.d.ts +2 -0
  20. package/dist/modules/calls/service.js +2 -0
  21. package/dist/modules/calls/types.d.ts +32 -0
  22. package/dist/modules/calls/types.js +1 -0
  23. package/dist/modules/handler/internal/attributes.d.ts +17 -0
  24. package/dist/modules/handler/internal/attributes.js +46 -0
  25. package/dist/modules/handler/internal/call-id.d.ts +2 -0
  26. package/dist/modules/handler/internal/call-id.js +5 -0
  27. package/dist/modules/handler/internal/call-metrics.d.ts +17 -0
  28. package/dist/modules/handler/internal/call-metrics.js +35 -0
  29. package/dist/modules/handler/internal/decided.d.ts +14 -0
  30. package/dist/modules/handler/internal/decided.js +106 -0
  31. package/dist/modules/handler/internal/defect.d.ts +4 -0
  32. package/dist/modules/handler/internal/defect.js +19 -0
  33. package/dist/modules/handler/internal/derived.d.ts +21 -0
  34. package/dist/modules/handler/internal/derived.js +96 -0
  35. package/dist/modules/handler/internal/device.d.ts +3 -0
  36. package/dist/modules/handler/internal/device.js +46 -0
  37. package/dist/modules/handler/internal/digest.d.ts +3 -0
  38. package/dist/modules/handler/internal/digest.js +52 -0
  39. package/dist/modules/handler/internal/environment.d.ts +3 -0
  40. package/dist/modules/handler/internal/environment.js +3 -0
  41. package/dist/modules/handler/internal/invariants.d.ts +12 -0
  42. package/dist/modules/handler/internal/invariants.js +28 -0
  43. package/dist/modules/handler/internal/move.d.ts +32 -0
  44. package/dist/modules/handler/internal/move.js +84 -0
  45. package/dist/modules/handler/internal/prehandle.d.ts +23 -0
  46. package/dist/modules/handler/internal/prehandle.js +34 -0
  47. package/dist/modules/handler/internal/read.d.ts +3 -0
  48. package/dist/modules/handler/internal/read.js +79 -0
  49. package/dist/modules/handler/internal/signal.d.ts +3 -0
  50. package/dist/modules/handler/internal/signal.js +10 -0
  51. package/dist/modules/handler/internal/span.d.ts +8 -0
  52. package/dist/modules/handler/internal/span.js +14 -0
  53. package/dist/modules/handler/service.d.ts +7 -0
  54. package/dist/modules/handler/service.js +163 -0
  55. package/dist/modules/handler/types.d.ts +217 -0
  56. package/dist/modules/handler/types.js +24 -0
  57. package/dist/modules/ids/service.d.ts +2 -0
  58. package/dist/modules/ids/service.js +11 -0
  59. package/dist/modules/ids/types.d.ts +8 -0
  60. package/dist/modules/ids/types.js +1 -0
  61. package/dist/modules/journal/service.d.ts +6 -0
  62. package/dist/modules/journal/service.js +4 -0
  63. package/dist/modules/journal/types.d.ts +22 -0
  64. package/dist/modules/journal/types.js +5 -0
  65. package/dist/modules/mcp/internal/input.d.ts +15 -0
  66. package/dist/modules/mcp/internal/input.js +35 -0
  67. package/dist/modules/mcp/internal/output.d.ts +16 -0
  68. package/dist/modules/mcp/internal/output.js +50 -0
  69. package/dist/modules/mcp/internal/tool.d.ts +4 -0
  70. package/dist/modules/mcp/internal/tool.js +56 -0
  71. package/dist/modules/mcp/service.d.ts +2 -0
  72. package/dist/modules/mcp/service.js +38 -0
  73. package/dist/modules/mcp/types.d.ts +101 -0
  74. package/dist/modules/mcp/types.js +1 -0
  75. package/dist/modules/mount/internal/none.d.ts +2 -0
  76. package/dist/modules/mount/internal/none.js +1 -0
  77. package/dist/modules/mount/service.d.ts +2 -0
  78. package/dist/modules/mount/service.js +12 -0
  79. package/dist/modules/mount/types.d.ts +11 -0
  80. package/dist/modules/mount/types.js +4 -0
  81. package/dist/modules/principals/service.d.ts +4 -0
  82. package/dist/modules/principals/service.js +4 -0
  83. package/dist/modules/principals/types.d.ts +15 -0
  84. package/dist/modules/principals/types.js +4 -0
  85. package/dist/modules/records/internal/holder.d.ts +16 -0
  86. package/dist/modules/records/internal/holder.js +55 -0
  87. package/dist/modules/records/internal/list.d.ts +12 -0
  88. package/dist/modules/records/internal/list.js +65 -0
  89. package/dist/modules/records/internal/order.d.ts +18 -0
  90. package/dist/modules/records/internal/order.js +41 -0
  91. package/dist/modules/records/internal/unique.d.ts +31 -0
  92. package/dist/modules/records/internal/unique.js +49 -0
  93. package/dist/modules/records/internal/unit.d.ts +3 -0
  94. package/dist/modules/records/internal/unit.js +135 -0
  95. package/dist/modules/records/service.d.ts +22 -0
  96. package/dist/modules/records/service.js +102 -0
  97. package/dist/modules/records/types.d.ts +170 -0
  98. package/dist/modules/records/types.js +9 -0
  99. package/dist/modules/timers/internal/world.d.ts +4 -0
  100. package/dist/modules/timers/internal/world.js +64 -0
  101. package/dist/modules/timers/service.d.ts +18 -0
  102. package/dist/modules/timers/service.js +125 -0
  103. package/dist/modules/timers/types.d.ts +102 -0
  104. package/dist/modules/timers/types.js +40 -0
  105. package/dist/modules/versions/internal/handlers.d.ts +6 -0
  106. package/dist/modules/versions/internal/handlers.js +36 -0
  107. package/dist/modules/versions/internal/keep.d.ts +21 -0
  108. package/dist/modules/versions/internal/keep.js +36 -0
  109. package/dist/modules/versions/service.d.ts +2 -0
  110. package/dist/modules/versions/service.js +14 -0
  111. package/dist/modules/versions/types.d.ts +27 -0
  112. package/dist/modules/versions/types.js +1 -0
  113. package/dist/modules/visibility/internal/rule.d.ts +7 -0
  114. package/dist/modules/visibility/internal/rule.js +23 -0
  115. package/dist/modules/visibility/internal/schema.d.ts +5 -0
  116. package/dist/modules/visibility/internal/schema.js +12 -0
  117. package/dist/modules/visibility/service.d.ts +15 -0
  118. package/dist/modules/visibility/service.js +27 -0
  119. package/dist/modules/visibility/types.d.ts +60 -0
  120. package/dist/modules/visibility/types.js +1 -0
  121. package/dist/modules/wire/internal/call-telemetry.d.ts +15 -0
  122. package/dist/modules/wire/internal/call-telemetry.js +31 -0
  123. package/dist/modules/wire/internal/refused-payload.d.ts +7 -0
  124. package/dist/modules/wire/internal/refused-payload.js +25 -0
  125. package/dist/modules/wire/internal/shown.d.ts +9 -0
  126. package/dist/modules/wire/internal/shown.js +32 -0
  127. package/dist/modules/wire/service.d.ts +3 -0
  128. package/dist/modules/wire/service.js +14 -0
  129. package/dist/modules/wire/types.d.ts +30 -0
  130. package/dist/modules/wire/types.js +1 -0
  131. package/dist/modules/work/internal/fake-world.d.ts +17 -0
  132. package/dist/modules/work/internal/fake-world.js +43 -0
  133. package/dist/modules/work/internal/fibers.d.ts +2 -0
  134. package/dist/modules/work/internal/fibers.js +5 -0
  135. package/dist/modules/work/service.d.ts +6 -0
  136. package/dist/modules/work/service.js +249 -0
  137. package/dist/modules/work/types.d.ts +103 -0
  138. package/dist/modules/work/types.js +19 -0
  139. package/dist/visibility.d.ts +1 -0
  140. package/dist/visibility.js +3 -0
  141. package/package.json +34 -3
@@ -0,0 +1,217 @@
1
+ import { Context, Data, type Effect, type Redacted, type Schema } from "effect";
2
+ import type { AnswerOf, ErrorOf, Field, InstanceOf, Operation, PayloadOf, Principal, Read, StepsOf, Thing } from "orthograph";
3
+ import type { NotAllowed } from "#modules/access/types.js";
4
+ import type { CallRunner, CallWiring, Callable } from "#modules/calls/types.js";
5
+ import type { Instance, Records, Store } from "#modules/records/types.js";
6
+ import type { Busy } from "#modules/work/types.js";
7
+ declare const IdempotencyConflict_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
8
+ readonly _tag: "IdempotencyConflict";
9
+ } & Readonly<A>;
10
+ /** A request key used again with a payload other than the one it was first used with: refused, never answered with the kept answer. It carries no field: the key is never shown. */
11
+ export declare class IdempotencyConflict extends IdempotencyConflict_base<{}> {
12
+ }
13
+ declare const ReadNotServed_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
14
+ readonly _tag: "ReadNotServed";
15
+ } & Readonly<A>;
16
+ /** A read whose derive looks at the problems every plugin declares has no store to list them from yet: it refuses, by name, and never answers as if it had no adds (a pinned or other derived read is served, slice 7 of Goal 17). */
17
+ export declare class ReadNotServed extends ReadNotServed_base<{
18
+ readonly read: string;
19
+ readonly message: string;
20
+ }> {
21
+ }
22
+ declare const InvalidPayload_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
23
+ readonly _tag: "InvalidPayload";
24
+ } & Readonly<A>;
25
+ /** The payload didn't match the operation's declaration. Refused before the handler runs. */
26
+ export declare class InvalidPayload extends InvalidPayload_base<{
27
+ readonly issues: string;
28
+ }> {
29
+ }
30
+ /**
31
+ * Each declared step, as a function that runs its work in a span named `<thing>.<verb>.<key>`. A call step runs the
32
+ * adapter's callable instead (`steps.price([payload.origin], failure)`), typed by `C[key]`, the callable's own type.
33
+ */
34
+ export type StepRunners<St, C = {}> = {
35
+ readonly [K in keyof St]: St[K] extends {
36
+ readonly type: "call";
37
+ } ? CallRunner<K extends keyof C ? (C[K] extends Callable ? C[K] : Callable) : Callable> : <A, E, R>(work: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>;
38
+ };
39
+ export interface HandlerContext<O, C = {}> {
40
+ readonly principal: Principal;
41
+ readonly steps: StepRunners<StepsOf<O>, C>;
42
+ /**
43
+ * Make the operation's move, ending in `to` (or its only outcome). Applied once the handler answers: the instance's
44
+ * state is set and the move's event journalled. A handler that never calls it makes no move and emits nothing.
45
+ */
46
+ readonly move: (to?: MoveTo<O>) => Effect.Effect<void>;
47
+ /**
48
+ * The instance this call is about, read before the handler ran (the from-check and the commit's version guard read the
49
+ * same one), so a handler never reads it again. Undefined when the payload names none, and for a creating move.
50
+ */
51
+ readonly subject: InstanceOf<ThingOf<O>> | undefined;
52
+ /**
53
+ * Each thing a payload field names by its id, read before the handler ran and keyed by that field (`refs.member`). A
54
+ * missing one never reaches the handler: it is refused `<Thing>NotFound`, or `NotAllowed` when a role check reads it.
55
+ */
56
+ readonly refs: {
57
+ readonly [K in RefKeys<O>]?: Instance;
58
+ };
59
+ /** A creating move's new id, minted before the handler ran: answer with it (`allowance: id`). Undefined otherwise. */
60
+ readonly id: CreatedId<O>;
61
+ }
62
+ type ThingOf<O> = O extends {
63
+ readonly thing: infer T extends Thing;
64
+ } ? T : Thing;
65
+ /** The value a thing's own id holds. */
66
+ type IdOf<T extends Thing> = T["fields"] extends {
67
+ readonly id: Field<infer V>;
68
+ } ? V["schema"]["Type"] : string;
69
+ /** Payload fields taken from some thing's field: those that may name an instance by its id. */
70
+ type RefKeys<O> = O extends Operation<any, infer P, any, any, any> ? {
71
+ [K in keyof P]: P[K] extends Field ? K : never;
72
+ }[keyof P] & string : never;
73
+ /**
74
+ * A move from no state makes its instance and has an id minted; a move from a state is given none. A machine keeps each
75
+ * move's `from` as the literal tuple it was written as, so `[]` is told apart from `["active"]` in the type.
76
+ */
77
+ type CreatedId<O> = O extends {
78
+ readonly move: infer M;
79
+ } ? [NonNullable<M>] extends [never] ? undefined : NonNullable<M> extends {
80
+ readonly from: infer F extends ReadonlyArray<string>;
81
+ } ? F extends readonly [] ? IdOf<ThingOf<O>> : undefined : undefined : undefined;
82
+ type MoveTo<O> = O extends {
83
+ readonly move: infer M;
84
+ } ? (NonNullable<M> extends {
85
+ readonly to: ReadonlyArray<infer S>;
86
+ } ? S : never) : never;
87
+ /** What a project writes in `<verb>.handler.ts`: the declared payload in, the declared answer or a declared error out. */
88
+ export type Handler<O, R = never, C = {}> = (payload: PayloadOf<O>, context: HandlerContext<O, C>) => Effect.Effect<AnswerOf<O>, ErrorOf<O>, R>;
89
+ export interface Served<O, R> {
90
+ readonly name: string;
91
+ /** The declaration this serves: what the visibility rule reads to cut an outcome for its caller. */
92
+ readonly operation: O;
93
+ /** From the outside: decode first, refusing with `InvalidPayload`. */
94
+ readonly call: (payload: unknown, principal: Principal) => Effect.Effect<AnswerOf<O>, ErrorOf<O> | InvalidPayload | NotAllowed | NotFrom, Exclude<R, Records> | Busy | Store>;
95
+ /**
96
+ * From a server that has already decoded the payload against the same declaration. `request` is the caller's
97
+ * idempotency key: for an operation declared `idempotent: "request"`, the same key from the same caller is one call.
98
+ */
99
+ readonly run: (payload: PayloadOf<O>, principal: Principal, request?: string) => Effect.Effect<AnswerOf<O>, ErrorOf<O> | NotAllowed | NotFrom, Exclude<R, Records> | Busy | Store>;
100
+ }
101
+ /** Nothing has the id a payload field names, and no role check read it. Named `<Thing>NotFound`; refused before the handler. */
102
+ export declare class NotFound extends Data.Error<{
103
+ readonly _tag: string;
104
+ readonly id: string;
105
+ }> {
106
+ }
107
+ /** The machine's own refusal: the instance is in a state the move can't start from. Named `<Thing>Not<State>`. */
108
+ export declare class NotFrom extends Data.Error<{
109
+ readonly _tag: string;
110
+ readonly state: string;
111
+ }> {
112
+ }
113
+ declare const BlankReached_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
114
+ readonly _tag: "BlankReached";
115
+ } & Readonly<A>;
116
+ /** A scaffolded handler not written yet. Reaching it is a defect that names what's missing. */
117
+ export declare class BlankReached extends BlankReached_base<{
118
+ readonly what: string;
119
+ }> {
120
+ get message(): string;
121
+ }
122
+ /** Where an operation on the device sends its spans: the collector's OTLP/HTTP base URL, when there is one, and the service they say they are from. */
123
+ export interface DeviceWhere {
124
+ readonly otlp: string | undefined;
125
+ readonly service: string;
126
+ }
127
+ /**
128
+ * What a world gives a plugin's `world` entry (the code prove runs in place of a device): the chain it stood, one funded
129
+ * key per host (`node`, `browser`, `keystore`, `world`), a folder of its own, and a place to keep what a call leaves
130
+ * for the next. A real device has none of this and its entries never ask for it.
131
+ */
132
+ export interface DeviceWorldOf {
133
+ readonly chain: undefined | {
134
+ readonly rpcUrl: string;
135
+ readonly chainId: number;
136
+ /** The funded key the world made for each host, redacted: it prints as `<redacted>`. */
137
+ readonly keys: Readonly<Record<string, Redacted.Redacted<string>>>;
138
+ /** How many blocks count before a send is `confirmed`, the including block as 1 (M1.38). Absent: the local chain's 1. */
139
+ readonly depth?: number;
140
+ };
141
+ /** A fresh folder the world made and will remove: for state an entry keeps on disk (a keystore file). */
142
+ readonly directory: string;
143
+ /** The value kept under `key` for this world, made by `make` the first time it is asked for. */
144
+ readonly remember: <A>(key: string, make: () => A) => A;
145
+ }
146
+ declare const DeviceWorld_base: Context.ServiceClass<DeviceWorld, "@orthograph/language-effect/DeviceWorld", DeviceWorldOf>;
147
+ export declare class DeviceWorld extends DeviceWorld_base {
148
+ }
149
+ export interface Device<O, R> {
150
+ readonly name: string;
151
+ /** Run the operation in this process. The payload is already what the declaration says; nothing is stored or journalled. */
152
+ readonly run: (payload: PayloadOf<O>, where: DeviceWhere) => Effect.Effect<AnswerOf<O>, ErrorOf<O>, R>;
153
+ }
154
+ export interface DeviceApi {
155
+ /** `name` comes from the generated code, which got it from the operation's path. */
156
+ readonly serve: <O, R>(spec: {
157
+ readonly name: string;
158
+ readonly operation: O;
159
+ readonly handler: Handler<O, R, any>;
160
+ }) => Device<O, R>;
161
+ }
162
+ export interface HandlerApi {
163
+ /** `name` comes from the generated code, which got it from the operation's path. */
164
+ readonly serve: <O, R>(spec: {
165
+ readonly name: string;
166
+ readonly operation: O;
167
+ readonly handler: Handler<O, R, any>;
168
+ /** What each call step runs: the adapter's callable, and its layer when it has one. Wired by the generated server. */
169
+ readonly calls?: Readonly<Record<string, CallWiring>>;
170
+ /** The machine's refusal for this operation's move, `<Thing>Not<State>`, named by the generated code. */
171
+ readonly notFrom?: string;
172
+ /** Each payload field whose missing instance is refused before the handler, and its `<Thing>NotFound`, named by the generated code. */
173
+ readonly notFound?: Readonly<Record<string, string>>;
174
+ /** Each refusal's code by tag (`Errors.codes`), so a refused call's span says `refusal.code`. */
175
+ readonly codes?: Readonly<Record<string, string>>;
176
+ /** Each refusal the runtime makes for a rule this operation can break (G5), by the error's tag, and the full name of the rule (`handle.oneHolderPerName`). */
177
+ readonly invariants?: Readonly<Record<string, string>>;
178
+ /** Each adapter's mount by the name it is mounted under, when some `allowed` entry is a `service` role: what that role is read against. */
179
+ readonly mounts?: ReadonlyMap<unknown, string>;
180
+ }) => Served<O, R>;
181
+ readonly blank: {
182
+ /** What a scaffold returns until it is written: dies with `BlankReached`, typed as anything. */
183
+ <A = never>(what: string): Effect.Effect<A>;
184
+ /** In the place of a call's failure mapping: the call that reaches it is a defect that names what's missing. */
185
+ (what: string, kind: "failure"): (failure: unknown) => never;
186
+ };
187
+ }
188
+ /** What a read answers: the fields it names, decoded, with `state` as text; or a list's `{ items, next }`. */
189
+ export type ReadAnswer = {
190
+ readonly [field: string]: unknown;
191
+ };
192
+ /** What a read is called with: `{ id }`, or a list's filters and cursor. */
193
+ export type ReadPayload = {
194
+ readonly [field: string]: unknown;
195
+ };
196
+ export interface ServedRead {
197
+ readonly name: string;
198
+ /** The declaration this serves. */
199
+ readonly operation: Read<any, any, any>;
200
+ /** From the outside: the payload decoded first. */
201
+ readonly call: (payload: unknown, principal: Principal) => Effect.Effect<ReadAnswer, NotAllowed | ReadNotServed | Schema.SchemaError, Store>;
202
+ /** From a server that already decoded the payload. */
203
+ readonly run: (payload: ReadPayload, principal: Principal) => Effect.Effect<ReadAnswer, NotAllowed | ReadNotServed, Store>;
204
+ }
205
+ export interface ReadsApi {
206
+ /**
207
+ * Serve a read: who may read is checked first (on the instance itself for a read by id, on the thing a filter names
208
+ * for a list), then its answer is made. A missing id is refused `NotAllowed`, so a read never tells an outsider what
209
+ * exists; a list answers `{ items, next }`, and `next` goes back as the `cursor` of the page after it.
210
+ */
211
+ readonly serve: <R extends Read<any, any, any>>(spec: {
212
+ readonly name: string;
213
+ readonly read: R;
214
+ readonly mounts?: ReadonlyMap<unknown, string>;
215
+ }) => ServedRead;
216
+ }
217
+ export {};
@@ -0,0 +1,24 @@
1
+ // The handler wrapper: what every generated operation runs through. Decode, check who may call, run the handler as
2
+ // counted work inside the operation's span, check the answer, give it back.
3
+ import { Context, Data } from "effect";
4
+ /** A request key used again with a payload other than the one it was first used with: refused, never answered with the kept answer. It carries no field: the key is never shown. */
5
+ export class IdempotencyConflict extends Data.TaggedError("IdempotencyConflict") {
6
+ }
7
+ /** A read whose derive looks at the problems every plugin declares has no store to list them from yet: it refuses, by name, and never answers as if it had no adds (a pinned or other derived read is served, slice 7 of Goal 17). */
8
+ export class ReadNotServed extends Data.TaggedError("ReadNotServed") {
9
+ }
10
+ /** The payload didn't match the operation's declaration. Refused before the handler runs. */
11
+ export class InvalidPayload extends Data.TaggedError("InvalidPayload") {
12
+ }
13
+ /** Nothing has the id a payload field names, and no role check read it. Named `<Thing>NotFound`; refused before the handler. */
14
+ export class NotFound extends Data.Error {
15
+ }
16
+ /** The machine's own refusal: the instance is in a state the move can't start from. Named `<Thing>Not<State>`. */
17
+ export class NotFrom extends Data.Error {
18
+ }
19
+ /** A scaffolded handler not written yet. Reaching it is a defect that names what's missing. */
20
+ export class BlankReached extends Data.TaggedError("BlankReached") {
21
+ get message() { return this.what; }
22
+ }
23
+ export class DeviceWorld extends Context.Service()("@orthograph/language-effect/DeviceWorld") {
24
+ }
@@ -0,0 +1,2 @@
1
+ import type { IdsApi } from "./types.ts";
2
+ export declare const Ids: IdsApi;
@@ -0,0 +1,11 @@
1
+ import { Effect, Random } from "effect";
2
+ const ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
3
+ const make = (prefix) => Effect.map(Effect.forEach(Array.from({ length: 16 }), () => Random.nextIntBetween(0, ALPHABET.length, { halfOpen: true })), (digits) => `${prefix}_${digits.map((d) => ALPHABET[d]).join("")}`);
4
+ export const Ids = {
5
+ make,
6
+ of: (field) => {
7
+ const meta = field.value.meta;
8
+ // An id field always carries its prefix; anything else is a mistake in the handler, caught the first time it runs.
9
+ return meta.type === "id" ? make(meta.prefix) : Effect.die(new Error(`Ids.of: field ${field.key} is not an id`));
10
+ },
11
+ };
@@ -0,0 +1,8 @@
1
+ import type { Effect } from "effect";
2
+ import type { Field, Value } from "orthograph";
3
+ export interface IdsApi {
4
+ /** A fresh id with this prefix: `alw_3k9x...`. */
5
+ readonly make: (prefix: string) => Effect.Effect<string>;
6
+ /** A fresh id for a thing's id field, typed as that field: `Ids.of(Allowance.fields.id)`. */
7
+ readonly of: <V extends Value>(field: Field<V>) => Effect.Effect<V["schema"]["Type"]>;
8
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,6 @@
1
+ import { Effect } from "effect";
2
+ import { type Entry } from "./types.ts";
3
+ /** A journal read from entries held in memory: what the in-memory store gives tests. */
4
+ export declare const journalOf: (entries: ReadonlyArray<Entry>) => {
5
+ readonly ofTrace: (trace: string) => Effect.Effect<ReadonlyArray<Entry>>;
6
+ };
@@ -0,0 +1,4 @@
1
+ import { Effect } from "effect";
2
+ import { Journal } from "./types.js";
3
+ /** A journal read from entries held in memory: what the in-memory store gives tests. */
4
+ export const journalOf = (entries) => Journal.of({ ofTrace: (trace) => Effect.sync(() => entries.filter((e) => e.trace === trace)) });
@@ -0,0 +1,22 @@
1
+ import { Context, type Effect } from "effect";
2
+ export interface Entry {
3
+ /** The trace of the call that made the move: how `prove` finds a step's events. */
4
+ readonly trace: string;
5
+ readonly operation: string;
6
+ readonly move: string;
7
+ /** The id of the instance that moved. */
8
+ readonly subject: string;
9
+ readonly event: string;
10
+ /** The event's fields in wire form (text for ids and amounts). */
11
+ readonly fields: {
12
+ readonly [field: string]: unknown;
13
+ };
14
+ }
15
+ declare const Journal_base: Context.ServiceClass<Journal, "@orthograph/language-effect/Journal", {
16
+ /** Every entry a trace wrote, in order. */
17
+ readonly ofTrace: (trace: string) => Effect.Effect<ReadonlyArray<Entry>>;
18
+ }>;
19
+ /** Reading the journal back. Entries are written only by `Store.commit`, with the move that emitted them. */
20
+ export declare class Journal extends Journal_base {
21
+ }
22
+ export {};
@@ -0,0 +1,5 @@
1
+ // The journal: every event a move emitted, committed with the move itself, with the trace of the call that made it.
2
+ import { Context } from "effect";
3
+ /** Reading the journal back. Entries are written only by `Store.commit`, with the move that emitted them. */
4
+ export class Journal extends Context.Service()("@orthograph/language-effect/Journal") {
5
+ }
@@ -0,0 +1,15 @@
1
+ import { Schema } from "effect";
2
+ import type { FieldsInput } from "orthograph";
3
+ type Json = {
4
+ readonly [key: string]: unknown;
5
+ };
6
+ /** A decimal's text as its value takes it (`values/internal/wire.ts`): no exponent, no `+`, no leading zero, no `-0`, at most `places` after the point. */
7
+ export declare const decimalPattern: (places: number) => string;
8
+ /** A payload field the caller may not give: declared, and not public. A tool never offers it and never takes it. */
9
+ export declare const hiddenInputs: (payload: FieldsInput) => ReadonlyArray<string>;
10
+ /**
11
+ * A tool's input schema: the JSON Schema of the operation's payload, as it travels (bigints as digit strings), with the
12
+ * fields that are not public taken out. Excess properties are refused, so a secret can't be sent by naming it anyway.
13
+ */
14
+ export declare const inputSchema: (payloadSchema: Schema.Top, payload: FieldsInput) => Json;
15
+ export {};
@@ -0,0 +1,35 @@
1
+ import { Schema } from "effect";
2
+ const UNSIGNED = "^(0|[1-9][0-9]*)$";
3
+ const SIGNED = "^(0|-?[1-9][0-9]*)$";
4
+ /** A decimal's text as its value takes it (`values/internal/wire.ts`): no exponent, no `+`, no leading zero, no `-0`, at most `places` after the point. */
5
+ export const decimalPattern = (places) => `^(?!-0(\\.0*)?$)-?(0|[1-9][0-9]*)${places > 0 ? `(\\.[0-9]{1,${places}})?` : ""}$`;
6
+ /** A payload field the caller may not give: declared, and not public. A tool never offers it and never takes it. */
7
+ export const hiddenInputs = (payload) => Object.keys(payload).filter((k) => payload[k].visibility !== "public");
8
+ /**
9
+ * A tool's input schema: the JSON Schema of the operation's payload, as it travels (bigints as digit strings), with the
10
+ * fields that are not public taken out. Excess properties are refused, so a secret can't be sent by naming it anyway.
11
+ */
12
+ export const inputSchema = (payloadSchema, payload) => {
13
+ const { schema, definitions } = Schema.toJsonSchemaDocument(payloadSchema);
14
+ const full = schema;
15
+ const hidden = new Set(hiddenInputs(payload));
16
+ return {
17
+ type: "object",
18
+ // Each property says what its field is for, in the blueprint's own words (M1.42).
19
+ properties: Object.fromEntries(Object.entries(full.properties ?? {}).filter(([k]) => !hidden.has(k)).map(([k, p]) => {
20
+ const description = payload[k]?.description;
21
+ const input = payload[k];
22
+ const meta = input === undefined ? undefined : (input.kind === "field" ? input.value : input).meta;
23
+ // A whole number travels as base-unit digits only (M6-money (c)); the pattern is on the string, which the generated schema does not carry, so it is said here.
24
+ const digits = meta?.type === "uint" ? UNSIGNED
25
+ : meta?.type === "money" ? (meta.signed ? SIGNED : UNSIGNED)
26
+ : meta?.type === "decimal" ? decimalPattern(meta.places)
27
+ : undefined;
28
+ const said = digits === undefined ? p : { ...p, pattern: digits };
29
+ return [k, description === undefined ? said : { ...said, description }];
30
+ })),
31
+ required: (full.required ?? []).filter((k) => !hidden.has(k)),
32
+ additionalProperties: false,
33
+ ...(Object.keys(definitions).length > 0 ? { $defs: definitions } : {}),
34
+ };
35
+ };
@@ -0,0 +1,16 @@
1
+ import type { FieldsInput } from "orthograph";
2
+ type Json = {
3
+ readonly [key: string]: unknown;
4
+ };
5
+ /** What a tool's output schema is made from: the answer's fields, and whether the call is an operation (which may issue a secret). */
6
+ interface Answering {
7
+ readonly answer: FieldsInput;
8
+ readonly kind: string;
9
+ }
10
+ /**
11
+ * A tool's output schema: the JSON Schema of the answer as an agent is shown it (M1.37). A field every caller sees is required; a field
12
+ * private to roles is optional, since the call cuts it for a caller without them; a secret is not named at all.
13
+ * A `state` is one of the thing's states, as an enum. `undefined` for an answer with no fields.
14
+ */
15
+ export declare const outputSchema: (op: Answering, items?: FieldsInput, states?: ReadonlyArray<string>) => Json | undefined;
16
+ export {};
@@ -0,0 +1,50 @@
1
+ import { Schema } from "effect";
2
+ import { wireStruct } from "orthograph/server";
3
+ import { decimalPattern } from "./input.js";
4
+ /** The fields an agent can ever be shown of an answer: a secret never leaves through MCP, not even one this call issued. */
5
+ const agentFields = (fields) => Object.fromEntries(Object.entries(fields).filter(([, f]) => f.visibility !== "secret"));
6
+ /** The field with a schema of its own choosing, keeping what the wire rule reads of it: its visibility and whether it is issued. */
7
+ const reschemed = (field, schema) => {
8
+ const value = field.kind === "field" ? field.value : field;
9
+ return { kind: "value", schema, meta: value.meta, visibility: field.visibility, ...(field.issued === true ? { issued: true } : {}) };
10
+ };
11
+ /** A decimal as the text it travels as, with its input's pattern; an optional one stays an optional key. */
12
+ const decimalShown = (places, optional) => {
13
+ const text = Schema.String.check(Schema.isPattern(new RegExp(decimalPattern(places), "u")));
14
+ return optional ? Schema.optionalKey(text) : text;
15
+ };
16
+ /**
17
+ * A field's sentence and, for `state`, the machine's own states as the only values it can hold (M1.37, M1.42). A decimal is shown as
18
+ * the text it travels as, with its input's pattern (#742): its own schema's sentence and pattern sit where JSON Schema doesn't show them.
19
+ */
20
+ const told = (fields, states) => Object.fromEntries(Object.entries(fields).map(([key, field]) => {
21
+ const value = field.kind === "field" ? field.value : field;
22
+ const base = key === "state" && states !== undefined && states.length > 0 ? Schema.Literals(states)
23
+ : value.meta?.type === "decimal" ? decimalShown(value.meta.places, value.optional === true)
24
+ : value.schema;
25
+ const schema = field.description === undefined ? base : base.annotate({ description: field.description });
26
+ return [key, schema === value.schema ? field : reschemed(field, schema)];
27
+ }));
28
+ /**
29
+ * A tool's output schema: the JSON Schema of the answer as an agent is shown it (M1.37). A field every caller sees is required; a field
30
+ * private to roles is optional, since the call cuts it for a caller without them; a secret is not named at all.
31
+ * A `state` is one of the thing's states, as an enum. `undefined` for an answer with no fields.
32
+ */
33
+ export const outputSchema = (op, items = {}, states) => {
34
+ if (Object.keys(op.answer).length === 0)
35
+ return undefined;
36
+ const wire = wireStruct(told(agentFields(op.answer), states), {
37
+ ...(Object.keys(items).length > 0 ? { items: told(agentFields(items), states) } : {}),
38
+ });
39
+ const { schema, definitions } = Schema.toJsonSchemaDocument(wire);
40
+ // A refusal comes back as a tool error whose structured content is `{ refusal, code, exit, status, ...its fields }`, and a client checks
41
+ // that against this schema too: so a result is one of two shapes, each with its own properties (an answer's own `status` is not the
42
+ // refusal's), the answer first.
43
+ const answer = { ...schema, type: "object" };
44
+ const refusal = {
45
+ type: "object",
46
+ properties: { refusal: { type: "string" }, code: { type: "string" }, exit: { type: "integer" }, status: { type: "integer" } },
47
+ required: ["refusal", "code", "exit", "status"],
48
+ };
49
+ return { type: "object", anyOf: [answer, refusal], ...(Object.keys(definitions).length > 0 ? { $defs: definitions } : {}) };
50
+ };
@@ -0,0 +1,4 @@
1
+ import type { Store } from "#modules/records/types.js";
2
+ import type { McpEntry, McpRefusals, McpServed, McpTool } from "../types.ts";
3
+ /** One operation or read as a tool: the call is the API's own (`run`), as the person the token names. */
4
+ export declare const toolOf: <R>(name: string, entry: McpEntry, served: McpServed<R>, refusals: McpRefusals) => McpTool<R | Store>;
@@ -0,0 +1,56 @@
1
+ import { Clock, Effect, Schema } from "effect";
2
+ import { listItemFields } from "orthograph/server";
3
+ import { recordCall } from "#modules/handler/internal/call-metrics.js";
4
+ import { Audience, Visibility } from "#modules/visibility/service.js";
5
+ import { Wire } from "#modules/wire/service.js";
6
+ import { hiddenInputs, inputSchema } from "./input.js";
7
+ import { outputSchema } from "./output.js";
8
+ const failed = (line, structured) => ({ isError: true, text: line, ...(structured ? { structured } : {}) });
9
+ /** What an unexpected failure says: a defect's detail is the operator's, never the caller's. */
10
+ const DEFECT = "[AR-500] InternalError";
11
+ const OWN = new Set(["_tag", "code", "message", "stack", "name", "cause"]);
12
+ /** Values as text: bigints as their digits, so what an MCP client reads is what the wire carries. */
13
+ const text = (x) => JSON.stringify(x, (_, v) => (typeof v === "bigint" ? v.toString() : v));
14
+ /** What an agent is shown of an answer: the agent case of the one visibility rule. */
15
+ const shownAnswer = (wire, op, agent) => Visibility.redact(agent, op.answer, wire, op.kind === "read" && op.by === "list" ? listItemFields(op.thing) : undefined);
16
+ /** A value as JSON carries it: a bigint as its digits, the rest as `text` writes it. */
17
+ const jsonOf = (v) => JSON.parse(text(v));
18
+ /** A refusal's line, `[code] Tag { field: value }`, and its structured form: its table row and the fields the caller may see. */
19
+ const refusalOf = (e, refusals, agent) => {
20
+ const tag = typeof e === "object" && e !== null ? e._tag : undefined;
21
+ const code = typeof tag === "string" ? refusals.codes[tag] : undefined;
22
+ if (typeof tag !== "string" || code === undefined)
23
+ return undefined;
24
+ const values = e;
25
+ const declared = refusals.declared[tag];
26
+ // A declared error shows the fields it declares that the caller may see; the machine's own refusal has `state`, public.
27
+ const keys = (declared ? Object.keys(declared.fields).filter((k) => Visibility.sees(agent, declared.fields[k])) : Object.keys(values).filter((k) => !OWN.has(k))).filter((k) => k in values);
28
+ const shown = keys.map((k) => `${k}: ${typeof values[k] === "object" ? text(values[k]) : String(values[k])}`);
29
+ const row = refusals.table?.[tag];
30
+ // Structured only with the table's row: code, exit and status come from one place, never pieced together here. They
31
+ // are written after the error's own fields, so a field named `exit`, `status`, `code` or `refusal` can't replace them.
32
+ const structured = row && { ...jsonOf(Object.fromEntries(keys.map((k) => [k, values[k]]))), refusal: tag, code: row.code, exit: row.exit, status: row.status };
33
+ return failed(`[${code}] ${tag}${shown.length > 0 ? ` { ${shown.join(", ")} }` : ""}`, structured);
34
+ };
35
+ /** One operation or read as a tool: the call is the API's own (`run`), as the person the token names. */
36
+ export const toolOf = (name, entry, served, refusals) => {
37
+ const op = entry.operation;
38
+ const decode = Schema.decodeUnknownEffect(op.payloadSchema);
39
+ const encode = Schema.encodeEffect(op.answerSchema);
40
+ const hidden = new Set(hiddenInputs(op.payload));
41
+ const items = op.kind === "read" && op.by === "list" ? listItemFields(op.thing) : {};
42
+ const call = (args, principal) => Effect.gen(function* () {
43
+ const start = yield* Clock.monotonicTimeNanos;
44
+ return yield* decode(Object.fromEntries(Object.entries(args).filter(([k]) => !hidden.has(k)))).pipe(Effect.matchEffect({
45
+ onFailure: (e) => recordCall(name, principal.kind, start, { outcome: "refused", refusal: "InvalidPayload" }).pipe(Effect.as(failed(`InvalidPayload: ${e.message}`))),
46
+ onSuccess: (payload) => served.run(payload, principal).pipe(Effect.flatMap((answer) => encode(answer).pipe(Effect.orDie)), Effect.flatMap((wire) => Wire.held(op, payload, principal, op.answer, items).pipe(Effect.map((held) => {
47
+ const shown = shownAnswer(wire, op, Audience.agent(held));
48
+ return { isError: false, text: text(shown), structured: shown };
49
+ }))), Effect.catch((e) => Wire.held(op, payload, principal, ...(typeof e === "object" && e !== null ? [refusals.declared[String(e._tag)]?.fields ?? {}] : [])).pipe(Effect.map((held) => refusalOf(e, refusals, Audience.agent(held))), Effect.flatMap((result) => (result === undefined ? Effect.die(e) : Effect.succeed(result)))))),
50
+ }),
51
+ // A defect (the handler's bug, a store that failed) is the operator's to read in telemetry, never the caller's.
52
+ Effect.catchCause(() => Effect.succeed(failed(DEFECT))));
53
+ });
54
+ const output = outputSchema(op, items, entry.states);
55
+ return { name, description: entry.description, input: inputSchema(op.payloadSchema, op.payload), ...(output ? { output } : {}), ...(entry.move ? { move: entry.move } : {}), readOnly: op.kind === "read", call };
56
+ };
@@ -0,0 +1,2 @@
1
+ import type { McpApi } from "./types.ts";
2
+ export declare const Mcp: McpApi;
@@ -0,0 +1,38 @@
1
+ import { Server } from "@modelcontextprotocol/sdk/server/index.js";
2
+ import { WebStandardStreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js";
3
+ import { CfWorkerJsonSchemaValidator } from "@modelcontextprotocol/sdk/validation/cfworker";
4
+ import { CallToolRequestSchema, ErrorCode, ListToolsRequestSchema, McpError } from "@modelcontextprotocol/sdk/types.js";
5
+ import { admitsAgent } from "orthograph";
6
+ import { toolOf } from "./internal/tool.js";
7
+ export const Mcp = {
8
+ // Every tool of the catalog is served: a call is judged by `allowed`, so an agent that names a tool it is not shown is refused NotAllowed.
9
+ tools: ({ catalog, served, refusals }) => Object.entries(catalog).map(([name, entry]) => ({ ...toolOf(name, entry, served[name], refusals), agentTool: admitsAgent(entry.operation.allowed) })),
10
+ handle: ({ name, version, tools, principal, run }, request) => {
11
+ // Stateless: a server for this one request, no session id, no Durable Object, answered as plain JSON.
12
+ const server = new Server({ name, version }, { capabilities: { tools: {} }, jsonSchemaValidator: new CfWorkerJsonSchemaValidator() });
13
+ // An agent is shown the tools some `allowed` entry admits one to (M2-auth, fork 2): consent and a new credential are a person's own.
14
+ const shown = principal.kind === "agent" ? tools.filter((t) => t.agentTool !== false) : tools;
15
+ server.setRequestHandler(ListToolsRequestSchema, () => ({
16
+ tools: shown.map((t) => ({
17
+ name: t.name,
18
+ description: t.description,
19
+ inputSchema: t.input,
20
+ ...(t.move ? { _meta: { move: t.move } } : {}),
21
+ ...(t.output ? { outputSchema: t.output } : {}),
22
+ ...(t.readOnly ? { annotations: { readOnlyHint: true } } : {}),
23
+ })),
24
+ }));
25
+ server.setRequestHandler(CallToolRequestSchema, (call) => {
26
+ const tool = tools.find((t) => t.name === call.params.name);
27
+ if (!tool)
28
+ return Promise.reject(new McpError(ErrorCode.InvalidParams, `no tool ${call.params.name}`));
29
+ return run(tool.call(call.params.arguments ?? {}, principal)).then((r) => ({
30
+ isError: r.isError,
31
+ content: [{ type: "text", text: r.text }],
32
+ ...(r.structured ? { structuredContent: r.structured } : {}),
33
+ }));
34
+ });
35
+ const transport = new WebStandardStreamableHTTPServerTransport({ enableJsonResponse: true });
36
+ return server.connect(transport).then(() => transport.handleRequest(request));
37
+ },
38
+ };