@blueshed/joined 0.3.4 → 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.
@@ -621,9 +621,16 @@ Working: `src/icons.ts`; the members panel and every example.
621
621
  read and written there (`.claude/skills/joined-door/SKILL.md`, the one text, `src/skill.ts`): by MCP's skills
622
622
  extension (`io.modelcontextprotocol/skills`, declared in `server/discover`; `skills/list`, `skills/get`, the
623
623
  resource `skill://joined-door/SKILL.md`), and in its instructions, where a client doesn't say it loads skills
624
- itself (one that does is told where the skill is). After it in the instructions come each app's words: its `routes.ts` may export `instructions`
625
- (`examples/trip/routes.ts`), what's its own alone (what its documents mean, its people, its clock), never how a read
626
- or a write goes. A change to how any document is read or written there changes that skill with it (`tests/mcp.test.ts`). Never print the token: the URL holds it. A project with no
624
+ itself (one that does is told where the skills are). Beside it each app has a skill of its own, served the same way
625
+ (`skill://<app>/SKILL.md`, written by `skillOf`): its words, then what each of its documents holds (its fields' types,
626
+ what a link is an id of, what an add needs, its tools), from the compiled rules as the tools are. Its words are its
627
+ `routes.ts`'s `instructions` (`examples/trip/routes.ts`), what's its own alone (what its documents mean, its people,
628
+ its clock), never how a read or a write goes. A change to how any document is read or written there changes that
629
+ skill with it (`tests/mcp.test.ts`). A document that names files has `upload_<doc>` too: the agent never sees its
630
+ key, so the server makes it a link (`src/upload.ts`), good once for 15 minutes, for its member and that document;
631
+ POSTed a file it's kept as a page's is and answered its value, opened in a browser it's a page to choose the file on,
632
+ and given `ops` (`"$file"` standing for the file) it makes that write as the agent's once the file's in
633
+ (`tests/upload.test.ts`). Never print the token: the URL holds it. A project with no
627
634
  members (every story anonymous, hello) has no group and no agent's link: its door is anyone's, `POST /mcp` with no
628
635
  token, as a stranger's page is, each write logged "by anyone" (`tests/server.test.ts`).
629
636
  - **Never put `ROOT_TOKEN`, `.env`, the store (`joined.sqlite`, which holds the keys) or anyone's link in a commit,** nor in chat
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: joined-door
3
- description: Use when reading or changing a joined document through its MCP door (the read_<doc> and write_<doc> tools), for how a read and a write go, an op's path, $n links, the forms a value takes, and a refusal. For any app on joined, in any client.
3
+ description: Use when reading or changing a joined document through its MCP door (the read_<doc>, write_<doc> and upload_<doc> tools), for how a read and a write go, an op's path, $n links, the forms a value takes, a file sent, and a refusal. For any app on joined, in any client.
4
4
  ---
5
5
 
6
6
  # A joined document, through its door
@@ -8,7 +8,8 @@ description: Use when reading or changing a joined document through its MCP door
8
8
  An app on joined keeps its documents, and every page open on them, in step. Its door gives you two tools for each
9
9
  document your link may hold: `read_<doc>` and `write_<doc>` (a document you can't write has only its read). Their
10
10
  descriptions say what each document holds and each op it takes: read them, they're written from the app's own rules.
11
- The app's own words, where it has any, come after these.
11
+ A document that names files has `upload_<doc>` too. Each app has a skill of its own beside this one: its words, and
12
+ what each of its documents holds.
12
13
 
13
14
  ## Read first
14
15
 
@@ -34,6 +35,20 @@ The app's own words, where it has any, come after these.
34
35
  write. In a value only, never in a path.
35
36
  - Done answers `{"done": true, "version", "ids"}`, the ids of what it added, in order.
36
37
 
38
+ ## A file
39
+
40
+ A file field's value is `file:<sha256>.<ext>`, a file the app keeps already: it comes in by `upload_<doc>`, never in a
41
+ write. You never see your link's key; the server does, so it makes the link for you:
42
+
43
+ - `upload_<doc>` (with `key`, for a kind's) and the file's `name` answers `{"url", "until"}`: a link good once, for 15
44
+ minutes, made for your link's member and that document alone.
45
+ - Where you can send bytes, POST the file to `url`: it answers `{"file": "file:…"}`, the value to write.
46
+ - Where you can't reach the site (a chat's sandbox), give `url` to your person: it opens a page to choose the file on.
47
+ Give the tool `ops` too, the write the file is for, `"$file"` in a value standing for it (`{"op": "add", "path":
48
+ "/papers/-", "value": {"move": 12, "file": "$file"}}`): it's made as yours once the file's in. Read the document
49
+ after, to see it there.
50
+ - A photo, an SVG, a PDF or a Markdown file, under 20 MB; anything else is refused, in words.
51
+
37
52
  ## Values
38
53
 
39
54
  Each field's form is in the tool's schema; a value in another is refused, in words.
@@ -167,8 +167,12 @@ into claude.ai's custom connectors, so Claude in a chat, on a phone too, can wor
167
167
  - **A write is a page's write.** It lands whole or not at all, under the app's trust rules, the grants
168
168
  and the group's, as the member via the agent, and every page holding the document sees it at once. A
169
169
  refusal comes back in its own words: "greeting is a string".
170
- - **An app can brief Claude.** Its `routes.ts` may export `instructions`, said as the connector opens
171
- (the trip's say how its times and places are written).
170
+ - **An app can brief Claude.** Each app has a skill at the door beside joined's own: what its documents
171
+ hold, from its rules, after its own words (its `routes.ts` may export `instructions`: the trip's say
172
+ how its times and places are written).
173
+ - **A file comes by a link the server makes.** Claude never sees its own key, so `upload_<doc>` asks the
174
+ server for a link to send one file by, for its member and that document: Claude sends it there, or,
175
+ in a chat that can't reach the site, gives it to you to open and choose the file.
172
176
  - **Only an agent's link opens the door.** A member's own link, one taken back, or an unknown one is
173
177
  refused, and the token is never printed.
174
178
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blueshed/joined",
3
- "version": "0.3.4",
3
+ "version": "0.3.5",
4
4
  "description": "Compiled documents, talking to web components as elements in the DOM.",
5
5
  "license": "MIT",
6
6
  "repository": {
package/src/mcp.ts CHANGED
@@ -7,14 +7,18 @@
7
7
  // rules, never the stories: read_<doc>, the document as its member sees it, and write_<doc>, one write, its ops typed
8
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
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
10
+ // door's own skill (src/skill.ts), served by MCP's skills extension beside each app's own (its words, its routes.ts's
11
+ // `instructions`, and what its documents hold, from their rules), and said as it opens. A document that names files
12
+ // has upload_<doc> too: a link the server makes for the agent's member to send a file by (src/upload.ts), since the
13
+ // agent never sees its own key. It speaks both eras of MCP: the modern (2026-07-28), each request saying its
12
14
  // version and the client's capabilities in its _meta, its headers checked against its body, server/discover in place
13
15
  // 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.
16
+ // skills itself the instructions say where the skills are, and the apps' words; to any other, what the skills say.
15
17
 
16
18
  import { FORMS, SAID } from "./compile.ts";
17
- import { skill, SKILLS } from "./skill.ts";
19
+ import { pointer, skill, skillOf, SKILLS } from "./skill.ts";
20
+ import type { Made } from "./upload.ts";
21
+ import { schemeOf } from "./proxy.ts";
18
22
  import type { Who } from "./members/group.ts";
19
23
  import { upTo } from "./files.ts";
20
24
  import { isOp, MESSAGE, NTH, OPS, parts, type Op, type Type } from "./ops.ts";
@@ -34,7 +38,16 @@ type Door = {
34
38
  read(doc: string, member: number): Promise<Doc>;
35
39
  /** A write by an agent's member; or, at a door that's anyone's, nobody's (null), as a stranger's page writes. */
36
40
  write(doc: string, ops: Op[], why: string | undefined, who: Who | null): Promise<Written>;
37
- instructions: string;
41
+ /** Each app: its name, its words for an agent, and its documents. */
42
+ apps: { app: string; words: string; docs: string[] }[];
43
+ /** A link for a member's agent (nobody's, at a door that's anyone's) to send a file for a document by (src/upload.ts). */
44
+ upload?(
45
+ origin: string,
46
+ doc: string,
47
+ who: Who | null,
48
+ name: string,
49
+ then: { ops?: Op[]; why?: string },
50
+ ): Promise<Made>;
38
51
  version: string;
39
52
  };
40
53
  type Schema = Record<string, unknown>;
@@ -205,9 +218,17 @@ const ANYONE: Who = { member: 0, token: "" };
205
218
  export function door(d: Door) {
206
219
  const rpc = (id: unknown, result: unknown) => ({ jsonrpc: "2.0", id, result });
207
220
  const fail = (id: unknown, code: number, message: string) => ({ jsonrpc: "2.0", id, error: { code, message } });
221
+ // each app's skill, beside the door's: its words and what its documents hold
222
+ const apps = d.apps.flatMap((a) => {
223
+ const rules = d.rules.filter((r) => a.docs.includes(r.doc));
224
+ return rules.length ? [skillOf(a.app, a.words, rules)] : [];
225
+ });
226
+ const skills = [skill, ...apps],
227
+ words = d.apps.map((a) => a.words).filter(Boolean);
228
+ const skillAt = (uri: unknown) => skills.find((s) => s.uri === uri);
208
229
 
209
230
  /** The tools for a member's agent: each document's read and, where pages write it, its write; a kind's take its key. */
210
- async function toolsFor(who: Who) {
231
+ async function toolsFor(who: Who, origin: string) {
211
232
  const tools: {
212
233
  name: string;
213
234
  description: string;
@@ -223,7 +244,12 @@ export function door(d: Door) {
223
244
  r.kind && !/^[1-9]\d*$/.test(String(args.key)) ? `key: which ${r.doc}, a whole number` : null;
224
245
  if (!r.kind && (await d.holds(r.doc, who.member))) continue;
225
246
  const key = r.kind
226
- ? { key: { type: "integer", description: `which ${r.doc}: the id of one of ${r.kind.doc}'s ${r.kind.root}` } }
247
+ ? {
248
+ key: {
249
+ type: "integer",
250
+ description: `which ${r.doc}: the id of one of the ${r.kind.root} in ${r.kind.doc}`,
251
+ },
252
+ }
227
253
  : {};
228
254
  const colls = Object.entries(r.collections)
229
255
  .filter(([, c]) => !c.own)
@@ -255,6 +281,22 @@ export function door(d: Door) {
255
281
  // an op's path as it's said: an add by a first step, what it gives
256
282
  const said = (o: (typeof ops)[number]) => `${o.path}${o.gives ? ` giving ${o.gives}` : ""}`;
257
283
  if (r.type !== "shared" || !ops.length) continue;
284
+ const opsOfWrite = {
285
+ type: "array",
286
+ minItems: 1,
287
+ items: {
288
+ anyOf: ops.map((o) => ({
289
+ type: "object",
290
+ properties: {
291
+ op: { type: "string", enum: [o.op] },
292
+ path: { type: "string", pattern: o.pattern, description: said(o) },
293
+ ...(o.value ? { value: o.value } : {}),
294
+ },
295
+ required: ["op", "path", ...(o.value ? ["value"] : [])],
296
+ })),
297
+ },
298
+ };
299
+ const why = { type: "string", description: "why, in a few words, where it helps those who read it" };
258
300
  tools.push({
259
301
  name: `write_${r.doc}`,
260
302
  description: `One write to ${r.doc}, whole or not at all, told to every page at once: its ops, each one of ${ops.map((o) => `${o.op} ${said(o)}`).join(", ")}. {id} is an item's id, as read_${r.doc} shows it. Done answers with its version and the ids of what it added; refused, with why.`,
@@ -262,22 +304,8 @@ export function door(d: Door) {
262
304
  type: "object",
263
305
  properties: {
264
306
  ...key,
265
- ops: {
266
- type: "array",
267
- minItems: 1,
268
- items: {
269
- anyOf: ops.map((o) => ({
270
- type: "object",
271
- properties: {
272
- op: { type: "string", enum: [o.op] },
273
- path: { type: "string", pattern: o.pattern, description: said(o) },
274
- ...(o.value ? { value: o.value } : {}),
275
- },
276
- required: ["op", "path", ...(o.value ? ["value"] : [])],
277
- })),
278
- },
279
- },
280
- why: { type: "string", description: "why, in a few words, where it helps those who read it" },
307
+ ops: opsOfWrite,
308
+ why,
281
309
  },
282
310
  required: [...Object.keys(key), "ops"],
283
311
  },
@@ -298,13 +326,45 @@ export function door(d: Door) {
298
326
  return "why" in w ? refused(w.why) : answered(w);
299
327
  },
300
328
  });
329
+ // a file it names comes by a link the server makes: the agent never sees its own key, the server does
330
+ if (!d.upload || !Object.values(r.collections).some((c) => Object.values(c.fields).includes("file"))) continue;
331
+ const upload = d.upload;
332
+ tools.push({
333
+ name: `upload_${r.doc}`,
334
+ description: `A link to send one file to ${r.doc} by, made for you (you never see your key; the server does): good once, for 15 minutes, a photo, an SVG, a PDF or a Markdown file under 20 MB. POST the file's bytes to its url, answered its value (file:<sha256>.<ext>) to put in a write; or, where you can't reach the site, give the url to your person to open and choose the file. With ops, the write it's for, "$file" in a value standing for the file, that write is made as yours once the file is in, and the url answers it.`,
335
+ inputSchema: {
336
+ type: "object",
337
+ properties: {
338
+ ...key,
339
+ name: {
340
+ type: "string",
341
+ description: "the file's name, as receipt.pdf (a Markdown file is known by its .md)",
342
+ },
343
+ ops: { ...opsOfWrite, description: 'the write it\'s for, made once the file is in: "$file" stands for it' },
344
+ why,
345
+ },
346
+ required: Object.keys(key),
347
+ },
348
+ annotations: { readOnlyHint: false, destructiveHint: false },
349
+ run: async (args) => {
350
+ if (args.ops !== undefined && (!Array.isArray(args.ops) || !args.ops.length || !args.ops.every(isOp)))
351
+ return refused(OPS);
352
+ const no = unkeyed(args) ?? (await d.holds(name(args), who.member));
353
+ if (no) return refused(no);
354
+ const made = await upload(origin, name(args), d.anyone ? null : who, String(args.name ?? ""), {
355
+ ...(args.ops ? { ops: texted(r, args.ops) } : {}),
356
+ ...(typeof args.why === "string" && args.why.trim() ? { why: args.why.trim() } : {}),
357
+ });
358
+ return "why" in made ? refused(made.why) : answered(made);
359
+ },
360
+ });
301
361
  }
302
362
  return tools;
303
363
  }
304
364
 
305
365
  /** One message, in its era: answered, or a notification (no id), which isn't. A modern answer says it's complete,
306
366
  * and where it may be kept a while, for how long (none: the grants can change) and for whom. */
307
- async function one(m: Message, who: Who, modern: boolean) {
367
+ async function one(m: Message, who: Who, modern: boolean, origin: string) {
308
368
  if (m.id === undefined) return null;
309
369
  const done = (result: object, kept?: "public" | "private") =>
310
370
  rpc(
@@ -313,7 +373,7 @@ export function door(d: Door) {
313
373
  );
314
374
  // to a client that loads skills itself (it says so in the request's capabilities), where the skill is
315
375
  const loads = !!m.params?._meta?.[`${MCP}clientCapabilities`]?.extensions?.[SKILLS];
316
- const instructions = [loads ? skill.pointer : skill.body, d.instructions].filter(Boolean).join("\n\n");
376
+ const instructions = (loads ? [pointer(apps), ...words] : skills.map((s) => s.body)).join("\n\n");
317
377
  if (modern && m.method === "server/discover")
318
378
  return done(
319
379
  {
@@ -332,20 +392,21 @@ export function door(d: Door) {
332
392
  instructions,
333
393
  });
334
394
  if (!modern && m.method === "ping") return rpc(m.id, {});
335
- if (m.method === "resources/list") return done({ resources: [skill.resource] }, "public");
395
+ const asked = skillAt(m.params?.uri);
396
+ if (m.method === "resources/list") return done({ resources: skills.map((s) => s.resource) }, "public");
336
397
  if (m.method === "resources/read")
337
- return m.params?.uri === skill.uri
338
- ? done({ contents: [{ uri: skill.uri, mimeType: "text/markdown", text: skill.text }] }, "public")
398
+ return asked
399
+ ? done({ contents: [{ uri: asked.uri, mimeType: "text/markdown", text: asked.text }] }, "public")
339
400
  : fail(m.id, -32602, `there's no resource at ${m.params?.uri}`);
340
- if (modern && m.method === "skills/list") return done({ skills: [skill.entry] }, "public");
401
+ if (modern && m.method === "skills/list") return done({ skills: skills.map((s) => s.entry) }, "public");
341
402
  if (modern && m.method === "skills/get")
342
- return m.params?.uri === skill.uri
343
- ? done({ skill: skill.entry }, "public")
403
+ return asked
404
+ ? done({ skill: asked.entry }, "public")
344
405
  : fail(m.id, -32602, `No skill is served at ${m.params?.uri}`);
345
406
  if (m.method === "tools/list")
346
- return done({ tools: (await toolsFor(who)).map(({ run: _, ...t }) => t) }, "private");
407
+ return done({ tools: (await toolsFor(who, origin)).map(({ run: _, ...t }) => t) }, "private");
347
408
  if (m.method === "tools/call") {
348
- const tool = (await toolsFor(who)).find((t) => t.name === m.params?.name);
409
+ const tool = (await toolsFor(who, origin)).find((t) => t.name === m.params?.name);
349
410
  return tool
350
411
  ? done(await tool.run(m.params.arguments ?? {}))
351
412
  : fail(m.id, -32602, `no tool called ${m.params?.name}`);
@@ -401,7 +462,9 @@ export function door(d: Door) {
401
462
  );
402
463
  }
403
464
  // never thrown: Bun's line for a request that throws names its URL, and the URL holds the agent's token
404
- const answer = await one(m, who!, version !== undefined).catch((e) => {
465
+ // where the door was asked, as a link it makes is said: the site's, behind its proxy too
466
+ const origin = `${schemeOf(req)}://${new URL(req.url).host}`;
467
+ const answer = await one(m, who!, version !== undefined, origin).catch((e) => {
405
468
  console.error("the MCP door failed:", e);
406
469
  return fail(m.id ?? null, -32603, "That wasn't done: the server had a problem with it.");
407
470
  });
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,
@@ -545,15 +546,27 @@ export async function start({
545
546
  holds: mayRead,
546
547
  read: asMember,
547
548
  write: (doc: string, ops: Op[], why: string | undefined, who: Who | null) => written([{ doc, ops, why }], who),
548
- instructions: apps.flatMap((a) => (a.instructions ? [a.instructions.trim()] : [])).join("\n\n"),
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),
549
559
  version,
550
560
  };
551
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
552
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. */
553
563
  const mayPut = async (req: Request, doc: string) => {
554
564
  if (anotherSite(req)) return "another site";
555
- const signed = await group.at(req),
556
- who = signed instanceof Response ? null : signed;
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) => {
557
570
  if (!(await store.exists(doc))) return `there's no document called ${doc}`;
558
571
  return (
559
572
  (await mayHold(doc, who?.member ?? null, !(members && rootToken))) ??
@@ -582,6 +595,13 @@ export async function start({
582
595
  /** Whether a document's kind keeps its files apart, each instance's in a folder of its own. */
583
596
  const apart = async (doc: string) =>
584
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
+ });
585
605
  const routes: Routes = {
586
606
  "/health": () => new Response("ok"),
587
607
  "/version": () => Response.json({ joined: version, build }),
@@ -645,6 +665,8 @@ export async function start({
645
665
  ...(members ? {} : { "/mcp": mine(door({ ...agents, anyone: true })) }),
646
666
  // a file a document names: sent by whoever may put one in it, kept by its hash, and served for good
647
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,
648
670
  };
649
671
  const bundles = `/_page-${crypto.randomUUID()}`;
650
672
  // an app's routes read the documents at once, as its rules do: each handler is run in settle, again until every
package/src/skill.ts CHANGED
@@ -1,40 +1,107 @@
1
- // The door's skill (.claude/skills/joined-door): how any joined document is read and written through the MCP door,
2
- // served as MCP's skills extension (SEP-2640, io.modelcontextprotocol/skills) says: its SKILL.md a resource at
3
- // skill://<name>/SKILL.md, and its entry (its frontmatter as written, each file's sha256 digest and size) for
4
- // skills/list and skills/get. One text, read from its file: what the door says as it opens is cut from it, never kept
5
- // apart from it.
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
- const text = await Bun.file(new URL("../.claude/skills/joined-door/SKILL.md", import.meta.url)).text();
13
- const [, front = "", body = ""] = /^---\n([\s\S]*?)\n---\n([\s\S]*)$/.exec(text) ?? [];
14
- /** Its frontmatter, as YAML reads it: its name and description, and whatever else it says. */
15
- const frontmatter = Bun.YAML.parse(front) as { name: string; description: string };
16
- const uri = `skill://${frontmatter.name}/SKILL.md`,
17
- bytes = new TextEncoder().encode(text);
18
-
19
- /** The door's skill: its SKILL.md whole, the words below its frontmatter, and how the extension and a resource say it. */
20
- export const skill = {
21
- uri,
22
- text,
23
- body: body.trim(),
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
- description: frontmatter.description,
35
- mimeType: "text/markdown",
36
- size: bytes.length,
37
- },
38
- /** What instructions say of it to a client that loads skills itself: where it is, not what it says. */
39
- pointer: `How any joined document is read and written here is the skill ${frontmatter.name} (${uri}): load it before a write.`,
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
+ }
package/src/upload.ts ADDED
@@ -0,0 +1,136 @@
1
+ // An upload link: a file sent for a document by an agent at the MCP door, which has no page's sign-in to send one by
2
+ // (its member's key is in its connector's link, which it never sees: the server does). The door's upload_<doc> asks
3
+ // for one: a link short-lived and used once, made for the agent's member and that document alone, so whoever has it
4
+ // sends one file as that member could, and nothing more. POSTed the file's bytes (by an agent that can send them,
5
+ // Claude Code), it's kept as a page's file is (src/files.ts) and answered its value; opened in a browser, it's a page to
6
+ // choose the file on, for an agent in a chat whose sandbox can't reach the site: its person opens it. Where the agent
7
+ // said the write it's for ("$file" in a value standing for the file), that write is made as the agent's once the file
8
+ // is in, so the person who chose it needn't tell the agent anything. Kept in the server's memory: a restart lets every
9
+ // link go, as it does whatever was being answered.
10
+
11
+ import { folderOf, MOST, TOO_BIG } from "./file-value.ts";
12
+ import { keep, upTo, type Files } from "./files.ts";
13
+ import type { Written } from "./mcp.ts";
14
+ import type { Who } from "./members/group.ts";
15
+ import type { Op } from "./ops.ts";
16
+
17
+ /** How long a link is good for, in ms. */
18
+ export const GOOD_FOR = 15 * 60_000;
19
+ /** What stands for the file in the write a link is for. */
20
+ export const FILE = "$file";
21
+
22
+ /** What makes the links, and is sent their files: who may put a file in a document, and how it's written (by a
23
+ * member's agent, or nobody, at a door that's anyone's). */
24
+ type Uploading = {
25
+ files: Files;
26
+ /** Why a member may not put a file in a document, or null. */
27
+ mayPut(doc: string, who: Who | null): Promise<string | null>;
28
+ /** Whether a document's kind keeps its files apart. */
29
+ apart(doc: string): Promise<boolean>;
30
+ write(doc: string, ops: Op[], why: string | undefined, who: Who | null): Promise<Written>;
31
+ };
32
+ type Link = { doc: string; who: Who | null; name: string; until: number; ops?: Op[]; why?: string; busy?: boolean };
33
+ /** A link made: its address, and till when (ISO); or why not. */
34
+ export type Made = { url: string; until: string } | { why: string };
35
+
36
+ /** A write's ops with the file's value where "$file" stood. */
37
+ const filled = (ops: Op[], file: string): Op[] => JSON.parse(JSON.stringify(ops), (_, v) => (v === FILE ? file : v));
38
+
39
+ const escaped = (s: string) =>
40
+ s.replace(/[&<>"']/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&#39;" })[c]!);
41
+
42
+ /** The page a link opens in a browser: the file chosen, sent, and what came of it said. */
43
+ const page = (l: Link) => `<!doctype html>
44
+ <html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
45
+ <meta name="color-scheme" content="light dark"><title>A file for your agent</title>
46
+ <style>
47
+ body{font:16px/1.5 system-ui,sans-serif;max-width:32rem;margin:0 auto;padding:2rem 1rem}
48
+ h1{font-size:1.25rem;margin:0 0 .5rem}p{margin:.5rem 0}
49
+ label{display:block;border:2px dashed currentColor;border-radius:12px;padding:2rem 1rem;text-align:center;cursor:pointer;opacity:.8}
50
+ label:hover{opacity:1}input,[hidden]{display:none}#said{font-weight:600}
51
+ </style></head><body>
52
+ <h1>Your agent asked for ${escaped(l.name || "a file")}</h1>
53
+ <p>Choose it here${l.ops ? ", and it's put where your agent said" : ", and your agent has it"}. It goes to ${escaped(l.doc)}.</p>
54
+ <label>Choose the file, or drop it here<input type="file" accept="image/*,.pdf,.svg,.md"></label>
55
+ <p id="said" role="status"></p>
56
+ <script>
57
+ const said = document.getElementById("said"), input = document.querySelector("input");
58
+ async function send(file) {
59
+ said.textContent = "Sending " + file.name + "…";
60
+ const r = await fetch(location.pathname, { method: "POST", body: file }).catch(() => null);
61
+ const a = r && (await r.json().catch(() => null));
62
+ said.textContent = !a ? "That wasn't sent: try again." : a.refused ? a.refused : a.why ? "It's kept, but not put in: " + a.why : "Done: " + file.name + " is in. You can close this page.";
63
+ // sent: the link's used, so there's nothing more to choose
64
+ if (a && a.file) document.querySelector("label").hidden = true;
65
+ }
66
+ input.onchange = () => input.files[0] && send(input.files[0]);
67
+ document.body.ondragover = (e) => e.preventDefault();
68
+ document.body.ondrop = (e) => { e.preventDefault(); const f = e.dataTransfer.files[0]; f && send(f); };
69
+ </script></body></html>`;
70
+
71
+ /** The links: made for an agent at the door, and the route that's sent their files. */
72
+ export function uploads(d: Uploading, now = Date.now) {
73
+ const links = new Map<string, Link>();
74
+ /** A link still good, or none: one past its time is let go as it's asked for. */
75
+ const good = (nonce: string) => {
76
+ const l = links.get(nonce);
77
+ if (l && l.until > now()) return l;
78
+ links.delete(nonce);
79
+ return undefined;
80
+ };
81
+ const gone = () => Response.json({ refused: "That link has gone: ask your agent for another." }, { status: 404 });
82
+ return {
83
+ /** A link for an agent's member to send one file for a document, at the site the door was asked at. */
84
+ async link(origin: string, doc: string, who: Who | null, name: string, then: { ops?: Op[]; why?: string } = {}) {
85
+ const no = await d.mayPut(doc, who);
86
+ if (no) return { why: no } satisfies Made;
87
+ for (const [n, l] of links) if (l.until <= now()) links.delete(n);
88
+ const nonce = crypto.randomUUID().replaceAll("-", "") + crypto.randomUUID().replaceAll("-", ""),
89
+ until = now() + GOOD_FOR;
90
+ links.set(nonce, { doc, who, name, until, ...then });
91
+ return { url: `${origin}/upload/${nonce}`, until: new Date(until).toISOString() } satisfies Made;
92
+ },
93
+ routes: {
94
+ "/upload/:nonce": {
95
+ GET: (req: Request & { params: { nonce: string } }) => {
96
+ const l = good(req.params.nonce);
97
+ return l
98
+ ? new Response(page(l), {
99
+ headers: {
100
+ "content-type": "text/html;charset=utf-8",
101
+ "cache-control": "no-store",
102
+ "content-security-policy": "frame-ancestors 'none'; base-uri 'none'; object-src 'none'",
103
+ "referrer-policy": "no-referrer",
104
+ },
105
+ })
106
+ : new Response("That link has gone: ask your agent for another.", { status: 404 });
107
+ },
108
+ async POST(req: Request & { params: { nonce: string } }) {
109
+ const l = good(req.params.nonce);
110
+ if (!l) return gone();
111
+ if (l.busy) return Response.json({ refused: "A file is being sent by this link already." }, { status: 409 });
112
+ if (Number(req.headers.get("content-length")) > MOST)
113
+ return Response.json({ refused: TOO_BIG }, { status: 413 });
114
+ l.busy = true;
115
+ try {
116
+ const bytes = await upTo(req, MOST);
117
+ if (!bytes) return Response.json({ refused: TOO_BIG }, { status: 413 });
118
+ // asked again as it's sent: what the member may do can have changed since the link was made
119
+ const no = await d.mayPut(l.doc, l.who);
120
+ if (no) return Response.json({ refused: no }, { status: 403 });
121
+ const kept = await keep(d.files, bytes, l.name, (await d.apart(l.doc)) ? folderOf(l.doc) : "");
122
+ if ("refused" in kept) return Response.json(kept, { status: 422 });
123
+ // used: a link sends one file
124
+ links.delete(req.params.nonce);
125
+ if (!l.ops) return Response.json(kept);
126
+ const w = await d.write(l.doc, filled(l.ops, kept.file), l.why, l.who);
127
+ return Response.json({ ...kept, ...w }, { status: "why" in w ? 422 : 200 });
128
+ } finally {
129
+ l.busy = false;
130
+ }
131
+ },
132
+ },
133
+ },
134
+ };
135
+ }
136
+ export type Uploads = ReturnType<typeof uploads>;