@blueshed/joined 0.3.3 → 0.3.5
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/.claude/skills/joined/reference.md +23 -8
- package/.claude/skills/joined-door/SKILL.md +17 -2
- package/docs/introduction.md +6 -2
- package/examples/cafe/migrations/003-guard-supplies.ts +6 -0
- package/examples/index.html +2 -2
- package/examples/trip/stories.jsonl +1 -0
- package/package.json +1 -1
- package/src/attachment.ts +2 -2
- package/src/compile.ts +45 -9
- package/src/drawer.ts +18 -2
- package/src/engine.ts +11 -2
- package/src/file-value.ts +4 -3
- package/src/files.ts +2 -7
- package/src/ics.ts +1 -1
- package/src/link.ts +11 -6
- package/src/map.ts +2 -1
- package/src/mcp.ts +102 -36
- package/src/members/demo.ts +6 -3
- package/src/members/group.ts +2 -1
- package/src/migrate.ts +125 -24
- package/src/page.ts +42 -37
- package/src/postgres-server.ts +69 -14
- package/src/proxy.ts +12 -0
- package/src/reading.ts +21 -3
- package/src/server.ts +57 -28
- package/src/skill.ts +100 -33
- package/src/store.ts +27 -18
- package/src/upkeep.ts +9 -8
- package/src/upload.ts +136 -0
- package/src/write.ts +71 -21
package/src/page.ts
CHANGED
|
@@ -431,38 +431,44 @@ function apply(held: Map<string, Held>, o: Op): Element | undefined {
|
|
|
431
431
|
const ids = (el?.getAttribute(field!) ?? "").split(" ").filter(Boolean).map(Number);
|
|
432
432
|
if (el) set(el, "ids", field!, o.op === "add" ? [...ids, o.value] : ids.filter((id) => id !== Number(link)));
|
|
433
433
|
} else if (o.op === "add") placed(h, element(h, o.value));
|
|
434
|
-
else if (o.op === "remove"
|
|
435
|
-
else if (el)
|
|
434
|
+
else if (o.op === "remove" && !field) (el?.remove(), h.items.delete(key!));
|
|
435
|
+
else if (el) {
|
|
436
|
+
set(el, h.fields[field!], field!, o.op === "remove" ? undefined : o.value);
|
|
437
|
+
if (field === h.order) placed(h, el);
|
|
438
|
+
}
|
|
436
439
|
return h.items.get(o.op === "add" && field === undefined ? String(o.value.id) : key!);
|
|
437
440
|
}
|
|
438
441
|
|
|
439
|
-
/** An item put where it goes:
|
|
440
|
-
*
|
|
442
|
+
/** An item put where it goes: after the last that ranks before it, found from the end, where most are added. The
|
|
443
|
+
* others are in their order already. */
|
|
441
444
|
function placed(h: Held, el: Element) {
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
if (after
|
|
452
|
-
h.el.insertBefore(el, after ?? null);
|
|
445
|
+
const [rank, key] = rankOf(h, el);
|
|
446
|
+
let before = h.el.lastElementChild;
|
|
447
|
+
for (; before; before = before.previousElementSibling) {
|
|
448
|
+
if (before === el) continue;
|
|
449
|
+
const [r, k] = rankOf(h, before);
|
|
450
|
+
if (r < rank || (r === rank && k < key)) break;
|
|
451
|
+
}
|
|
452
|
+
// moved only if it isn't there already
|
|
453
|
+
const after = before ? before.nextElementSibling : h.el.firstElementChild;
|
|
454
|
+
if (after !== el) h.el.insertBefore(el, after);
|
|
453
455
|
}
|
|
454
456
|
|
|
455
|
-
/** Where an item ranks
|
|
456
|
-
const rankOf = (h: Held, el: Element) =>
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
457
|
+
/** Where an item ranks: by its collection's order (without one, or a place in it, by its key), then by its key. */
|
|
458
|
+
const rankOf = (h: Held, el: Element) => {
|
|
459
|
+
const key = Number(el.getAttribute("key"));
|
|
460
|
+
return [Number((h.order && el.getAttribute(h.order)) ?? key), key] as const;
|
|
461
|
+
};
|
|
462
|
+
|
|
463
|
+
/** A collection's items all put in their order: its own, each one's rank read once, or as they're given. The longest
|
|
464
|
+
* run of them in order already stays where it is, and only the rest are moved, each before the next that stays. */
|
|
465
|
+
function inOrder(h: Held, items: Element[]) {
|
|
466
|
+
const want = h.order
|
|
467
|
+
? items
|
|
468
|
+
.map((el) => ({ el, at: rankOf(h, el) }))
|
|
469
|
+
.sort((a, b) => a.at[0] - b.at[0] || a.at[1] - b.at[1])
|
|
470
|
+
.map(({ el }) => el)
|
|
471
|
+
: items;
|
|
466
472
|
const now = new Map([...h.el.children].map((el, i) => [el, i]));
|
|
467
473
|
// the longest run: for each length, the item one so long ends with (the earliest on the page), and for each item the
|
|
468
474
|
// one before it in its run
|
|
@@ -496,18 +502,17 @@ function inOrder(h: Held) {
|
|
|
496
502
|
/** A collection, whole, as the document has it: each item kept by key and changed only where it
|
|
497
503
|
* differs, those gone taken away, and those new added. */
|
|
498
504
|
function whole(h: Held, items: Record<string, unknown>[]) {
|
|
499
|
-
const gone = new Set(h.items.keys())
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
const
|
|
505
|
-
|
|
506
|
-
}
|
|
507
|
-
gone.delete(String(item.id));
|
|
508
|
-
}
|
|
505
|
+
const gone = new Set(h.items.keys()),
|
|
506
|
+
given = items.map((item) => {
|
|
507
|
+
const el = h.items.get(String(item.id));
|
|
508
|
+
gone.delete(String(item.id));
|
|
509
|
+
if (!el) return element(h, item);
|
|
510
|
+
for (const [field, type] of Object.entries(h.fields)) set(el, type, field, valueAt(item, field));
|
|
511
|
+
return el;
|
|
512
|
+
});
|
|
509
513
|
for (const key of gone) (h.items.get(key)!.remove(), h.items.delete(key));
|
|
510
|
-
|
|
514
|
+
// (a document's own element holds no items)
|
|
515
|
+
if (!h.own) inOrder(h, given);
|
|
511
516
|
}
|
|
512
517
|
|
|
513
518
|
function element({ tag, fields, items, may }: Held, item: Record<string, unknown>) {
|
package/src/postgres-server.ts
CHANGED
|
@@ -3,6 +3,9 @@
|
|
|
3
3
|
|
|
4
4
|
import { postgresOf, type Engine } from "./engine.ts";
|
|
5
5
|
|
|
6
|
+
/** What Bun.sql calls no answer at all: its connection closed, reset, or timed out. */
|
|
7
|
+
const GONE = /^(ERR_POSTGRES_(CONNECTION|IDLE|LIFETIME)|ECONN|EPIPE)/;
|
|
8
|
+
|
|
6
9
|
/** A Postgres server, by its URL (JOINED_POSTGRES: postgres://user:password@host:port/database), through Bun.sql: one
|
|
7
10
|
* connection held for the store, and LISTEN on a connection of its own. `fresh`: a database of its own, made as it
|
|
8
11
|
* opens and dropped as it closes (a test's). */
|
|
@@ -20,33 +23,85 @@ export async function server(url: string, { fresh = false } = {}): Promise<Engin
|
|
|
20
23
|
}
|
|
21
24
|
at.pathname = `/${made}`;
|
|
22
25
|
}
|
|
26
|
+
// (a connection lost isn't given back to a pool that may hand it out again: each is a pool of its own, of one)
|
|
23
27
|
const sql = new SQL(at.href, { max: 2 });
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
28
|
+
const hold = async () => {
|
|
29
|
+
const pool = new SQL(at.href, { max: 1 });
|
|
30
|
+
try {
|
|
31
|
+
return { pool, held: await pool.reserve() };
|
|
32
|
+
} catch (e) {
|
|
33
|
+
await pool.close();
|
|
34
|
+
throw e;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
let { pool, held } = await hold();
|
|
38
|
+
// the connection lost (the server restarted, a network gone): another is made in its place as the next thing is asked,
|
|
39
|
+
// with what's the connection's own. What was asked is asked again only where that's safe: a transaction begun, or a
|
|
40
|
+
// read outside one. A transaction it was lost in is refused whole, however much of it is still asked. (Bun listens
|
|
41
|
+
// again by itself.)
|
|
42
|
+
const own: string[] = [];
|
|
43
|
+
let lost = false,
|
|
44
|
+
within = false,
|
|
45
|
+
making: Promise<void> | undefined;
|
|
46
|
+
const on = async <T>(text: string, ask: () => Promise<T>): Promise<T | undefined> => {
|
|
47
|
+
const ends = /^(COMMIT|ROLLBACK)$/.test(text);
|
|
48
|
+
if (lost && within) {
|
|
49
|
+
if (ends) within = false;
|
|
50
|
+
if (/^ROLLBACK/.test(text)) return undefined;
|
|
51
|
+
throw new Error("the database's connection was lost in the middle of a write: none of it was made");
|
|
52
|
+
}
|
|
53
|
+
for (let again = false; ; again = true) {
|
|
54
|
+
// (one made, however much is asked meanwhile)
|
|
55
|
+
if (lost)
|
|
56
|
+
await (making ??= (async () => {
|
|
57
|
+
const [gone, was] = [pool, held];
|
|
58
|
+
({ pool, held } = await hold());
|
|
59
|
+
for (const s of own) await held.unsafe(s);
|
|
60
|
+
lost = false;
|
|
61
|
+
// (not waited for: nothing answers it)
|
|
62
|
+
was.release();
|
|
63
|
+
void gone.close({ timeout: 0 }).catch(() => {});
|
|
64
|
+
})().finally(() => (making = undefined)));
|
|
65
|
+
const asked = held;
|
|
66
|
+
try {
|
|
67
|
+
const answer = await ask();
|
|
68
|
+
if (text === "BEGIN") within = true;
|
|
69
|
+
if (ends) within = false;
|
|
70
|
+
return answer;
|
|
71
|
+
} catch (e) {
|
|
72
|
+
// refused by a server that's going (57P…), or by no server at all
|
|
73
|
+
const { errno, code } = e as { errno?: unknown; code?: string };
|
|
74
|
+
const gone = /^(57P|08)/.test(String(errno)) || GONE.test(String(code));
|
|
75
|
+
// (said by one another has taken the place of already, it's said of that one alone)
|
|
76
|
+
if (gone && asked === held) lost = true;
|
|
77
|
+
if (!gone || again || within || !/^(BEGIN$|SELECT\b)/.test(text)) {
|
|
78
|
+
if (ends) within = false;
|
|
79
|
+
throw e;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
};
|
|
31
84
|
const types = (columns: unknown) =>
|
|
32
85
|
new Map(((columns as { name: string; type: number }[] | undefined) ?? []).map((f) => [f.name, f.type]));
|
|
33
86
|
return postgresOf(
|
|
34
87
|
{
|
|
35
88
|
async query(text, values) {
|
|
36
|
-
const r = (await held.unsafe(text, values as never[])) as unknown as
|
|
37
|
-
count: number | null;
|
|
38
|
-
|
|
39
|
-
};
|
|
89
|
+
const r = (await on(text, async () => held.unsafe(text, values as never[]))) as unknown as
|
|
90
|
+
(Record<string, unknown>[] & { count: number | null; columns?: unknown }) | undefined;
|
|
91
|
+
if (!r) return { rows: [], changes: 0, types: new Map() };
|
|
40
92
|
return { rows: [...r], changes: r.count ?? 0, types: types(r.columns) };
|
|
41
93
|
},
|
|
42
|
-
many: (text) => held.unsafe(text).simple(),
|
|
94
|
+
many: (text) => on(text, async () => held.unsafe(text).simple()),
|
|
43
95
|
},
|
|
44
96
|
{
|
|
45
97
|
listen: async (channel, heard) => void (await sql.listen(channel, heard)),
|
|
98
|
+
each: (text) => (own.push(text), on(text, async () => held.unsafe(text))),
|
|
46
99
|
notify: (channel, payload) => held.unsafe("SELECT pg_notify($1, $2)", [channel, payload]),
|
|
47
100
|
async close() {
|
|
48
|
-
|
|
49
|
-
|
|
101
|
+
await making?.catch(() => {});
|
|
102
|
+
if (!lost) held.release();
|
|
103
|
+
await pool.close({ timeout: 1 });
|
|
104
|
+
await sql.close({ timeout: 1 });
|
|
50
105
|
if (!made) return;
|
|
51
106
|
const admin = new SQL(url, { max: 1 });
|
|
52
107
|
try {
|
package/src/proxy.ts
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// What a proxy in front (Railway's) says of a request it passed on: joined itself is asked over http, on this machine.
|
|
2
|
+
// Anyone may say it; nothing is let in by it: an https said falsely only keeps the speaker's own cookie to https.
|
|
3
|
+
|
|
4
|
+
/** The scheme a request came by: the first a proxy says, being the one nearest the person, else its own URL's. */
|
|
5
|
+
export const schemeOf = (req: Request) =>
|
|
6
|
+
req.headers.get("x-forwarded-proto")?.split(",")[0]!.trim() || new URL(req.url).protocol.slice(0, -1);
|
|
7
|
+
|
|
8
|
+
/** Whether a request was passed on by a proxy, so its address is the proxy's and not who asked. */
|
|
9
|
+
export const passedOn = (req: Request) =>
|
|
10
|
+
["x-forwarded-for", "x-real-ip", "x-forwarded-host", "x-forwarded-proto", "forwarded", "via"].some((h) =>
|
|
11
|
+
req.headers.has(h),
|
|
12
|
+
);
|
package/src/reading.ts
CHANGED
|
@@ -40,6 +40,11 @@ export abstract class Reading extends HTMLElement {
|
|
|
40
40
|
#watch = new MutationObserver(() => this.again());
|
|
41
41
|
#away = new AbortController();
|
|
42
42
|
#due = false;
|
|
43
|
+
/** While it draws, the page's sheet, found once: asked for each item, it cost a look through the page each. */
|
|
44
|
+
#sheet?: PageSheet | null;
|
|
45
|
+
#stale = false;
|
|
46
|
+
#drawn = false;
|
|
47
|
+
#shown = new ResizeObserver(() => this.#stale && this.again());
|
|
43
48
|
|
|
44
49
|
get for() {
|
|
45
50
|
return this.getAttribute("for") ?? "";
|
|
@@ -91,18 +96,31 @@ export abstract class Reading extends HTMLElement {
|
|
|
91
96
|
this.root.append(this.line);
|
|
92
97
|
}
|
|
93
98
|
this.#watch.observe(document.body, { childList: true, subtree: true, attributes: true });
|
|
99
|
+
this.#shown.observe(this);
|
|
94
100
|
this.again();
|
|
95
101
|
});
|
|
96
102
|
}
|
|
97
103
|
disconnectedCallback() {
|
|
98
104
|
this.#watch.disconnect();
|
|
105
|
+
this.#shown.disconnect();
|
|
99
106
|
this.#away.abort();
|
|
100
107
|
}
|
|
101
|
-
/** Drawn again, once a moment however much changed; hidden, when it's shown again. */
|
|
108
|
+
/** Drawn again, once a moment however much changed; hidden, when it's shown again (its first drawing apart). */
|
|
102
109
|
again() {
|
|
103
110
|
if (this.#due || !this.spec) return;
|
|
104
111
|
this.#due = true;
|
|
105
|
-
queueMicrotask(() =>
|
|
112
|
+
queueMicrotask(() => {
|
|
113
|
+
this.#due = false;
|
|
114
|
+
this.#stale = this.#drawn && !this.checkVisibility();
|
|
115
|
+
if (this.#stale) return;
|
|
116
|
+
this.#drawn = true;
|
|
117
|
+
this.#sheet = this.sheet;
|
|
118
|
+
try {
|
|
119
|
+
this.draw();
|
|
120
|
+
} finally {
|
|
121
|
+
this.#sheet = undefined;
|
|
122
|
+
}
|
|
123
|
+
});
|
|
106
124
|
}
|
|
107
125
|
/** Its collection's items on the page, as the search finds them. */
|
|
108
126
|
items(): Item[] {
|
|
@@ -127,7 +145,7 @@ export abstract class Reading extends HTMLElement {
|
|
|
127
145
|
}
|
|
128
146
|
/** The page's sheet of its collection. */
|
|
129
147
|
get sheet() {
|
|
130
|
-
return document.querySelector<PageSheet>(`j-sheet[for="${this.for}"]`);
|
|
148
|
+
return this.#sheet !== undefined ? this.#sheet : document.querySelector<PageSheet>(`j-sheet[for="${this.for}"]`);
|
|
131
149
|
}
|
|
132
150
|
open(it: Item) {
|
|
133
151
|
this.sheet?.show(it);
|
package/src/server.ts
CHANGED
|
@@ -23,6 +23,7 @@ import { doc as GROUP } from "./members/generated/rules.ts";
|
|
|
23
23
|
import { groupOf, say, type Data, type Who } from "./members/group.ts";
|
|
24
24
|
import { fromHere } from "./members/demo.ts";
|
|
25
25
|
import { door, type Written } from "./mcp.ts";
|
|
26
|
+
import { uploads, type Uploads } from "./upload.ts";
|
|
26
27
|
import { bdflOf, type Asked, type Member } from "./members/trust.ts";
|
|
27
28
|
import {
|
|
28
29
|
attribute,
|
|
@@ -37,7 +38,8 @@ import {
|
|
|
37
38
|
type Op,
|
|
38
39
|
type Type,
|
|
39
40
|
} from "./ops.ts";
|
|
40
|
-
import {
|
|
41
|
+
import { schemeOf } from "./proxy.ts";
|
|
42
|
+
import { openStore, Refused, rootCode, type Doc } from "./store.ts";
|
|
41
43
|
import { madeBy, type Part } from "./together.ts";
|
|
42
44
|
import { Made, writes, type Held, type Reactions, type Read, type Rules, type Told, type Trust } from "./write.ts";
|
|
43
45
|
/** A write refused, and why, in words a page shows as they are: a reaction or a route throws it. */
|
|
@@ -122,10 +124,8 @@ const anotherSite = (req: Request) => {
|
|
|
122
124
|
const origin = req.headers.get("origin");
|
|
123
125
|
if (!origin) return false;
|
|
124
126
|
if (!URL.canParse(origin)) return true;
|
|
125
|
-
const from = new URL(origin)
|
|
126
|
-
|
|
127
|
-
scheme = req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim();
|
|
128
|
-
return from.host !== to.host || from.protocol !== (scheme ? `${scheme}:` : to.protocol);
|
|
127
|
+
const from = new URL(origin);
|
|
128
|
+
return from.host !== new URL(req.url).host || from.protocol !== `${schemeOf(req)}:`;
|
|
129
129
|
};
|
|
130
130
|
/** A route's answer, but to another site's page sending what isn't a read (a sign-out, a post to an edge). */
|
|
131
131
|
const ownSite =
|
|
@@ -135,7 +135,9 @@ const ownSite =
|
|
|
135
135
|
? new Response("another site", { status: 403 })
|
|
136
136
|
: answer(req);
|
|
137
137
|
|
|
138
|
-
/** The MCP door, but to another site's page posting to it
|
|
138
|
+
/** The MCP door, but to another site's page posting to it, refused 403. A DNS rebinding (a site's name pointed at this
|
|
139
|
+
* machine) is this site by its host, so it isn't refused: it has no member's link, so it reaches an open group alone
|
|
140
|
+
* (#233). */
|
|
139
141
|
const mine = (d: ReturnType<typeof door>) => ({ ...d, POST: ownSite(d.POST) });
|
|
140
142
|
|
|
141
143
|
/** What fails in the background (a change told, the clock, another server's change heard), said, and the server goes on. */
|
|
@@ -544,15 +546,27 @@ export async function start({
|
|
|
544
546
|
holds: mayRead,
|
|
545
547
|
read: asMember,
|
|
546
548
|
write: (doc: string, ops: Op[], why: string | undefined, who: Who | null) => written([{ doc, ops, why }], who),
|
|
547
|
-
|
|
549
|
+
// each app's words and documents, for its skill (src/skill.ts)
|
|
550
|
+
apps: apps.flatMap((a) => {
|
|
551
|
+
const docs = docsOf(a)
|
|
552
|
+
.map((r) => r.doc)
|
|
553
|
+
.filter((doc) => doc !== GROUP && rules[doc]);
|
|
554
|
+
return docs.length || a.instructions
|
|
555
|
+
? [{ app: a.app || basename(dir), words: a.instructions?.trim() ?? "", docs }]
|
|
556
|
+
: [];
|
|
557
|
+
}),
|
|
558
|
+
upload: (...asked: Parameters<Uploads["link"]>) => uploading.link(...asked),
|
|
548
559
|
version,
|
|
549
560
|
};
|
|
550
561
|
/** Why someone may not send a file for a document (src/files.ts), or null: they may hold it, and may put a file in
|
|
551
562
|
* it (an add to a collection with a file field, or its replace), as a member by their link or a guest by its code. */
|
|
552
563
|
const mayPut = async (req: Request, doc: string) => {
|
|
553
564
|
if (anotherSite(req)) return "another site";
|
|
554
|
-
const signed = await group.at(req)
|
|
555
|
-
|
|
565
|
+
const signed = await group.at(req);
|
|
566
|
+
return mayPutAs(doc, signed instanceof Response ? null : signed);
|
|
567
|
+
};
|
|
568
|
+
/** The same, for whoever's known already: a member's agent by an upload link (src/upload.ts). */
|
|
569
|
+
const mayPutAs = async (doc: string, who: Who | null) => {
|
|
556
570
|
if (!(await store.exists(doc))) return `there's no document called ${doc}`;
|
|
557
571
|
return (
|
|
558
572
|
(await mayHold(doc, who?.member ?? null, !(members && rootToken))) ??
|
|
@@ -563,8 +577,12 @@ export async function start({
|
|
|
563
577
|
};
|
|
564
578
|
/** Why someone may not be sent an instance's file (src/files.ts), or null: they may hold it, as a member by their
|
|
565
579
|
* link or a guest by its code, and see an item naming it. */
|
|
566
|
-
const mayHoldFiles = async (req: Request,
|
|
567
|
-
|
|
580
|
+
const mayHoldFiles = async (req: Request, asked: string, name: string) => {
|
|
581
|
+
const { base, params } = docParts(asked);
|
|
582
|
+
if (!(await store.exists(base))) return `there's no document called ${base}`;
|
|
583
|
+
// held by its root's code, whatever the kind's guests call it; the page's window, if it holds one, says nothing here
|
|
584
|
+
const by = rootCode(rulesOf(base)),
|
|
585
|
+
doc = by && params[by] !== undefined ? `${base}?${by}=${encodeURIComponent(params[by])}` : base;
|
|
568
586
|
const signed = await group.at(req),
|
|
569
587
|
who = signed instanceof Response ? null : signed;
|
|
570
588
|
return (
|
|
@@ -577,6 +595,13 @@ export async function start({
|
|
|
577
595
|
/** Whether a document's kind keeps its files apart, each instance's in a folder of its own. */
|
|
578
596
|
const apart = async (doc: string) =>
|
|
579
597
|
((await exists(doc)) || (await store.exists(doc))) && rulesOf(doc).kind?.files === "apart";
|
|
598
|
+
/** The links an agent at the door sends a file by, made for its member (src/upload.ts). */
|
|
599
|
+
const uploading = uploads({
|
|
600
|
+
files: filesKept,
|
|
601
|
+
mayPut: mayPutAs,
|
|
602
|
+
apart,
|
|
603
|
+
write: (doc, ops, why, who) => written([{ doc, ops, why }], who),
|
|
604
|
+
});
|
|
580
605
|
const routes: Routes = {
|
|
581
606
|
"/health": () => new Response("ok"),
|
|
582
607
|
"/version": () => Response.json({ joined: version, build }),
|
|
@@ -640,7 +665,10 @@ export async function start({
|
|
|
640
665
|
...(members ? {} : { "/mcp": mine(door({ ...agents, anyone: true })) }),
|
|
641
666
|
// a file a document names: sent by whoever may put one in it, kept by its hash, and served for good
|
|
642
667
|
...fileRoutes(filesKept, mayPut, mayHoldFiles, apart),
|
|
668
|
+
// and one sent by an agent's upload link, made for its member at the door
|
|
669
|
+
...uploading.routes,
|
|
643
670
|
};
|
|
671
|
+
const bundles = `/_page-${crypto.randomUUID()}`;
|
|
644
672
|
// an app's routes read the documents at once, as its rules do: each handler is run in settle, again until every
|
|
645
673
|
// document it reads is here (src/write.ts)
|
|
646
674
|
const settled =
|
|
@@ -650,9 +678,10 @@ export async function start({
|
|
|
650
678
|
for (const { app, routes: of = {} } of apps)
|
|
651
679
|
for (const [path, answer] of Object.entries(typeof of === "function" ? of(now, write) : of)) {
|
|
652
680
|
if (path in routes) throw new Error(`${app || "the root"} and another app both answer ${path}`);
|
|
653
|
-
// a page (Bun's bundle of its index.html) is kept at
|
|
681
|
+
// a page (Bun's bundle of its index.html) is kept at a path no one is told, as it has none of the page's headers,
|
|
682
|
+
// and served at its own path rendered
|
|
654
683
|
if (typeof answer === "object" && "index" in answer) {
|
|
655
|
-
routes[
|
|
684
|
+
routes[`${bundles}${path}`] = answer;
|
|
656
685
|
routes[path] = (req: Request) => rendered(req, path);
|
|
657
686
|
continue;
|
|
658
687
|
}
|
|
@@ -689,13 +718,13 @@ export async function start({
|
|
|
689
718
|
.filter((r) => !r.derived)
|
|
690
719
|
.flatMap((r) => Object.entries(r.collections).map(([coll, c]) => [c.place, { doc: r.doc, coll, ...c }] as const)),
|
|
691
720
|
);
|
|
692
|
-
/** A page as Bun bundles it (kept at
|
|
721
|
+
/** A page as Bun bundles it (kept at `bundles`), and the documents it holds: read once live, and each time in
|
|
693
722
|
* development, where it's bundled afresh. */
|
|
694
723
|
const shells = new Map<string, { html: string; docs: string[] }>();
|
|
695
724
|
async function shell(path: string) {
|
|
696
725
|
const kept = shells.get(path);
|
|
697
726
|
if (kept) return kept;
|
|
698
|
-
const html = await (await fetch(new URL(
|
|
727
|
+
const html = await (await fetch(new URL(`${bundles}${path}`, server.url))).text();
|
|
699
728
|
const docs = new Set<string>();
|
|
700
729
|
const finding = new HTMLRewriter();
|
|
701
730
|
for (const [place, { doc }] of places)
|
|
@@ -716,9 +745,6 @@ export async function start({
|
|
|
716
745
|
return a === null ? "" : a === "" ? ` ${f}` : ` ${f}="${escaped(a)}"`;
|
|
717
746
|
})
|
|
718
747
|
.join("")}></${tag}>`;
|
|
719
|
-
/** Whether a request came over https: its own URL's, or a proxy's in front (Railway's) saying so. */
|
|
720
|
-
const secure = (req: Request) =>
|
|
721
|
-
new URL(req.url).protocol === "https:" || req.headers.get("x-forwarded-proto") === "https";
|
|
722
748
|
async function rendered(req: Request, path: string) {
|
|
723
749
|
const { html, docs } = await shell(path);
|
|
724
750
|
const headers = {
|
|
@@ -729,7 +755,7 @@ export async function start({
|
|
|
729
755
|
"content-security-policy": "frame-ancestors 'self'; base-uri 'self'; object-src 'none'",
|
|
730
756
|
"x-frame-options": "SAMEORIGIN",
|
|
731
757
|
"x-content-type-options": "nosniff",
|
|
732
|
-
...(
|
|
758
|
+
...(schemeOf(req) === "https" ? { "strict-transport-security": "max-age=31536000" } : {}),
|
|
733
759
|
};
|
|
734
760
|
const signed = await group.at(req),
|
|
735
761
|
who = signed instanceof Response ? null : signed;
|
|
@@ -808,14 +834,17 @@ export async function start({
|
|
|
808
834
|
const missed = m.since === undefined || part ? null : await store.since(doc, m.since);
|
|
809
835
|
if (missed) for (const c of missed) say(ws, c);
|
|
810
836
|
else {
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
const
|
|
814
|
-
?
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
837
|
+
// a part's topic is here before it's read, so a write landing meanwhile is told to it; and read again, where one
|
|
838
|
+
// told was newer than what was read
|
|
839
|
+
const member = ws.data.who?.member ?? 0,
|
|
840
|
+
asWho = topic !== doc || r.view ? { member: topic === doc ? 0 : member } : {},
|
|
841
|
+
t = part ? (topics.get(topic) ?? topics.set(topic, { doc, ...asWho, version: 0 }).get(topic)!) : null;
|
|
842
|
+
let seen: Doc;
|
|
843
|
+
do seen = await view(doc, member);
|
|
844
|
+
while (t && seen.version < t.version);
|
|
845
|
+
const { version, ...value } = seen;
|
|
846
|
+
// (the first to hold it: what it's told next follows what it's sent)
|
|
847
|
+
if (t && !t.version) t.version = version;
|
|
819
848
|
say(ws, { doc, version: t?.version ?? version, ops: [{ op: "replace", path: "", value }] });
|
|
820
849
|
}
|
|
821
850
|
// and what its person may do there, told afresh
|
|
@@ -1099,7 +1128,7 @@ export async function start({
|
|
|
1099
1128
|
members,
|
|
1100
1129
|
build,
|
|
1101
1130
|
// what's answered, without the bundles the pages are rendered from
|
|
1102
|
-
paths: Object.keys(routes).filter((p) => !p.startsWith(
|
|
1131
|
+
paths: Object.keys(routes).filter((p) => !p.startsWith(bundles)),
|
|
1103
1132
|
tokenOf: group.tokenOf,
|
|
1104
1133
|
/** Each app with rules of its own (a trust.ts), and how many writes they've refused. */
|
|
1105
1134
|
ruled,
|
package/src/skill.ts
CHANGED
|
@@ -1,40 +1,107 @@
|
|
|
1
|
-
// The door's
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
1
|
+
// The door's skills, served as MCP's skills extension (SEP-2640, io.modelcontextprotocol/skills) says: each SKILL.md a
|
|
2
|
+
// resource at skill://<name>/SKILL.md, and its entry (its frontmatter as written, each file's sha256 digest and size)
|
|
3
|
+
// for skills/list and skills/get. The door's own (.claude/skills/joined-door): how any joined document is read and
|
|
4
|
+
// written, one text read from its file, what the door says as it opens cut from it, never kept apart from it. And each
|
|
5
|
+
// app's: what its documents hold and mean, its own words (its routes.ts's `instructions`) and its documents' shapes,
|
|
6
|
+
// written from their compiled rules as their tools are, so it says what the app holds and never another thing.
|
|
6
7
|
|
|
7
8
|
import { createHash } from "node:crypto";
|
|
9
|
+
import type { Rules } from "./write.ts";
|
|
8
10
|
|
|
9
11
|
/** The extension's name, as a server declares it among its capabilities' extensions. */
|
|
10
12
|
export const SKILLS = "io.modelcontextprotocol/skills";
|
|
11
13
|
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
/**
|
|
20
|
-
|
|
21
|
-
uri
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
/** A skills/list entry, and skills/get's: its one file is its SKILL.md. */
|
|
25
|
-
entry: {
|
|
26
|
-
uri,
|
|
27
|
-
frontmatter,
|
|
28
|
-
resources: [{ uri, digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, size: bytes.length }],
|
|
29
|
-
},
|
|
30
|
-
/** It as resources/list names it. */
|
|
31
|
-
resource: {
|
|
32
|
-
uri,
|
|
14
|
+
/** A skill as the door serves it: its SKILL.md whole, the words below its frontmatter, and how the extension and a
|
|
15
|
+
* resource say it. */
|
|
16
|
+
export type Skill = ReturnType<typeof served>;
|
|
17
|
+
|
|
18
|
+
/** A skill, from its SKILL.md. */
|
|
19
|
+
function served(text: string) {
|
|
20
|
+
const [, front = "", body = ""] = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text) ?? [];
|
|
21
|
+
/** Its frontmatter, as YAML reads it: its name and description, and whatever else it says. */
|
|
22
|
+
const frontmatter = Bun.YAML.parse(front) as { name: string; description: string };
|
|
23
|
+
const uri = `skill://${frontmatter.name}/SKILL.md`,
|
|
24
|
+
bytes = new TextEncoder().encode(text);
|
|
25
|
+
return {
|
|
33
26
|
name: frontmatter.name,
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
27
|
+
uri,
|
|
28
|
+
text,
|
|
29
|
+
body: body.trim(),
|
|
30
|
+
/** A skills/list entry, and skills/get's: its one file is its SKILL.md. */
|
|
31
|
+
entry: {
|
|
32
|
+
uri,
|
|
33
|
+
frontmatter,
|
|
34
|
+
resources: [{ uri, digest: `sha256:${createHash("sha256").update(bytes).digest("hex")}`, size: bytes.length }],
|
|
35
|
+
},
|
|
36
|
+
/** It as resources/list names it. */
|
|
37
|
+
resource: {
|
|
38
|
+
uri,
|
|
39
|
+
name: frontmatter.name,
|
|
40
|
+
description: frontmatter.description,
|
|
41
|
+
mimeType: "text/markdown",
|
|
42
|
+
size: bytes.length,
|
|
43
|
+
},
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The door's own skill. */
|
|
48
|
+
export const skill = served(await Bun.file(new URL("../.claude/skills/joined-door/SKILL.md", import.meta.url)).text());
|
|
49
|
+
|
|
50
|
+
/** What instructions say of the skills to a client that loads skills itself: where they are, not what they say. */
|
|
51
|
+
export const pointer = (apps: Skill[]) =>
|
|
52
|
+
`How any joined document is read and written here is the skill ${skill.name} (${skill.uri})${
|
|
53
|
+
apps.length
|
|
54
|
+
? `, and what each app's documents hold and mean is the app's own: ${apps.map((a) => `${a.name} (${a.uri})`).join(", ")}`
|
|
55
|
+
: ""
|
|
56
|
+
}: load them before a write.`;
|
|
57
|
+
|
|
58
|
+
type Collection = Rules["collections"][string] & { needs?: readonly string[] };
|
|
59
|
+
|
|
60
|
+
/** A collection's fields, as an agent reads them: each its type, a link what it's an id of, and what an add needs. */
|
|
61
|
+
const fieldsOf = (c: Collection) =>
|
|
62
|
+
Object.entries(c.fields)
|
|
63
|
+
.filter(([f]) => !(f in (c.fills ?? {})))
|
|
64
|
+
.map(([f, t]) => {
|
|
65
|
+
const to = c.links?.[f];
|
|
66
|
+
const said = to ? (t === "ids" ? `ids of ${to}` : `an id of ${to}`) : t;
|
|
67
|
+
return `${f} (${said}${c.needs?.includes(f) ? ", needed" : ""})`;
|
|
68
|
+
})
|
|
69
|
+
.join(", ");
|
|
70
|
+
|
|
71
|
+
/** A document's shape: its name (a kind's, by its key), its own fields, each collection's, and its tools. */
|
|
72
|
+
function shapeOf(r: Rules) {
|
|
73
|
+
const colls = Object.entries(r.collections) as [string, Collection][];
|
|
74
|
+
const files = colls.some(([, c]) => Object.values(c.fields).includes("file"));
|
|
75
|
+
const writes = r.type === "shared" && Object.keys(r.grants ?? {}).length;
|
|
76
|
+
return [
|
|
77
|
+
`## ${r.kind ? `${r.doc}:<key>` : r.doc}`,
|
|
78
|
+
"",
|
|
79
|
+
[
|
|
80
|
+
r.kind ? `One for each of the ${r.kind.root} in ${r.kind.doc}, its key that one's id.` : "",
|
|
81
|
+
`Read by read_${r.doc}${writes ? `, written by write_${r.doc}` : ", which only reads"}${
|
|
82
|
+
files && writes ? `; a file it names comes in by upload_${r.doc}` : ""
|
|
83
|
+
}.`,
|
|
84
|
+
]
|
|
85
|
+
.filter(Boolean)
|
|
86
|
+
.join(" "),
|
|
87
|
+
"",
|
|
88
|
+
...colls.map(([name, c]) => `- ${c.own ? "its own fields" : name}: ${fieldsOf(c)}`),
|
|
89
|
+
].join("\n");
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** An app's skill: its words, then what each of its documents holds. */
|
|
93
|
+
export function skillOf(app: string, words: string, rules: Rules[]): Skill {
|
|
94
|
+
const docs = rules.map((r) => (r.kind ? `${r.doc}:<key>` : r.doc)).join(", ");
|
|
95
|
+
const description = `Use when reading or writing the ${app} app's documents (${docs}): what they hold, and what they mean.`;
|
|
96
|
+
return served(
|
|
97
|
+
[
|
|
98
|
+
`---\nname: ${app}\ndescription: ${JSON.stringify(description)}\n---`,
|
|
99
|
+
`# ${app}`,
|
|
100
|
+
words,
|
|
101
|
+
"What each document holds: a field's type, a link an id of what it links to (or \"$1\", the write's first add), and what an add needs.",
|
|
102
|
+
...rules.map(shapeOf),
|
|
103
|
+
]
|
|
104
|
+
.filter(Boolean)
|
|
105
|
+
.join("\n\n") + "\n",
|
|
106
|
+
);
|
|
107
|
+
}
|