@blueshed/joined 0.2.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/.claude/skills/joined/SKILL.md +9 -1
  2. package/.claude/skills/joined/reference.md +270 -55
  3. package/.claude/skills/joined-door/SKILL.md +57 -0
  4. package/README.md +19 -50
  5. package/docs/design.md +76 -10
  6. package/docs/introduction.md +18 -18
  7. package/docs/light-and-shadow.svg +1 -1
  8. package/examples/README.md +20 -0
  9. package/examples/account/account.json +1 -0
  10. package/examples/account/derive.ts +41 -0
  11. package/examples/account/generated/elements.ts +52 -0
  12. package/examples/account/generated/rows.ts +22 -0
  13. package/examples/account/generated/rules.ts +32 -0
  14. package/examples/account/routes.ts +5 -0
  15. package/examples/app.css +2 -1
  16. package/examples/cafe/books.html +2 -2
  17. package/examples/cafe/cafe.css +9 -16
  18. package/examples/cafe/generated/books.rows.ts +22 -0
  19. package/examples/cafe/generated/books.rules.ts +3 -2
  20. package/examples/cafe/generated/kitchen.rows.ts +27 -0
  21. package/examples/cafe/generated/kitchen.rules.ts +11 -1
  22. package/examples/cafe/generated/menu.rows.ts +22 -0
  23. package/examples/cafe/generated/menu.rules.ts +3 -2
  24. package/examples/cafe/generated/order.rows.ts +27 -0
  25. package/examples/cafe/generated/order.rules.ts +11 -1
  26. package/examples/cafe/generated/staff.rows.ts +22 -0
  27. package/examples/cafe/generated/staff.rules.ts +6 -1
  28. package/examples/cafe/generated/supplies.queries.ts +4 -2
  29. package/examples/cafe/generated/supplies.rows.ts +22 -0
  30. package/examples/cafe/generated/supplies.rules.ts +12 -1
  31. package/examples/cafe/generated/till.queries.ts +2 -0
  32. package/examples/cafe/generated/till.rows.ts +27 -0
  33. package/examples/cafe/generated/till.rules.ts +11 -1
  34. package/examples/cafe/index.html +14 -15
  35. package/examples/cafe/kitchen.ts +1 -1
  36. package/examples/cafe/look.ts +30 -0
  37. package/examples/cafe/menu.html +10 -26
  38. package/examples/cafe/menu.ts +8 -80
  39. package/examples/cafe/order.html +6 -6
  40. package/examples/cafe/order.ts +5 -1
  41. package/examples/cafe/routes.ts +0 -1
  42. package/examples/cafe/stories.jsonl +3 -1
  43. package/examples/cafe/supplies.html +34 -34
  44. package/examples/cafe/supplies.ts +14 -11
  45. package/examples/cafe/till.ts +5 -1
  46. package/examples/chart/arches.ts +148 -0
  47. package/examples/chart/chart.css +6 -0
  48. package/examples/chart/chart.json +87 -0
  49. package/examples/chart/generated/elements.ts +105 -0
  50. package/examples/chart/generated/queries.ts +36 -0
  51. package/examples/chart/generated/rows.ts +27 -0
  52. package/examples/chart/generated/rules.ts +111 -0
  53. package/examples/chart/grid.ts +118 -0
  54. package/examples/chart/index.html +78 -0
  55. package/examples/chart/migrations/001-chart.ts +6 -0
  56. package/examples/chart/migrations/002-create-conditions.ts +6 -0
  57. package/examples/chart/page.ts +20 -0
  58. package/examples/chart/routes.ts +7 -0
  59. package/examples/chart/stories.jsonl +14 -0
  60. package/examples/chart/teeth.ts +57 -0
  61. package/examples/desk/generated/rows.ts +22 -0
  62. package/examples/desk/generated/rules.ts +34 -1
  63. package/examples/desk/index.html +9 -2
  64. package/examples/desk/routes.ts +0 -2
  65. package/examples/desk/stories.jsonl +3 -2
  66. package/examples/desk/thumbs.ts +2 -2
  67. package/examples/hello/generated/elements.ts +2 -2
  68. package/examples/hello/generated/rules.ts +3 -2
  69. package/examples/hello/hello.css +2 -4
  70. package/examples/hello/index.html +10 -3
  71. package/examples/hello/page.ts +4 -4
  72. package/examples/index.html +4 -5
  73. package/examples/notes/generated/elements.ts +112 -0
  74. package/examples/notes/generated/queries.ts +36 -0
  75. package/examples/notes/generated/rows.ts +27 -0
  76. package/examples/notes/generated/rules.ts +133 -0
  77. package/examples/notes/index.html +32 -0
  78. package/examples/notes/look.ts +41 -0
  79. package/examples/notes/migrations/001-notes.ts +7 -0
  80. package/examples/notes/notes.json +78 -0
  81. package/examples/notes/page.ts +21 -0
  82. package/examples/notes/routes.ts +6 -0
  83. package/examples/notes/stories.jsonl +21 -0
  84. package/examples/people/generated/rows.ts +22 -0
  85. package/examples/people/generated/rules.ts +11 -1
  86. package/examples/people/links.ts +2 -1
  87. package/examples/people/routes.ts +1 -3
  88. package/examples/people/stories.jsonl +1 -0
  89. package/examples/people/view.ts +5 -2
  90. package/examples/trip/generated/elements.ts +4 -2
  91. package/examples/trip/generated/queries.ts +12 -1
  92. package/examples/trip/generated/rows.ts +27 -0
  93. package/examples/trip/generated/rules.ts +56 -2
  94. package/examples/trip/index.html +58 -12
  95. package/examples/trip/line.css +186 -0
  96. package/examples/trip/line.ts +51 -40
  97. package/examples/trip/page.ts +65 -71
  98. package/examples/trip/routes.ts +9 -5
  99. package/examples/trip/stays.css +12 -12
  100. package/examples/trip/stays.ts +15 -10
  101. package/examples/trip/stories.jsonl +2 -0
  102. package/examples/trip/told.ts +3 -26
  103. package/examples/trip/trip.css +16 -0
  104. package/examples/trips/generated/rows.ts +22 -0
  105. package/examples/trips/generated/rules.ts +9 -1
  106. package/examples/trips/index.html +10 -10
  107. package/examples/trips/map.ts +3 -14
  108. package/examples/trips/new-trip.ts +14 -16
  109. package/examples/weeks/generated/elements.ts +1 -1
  110. package/examples/weeks/generated/queries.ts +11 -0
  111. package/examples/weeks/generated/rows.ts +22 -0
  112. package/examples/weeks/generated/rules.ts +11 -5
  113. package/examples/weeks/routes.ts +3 -2
  114. package/examples/weeks/stories.jsonl +1 -0
  115. package/examples/welcome.css +7 -5
  116. package/package.json +8 -2
  117. package/src/awesome.ts +103 -0
  118. package/src/board.css +75 -0
  119. package/src/board.ts +173 -0
  120. package/src/cli.ts +15 -2
  121. package/src/compile.ts +569 -35
  122. package/src/definitions.ts +53 -15
  123. package/src/draft.ts +38 -23
  124. package/src/drawer.ts +222 -0
  125. package/src/engine.ts +240 -166
  126. package/src/fields.ts +268 -0
  127. package/src/files.ts +6 -4
  128. package/src/ground.ts +110 -0
  129. package/src/icon-names.ts +15 -2
  130. package/src/kit.ts +51 -0
  131. package/src/link.ts +3 -3
  132. package/src/map.css +133 -0
  133. package/src/map.ts +200 -0
  134. package/src/mcp.ts +176 -38
  135. package/src/members/demo.ts +13 -12
  136. package/src/members/generated/rows.ts +22 -0
  137. package/src/members/generated/rules.ts +3 -2
  138. package/src/members/group.ts +65 -39
  139. package/src/members/keys.ts +93 -77
  140. package/src/members/panel.css +23 -17
  141. package/src/members/panel.ts +49 -35
  142. package/src/migrate.ts +120 -104
  143. package/src/month.css +125 -0
  144. package/src/month.ts +179 -0
  145. package/src/page.css +8 -0
  146. package/src/page.ts +11 -7
  147. package/src/parts.css +462 -170
  148. package/src/parts.ts +209 -26
  149. package/src/plane.css +56 -0
  150. package/src/plane.ts +151 -0
  151. package/src/postgres-server.ts +60 -0
  152. package/src/reading.css +77 -0
  153. package/src/reading.ts +238 -0
  154. package/src/rows.css +308 -0
  155. package/src/rows.ts +780 -0
  156. package/src/search.css +80 -0
  157. package/src/search.ts +130 -0
  158. package/src/server.ts +211 -114
  159. package/src/settings.ts +9 -4
  160. package/src/sheet.ts +114 -0
  161. package/src/skill.ts +40 -0
  162. package/src/slots.css +94 -0
  163. package/src/slots.ts +213 -0
  164. package/src/specs.ts +38 -0
  165. package/src/starter.ts +5 -2
  166. package/src/store.ts +184 -143
  167. package/src/stories.ts +43 -11
  168. package/src/surface.ts +159 -0
  169. package/src/timeline.css +111 -0
  170. package/src/timeline.ts +226 -0
  171. package/src/toast.ts +21 -48
  172. package/src/together.ts +0 -7
  173. package/src/tokens.css +78 -1
  174. package/src/tokens.json +249 -0
  175. package/src/tool.ts +211 -0
  176. package/src/upkeep.ts +18 -20
  177. package/src/views.css +44 -0
  178. package/src/views.ts +94 -0
  179. package/src/week.css +151 -0
  180. package/src/week.ts +250 -0
  181. package/src/write.ts +219 -73
  182. package/starter/CLAUDE.md +3 -3
  183. package/starter/bunfig +4 -0
  184. package/starter/prettierignore +4 -0
  185. package/starter/tests/hello.test.ts +2 -0
  186. package/docs/learning.md +0 -76
  187. package/examples/cafe/trust.ts +0 -20
  188. package/examples/desk/trust.ts +0 -24
  189. package/examples/people/trust.ts +0 -14
  190. package/examples/trip/answer-rows.ts +0 -70
  191. package/examples/trip/bar.ts +0 -89
  192. package/examples/trip/calendar-map.css +0 -711
  193. package/examples/trip/calendar-map.ts +0 -249
  194. package/examples/trip/drags.ts +0 -143
  195. package/examples/trip/drawer.ts +0 -250
  196. package/examples/trip/event-form.ts +0 -200
  197. package/examples/trip/holding.ts +0 -61
  198. package/examples/trip/map.ts +0 -234
  199. package/examples/trip/month.ts +0 -87
  200. package/examples/trip/other-weeks.ts +0 -67
  201. package/examples/trip/peek.ts +0 -71
  202. package/examples/trip/people-chips.ts +0 -74
  203. package/examples/trip/shell.ts +0 -39
  204. package/examples/trip/trust.ts +0 -51
  205. package/examples/trip/week.ts +0 -237
  206. package/examples/trip/writes.ts +0 -91
  207. package/examples/trip/zones.ts +0 -16
  208. package/examples/weeks/derive.ts +0 -23
  209. package/src/scrim.ts +0 -81
package/src/map.ts ADDED
@@ -0,0 +1,200 @@
1
+ // <j-map for="plans" at="at"> (joined/kit): a collection on a map, OpenStreetMap's, each item with a place a pin there.
2
+ // It opens holding every pin, as near as they let it, and stays where a person moves it: dragged it pans, its buttons
3
+ // (or a pinch, or a trackpad's) bring it nearer and farther. A pin tapped is peeked: a card at the map's foot says
4
+ // what it is, when, and where, with Open (its sheet, in full) and Open in Maps; peek, then open in full. Held and
5
+ // dragged, a pin moves its item's place where its `may` lets it, and is put back if it's refused.
6
+
7
+ import { follow, held } from "./follow.ts";
8
+ import { hueOf } from "./hues.ts";
9
+ import { moves, tiles, type View } from "./ground.ts";
10
+ import { bounds, geo, mapsLink, placeAt, world } from "./geo.ts";
11
+ import { icon, iconButton } from "./icons.ts";
12
+ import { el, Reading } from "./reading.ts";
13
+ import type { Item } from "./rows.ts";
14
+ import { dated, dayOf } from "./time.ts";
15
+ import STYLE from "./map.css" with { type: "text" };
16
+
17
+ const SHEET = new CSSStyleSheet();
18
+ SHEET.replaceSync(STYLE);
19
+
20
+ export class JMap extends Reading {
21
+ static override sheets = [SHEET];
22
+ #map = el("div", { className: "map", role: "application", ariaLabel: "Map" });
23
+ #tiles = el("div", { className: "tiles", ariaHidden: "true" });
24
+ #peek = el("section", { className: "peek", hidden: true, ariaLive: "polite" });
25
+ #pins = new Map<Item, HTMLButtonElement>();
26
+ #view: View = { z: 0, x: 0, y: 0 };
27
+ /** Where a person moved it: kept, so the pins coming and going don't move it again. */
28
+ #moved = false;
29
+ #fitted = "";
30
+ #peeked: Item | null = null;
31
+ /** A press that pans it, from a finger that swipes from a pin. */
32
+ #press: (down: PointerEvent) => void = () => {};
33
+
34
+ get #at() {
35
+ return this.field("at") ?? this.spec?.fields.find((f) => f.type === "place");
36
+ }
37
+ protected made() {
38
+ const { zoom: step, press } = moves(
39
+ this.#map,
40
+ () => this.#view,
41
+ (v) => this.#look(v),
42
+ { not: ".pin, .peek, .zoom, a, button" },
43
+ );
44
+ this.#press = press;
45
+ const zoom = el(
46
+ "div",
47
+ { className: "zoom" },
48
+ iconButton("zoom-in", "Nearer", () => step(1)),
49
+ iconButton("zoom-out", "Farther", () => step(-1)),
50
+ );
51
+ const credit = el(
52
+ "small",
53
+ {},
54
+ "© ",
55
+ el("a", { href: "https://www.openstreetmap.org/copyright", target: "_blank", rel: "noopener" }, "OpenStreetMap"),
56
+ );
57
+ this.#map.append(this.#tiles, zoom, credit, this.#peek);
58
+ // a press on the ground lets a peek go
59
+ this.#map.addEventListener("pointerdown", (e) => {
60
+ if (!(e.target as Element).closest(".pin, .peek, .zoom, a, button")) this.#show(null);
61
+ });
62
+ new ResizeObserver(() => this.again()).observe(this.#map);
63
+ this.root.append(this.#map);
64
+ }
65
+ protected draw() {
66
+ const at = this.#at;
67
+ if (!at) return;
68
+ const placed = this.items().flatMap((it) => {
69
+ const p = geo(it.data[at.name]);
70
+ return p ? [{ it, p }] : [];
71
+ });
72
+ const W = this.#map.clientWidth,
73
+ H = this.#map.clientHeight;
74
+ if (!W || !H) return;
75
+ // fitted to every pin as near as they let it, until a person moves it
76
+ const fit = JSON.stringify([W, H, placed.map(({ p }) => [p.lat, p.lng])]);
77
+ if (!this.#moved && fit !== this.#fitted) {
78
+ this.#fitted = fit;
79
+ this.#view = { z: 2, x: 0, y: 0 };
80
+ if (placed.length)
81
+ for (let z = 16; z >= 1; z--) {
82
+ const [x0, x1, y0, y1] = bounds(placed.map(({ p }) => world(p.lat, p.lng, z)));
83
+ this.#view = { z, x: (x0 + x1) / 2 - W / 2, y: (y0 + y1) / 2 - H / 2 };
84
+ if (x1 - x0 <= W - 80 && y1 - y0 <= H - 80) break;
85
+ }
86
+ this.#look(this.#view, false);
87
+ }
88
+ for (const [it, pin] of this.#pins) if (!placed.some((p) => p.it === it)) (pin.remove(), this.#pins.delete(it));
89
+ for (const { it, p } of placed) {
90
+ let pin = this.#pins.get(it);
91
+ if (!pin) {
92
+ pin = el("button", { type: "button", className: "pin" });
93
+ this.#hold(pin, it);
94
+ this.#pins.set(it, pin);
95
+ this.#map.insertBefore(pin, this.#peek);
96
+ }
97
+ pin.style.setProperty("--hue", hueOf(it.key));
98
+ pin.ariaLabel = this.named(it);
99
+ pin.title = this.named(it);
100
+ pin.toggleAttribute("open", this.opened(it));
101
+ pin.toggleAttribute("peeked", this.#peeked === it);
102
+ this.#place(pin, p);
103
+ }
104
+ if (this.#peeked && !this.#pins.has(this.#peeked)) this.#show(null);
105
+ else if (this.#peeked) this.#show(this.#peeked);
106
+ }
107
+ /** A pin pressed: a tap peeks it; held (a mouse's at once), dragged, it moves its place where it may. */
108
+ #hold(pin: HTMLButtonElement, it: Item) {
109
+ pin.addEventListener("click", (e) => e.detail === 0 && this.#show(it));
110
+ pin.addEventListener("pointerdown", (down) => {
111
+ const at = this.#at!.name,
112
+ peek = () => this.#show(it);
113
+ if (!this.may(it, at)) return void pin.addEventListener("pointerup", peek, { once: true });
114
+ held(
115
+ down,
116
+ () => {
117
+ const r = this.#map.getBoundingClientRect();
118
+ let far = false;
119
+ pin.toggleAttribute("dragged", true);
120
+ follow(
121
+ down,
122
+ (e) => {
123
+ if (!far && Math.hypot(e.clientX - down.clientX, e.clientY - down.clientY) < 4) return;
124
+ far = true;
125
+ pin.style.left = `${e.clientX - r.left}px`;
126
+ pin.style.top = `${e.clientY - r.top}px`;
127
+ },
128
+ (e) => {
129
+ pin.toggleAttribute("dragged", false);
130
+ if (!far || !e) return (this.again(), e && peek());
131
+ const place = placeAt(this.#view.x + e.clientX - r.left, this.#view.y + e.clientY - r.top, this.#view.z);
132
+ void this.change(it, { [at]: place });
133
+ },
134
+ );
135
+ },
136
+ () => this.#press(down),
137
+ peek,
138
+ );
139
+ });
140
+ }
141
+ /** An item peeked, at the map's foot: what, when, where, and the ways on; or none. */
142
+ #show(it: Item | null) {
143
+ this.#peeked = it;
144
+ for (const [i, pin] of this.#pins) pin.toggleAttribute("peeked", i === it);
145
+ this.#peek.hidden = !it;
146
+ if (!it) return this.#peek.replaceChildren();
147
+ this.#peek.style.setProperty("--hue", hueOf(it.key));
148
+ const when = this.when,
149
+ place = it.data[this.#at!.name],
150
+ maps = mapsLink(place),
151
+ open = el("button", { type: "button", className: "act small ink" }, icon("grow"), "Open");
152
+ open.addEventListener("click", () => (this.open(it), this.#show(null)));
153
+ const w = when ? it.data[when.name] : undefined,
154
+ facts =
155
+ typeof w === "string"
156
+ ? [`${dated(dayOf(w), { weekday: "short", day: "numeric", month: "short" })}, ${w.slice(11, 16)}`]
157
+ : [];
158
+ this.#peek.replaceChildren(
159
+ el(
160
+ "header",
161
+ {},
162
+ el("b", {}, this.named(it)),
163
+ iconButton("close", "Close", () => this.#show(null)),
164
+ ),
165
+ el("p", {}, facts.join(" · ")),
166
+ el(
167
+ "footer",
168
+ {},
169
+ ...(maps
170
+ ? [
171
+ el(
172
+ "a",
173
+ { className: "act small", href: maps, target: "_blank", rel: "noopener" },
174
+ icon("place"),
175
+ "Open in Maps",
176
+ ),
177
+ ]
178
+ : []),
179
+ open,
180
+ ),
181
+ );
182
+ }
183
+ #place(pin: HTMLElement, p: { lat: number; lng: number }) {
184
+ const w = world(p.lat, p.lng, this.#view.z);
185
+ pin.style.left = `${w.x - this.#view.x}px`;
186
+ pin.style.top = `${w.y - this.#view.y}px`;
187
+ }
188
+ /** The map looking somewhere: its tiles there, and its pins. */
189
+ #look(view: View, moved = true) {
190
+ this.#view = view;
191
+ this.#moved ||= moved;
192
+ this.#tiles.replaceChildren(...tiles(view.z, view.x, view.y, this.#map.clientWidth, this.#map.clientHeight));
193
+ const at = this.#at?.name;
194
+ if (at)
195
+ for (const [it, pin] of this.#pins) {
196
+ const p = geo(it.data[at]);
197
+ if (p) this.#place(pin, p);
198
+ }
199
+ }
200
+ }
package/src/mcp.ts CHANGED
@@ -5,12 +5,18 @@
5
5
  // page does: each write its member's, via the agent, under the same rules (the app's trust.ts, the grants, the
6
6
  // group's), whole or not at all, and told to every page at once. Its tools are written from each document's compiled
7
7
  // rules, never the stories: read_<doc>, the document as its member sees it, and write_<doc>, one write, its ops typed
8
- // as the grants allow; a kind's (trip:1) take the instance's key. A window isn't a tool's: a document is read whole,
9
- // as its member sees it. Each app may give the agent its own words (its routes.ts's `instructions`), said as it opens.
8
+ // as the grants allow; a kind's (trip:1) take the instance's key. A window isn't a tool's: a document is read as its
9
+ // member sees it, whole or one collection's items (some, by id). How any document is read and written here is the
10
+ // door's own skill (src/skill.ts), served by MCP's skills extension, and said as it opens, then each app's own words
11
+ // (its routes.ts's `instructions`). It speaks both eras of MCP: the modern (2026-07-28), each request saying its
12
+ // version and the client's capabilities in its _meta, its headers checked against its body, server/discover in place
13
+ // of a handshake, and the skills extension declared; and the legacy, opened by initialize. To a client that loads
14
+ // skills itself the instructions say where the skill is; to any other, what it says.
10
15
 
11
16
  import { FORMS, SAID } from "./compile.ts";
17
+ import { skill, SKILLS } from "./skill.ts";
12
18
  import type { Who } from "./members/group.ts";
13
- import type { Op, Type } from "./ops.ts";
19
+ import { NTH, parts, type Op, type Type } from "./ops.ts";
14
20
  import type { Doc } from "./store.ts";
15
21
  import type { Rules } from "./write.ts";
16
22
 
@@ -23,8 +29,8 @@ type Door = {
23
29
  /** Where nobody's a member: anyone's, with no link, as a stranger's page is. */
24
30
  anyone?: boolean;
25
31
  /** Why a member may not hold a document (or it isn't there), or null. */
26
- holds(doc: string, member: number): string | null;
27
- read(doc: string, member: number): Doc;
32
+ holds(doc: string, member: number): Promise<string | null>;
33
+ read(doc: string, member: number): Promise<Doc>;
28
34
  /** A write by an agent's member; or, at a door that's anyone's, nobody's (null), as a stranger's page writes. */
29
35
  write(doc: string, ops: Op[], why: string | undefined, who: Who | null): Promise<Written>;
30
36
  instructions: string;
@@ -35,17 +41,52 @@ type Collection = Rules["collections"][string] & { needs?: readonly string[] };
35
41
  /** A tool's answer, as MCP says it: its words, and whether it's a refusal. */
36
42
  type Result = { content: { type: "text"; text: string }[]; isError?: true };
37
43
 
38
- /** The versions of MCP it speaks: the one a client asks, if it's one of these, else the newest. */
44
+ /** The versions of MCP it speaks: the modern, said on every request; and the legacy, opened by initialize (the one a
45
+ * client asks, if it's one of these, else the newest). */
46
+ const MODERN = ["2026-07-28"];
39
47
  const VERSIONS = ["2025-06-18", "2025-03-26", "2024-11-05"];
48
+ /** The prefix of what MCP itself names in a _meta. */
49
+ const MCP = "io.modelcontextprotocol/";
50
+ /** A JSON-RPC message, as it's posted. */
51
+ type Message = { id?: unknown; method?: string; params?: any };
52
+ /** What the modern HTTP transport has a request name in its Mcp-Name header, by its method. */
53
+ const NAMED: Record<string, string> = { "tools/call": "name", "resources/read": "uri", "prompts/get": "name" };
54
+
55
+ /** A header's value as it's meant: =?base64?…?= decoded (a name that isn't plain ASCII), anything else as it is. */
56
+ const decoded = (v: string | null) => {
57
+ const b64 = v && /^=\?base64\?(.*)\?=$/.exec(v)?.[1];
58
+ return b64 ? Buffer.from(b64, "base64").toString("utf8") : v;
59
+ };
60
+
61
+ /** Why a modern request's headers don't say what its body does (its version, its method, a call's or a read's name),
62
+ * or null: the transport refuses a mismatch, so nothing on the way acts on one thing and the door on another. */
63
+ function unheaded(req: Request, m: Message, version: string): string | null {
64
+ if (req.headers.get("mcp-protocol-version") !== version)
65
+ return `MCP-Protocol-Version isn't ${version}, as the request's _meta says`;
66
+ if (req.headers.get("mcp-method") !== m.method) return `Mcp-Method isn't ${m.method}, as the request says`;
67
+ const named = NAMED[m.method ?? ""];
68
+ if (named && decoded(req.headers.get("mcp-name")) !== m.params?.[named])
69
+ return `Mcp-Name isn't ${m.params?.[named]}, as the request's ${named} says`;
70
+ return null;
71
+ }
40
72
  const ID = "[1-9]\\d*";
41
73
 
42
74
  const answered = (value: unknown): Result => ({ content: [{ type: "text", text: JSON.stringify(value) }] });
43
75
  const refused = (why: string): Result => ({ content: [{ type: "text", text: why }], isError: true });
44
76
 
45
- /** A field's value, as its type says it: its JSON type, and a string's form and words, as the database holds it to. */
77
+ /** An id of a collection's: a number, or "$n", the nth add of the same write (anyOf, as a strict client's schema
78
+ * says either, never a list of types). */
79
+ const idOf = (of: string | undefined, said = `an id of ${of}`): Schema => ({
80
+ anyOf: [{ type: "integer" }, { type: "string", pattern: NTH.source, description: "$1: this write's first add" }],
81
+ description: said,
82
+ });
83
+
84
+ /** A field's value, as its type says it: its JSON type, and a string's form and words, as the database holds it to; a
85
+ * link, an id of what it links to. */
46
86
  function formOf(c: Collection, field: string): Schema {
47
87
  const t = c.fields[field] as Type;
48
- if (t === "ids") return { type: "array", items: { type: "integer" }, description: `ids of ${c.links[field]}` };
88
+ if (t === "ids") return { type: "array", items: idOf(c.links[field]), description: `ids of ${c.links[field]}` };
89
+ if (c.links?.[field]) return idOf(c.links[field]);
49
90
  const json = t === "boolean" ? "boolean" : t === "integer" ? "integer" : t === "decimal" ? "number" : "string";
50
91
  const form = FORMS[t as keyof typeof FORMS];
51
92
  return { type: json, description: SAID[t], ...(form ? { pattern: form.source } : {}) };
@@ -66,6 +107,9 @@ function itemOf(c: Collection): Schema {
66
107
  return { type: "object", properties, required: (c.needs ?? []).filter((f) => !filled.includes(f)) };
67
108
  }
68
109
 
110
+ /** A document's own fields, as a collection's. */
111
+ const ownOf = (r: Rules) => Object.values(r.collections).find((c) => c.own) as Collection;
112
+
69
113
  /** Each op a write may hold, read off a document's grants: the op on its path's form (`replace /events/{id}/title`), the
70
114
  * pattern its path matches, and the value it takes; an add by a first step (`add posts.status:>waiting`), what it
71
115
  * gives (`status waiting`). */
@@ -78,10 +122,7 @@ function opsOf(r: Rules): { op: string; path: string; pattern: string; value?: S
78
122
  [coll, rest] = dot < 0 ? [of, ""] : [of.slice(0, dot), of.slice(dot + 1)];
79
123
  const c = r.collections[coll] as Collection | undefined;
80
124
  // a document's own field, at its top (/greeting)
81
- if (!c) {
82
- const own = Object.values(r.collections).find((c) => c.own) as Collection;
83
- return { op, path: `/${of}`, pattern: `^/${of}$`, value: formOf(own, of) };
84
- }
125
+ if (!c) return { op, path: `/${of}`, pattern: `^/${of}$`, value: formOf(ownOf(r), of) };
85
126
  if (!rest)
86
127
  return op === "add"
87
128
  ? { op, path: `/${coll}/-`, pattern: `^/${coll}/-$`, value: itemOf(c) }
@@ -94,7 +135,7 @@ function opsOf(r: Rules): { op: string; path: string; pattern: string; value?: S
94
135
  op,
95
136
  path: `/${coll}/{id}/${f}/-`,
96
137
  pattern: `^/${coll}/${ID}/${f}/-$`,
97
- value: { type: "integer", description: `an id of ${c.links[f]}` },
138
+ value: idOf(c.links[f]),
98
139
  }
99
140
  : { op, path: `/${coll}/{id}/${f}/{its id}`, pattern: `^/${coll}/${ID}/${f}/${ID}$` };
100
141
  }
@@ -105,11 +146,11 @@ function opsOf(r: Rules): { op: string; path: string; pattern: string; value?: S
105
146
  // an add by its field's first step: an item, giving that step
106
147
  if (op === "add") {
107
148
  const item = itemOf(c);
108
- const value = { ...item, properties: { ...(item.properties as object), [field]: { const: to } } };
149
+ const value = { ...item, properties: { ...(item.properties as object), [field]: { enum: [to] } } };
109
150
  return { op, path: `/${coll}/-`, pattern: `^/${coll}/-$`, value, gives: `${field} ${to}` };
110
151
  }
111
152
  const value =
112
- op === "remove" ? undefined : step ? { const: to, description: `only from ${from}` } : formOf(c, field);
153
+ op === "remove" ? undefined : step ? { enum: [to], description: `only from ${from}` } : formOf(c, field);
113
154
  return { op, path: `/${coll}/{id}/${at}`, pattern: `^/${coll}/${ID}/${at}$`, ...(value ? { value } : {}) };
114
155
  });
115
156
  }
@@ -125,6 +166,36 @@ const described = (r: Rules) =>
125
166
  )
126
167
  .join("; ");
127
168
 
169
+ /** A write's ops as a small model sends them: an object or a list given for a string field (a bag of pairs) is said as
170
+ * its JSON text, as the field holds it; anything else is left for the write to refuse in its words. */
171
+ function texted(r: Rules, ops: Op[]): Op[] {
172
+ const text = (c: Collection | undefined, f: string, v: unknown) =>
173
+ c?.fields[f] === "string" && v !== null && typeof v === "object" ? JSON.stringify(v) : v;
174
+ return ops.map((o) => {
175
+ if (!o || typeof o !== "object" || !("value" in o) || typeof o.path !== "string") return o;
176
+ const { coll, key, field, link } = parts(o.path),
177
+ c = r.collections[coll] as Collection | undefined;
178
+ // a document's own field, at its top (/greeting)
179
+ if (!c) return { ...o, value: text(ownOf(r), coll, o.value) } as Op;
180
+ if (key === "-" && field === undefined && o.value && typeof o.value === "object" && !Array.isArray(o.value))
181
+ return {
182
+ ...o,
183
+ value: Object.fromEntries(Object.entries(o.value).map(([f, v]) => [f, text(c, f, v)])),
184
+ } as Op;
185
+ return field !== undefined && link === undefined ? ({ ...o, value: text(c, field, o.value) } as Op) : o;
186
+ });
187
+ }
188
+
189
+ /** What a read asks for: a collection's items alone, and of those only the ids named; else the whole document. */
190
+ function readOf(doc: Doc, args: { collection?: unknown; ids?: unknown }): Doc | string {
191
+ if (args.collection === undefined) return doc;
192
+ const coll = String(args.collection),
193
+ items = (doc as Record<string, unknown>)[coll];
194
+ if (!Array.isArray(items)) return `it has no ${coll}`;
195
+ const ids = Array.isArray(args.ids) ? new Set(args.ids.map(Number)) : null;
196
+ return { version: doc.version, [coll]: ids ? items.filter((i) => ids.has(i.id)) : items } as Doc;
197
+ }
198
+
128
199
  /** Who comes to a door that's anyone's: nobody, as a stranger's page is. */
129
200
  const ANYONE: Who = { member: 0, token: "" };
130
201
 
@@ -134,7 +205,7 @@ export function door(d: Door) {
134
205
  const fail = (id: unknown, code: number, message: string) => ({ jsonrpc: "2.0", id, error: { code, message } });
135
206
 
136
207
  /** The tools for a member's agent: each document's read and, where pages write it, its write; a kind's take its key. */
137
- function toolsFor(who: Who) {
208
+ async function toolsFor(who: Who) {
138
209
  const tools: {
139
210
  name: string;
140
211
  description: string;
@@ -144,17 +215,32 @@ export function door(d: Door) {
144
215
  for (const r of d.rules) {
145
216
  // the document a call names: a kind's instance by its key (trip:1), or the one
146
217
  const name = (args: { key?: unknown }) => (r.kind ? `${r.doc}:${args.key}` : r.doc);
147
- if (!r.kind && d.holds(r.doc, who.member)) continue;
218
+ if (!r.kind && (await d.holds(r.doc, who.member))) continue;
148
219
  const key = r.kind
149
220
  ? { key: { type: "integer", description: `which ${r.doc}: the id of one of ${r.kind.doc}'s ${r.kind.root}` } }
150
221
  : {};
222
+ const colls = Object.entries(r.collections)
223
+ .filter(([, c]) => !c.own)
224
+ .map(([n]) => n);
225
+ const part = colls.length
226
+ ? {
227
+ collection: { type: "string", enum: colls, description: "only this collection's items (a big document)" },
228
+ ids: {
229
+ type: "array",
230
+ items: { type: "integer" },
231
+ description: "only these of the collection's items, by id",
232
+ },
233
+ }
234
+ : {};
151
235
  tools.push({
152
236
  name: `read_${r.doc}`,
153
- description: `Read ${r.doc}, as you see it, with its version. It holds ${described(r)}.`,
154
- inputSchema: { type: "object", properties: key, required: Object.keys(key) },
155
- run: (args) => {
156
- const no = d.holds(name(args), who.member);
157
- return no ? refused(no) : answered(d.read(name(args), who.member));
237
+ description: `Read ${r.doc}, as you see it, with its version${colls.length ? `: whole, or one collection's items, or some of them by id` : ""}. It holds ${described(r)}.`,
238
+ inputSchema: { type: "object", properties: { ...key, ...part }, required: Object.keys(key) },
239
+ run: async (args) => {
240
+ const no = await d.holds(name(args), who.member);
241
+ if (no) return refused(no);
242
+ const read = readOf(await d.read(name(args), who.member), args);
243
+ return typeof read === "string" ? refused(read) : answered(read);
158
244
  },
159
245
  });
160
246
  const ops = opsOf(r);
@@ -172,10 +258,10 @@ export function door(d: Door) {
172
258
  type: "array",
173
259
  minItems: 1,
174
260
  items: {
175
- oneOf: ops.map((o) => ({
261
+ anyOf: ops.map((o) => ({
176
262
  type: "object",
177
263
  properties: {
178
- op: { const: o.op },
264
+ op: { type: "string", enum: [o.op] },
179
265
  path: { type: "string", pattern: o.pattern, description: said(o) },
180
266
  ...(o.value ? { value: o.value } : {}),
181
267
  },
@@ -190,11 +276,11 @@ export function door(d: Door) {
190
276
  run: async (args) => {
191
277
  if (!Array.isArray(args.ops) || !args.ops.length)
192
278
  return refused("ops: one write's ops, a list of at least one");
193
- const no = d.holds(name(args), who.member);
279
+ const no = await d.holds(name(args), who.member);
194
280
  if (no) return refused(no);
195
281
  const w = await d.write(
196
282
  name(args),
197
- args.ops,
283
+ texted(r, args.ops),
198
284
  typeof args.why === "string" ? args.why.trim() || undefined : undefined,
199
285
  d.anyone ? null : who,
200
286
  );
@@ -205,22 +291,52 @@ export function door(d: Door) {
205
291
  return tools;
206
292
  }
207
293
 
208
- /** One message: answered, or a notification (no id), which isn't. */
209
- async function one(m: { id?: unknown; method?: string; params?: any }, who: Who) {
294
+ /** One message, in its era: answered, or a notification (no id), which isn't. A modern answer says it's complete,
295
+ * and where it may be kept a while, for how long (none: the grants can change) and for whom. */
296
+ async function one(m: Message, who: Who, modern: boolean) {
210
297
  if (m.id === undefined) return null;
211
- if (m.method === "initialize")
298
+ const done = (result: object, kept?: "public" | "private") =>
299
+ rpc(
300
+ m.id,
301
+ modern ? { resultType: "complete", ...result, ...(kept ? { ttlMs: 0, cacheScope: kept } : {}) } : result,
302
+ );
303
+ // to a client that loads skills itself (it says so in the request's capabilities), where the skill is
304
+ const loads = !!m.params?._meta?.[`${MCP}clientCapabilities`]?.extensions?.[SKILLS];
305
+ const instructions = [loads ? skill.pointer : skill.body, d.instructions].filter(Boolean).join("\n\n");
306
+ if (modern && m.method === "server/discover")
307
+ return done(
308
+ {
309
+ supportedVersions: MODERN,
310
+ capabilities: { tools: {}, resources: {}, extensions: { [SKILLS]: {} } },
311
+ _meta: { [`${MCP}serverInfo`]: { name: "joined", version: d.version } },
312
+ instructions,
313
+ },
314
+ "private",
315
+ );
316
+ if (!modern && m.method === "initialize")
212
317
  return rpc(m.id, {
213
318
  protocolVersion: VERSIONS.includes(m.params?.protocolVersion) ? m.params.protocolVersion : VERSIONS[0],
214
- capabilities: { tools: {} },
319
+ capabilities: { tools: {}, resources: {} },
215
320
  serverInfo: { name: "joined", version: d.version },
216
- ...(d.instructions ? { instructions: d.instructions } : {}),
321
+ instructions,
217
322
  });
218
- if (m.method === "ping") return rpc(m.id, {});
219
- if (m.method === "tools/list") return rpc(m.id, { tools: toolsFor(who).map(({ run: _, ...t }) => t) });
323
+ if (!modern && m.method === "ping") return rpc(m.id, {});
324
+ if (m.method === "resources/list") return done({ resources: [skill.resource] }, "public");
325
+ if (m.method === "resources/read")
326
+ return m.params?.uri === skill.uri
327
+ ? done({ contents: [{ uri: skill.uri, mimeType: "text/markdown", text: skill.text }] }, "public")
328
+ : fail(m.id, -32602, `there's no resource at ${m.params?.uri}`);
329
+ if (modern && m.method === "skills/list") return done({ skills: [skill.entry] }, "public");
330
+ if (modern && m.method === "skills/get")
331
+ return m.params?.uri === skill.uri
332
+ ? done({ skill: skill.entry }, "public")
333
+ : fail(m.id, -32602, `No skill is served at ${m.params?.uri}`);
334
+ if (m.method === "tools/list")
335
+ return done({ tools: (await toolsFor(who)).map(({ run: _, ...t }) => t) }, "private");
220
336
  if (m.method === "tools/call") {
221
- const tool = toolsFor(who).find((t) => t.name === m.params?.name);
337
+ const tool = (await toolsFor(who)).find((t) => t.name === m.params?.name);
222
338
  return tool
223
- ? rpc(m.id, await tool.run(m.params.arguments ?? {}))
339
+ ? done(await tool.run(m.params.arguments ?? {}))
224
340
  : fail(m.id, -32602, `no tool called ${m.params?.name}`);
225
341
  }
226
342
  return fail(m.id, -32601, `no method called ${m.method}`);
@@ -238,15 +354,37 @@ export function door(d: Door) {
238
354
  status: 401,
239
355
  },
240
356
  );
241
- const m = await req.json().catch(() => undefined);
357
+ const m: Message | undefined = await req.json().catch(() => undefined);
242
358
  if (!m || typeof m !== "object")
243
359
  return Response.json(fail(null, -32700, "that isn't a JSON-RPC message"), { status: 400 });
360
+ // modern, where the request says its version in its _meta: its headers saying the same, and a version it speaks
361
+ const version = m.params?._meta?.[`${MCP}protocolVersion`];
362
+ if (version !== undefined) {
363
+ const why = unheaded(req, m, String(version));
364
+ if (why) return Response.json(fail(m.id ?? null, -32020, `Header mismatch: ${why}`), { status: 400 });
365
+ if (!MODERN.includes(version))
366
+ return Response.json(
367
+ {
368
+ jsonrpc: "2.0",
369
+ id: m.id ?? null,
370
+ error: {
371
+ code: -32022,
372
+ message: "Unsupported protocol version",
373
+ data: { supported: MODERN, requested: version },
374
+ },
375
+ },
376
+ { status: 400 },
377
+ );
378
+ }
244
379
  // never thrown: Bun's line for a request that throws names its URL, and the URL holds the agent's token
245
- const answer = await one(m, who!).catch((e) => {
380
+ const answer = await one(m, who!, version !== undefined).catch((e) => {
246
381
  console.error("the MCP door failed:", e);
247
382
  return fail(m.id ?? null, -32603, "That wasn't done: the server had a problem with it.");
248
383
  });
249
- return answer ? Response.json(answer) : new Response(null, { status: 202 });
384
+ if (!answer) return new Response(null, { status: 202 });
385
+ // a method it hasn't, to a modern request, is a 404 (a legacy one's is answered as any error is)
386
+ const missing = version !== undefined && "error" in answer && answer.error.code === -32601;
387
+ return Response.json(answer, missing ? { status: 404 } : undefined);
250
388
  },
251
389
  };
252
390
  }
@@ -26,26 +26,27 @@ export function demoRoutes({
26
26
  signIn,
27
27
  }: {
28
28
  here: (req: Request) => boolean;
29
- members: () => Member[];
30
- bdfl: () => number;
29
+ members: () => Promise<Member[]>;
30
+ bdfl: () => Promise<number>;
31
31
  me: (req: Request) => Promise<number | null>;
32
32
  signIn: (req: Request, member: number) => Promise<Response>;
33
33
  }) {
34
34
  const refused = () => new Response("a demo answers this machine alone", { status: 403 });
35
35
  return {
36
- "/as": async (req: Request) =>
37
- here(req)
38
- ? Response.json({
39
- me: await me(req),
40
- people: [...members()]
41
- .sort((a, b) => Number(b.id === bdfl()) - Number(a.id === bdfl()))
42
- .map((m) => ({ id: m.id, name: m.name, bdfl: m.id === bdfl() })),
43
- })
44
- : refused(),
36
+ "/as": async (req: Request) => {
37
+ if (!here(req)) return refused();
38
+ const top = await bdfl();
39
+ return Response.json({
40
+ me: await me(req),
41
+ people: [...(await members())]
42
+ .sort((a, b) => Number(b.id === top) - Number(a.id === top))
43
+ .map((m) => ({ id: m.id, name: m.name, bdfl: m.id === top })),
44
+ });
45
+ },
45
46
  "/as/:member": async (req: Bun.BunRequest<"/as/:member">) => {
46
47
  const member = Number(req.params.member);
47
48
  if (!here(req)) return refused();
48
- return members().some((m) => m.id === member)
49
+ return (await members()).some((m) => m.id === member)
49
50
  ? signIn(req, member)
50
51
  : new Response("no such member", { status: 404 });
51
52
  },
@@ -0,0 +1,22 @@
1
+ // Written by src/compile.ts from src/members/stories.jsonl: change the stories, not this.
2
+
3
+ // Each collection of members as rows (joined/rows, the skill's §3): a page defines the ones it shows, as they are or
4
+ // extended, by define() from joined/rows, and holds each collection's element in its rows:
5
+ // <j-members-rows><j-members></j-members></j-members-rows>
6
+ // A collection whose items are each of one of another's is drawn under it there, where its element is put in too.
7
+ // To change what one says or does, extend its class and override a part (label, named, says, facts, deeds, row,
8
+ // step, asks); to change how it looks, style its parts (::part(row), title, state, facts, deeds, mine, step, add,
9
+ // under, drawer). Its sheet, a search of it and how a field reads are joined/kit's, given these collections by
10
+ // use(specs) (define() gives a display's own). To draw something else altogether, don't define it: a display of the app's own holds the same
11
+ // elements. Never change this file: change the stories.
12
+
13
+ import { rows, type Spec } from "joined/rows";
14
+ import { JMember } from "./elements.ts";
15
+
16
+ const members: Spec = {"doc":"members","name":"members","place":"j-members","tag":"j-member","one":"member","title":"name","fields":[{"name":"name","type":"string","needed":true},{"name":"inviter","type":"integer","needed":true},{"name":"act","type":"string"},{"name":"readonly","type":"integer"}]};
17
+
18
+ /** Each collection as joined's kit (joined/kit) is given it, by name: use(specs). */
19
+ export const specs = { "members": members };
20
+
21
+ /** <j-members-rows>: members's members as rows, each named by its name. */
22
+ export class JMembersRows extends rows(members, { "j-member": JMember }) {}
@@ -3,7 +3,7 @@
3
3
  export type Op = { op: "add" | "replace" | "remove"; path: string; value?: any };
4
4
 
5
5
  /** The document, and each collection: its element, the element its items are, their fields, those an add needs, and
6
- * what each link is to. */
6
+ * what each link is to and what each field pops (a value with a form, its view; a reference, what it points at). */
7
7
  export const doc = "members";
8
8
  export const collections = {
9
9
  "members": {
@@ -19,7 +19,8 @@ export const collections = {
19
19
  "name",
20
20
  "inviter"
21
21
  ],
22
- "links": {}
22
+ "links": {},
23
+ "pops": {}
23
24
  }
24
25
  } as const;
25
26
  /** Whether every story is anonymous, none told as a member: where every app's is, the project has no members. */