Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Team templates: a team library, private GitHub repos, scripts travel with skills (#6345)

Milind Soni844b91ecb4e0
diff --git a/docs/team-sharing.md b/docs/team-sharing.md
index ad3d7befb2..d0d7e2476b 100644
--- a/docs/team-sharing.md
+++ b/docs/team-sharing.md
@@ -8,7 +8,8 @@ A bot or a whole department can be shared as a **template**: a small folder anyo
- **A department.** The department's **…** → **Share** shows its card at once, with **Publish to community** and
**Save folder…**. A Chief can also be asked in chat to share its department.
- **Adding one.** **+** → **Import…**: paste a GitHub link or choose a folder, look at what it brings, then **Add**.
- A bot can also add one when you paste the link or folder path in your own message ("import <link>").
+ A bot can also add one when you paste the link or folder path in your own message ("import <link>"). A link to a
+ private repository works once GitHub is connected in Apps (below).
## What the folder holds
@@ -16,6 +17,7 @@ A bot or a whole department can be shared as a **template**: a small folder anyo
<name>/
bot.md or team.md the bots, their instructions, group chats, the Chief, routines and apps by name
skills/<name>/SKILL.md every skill, as standard Agent Skills
+ skills/<name>/<path> the scripts and other text files beside a skill, named in bot.md's skillFiles
avatars/<key>.webp pictures, at most 64 KB each
```
@@ -27,11 +29,68 @@ Never in a template: chats, memory, keys, passwords, tokens, connection addresse
computers or who may see a bot. Every text is checked for key- and password-shaped values, which are replaced; the card
says how many. Routines always arrive paused, and each app is connected with the new owner's own account.
+**A skill's scripts travel with it** (`shared/skill-files.ts`): the files that came in with the skill, only those its
+record lists and only while they are unchanged, never anything a run left beside it. Text files only, at most 30 per
+skill, 128 KB each and 512 KB together, six folders deep. Left out, and named on the card under "Left out": hidden files
+and folders, `node_modules`, `__pycache__` and `venv`, pictures and other binaries, files named like keys (`.env`,
+`*.pem`, `*.key`, `id_rsa`, `credentials.json`, `secrets.*`…) and any file holding a key's shape (a provider's key, a
+private key block). A script's code is never rewritten to hide a value: a file with one stays home instead. Reading a
+folder applies the same rules, so a template whose named file breaks one is refused with the file's name. Scripts
+arrive with the skill switched off, as every imported skill does, and without execute bits; a bot runs them through
+their interpreter (`python3 scripts/report.py`). Older apps ignore the extra files and read the rest.
+
## Publishing
**Publish** sends the folder to the MausBot Admin, which opens a pull request on the community repository
(`milind-soni/openmausbot-teams`); nobody needs a GitHub account. The card then has **Copy link**, a GitHub folder link
that **Import…** accepts, and **View on GitHub**. Publishing needs a MausBot sign-in; without one, the card offers
-**Save folder…** and **Upload on GitHub**, the repository's own upload page.
+**Save folder…** and **Upload on GitHub**, the repository's own upload page. The community repository takes each skill's
+SKILL.md alone for now, so a published template leaves its scripts out; the other targets keep them.
+
+### Your own GitHub repository
+
+**Your GitHub repo…** (in the card's **…**, and beside **Publish to community** in a department's Share) publishes to a
+repository the GitHub connection in Apps can write to: `owner/repo`, an optional folder, and the template goes in
+`<folder>/<slug>/` as one commit on a new branch `mausbot-<slug>-<6 hex>` with a pull request, or straight on the default
+branch with **Commit directly to the default branch**. Files already in that folder under other names stay. Without a
+GitHub connection it says **Connect GitHub in Apps first** with **Open Apps**. On a Team Cloud it uses the team's GitHub,
+or the person's own when the team has each person connect GitHub; the team's Rules apply as to any app call.
+
+**Import…** reads a link GitHub doesn't serve publicly (a private `github.com/<owner>/<repo>/tree/<ref>/<path>`, a
+`blob/…/bot.md`, a repository) through the same connection, only after the public read found nothing, with the public
+reader's caps (1 MB for bot.md or team.md, 4 MB and 300 files in all, only the files it names). Without a connection,
+the not-found sentence adds "If the repository is private, connect GitHub in Apps first."
+
+Both go from the server through the connected-apps service (Composio's GitHub tools, `server/share-github-repo.ts`): the
+token never reaches the app or a model. The tool names and answer shapes follow Composio's documentation and are
+checked against a fake in tests, not yet against the live service.
+
+## A team's own templates
+
+On a Team Cloud, its owner and admins get **Add to {team}'s templates** (the card's **…**, and a department's Share).
+It saves the template folder as it is now in the team's files, `team-files/templates/<slug>/` under the server's data
+folder; adding one with the same slug again replaces it and keeps the one it replaced as `<slug>.previous/`. **Import…**
+then lists **From {team}'s templates**, each with its name, whether it is a bot or a department, who added it and when;
+opening one previews it like any other, and **Add** adds it. The trash button removes one from the list, and its folder
+stays as `<slug>.previous/`. Templates, like packages and backups, are an admin's on a Team Cloud: members don't see the
+list and the routes refuse them. Who added each and when is kept in `share/team-library.json`, outside the team's files;
+a folder there is read through the folder reader and checked again at every import, like any other.
+
+| Route | Who | |
+|---|---|---|
+| `GET /api/share/library` | owner, admin | `{ team, templates: [{ slug, name, scope, tagline, addedBy?, addedAt }] }`; 404 off a Team Cloud |
+| `POST /api/share/<id>/library` | owner, admin | `{ template, replaced }` |
+| `DELETE /api/share/library/<slug>` | owner, admin | `{ ok: true }` |
+| `POST /api/share/import` `{ library: "<slug>" }` | owner, admin | as any import; `?preview=1` previews |
+| `GET /api/share/github` | as Share | `{ connected, reason?, error? }` |
+| `POST /api/share/<id>/publish-repo` `{ repo, folder?, direct? }` | as Share | `{ kind: "pull_request" \| "commit", url, link, branch }`; 409 `github_not_connected` |
+
+## In chat
+
+The `share` tool has the same actions: `export`, `publish`, `publish_to_repo` (`repo` as owner/repo, `path` its folder,
+`direct`), `add_to_team_library`, `import`, `list_team_library` and `import_from_team_library` (`slug`). `import` and
+`publish_to_repo` need the link or the `owner/repo` in the person's own message that started the turn. The team's
+library actions and `publish_to_repo` need a person's own request on a Team Cloud from its owner or an admin, read from
+the server's records of who the turn acts for, never from what the model says.
Backups are separate: Settings → Backup saves everything, chats included.
diff --git a/docs/verification/team-sharing.md b/docs/verification/team-sharing.md
index eca472867f..ab2ab54076 100644
--- a/docs/verification/team-sharing.md
+++ b/docs/verification/team-sharing.md
@@ -9,8 +9,8 @@ from a GitHub link or a folder.
## Automated checks
```sh
-pnpm exec vitest run shared/share-folder.test.ts server/share.test.ts server/share-github.test.ts src/components/TemplateCard.test.ts src/components/ImportDialog.test.ts src/lib/template-share.test.ts
-pnpm exec vitest run server/share.e2e.test.ts --silent=false
+pnpm exec vitest run shared/share-folder.test.ts shared/skill-files.test.ts server/share.test.ts server/share-github.test.ts server/share-skill-files.test.ts server/share-team-templates.test.ts src/components/TemplateCard.test.ts src/components/ImportDialog.test.ts src/lib/template-share.test.ts
+pnpm exec vitest run server/share.e2e.test.ts server/cloud-team-templates.e2e.test.ts --silent=false
OMB_UI_E2E=1 pnpm exec vitest run scripts/testing/team-share-ui.e2e.test.ts scripts/testing/team-template-ui.e2e.test.ts --maxWorkers=1
```
@@ -19,6 +19,13 @@ share itself; the test checks the card in the chat, saves the folder, finds no k
address in it, adds it back as an equivalent bot with its routine paused and skill off, refuses a chat import whose path
the person didn't write, and round-trips a department with its group chat, brief and Chief.
+`server/cloud-team-templates.e2e.test.ts` launches a Team Cloud with an owner, an admin and a member: a bot with a skill
+and its script is shared into `team-files/templates/<slug>/`, added again (the old one kept as `<slug>.previous/`),
+listed, imported as a new bot whose skill brings the script, and removed, each refused to the member, over HTTP and
+through the share tool in a chat. `server/share-team-templates.test.ts` covers a private GitHub link and publishing to
+a person's own repository against a fake GitHub behind a fake connected-apps relay (`server/testing/fake-composio-github.ts`):
+no network is reached.
+
## By hand in a fixture
```sh
diff --git a/packages/phone-protocol/src/share-card.ts b/packages/phone-protocol/src/share-card.ts
index d344904750..0df06c5ecd 100644
--- a/packages/phone-protocol/src/share-card.ts
+++ b/packages/phone-protocol/src/share-card.ts
@@ -62,6 +62,28 @@ export interface TemplateDetails {
brief?: string;
}
+/** A template in a Team Cloud's own library (GET /api/share/library), which its admins add to from Share. */
+export interface TeamTemplate {
+ slug: string;
+ name: string;
+ scope: TemplateScope;
+ tagline: string;
+ /** Who added it last, by name or address. */
+ addedBy?: string;
+ addedAt: number;
+}
+
+/** Where "Publish to GitHub" sends a template besides the community repository: a repository the person's own GitHub
+ * connection can write to, as a pull request from a new branch or one commit on its default branch. */
+export interface TemplateRepoPublish {
+ kind: "pull_request" | "commit";
+ /** The pull request, or the folder on the default branch. */
+ url: string;
+ /** The folder's link that Import accepts. */
+ link: string;
+ branch: string;
+}
+
/** The community repository a published template lands in, and the page anyone can upload a folder through. */
export const COMMUNITY_REPOSITORY_URL = "https://github.com/milind-soni/openmausbot-teams";
export const COMMUNITY_UPLOAD_URL = `${COMMUNITY_REPOSITORY_URL}/upload/main/teams`;
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index ecd79d035f..98b070beb4 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -116,6 +116,7 @@ export const VITEST_SUBSETS = {
"server/cloud-team-requests.e2e.test.ts",
"server/cloud-team-routines.e2e.test.ts",
"server/cloud-team-setup-request.e2e.test.ts",
+ "server/cloud-team-templates.e2e.test.ts",
"server/cloud-team.e2e.test.ts",
"server/host/brief-words.test.ts",
"server/host/lending-lifts.test.ts",
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index b2397b5bb4..869c83baba 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -256,6 +256,7 @@ describe("CI outputs", () => {
"server/cloud-team-requests.e2e.test.ts",
"server/cloud-team-routines.e2e.test.ts",
"server/cloud-team-setup-request.e2e.test.ts",
+ "server/cloud-team-templates.e2e.test.ts",
"server/cloud-team.e2e.test.ts",
"server/host/brief-words.test.ts",
"server/host/lending-lifts.test.ts",
diff --git a/server/cloud-team-templates.e2e.test.ts b/server/cloud-team-templates.e2e.test.ts
new file mode 100644
index 0000000000..47fc883f47
--- /dev/null
+++ b/server/cloud-team-templates.e2e.test.ts
@@ -0,0 +1,128 @@
+// A Team Cloud's own templates on a real Team Cloud, as its owner, an admin and a member: an admin adds a bot's
+// template (its skill's script included) to team-files/templates/<slug>/, adding it again keeps the old one as
+// <slug>.previous/, an admin lists and imports it as a new bot whose skill brings the script, and only an admin removes
+// one. A member reaches none of it, over HTTP or through the share tool in a chat; the owner's own chat request can.
+import { existsSync, readFileSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+import { randomBytes } from "node:crypto";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { launchCloudSendFixture, type CloudSendFixture, type CloudTeamFixture } from "../scripts/testing/cloud-send-fixture.ts";
+import { hostTimeout } from "./testing/host-timeout.ts";
+
+const ENGINE = `process.env.FAKE_CLAUDE_TOOL_CALLS_FILE = process.env.FAKE_CLAUDE_FIXTURE_DIR + "/calls.json";
+process.env.FAKE_CLAUDE_EXIT_AFTER_TURN = "1";`;
+const OLIVE = { email: "[email protected]", role: "owner" as const };
+const ADELE = { email: "[email protected]", role: "admin" as const };
+const RUI = { email: "[email protected]", role: "member" as const };
+const SKILL = "---\nname: report\ndescription: Weekly report.\n---\n\n# Report\n\nRun scripts/report.py.\n";
+const SCRIPT = "import os\ntoken = os.environ.get('REPORT_TOKEN', '')\nprint('weekly report')\n";
+
+let fx: CloudSendFixture, team: CloudTeamFixture;
+const tokens = { olive: "", adele: "", rui: "" };
+type Who = keyof typeof tokens;
+const as = (who: Who, method: string, path: string, body?: unknown) => team.as(tokens[who], method, path, body);
+let reporter: { id: string; threadId: string };
+let templateId = "";
+
+const templates = () => join(team.home, ".openmausbot", "team-files", "templates");
+const toolCalls = (list: unknown[]) => writeFileSync(join(team.home, "calls.json"), JSON.stringify(list));
+async function until(done: () => Promise<boolean>, timeoutMs = 60_000): Promise<void> {
+ const end = Date.now() + timeoutMs;
+ while (!(await done())) {
+ if (Date.now() > end) throw new Error("timed out waiting");
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ }
+}
+const idle = async () => ((await as("olive", "GET", "/api/bots")).body.bots as Array<{ activity?: string; busy?: boolean }>).every((bot) => bot.activity !== "working" && !bot.busy);
+async function say(who: Who, text: string) {
+ const before = ((await as(who, "GET", `/api/threads/${reporter.threadId}/messages?limit=200`)).body.messages as unknown[]).length;
+ const sent = await as(who, "POST", `/api/bots/${reporter.id}/messages`, { text, threadId: reporter.threadId });
+ expect(sent.status, JSON.stringify(sent.body)).toBe(202);
+ await until(async () => await idle() && ((await as(who, "GET", `/api/threads/${reporter.threadId}/messages?limit=200`)).body.messages as unknown[]).length >= before + 2);
+}
+
+beforeAll(async () => {
+ fx = await launchCloudSendFixture({ onePasswordToken: `ops_fake-templates-${randomBytes(8).toString("hex")}`, team: { id: "team-acme-templates", name: "Acme", engine: ENGINE } });
+ team = fx.team!;
+ toolCalls([]);
+ for (const [who, person] of [["olive", OLIVE], ["adele", ADELE], ["rui", RUI]] as const) tokens[who] = (await team.pair(person)).token!;
+ const seeded = await as("olive", "POST", "/api/teams/import", {
+ format: "openmaus.package", version: 2,
+ package: {
+ id: "reporter", release: "1.0.0", name: "Reporter", tagline: "Writes the weekly report.", summary: "Writes reports.", category: "Ops",
+ author: { name: "Fixture" }, license: "MIT", outcomes: ["Reports."], setupMinutes: 2, requirements: { apps: [], capabilities: [] },
+ team: { name: "Seed" }, agents: [{ key: "reporter", name: "Reporter", appearance: { color: "green" }, skills: ["report"] }],
+ skills: { version: 1, entries: [{ name: "report", description: "Weekly report.", instructions: SKILL, files: [{ path: "scripts/report.py", content: SCRIPT }] }] },
+ },
+ });
+ expect(seeded.status, JSON.stringify(seeded.body)).toBe(201);
+ reporter = seeded.body.bots[0];
+ expect((await as("olive", "PUT", `/api/bots/${reporter.id}/access`, { everyone: "chat", people: {} })).status).toBe(200);
+ const skills = (await as("olive", "GET", `/api/bots/${reporter.id}/skills`)).body.skills;
+ expect(skills).toEqual([expect.objectContaining({ name: "report", files: ["scripts/report.py"] })]);
+}, hostTimeout(240_000));
+
+afterAll(async () => {
+ await fx?.close();
+});
+
+describe("a Team Cloud's own templates", () => {
+ it("an admin adds a template with its skill's script; a member can't add, list or import", async () => {
+ const made = await as("olive", "POST", "/api/share/export", { botId: reporter.id });
+ expect(made.status, JSON.stringify(made.body)).toBe(201);
+ templateId = made.body.id;
+ expect(made.body.skipped).toEqual([]);
+ expect((await as("rui", "POST", `/api/share/${templateId}/library`)).status).toBe(403);
+ expect((await as("rui", "GET", "/api/share/library")).status).toBe(403);
+ expect((await as("rui", "POST", "/api/share/import?preview=1", { library: "reporter" })).status).toBe(403);
+ const added = await as("adele", "POST", `/api/share/${templateId}/library`);
+ expect(added.status, JSON.stringify(added.body)).toBe(201);
+ expect(added.body).toMatchObject({ replaced: false, template: { slug: "reporter", name: "Reporter", scope: "bot", addedBy: expect.stringMatching(/adele/i) } });
+ expect(readFileSync(join(templates(), "reporter", "skills", "report", "scripts", "report.py"), "utf8")).toBe(SCRIPT);
+ expect(readFileSync(join(templates(), "reporter", "bot.md"), "utf8")).toContain("skillFiles:");
+ }, hostTimeout(60_000));
+
+ it("adding it again replaces it and keeps the previous one; an admin lists it with who added it and when", async () => {
+ const again = await as("olive", "POST", `/api/share/${templateId}/library`);
+ expect(again.body).toMatchObject({ replaced: true, template: { addedBy: expect.stringMatching(/olive/i) } });
+ expect(existsSync(join(templates(), "reporter.previous", "bot.md"))).toBe(true);
+ const listed = await as("adele", "GET", "/api/share/library");
+ expect(listed).toMatchObject({ status: 200, body: { team: "Acme", templates: [{ slug: "reporter", name: "Reporter", scope: "bot", addedBy: expect.stringMatching(/olive/i), addedAt: expect.any(Number) }] } });
+ }, hostTimeout(60_000));
+
+ it("an admin imports it as a new bot whose skill brings the script, off until someone turns it on", async () => {
+ const preview = await as("adele", "POST", "/api/share/import?preview=1", { library: "reporter" });
+ expect(preview).toMatchObject({ status: 200, body: { details: { scope: "bot", name: "Reporter", skills: [{ name: "report" }] } } });
+ const added = await as("adele", "POST", "/api/share/import", { library: "reporter" });
+ expect(added.status, JSON.stringify(added.body)).toBe(201);
+ const copy = added.body.bots[0];
+ expect(copy.name).toBe("Reporter 2");
+ expect((await as("adele", "GET", `/api/bots/${copy.id}/skills`)).body.skills).toEqual([expect.objectContaining({ name: "report", enabled: false, files: ["scripts/report.py"] })]);
+ }, hostTimeout(60_000));
+
+ it("the share tool: a member's chat request can't add to or import from the library; the owner's can", async () => {
+ const bots = async () => ((await as("olive", "GET", "/api/bots?messages=0")).body.bots as Array<{ name: string }>).length;
+ const before = await bots();
+ toolCalls([{ name: "share", server: "agents", input: { action: "import_from_team_library", slug: "reporter" } }]);
+ await say("rui", "Add the reporter from our templates");
+ expect(await bots()).toBe(before);
+ toolCalls([{ name: "share", server: "agents", input: { action: "export" } }, { name: "share", server: "agents", input: { action: "add_to_team_library" } }]);
+ const listedBefore = (await as("olive", "GET", "/api/share/library")).body.templates[0].addedAt;
+ await say("rui", "Share yourself to the team's templates");
+ expect((await as("olive", "GET", "/api/share/library")).body.templates[0].addedAt).toBe(listedBefore);
+ await say("olive", "Share yourself to the team's templates");
+ toolCalls([]);
+ await until(async () => (await as("olive", "GET", "/api/share/library")).body.templates[0].addedAt > listedBefore, 30_000);
+ expect((await as("olive", "GET", "/api/share/library")).body.templates[0].addedBy).toMatch(/olive/i);
+ }, hostTimeout(180_000));
+
+ it("only an admin removes one, and its folder stays as <slug>.previous", async () => {
+ expect((await as("rui", "DELETE", "/api/share/library/reporter")).status).toBe(403);
+ expect(await as("adele", "DELETE", "/api/share/library/reporter")).toMatchObject({ status: 200, body: { ok: true } });
+ expect((await as("adele", "GET", "/api/share/library")).body.templates).toEqual([]);
+ expect(existsSync(join(templates(), "reporter"))).toBe(false);
+ expect(existsSync(join(templates(), "reporter.previous", "bot.md"))).toBe(true);
+ expect((await as("adele", "POST", "/api/share/import?preview=1", { library: "reporter" })).status).toBe(404);
+ }, hostTimeout(60_000));
+});
diff --git a/server/drivers/agents-catalog-goldens/bridged.profiles.json b/server/drivers/agents-catalog-goldens/bridged.profiles.json
index 9361adbe74..68a660d8fa 100644
--- a/server/drivers/agents-catalog-goldens/bridged.profiles.json
+++ b/server/drivers/agents-catalog-goldens/bridged.profiles.json
@@ -1,7 +1,7 @@
{
"default": {
- "bytes": 17726,
- "sha256": "d64b9f99aa4d4cd6cdbcfc61970fe7990e63fee9cdbed873054b2668989c5a43",
+ "bytes": 17989,
+ "sha256": "9c00b6de2bb08abff37fa675570bb80fad5bd869ad008ddc5d3e0c2450b356a6",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -24,8 +24,8 @@
]
},
"voice": {
- "bytes": 18507,
- "sha256": "8f5810b08cb2564e005cd9cd366625e624b8d399a9ec94dcfc3b5561026d1e13",
+ "bytes": 18770,
+ "sha256": "b7290180ade5ef3aeab4ba22e0c33869338092ab51527cbc801a09f6e8d52be8",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -49,8 +49,8 @@
]
},
"shared": {
- "bytes": 17766,
- "sha256": "e64b038f41d03f3b1dbf890d5237bd51387c0cfe0e9acf0dd86d41cf40dca15c",
+ "bytes": 18029,
+ "sha256": "4d1b6bbda1ac05cf4c7c341015002cea9ac454f48fb834df27829a5873475c57",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -73,8 +73,8 @@
]
},
"shared+voice": {
- "bytes": 18547,
- "sha256": "415484afe582b0eebf130d8414f89cde7bf691d034098d024ca5138ef7c9a33a",
+ "bytes": 18810,
+ "sha256": "ea0e25d650f83d05334ea64e29aafa0f8865f27e22d860b4d9df543d32e94112",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -98,8 +98,8 @@
]
},
"skills": {
- "bytes": 17753,
- "sha256": "7f3d088cd61beb6d5001ee5d1ab0222086deaca9f6896bac69f407c85127efa2",
+ "bytes": 18016,
+ "sha256": "5f3f06912b5fb36e54000ee1accfe6afa130f404aed0319aff8cf2adbd5aae4f",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -122,8 +122,8 @@
]
},
"skills+voice": {
- "bytes": 18534,
- "sha256": "e766f1d5b5ec6fb3688de2ade8ef498f4ab67ec2feb4abeeb9cee62b3791073f",
+ "bytes": 18797,
+ "sha256": "ab4bc17bb6275e90572f9ab754e22950aedfe00795c12b6733fb7232fcfc8c35",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -147,8 +147,8 @@
]
},
"skills+shared": {
- "bytes": 17793,
- "sha256": "bc9224741239b341aaf2cfb395598f483b122fb4b6d4a10c02fbe5c951c04c87",
+ "bytes": 18056,
+ "sha256": "7d90ef08c89110ae20023637ab700c634ce65b2402ddbbd4453d4851e6bfcaf9",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -171,8 +171,8 @@
]
},
"skills+shared+voice": {
- "bytes": 18574,
- "sha256": "623623f250d909353892daf6bc6f0960fd2bd4563e378efc0ca92be3e8f8f46d",
+ "bytes": 18837,
+ "sha256": "531c8fffd12ec8f0764f50935731d5477908b5ecd06715fa81977e56e4c4ea04",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -196,8 +196,8 @@
]
},
"non-chief": {
- "bytes": 17609,
- "sha256": "dce9a2d7d5e2cf19879e30451f7bf28e0bd3ec7abf524cbe807435f13ca1c2bb",
+ "bytes": 17872,
+ "sha256": "1d40c68606e417c06e18ca1d83ccbb7b1a54184a279e3c8d771537145838b1a4",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -220,8 +220,8 @@
]
},
"voice+non-chief": {
- "bytes": 18390,
- "sha256": "5aef762e6a020cf13ac0c4146afbdeed13ae3f7252d34c96c7c361c61045c089",
+ "bytes": 18653,
+ "sha256": "a9dadc3dded6cef839c7f6bd8bdcf7e6ce652f1c3ec4e623e436b4420a4cb08b",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -245,8 +245,8 @@
]
},
"shared+non-chief": {
- "bytes": 17649,
- "sha256": "215564adf5f8964f50bad4a256294bb46e028b171bbf719c35e290a10cada7bd",
+ "bytes": 17912,
+ "sha256": "8aa44871ce811407aee21b17352128b293a547437f1c0005b69ada2002ee651c",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -269,8 +269,8 @@
]
},
"shared+voice+non-chief": {
- "bytes": 18430,
- "sha256": "2f8a7efe8203c0b6c7ef989d1214b847cf71a11df100cc24c029f05b82854cd8",
+ "bytes": 18693,
+ "sha256": "db49fa84da8e11f651e54f2cb91ef0979a912a9ef10afaabc3279836951899b1",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -294,8 +294,8 @@
]
},
"skills+non-chief": {
- "bytes": 17636,
- "sha256": "86aa9c491a5d2a13cfe0524233eb381c1f435db2ada208dc0f94fb2a4c54b3cd",
+ "bytes": 17899,
+ "sha256": "b24e363e8c7c792c1b30b94c715c73c6293547a5db621978353d6344b6b6823e",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -318,8 +318,8 @@
]
},
"skills+voice+non-chief": {
- "bytes": 18417,
- "sha256": "c0701e10daaffcb3e2976e7f51c18a4f628c0e3ba2666a7bbd30e94a42c55710",
+ "bytes": 18680,
+ "sha256": "5af1a7fab9daae269f86077ff2d60482c464670f662b671d3d4baafc6b81c08a",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -343,8 +343,8 @@
]
},
"skills+shared+non-chief": {
- "bytes": 17676,
- "sha256": "63d2fc9cd00dc9e731691939c498aeda4c744cde2d5710234040ea7f5b64fbcb",
+ "bytes": 17939,
+ "sha256": "6854aa03b46f74f3e658b08def8308301466d70f47a0942c1bdd85b98f7ea918",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -367,8 +367,8 @@
]
},
"skills+shared+voice+non-chief": {
- "bytes": 18457,
- "sha256": "d36147c039c56425cddf8444932838abe9652f81455649bf0e741271b085a51a",
+ "bytes": 18720,
+ "sha256": "949db9bed55d5ea0737a8219ec7e18949163aed3ccf4989c4e2095c629ee3c04",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -392,8 +392,8 @@
]
},
"skills+shared+voice+cloud-home": {
- "bytes": 18590,
- "sha256": "7bd1650502d598192bec1669696b49d0c4d723dd36bcf3d5d9b5670991663b71",
+ "bytes": 18853,
+ "sha256": "61abe16319e25c98d307527b3bada8ea37f160a8d77bda58f73618fb2a49adf7",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -417,8 +417,8 @@
]
},
"skills+shared+voice+non-chief+cloud-home": {
- "bytes": 18473,
- "sha256": "200d0e55fe484abd975f43e19be0129a6be8fc6fabbb298097e49bd8d0e70819",
+ "bytes": 18736,
+ "sha256": "41da042d5aab412415da6129de29be17df1e342eaf9cced823fa2e80bc636a3f",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -442,8 +442,8 @@
]
},
"skills+shared+voice+x": {
- "bytes": 18635,
- "sha256": "dbc23ce2cf6db410f9d0c2bf0fae33c4efe445064beb32b2cf3d5e7e408f2b69",
+ "bytes": 18898,
+ "sha256": "66766d81cb153531ebbb95eafbf5f86686b4aece4cb8276ae7e6e7a10d30095a",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -467,8 +467,8 @@
]
},
"skills+shared+voice+x+team": {
- "bytes": 18635,
- "sha256": "dbc23ce2cf6db410f9d0c2bf0fae33c4efe445064beb32b2cf3d5e7e408f2b69",
+ "bytes": 18898,
+ "sha256": "66766d81cb153531ebbb95eafbf5f86686b4aece4cb8276ae7e6e7a10d30095a",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -492,8 +492,8 @@
]
},
"skills+shared+voice+x+team+images": {
- "bytes": 18651,
- "sha256": "5ae63dd63893a09b66f3327415e7c8a0de1453faa56ffcd0f2400a3b0813cb9e",
+ "bytes": 18914,
+ "sha256": "de639176826c371bc402759b2b5cc70476872adaf77f8b81e714171631b2611a",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -517,8 +517,8 @@
]
},
"default+legacy-switches": {
- "bytes": 17726,
- "sha256": "d64b9f99aa4d4cd6cdbcfc61970fe7990e63fee9cdbed873054b2668989c5a43",
+ "bytes": 17989,
+ "sha256": "9c00b6de2bb08abff37fa675570bb80fad5bd869ad008ddc5d3e0c2450b356a6",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -541,8 +541,8 @@
]
},
"default+mausbot": {
- "bytes": 17778,
- "sha256": "4b852e5e84ed4548f259fdd31378cd09fc88ff8a76f152a348189c81bed47692",
+ "bytes": 18041,
+ "sha256": "0d70e9060492efe1cf18fa9cf0148d0175d5dc68c1ef9e9d81af0695ffe4ddef",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -565,8 +565,8 @@
]
},
"skills+shared+voice+mausbot": {
- "bytes": 18626,
- "sha256": "5f9e42bc0bd07c85cb46aa0adc8484a5afa58b5725b483c25a81ee70ad57add6",
+ "bytes": 18889,
+ "sha256": "947fc6cb7bb1213006eac4391dbdf42628cb0770eeb72e984be10bca3a05c4f3",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -590,8 +590,8 @@
]
},
"default+no-computer-pick": {
- "bytes": 16514,
- "sha256": "e08060bb80b69c1b900ce1a5242302dd49c7da95299d4781a9aca2add45107f5",
+ "bytes": 16777,
+ "sha256": "d4d796758cedfaebd632f82712b8a5b1fbcb1d2904d28c84dbdcfe8c94294afb",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -613,8 +613,8 @@
]
},
"default+room": {
- "bytes": 16455,
- "sha256": "59fb1d20a7c7aa098b7c4c4c1268b98d7697a87e5b06518ebf44470e5a6934aa",
+ "bytes": 16718,
+ "sha256": "6252ee18fdd37ea6eefdac454ec5da00ddc809d38e2d67b722d3c6a44d42568d",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -636,8 +636,8 @@
]
},
"non-chief+room": {
- "bytes": 16338,
- "sha256": "466142b8331dbf1f41a0bbf244c7ade2e36c703ce98d51dd5cd632205fe4bd5f",
+ "bytes": 16601,
+ "sha256": "b6e0179a79c8aaee24e2fb48aae08a8106eaea4fb9d8b95e41ee85a481cf1144",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -659,8 +659,8 @@
]
},
"default+images": {
- "bytes": 17742,
- "sha256": "14c51eaabfa2bd2b946077c148840cc8efdb1cbdd3e32d8afad7fbf8a4b454fb",
+ "bytes": 18005,
+ "sha256": "9951ca6b93885b0261a11e4fbcdaf624371da1a2523776aceadd6abcf61da2fd",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -683,8 +683,8 @@
]
},
"skills+shared+voice+x+team+images+hosting": {
- "bytes": 19853,
- "sha256": "31086e1245ae972f8aa656cb62e55d0580224024191b887b7615bf7389451fed",
+ "bytes": 20116,
+ "sha256": "e12ea96f9b2e54dcc912e2d47065cc85ed421ec8496d84b615bce8efb5466458",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -709,8 +709,8 @@
]
},
"default+hosting": {
- "bytes": 18928,
- "sha256": "72b06100281e30d949405ed48eebe4bcda647b0d97a5ac398520d3be57427991",
+ "bytes": 19191,
+ "sha256": "a147a7896bf34951b6ef3c44951f1ae04b2174e21e452761893db1e6cbe85254",
"tools": [
"tool_result_read",
"list_room_targets",
diff --git a/server/drivers/agents-catalog-goldens/bridged.tools-list.json b/server/drivers/agents-catalog-goldens/bridged.tools-list.json
index 47a445de18..28276f61a6 100644
--- a/server/drivers/agents-catalog-goldens/bridged.tools-list.json
+++ b/server/drivers/agents-catalog-goldens/bridged.tools-list.json
@@ -457,7 +457,7 @@
},
{
"name": "share",
- "description": "Share yourself (or, as Chief, your department) as a template: no chats, memory or keys. export shows a card; publish puts it on the community GitHub; import adds one the person linked.",
+ "description": "Share yourself (or, as Chief, your department) as a template, no chats, memory or keys: export shows a card; publish to the community GitHub, publish_to_repo to repo (path: its folder), add_to_team_library; import a link the person gave, list_team_library, import_from_team_library.",
"inputSchema": {
"type": "object",
"additionalProperties": false,
@@ -467,7 +467,11 @@
"enum": [
"export",
"publish",
- "import"
+ "publish_to_repo",
+ "add_to_team_library",
+ "import",
+ "list_team_library",
+ "import_from_team_library"
]
},
"department": {
@@ -478,6 +482,15 @@
},
"path": {
"type": "string"
+ },
+ "slug": {
+ "type": "string"
+ },
+ "repo": {
+ "type": "string"
+ },
+ "direct": {
+ "type": "boolean"
}
},
"required": [
diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.json
index 98b146d7fd..07b568d3ff 100644
--- a/server/drivers/agents-catalog-goldens/full.tools-list.json
+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json
@@ -1347,7 +1347,7 @@
},
{
"name": "share",
- "description": "Share yourself (or, as Chief, your department) as a template: no chats, memory or keys. export shows a card; publish puts it on the community GitHub; import adds one the person linked.",
+ "description": "Share yourself (or, as Chief, your department) as a template, no chats, memory or keys: export shows a card; publish to the community GitHub, publish_to_repo to repo (path: its folder), add_to_team_library; import a link the person gave, list_team_library, import_from_team_library.",
"inputSchema": {
"type": "object",
"additionalProperties": false,
@@ -1357,7 +1357,11 @@
"enum": [
"export",
"publish",
- "import"
+ "publish_to_repo",
+ "add_to_team_library",
+ "import",
+ "list_team_library",
+ "import_from_team_library"
]
},
"department": {
@@ -1368,6 +1372,15 @@
},
"path": {
"type": "string"
+ },
+ "slug": {
+ "type": "string"
+ },
+ "repo": {
+ "type": "string"
+ },
+ "direct": {
+ "type": "boolean"
}
},
"required": [
diff --git a/server/drivers/agents-catalog-goldens/profiles.json b/server/drivers/agents-catalog-goldens/profiles.json
index 43c491c07f..a758c9e537 100644
--- a/server/drivers/agents-catalog-goldens/profiles.json
+++ b/server/drivers/agents-catalog-goldens/profiles.json
@@ -1,7 +1,7 @@
{
"default": {
- "bytes": 57945,
- "sha256": "694f5f133230d8c71d26aaed4f06d214102f68bf6b3e6d29d99337b71549046e",
+ "bytes": 58208,
+ "sha256": "59b039ab48daf62260736259455c490eaa3c0b04ea6e979a55e9c65eabf50179",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -57,8 +57,8 @@
]
},
"voice": {
- "bytes": 58726,
- "sha256": "ca86753e1456ecd1389846e7b07e1d1a9f48cb79f81f79315cbf0c20c60ace5a",
+ "bytes": 58989,
+ "sha256": "83e8671516b9a4f3c617df9d59fdafa1a8d72d25ae618c83cb86baef855eb712",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -115,8 +115,8 @@
]
},
"shared": {
- "bytes": 60210,
- "sha256": "32a509b1706e944ec8287748f0a57326220f9c1ea00896efe6f2d958287f3799",
+ "bytes": 60473,
+ "sha256": "9f751b38a2ad13ca9d2240f4751a86607b07fbe05fe797b1c7298038031e2089",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -174,8 +174,8 @@
]
},
"shared+voice": {
- "bytes": 60991,
- "sha256": "d894a3b93d39f4a36bd66092899444349ec8a8acb60009e29ff491c3e6a4cdb4",
+ "bytes": 61254,
+ "sha256": "2c46f5c48fd34d1b5b42ff77db28b2b9b3e908f2cecf84fa017da879c7b2c6e6",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -234,8 +234,8 @@
]
},
"skills": {
- "bytes": 60031,
- "sha256": "4629426d1ec0aec516a553e2eaec79a829a931c475628f23aa2922fb52246732",
+ "bytes": 60294,
+ "sha256": "9f375e95e3c2d37ded718d9d416924cd4749007c665b404c037e79e2dbcde7c6",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -293,8 +293,8 @@
]
},
"skills+voice": {
- "bytes": 60812,
- "sha256": "0d43e3216fea3ff30d1720bb01e074d7b0ffbae5b60eb44f76fd25edc3568bfb",
+ "bytes": 61075,
+ "sha256": "122dd36954b22a3987a28fa0bbad80eea7270c9164ecaf04ccb76c20bf61b921",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -353,8 +353,8 @@
]
},
"skills+shared": {
- "bytes": 62296,
- "sha256": "251aad09ddfd6e05bec2964a78ab24cee36d9622513e4fdfd5aed25f7e87f5e0",
+ "bytes": 62559,
+ "sha256": "f9ebb60b88ece0249462ae2d6a1c5cf4e7a7c80f1c5ca6dcf4029fbb11f2443e",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -414,8 +414,8 @@
]
},
"skills+shared+voice": {
- "bytes": 63077,
- "sha256": "766cab548273a71c5e5c953ff92b3f53ec12576b2eda0b9ca4a4ccc7a5fffd79",
+ "bytes": 63340,
+ "sha256": "eb48a68a1a4802210e7d38685823922a3676e34b47c8f09c6b83d376989c846e",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -476,8 +476,8 @@
]
},
"non-chief": {
- "bytes": 49528,
- "sha256": "d55dac8f5570038d89d6f0e54a96d9efe17839aab0b6f98a3ec59bef703c6120",
+ "bytes": 49791,
+ "sha256": "674974ee50050405f4ba10e46a5b0ef03439296c0876f6e4ca2f29a4e1ca15fd",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -526,8 +526,8 @@
]
},
"voice+non-chief": {
- "bytes": 50309,
- "sha256": "ff2d0bcb336d5ab8e742b70297d9eb3da1eb38dfdba75fbc20edce3c3ef3d1d2",
+ "bytes": 50572,
+ "sha256": "0aff8c7f3e5161fcc6779bad4061c131c07b8ffa691338972a208fd136778c3f",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -577,8 +577,8 @@
]
},
"shared+non-chief": {
- "bytes": 51793,
- "sha256": "ba5228e1196d565d007e61e8fe19c4f61c02e1ec7f9e3fb6cafb962f0bb3b465",
+ "bytes": 52056,
+ "sha256": "7c66dbbb003e69d4365c85558ac7cb0f5a875ac340d9c4980419311ab4adc63a",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -629,8 +629,8 @@
]
},
"shared+voice+non-chief": {
- "bytes": 52574,
- "sha256": "e5d2ef0328793cd1fab4077fe9e3cddca1ff8663d809c7c4a597db782b081ef6",
+ "bytes": 52837,
+ "sha256": "a1f3a050e3ab1d4a683702f58efb372aa06fa4728318b65a7311f5cf507a81ea",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -682,8 +682,8 @@
]
},
"skills+non-chief": {
- "bytes": 51614,
- "sha256": "916e858544b22f5af96d1e442b25a313952d7f8c6fd073e3b85869eae849a820",
+ "bytes": 51877,
+ "sha256": "ae477368a2fd375b9d3171b4ce06486efe575667cdb251a285a05f0cf715bdab",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -734,8 +734,8 @@
]
},
"skills+voice+non-chief": {
- "bytes": 52395,
- "sha256": "e8b24322125964ebef751162fb2955fc24d5ae0a781de5439cb283d2b7c1c0ad",
+ "bytes": 52658,
+ "sha256": "6c656392c283c6b27538e5bb29e00ef0a2f014e19d909eb574fafb1f5da7d730",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -787,8 +787,8 @@
]
},
"skills+shared+non-chief": {
- "bytes": 53879,
- "sha256": "698de0210e5156591feae7d15e1d5d0ff902eeede1a08b12609bacad177e1772",
+ "bytes": 54142,
+ "sha256": "ccdd9890eed20f02c8bcf0cdc2aa74489b3cbe45e5dc759cc1cc8f321dcce487",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -841,8 +841,8 @@
]
},
"skills+shared+voice+non-chief": {
- "bytes": 54660,
- "sha256": "bf84e2d96446c93d5989c9aa220ff7bba56b067c0467ca7f344409de08c1f57e",
+ "bytes": 54923,
+ "sha256": "1f70489c75f0f8998333b8780730848d18170bc99cb02f679db25a8931645fd9",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -896,8 +896,8 @@
]
},
"skills+shared+voice+cloud-home": {
- "bytes": 62843,
- "sha256": "0c08e5112b5c53fd4842984082fa9d93de936aa365d83b10049ef5d33977de20",
+ "bytes": 63106,
+ "sha256": "1966d8684d3168ca7be275f793c59211d246e5a9ddf622c16bf48730571b34c6",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -958,8 +958,8 @@
]
},
"skills+shared+voice+non-chief+cloud-home": {
- "bytes": 54426,
- "sha256": "4b65d908fa2988d164177ce3fe2ff958be00cbff37dd2378dc8fb7e5ccea0066",
+ "bytes": 54689,
+ "sha256": "f3dce8fe1f34aa42a4f4e0bb55711267b0471956347c8f87c912b6ced09d7887",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1013,8 +1013,8 @@
]
},
"skills+shared+voice+x": {
- "bytes": 66916,
- "sha256": "aa1ee7cacd5945c100cbe2ecf7c9af2bff2402ed6091afce55548327c1342f44",
+ "bytes": 67179,
+ "sha256": "ba651aebfc222fdefa0dc4ac7dc9cc8e6752b6d1e2c5caaaca472162d4d0fe73",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1079,8 +1079,8 @@
]
},
"skills+shared+voice+x+team": {
- "bytes": 66916,
- "sha256": "aa1ee7cacd5945c100cbe2ecf7c9af2bff2402ed6091afce55548327c1342f44",
+ "bytes": 67179,
+ "sha256": "ba651aebfc222fdefa0dc4ac7dc9cc8e6752b6d1e2c5caaaca472162d4d0fe73",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1145,8 +1145,8 @@
]
},
"skills+shared+voice+x+team+images": {
- "bytes": 67689,
- "sha256": "3f0103a64eafa823ceaa2e34d92f3f9128e0e1ad7ab35381e95f6b1ac100652f",
+ "bytes": 67952,
+ "sha256": "dc5c8cf6bb049b803ee7b64d225acc94593e0fa54ec0f9f4f5f1d319366d26a0",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1212,8 +1212,8 @@
]
},
"default+legacy-switches": {
- "bytes": 57945,
- "sha256": "694f5f133230d8c71d26aaed4f06d214102f68bf6b3e6d29d99337b71549046e",
+ "bytes": 58208,
+ "sha256": "59b039ab48daf62260736259455c490eaa3c0b04ea6e979a55e9c65eabf50179",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1269,8 +1269,8 @@
]
},
"default+mausbot": {
- "bytes": 58596,
- "sha256": "e7d47f6487e02eb2721f140c460700b079aef32f913e7497e6b45c74b7a8757a",
+ "bytes": 58859,
+ "sha256": "d24be1ff45034e27f9ae71a315e369a9cd70fc076f9e5dbe24c990352e09ce1c",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1328,8 +1328,8 @@
]
},
"skills+shared+voice+mausbot": {
- "bytes": 63728,
- "sha256": "a5436bdfba1c92a5d7e1ca3c7959492820fd8e9383f89d238da636158ad25a08",
+ "bytes": 63991,
+ "sha256": "24df79984b3017182c1a5fb62c41a1c6ed1758325da1863bced4ccf3c09c9b78",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1392,8 +1392,8 @@
]
},
"default+no-computer-pick": {
- "bytes": 56733,
- "sha256": "0fe4b1a3a763b5f603b488b2d1743193747633aef7cfa2c5c68fad553b3054cb",
+ "bytes": 56996,
+ "sha256": "f9ba7875dce0c5ad6209fadac8fe2859d68bb91525457a8ee5761cf687e078f0",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1448,8 +1448,8 @@
]
},
"default+room": {
- "bytes": 53729,
- "sha256": "f3493eaaab6e143d221a9a89faf74d7d5daa3e5a4f1d0d13bba7f5eb3ac5e88e",
+ "bytes": 53992,
+ "sha256": "eef3d8828c77f968f34b9e4dbede075ef81c3fa63a0d587cedbc9a2d7ebd3d2c",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1499,8 +1499,8 @@
]
},
"non-chief+room": {
- "bytes": 45312,
- "sha256": "f1155600188c1cdd2089a311e8760b1b9f1efb9de024b0618330d37a855b1788",
+ "bytes": 45575,
+ "sha256": "4314e9768e67df941f8c149d17713ba920e5bfc28b7a062b0ebb311752c6b94e",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1543,8 +1543,8 @@
]
},
"default+images": {
- "bytes": 58718,
- "sha256": "059cbad7bdc05a6631107f6f31b9b56097b585e5a4d831361ec2469e7e515459",
+ "bytes": 58981,
+ "sha256": "9fffd3ed2acfa15fe28a133d9d56c90b0fb744a97d6355b26a51798a265d1832",
"tools": [
"tool_result_read",
"list_room_targets",
@@ -1601,8 +1601,8 @@
]
},
"skills+shared+voice+x+team+images+hosting": {
- "bytes": 69552,
- "sha256": "72c2f23b3a58648fc2188952cdb92d468d42bb07e49a77da250f8ec0c513bb77",
+ "bytes": 69815,
+ "sha256": "924a7b17b4a013427a66af3c7990648b2b5783d1d918ca6f3f437322354046ff",
"tools": [
"tool_result_read",
"list_shared_computers",
@@ -1670,8 +1670,8 @@
]
},
"default+hosting": {
- "bytes": 59808,
- "sha256": "81aeaa7a16615c9a228420884910854136edef3972c41c49a691e7bb49484f7b",
+ "bytes": 60071,
+ "sha256": "8f00c59babb861f835ad4f553c43b5a03d9e6e38f5edb7ce48b6d9d1b2f37de0",
"tools": [
"tool_result_read",
"list_room_targets",
diff --git a/server/drivers/agents-catalog-wire.test.ts b/server/drivers/agents-catalog-wire.test.ts
index 7fff697e84..4e2a59b9a3 100644
--- a/server/drivers/agents-catalog-wire.test.ts
+++ b/server/drivers/agents-catalog-wire.test.ts
@@ -108,14 +108,14 @@ const BUDGET_BASELINE: Record<string, number> = {
"default+legacy-switches": 57945,
"default+mausbot": 58596,
"skills+shared+voice+mausbot": 63728,
- "skills+shared+voice+x": 65605,
- "skills+shared+voice+x+team": 65605,
+ "skills+shared+voice+x": 67179,
+ "skills+shared+voice+x+team": 67179,
"default+no-computer-pick": 56733,
"default+room": 53729,
"non-chief+room": 45312,
- "skills+shared+voice+x+team+images": 66378,
+ "skills+shared+voice+x+team+images": 67952,
"default+images": 58718,
- "skills+shared+voice+x+team+images+hosting": 68241,
+ "skills+shared+voice+x+team+images+hosting": 69815,
"default+hosting": 59808,
"default+tools-off": 53040,
};
diff --git a/server/drivers/agents-share-tool.ts b/server/drivers/agents-share-tool.ts
index 99b73aff16..25bfdcd45a 100644
--- a/server/drivers/agents-share-tool.ts
+++ b/server/drivers/agents-share-tool.ts
@@ -9,15 +9,18 @@ export const SHARE_TOOL_DEFINITIONS = [
{
name: "share",
description:
- "Share yourself (or, as Chief, your department) as a template: no chats, memory or keys. export shows a card; publish puts it on the community GitHub; import adds one the person linked.",
+ "Share yourself (or, as Chief, your department) as a template, no chats, memory or keys: export shows a card; publish to the community GitHub, publish_to_repo to repo (path: its folder), add_to_team_library; import a link the person gave, list_team_library, import_from_team_library.",
inputSchema: {
type: "object",
additionalProperties: false,
properties: {
- action: { type: "string", enum: ["export", "publish", "import"] },
+ action: { type: "string", enum: ["export", "publish", "publish_to_repo", "add_to_team_library", "import", "list_team_library", "import_from_team_library"] },
department: { type: "boolean" },
url: { type: "string" },
path: { type: "string" },
+ slug: { type: "string" },
+ repo: { type: "string" },
+ direct: { type: "boolean" },
},
required: ["action"],
},
diff --git a/server/host/share-github-access.ts b/server/host/share-github-access.ts
new file mode 100644
index 0000000000..eb0ea967e1
--- /dev/null
+++ b/server/host/share-github-access.ts
@@ -0,0 +1,49 @@
+// Which GitHub connection a template's private import or repository publish uses: the team's (or this computer's) own,
+// or, when a Team Cloud has each person connect GitHub themselves, the requesting person's. Security: the team's Rules
+// apply as they do to a bot's app calls, and the relay goes to the connected-apps service from here, so no token reaches
+// the app or a model.
+import type * as Composio from "../composio.ts";
+import type { AppConfig } from "../config.ts";
+import { CONNECT_GITHUB, type GithubConnection } from "../share-github-repo.ts";
+import { asPerson, type PersonAppsAccess } from "../team-connections.ts";
+
+export interface ShareGithubAccessDeps {
+ cfg(): AppConfig;
+ composio: Pick<typeof Composio, "configured" | "connectedServices" | "relayMcp">;
+ /** The apps each person connects for themselves (only on a Team Cloud). */
+ personApps(): readonly string[];
+ appsAccess(person: string): PersonAppsAccess | null;
+ /** Why the team's Rules refuse an app; null when they allow it. */
+ appRefusal(slug: string): string | null;
+}
+
+const APP = "github";
+
+export function createShareGithubAccess(deps: ShareGithubAccessDeps) {
+ /** The connection for `person` (the request's or the turn's; null for none). */
+ return async function githubConnection(person: string | null): Promise<GithubConnection> {
+ const refused = deps.appRefusal(APP);
+ if (refused) return { ok: false, reason: "refused", message: refused };
+ let [cfg, access] = [deps.cfg(), undefined as ReturnType<typeof asPerson>[1]];
+ if (!deps.composio.configured(cfg)) return { ok: false, reason: "not_connected", message: CONNECT_GITHUB };
+ if (deps.personApps().includes(APP)) {
+ const own = person ? deps.appsAccess(person) : null;
+ if (!own) return { ok: false, reason: "not_connected", message: CONNECT_GITHUB };
+ [cfg, access] = asPerson(cfg, own);
+ }
+ let state;
+ try {
+ state = (await deps.composio.connectedServices(cfg, access))[APP];
+ } catch {
+ return { ok: false, reason: "unavailable", message: "Apps can't be reached right now. Try again in a few minutes." };
+ }
+ const active = (state?.accounts ?? []).filter((account) => /^active$/i.test(account.status));
+ if (!state?.connected || !active.length) return { ok: false, reason: "not_connected", message: CONNECT_GITHUB };
+ return {
+ ok: true,
+ ...(active.length > 1 ? { account: active[0]!.id } : {}),
+ relay: (payload, session, signal) => deps.composio.relayMcp(cfg, payload as never, session, undefined, signal, access),
+ };
+ };
+}
+export type ShareGithubAccess = ReturnType<typeof createShareGithubAccess>;
diff --git a/server/host/share.ts b/server/host/share.ts
index c7ee8c53ee..e193f43156 100644
--- a/server/host/share.ts
+++ b/server/host/share.ts
@@ -12,8 +12,10 @@ import { createShareRoutes, createShareToolRoute } from "../routes/share.ts";
import { createShareHost, type ShareHostDeps } from "../share.ts";
import { createCommunityPublisher } from "../share-publish.ts";
import type { BotRecord, GroupRecord } from "../store.ts";
+import { createTeamTemplates } from "../team-templates.ts";
+import { createShareGithubAccess, type ShareGithubAccessDeps } from "./share-github-access.ts";
-export interface ShareWiringDeps extends Pick<ShareHostDeps, "dataDir" | "groups" | "brief" | "botFolder" | "collectTeamSkills"> {
+export interface ShareWiringDeps extends Pick<ShareHostDeps, "dataDir" | "groups" | "brief" | "botFolder" | "collectTeamSkills" | "skillFiles"> {
bots(): readonly BotRecord[];
routines(): readonly Routine[];
access(): PagesAccess | null;
@@ -27,6 +29,12 @@ export interface ShareWiringDeps extends Pick<ShareHostDeps, "dataDir" | "groups
publicBot(bot: BotRecord): WireBot;
publicGroup(group: GroupRecord): WireGroup;
broadcast(payload: Record<string, unknown>): void;
+ /** A Team Cloud's team: it gets a library of its own templates. */
+ team: { name: string } | null;
+ /** A request's person on a Team Cloud, and how the team's library names them. */
+ personOf(auth: RequestAuth): string | null;
+ who(auth: RequestAuth): string | undefined;
+ github: ShareGithubAccessDeps;
}
/** A bot's own picture as a data: URL; none for a mascot. */
@@ -41,17 +49,19 @@ function botPicture(bot: BotRecord): string | undefined {
export function createShareWiring(deps: ShareWiringDeps) {
const host = createShareHost({
dataDir: deps.dataDir, bots: deps.bots, groups: deps.groups, routines: deps.routines, brief: deps.brief, botFolder: deps.botFolder,
- collectTeamSkills: deps.collectTeamSkills, picture: botPicture,
+ collectTeamSkills: deps.collectTeamSkills, skillFiles: deps.skillFiles, picture: botPicture,
publisher: createCommunityPublisher({ access: deps.access, notOffered: deps.notOffered, selfHosted: deps.selfHosted }),
patch: (threadId, messageId, text, template) => deps.patchMessage(threadId, messageId, { text, template }),
});
const view = { publicBot: deps.publicBot, publicGroup: deps.publicGroup, broadcast: deps.broadcast };
+ const library = deps.team ? { team: deps.team.name, templates: createTeamTemplates(deps.dataDir) } : null;
+ const github = createShareGithubAccess(deps.github);
const routes = createShareRoutes({
- host, localFolders: deps.localFolders, ...view,
+ host, localFolders: deps.localFolders, ...view, library, github, personOf: deps.personOf, who: deps.who,
bots: (auth) => { const shown = deps.visibleBot?.(auth); return shown ? deps.bots().filter((bot) => shown(bot.id)) : deps.bots(); },
routines: (auth) => { const shown = deps.visibleRoutine?.(auth); return shown ? deps.routines().filter(shown) : deps.routines(); },
importDeps: async (auth) => ({ ...await deps.importDeps(), ...(auth ? teamCreator(auth) : {}) }),
});
- const tool = createShareToolRoute({ host, localFolders: deps.localFolders, ...view, bots: deps.bots, routines: deps.routines, importDeps: () => deps.importDeps() });
+ const tool = createShareToolRoute({ host, localFolders: deps.localFolders, ...view, library, github, bots: deps.bots, routines: deps.routines, importDeps: () => deps.importDeps() });
return { host, routes, tool };
}
diff --git a/server/host/skills-library.ts b/server/host/skills-library.ts
index 73895926f7..9e0e6b5d48 100644
--- a/server/host/skills-library.ts
+++ b/server/host/skills-library.ts
@@ -16,6 +16,7 @@ import { nativeSkillListing, nativeSkills, projectSkillListing, projectSkills, p
import { redactSecretsInText } from "../redact.ts";
import { readSectionContext } from "../section-context.ts";
import { librarySkillOptOuts, listLibrarySkills, readLibrarySkillFile, readSkillLibraryIndex, skillsLibraryEnabled } from "../skill-library.ts";
+import { librarySkillFiles, ownSkillFiles, type StoredSkillFiles } from "../skill-side-files.ts";
import {
conversationAssignedSkills,
prepareShareNote,
@@ -112,6 +113,14 @@ export function createSkillsLibraryHost(deps: SkillsLibraryHostDeps) {
const native = nativesFor(bot).find((skill) => skill.name === name) ?? projectFor(bot, bot.threadId).find((skill) => skill.name === name);
return native ? readNativeSkillFile(native) : null;
};
+ /** The files beside the SKILL.md readBotSkillFile reads, from the same copy: none for a skill shared from this
+ * computer, null when they changed since they came in. */
+ const readBotSkillFiles = (bot: BotRecord, name: string): StoredSkillFiles => {
+ if (readSkillFile(bot.id, name) !== null) return ownSkillFiles(bot.id, name);
+ if (listSkills(bot.id).some((skill) => skill.name === name)) return null;
+ if (skillsLibraryEnabled(cfg) && listLibrarySkills().some((skill) => skill.name === name && (bot.assignedSkills?.includes(name) || (skill.everyBot && !librarySkillOptOuts(bot.id).has(name))))) return librarySkillFiles(name);
+ return [];
+ };
const shareBotsNow = (): ShareBot[] =>
store.bots.map((bot) => ({ id: bot.id, name: bot.name, section: bot.section, assignedSkills: bot.assignedSkills, visibility: bot.visibility }));
@@ -283,6 +292,7 @@ export function createSkillsLibraryHost(deps: SkillsLibraryHostDeps) {
return {
listBotSkills,
readBotSkillFile,
+ readBotSkillFiles,
mode,
diff --git a/server/index.ts b/server/index.ts
index ac2e5ef3e7..d0fa5c8057 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -12257,8 +12257,8 @@ ROUTES.push(createTeamRoutes({
packageImportDeps,
threadShown, botShown: (auth) => (botId) => visibleTo(viewerFor(auth)).bot(botId), routineShown: (auth) => (routine) => routineVisible(routine, visibleTo(viewerFor(auth))),
}));
-const share = createShareWiring({ dataDir: DATA_DIR, bots: () => store.bots, groups: () => store.groups, routines: () => routines?.listRoutines() ?? [], brief: (section) => readSectionContext(section)?.text, botFolder: workspaceDir, collectTeamSkills: skillExport(skillsHost).collectTeamSkills, access: () => pagesAccess(CLOUD_HOME), notOffered: () => pagesNotOffered(CLOUD_HOME), selfHosted: !CLOUD_HOME && !HOSTED_WORKSPACE && utilityParentPort === undefined, localFolders: !CLOUD_HOME && !HOSTED_WORKSPACE,
- visibleBot: (auth) => (botId) => visibleTo(viewerFor(auth)).bot(botId), visibleRoutine: (auth) => (routine) => routineVisible(routine, visibleTo(viewerFor(auth))), patchMessage: (threadId, messageId, patch) => void store.patchMessage(threadId, messageId, patch), importDeps: async () => packageImportDeps(await defaultSelection()), publicBot, publicGroup: publicGroupState, broadcast }); ROUTES.push(share.routes);
+const share = createShareWiring({ dataDir: DATA_DIR, bots: () => store.bots, groups: () => store.groups, routines: () => routines?.listRoutines() ?? [], brief: (section) => readSectionContext(section)?.text, botFolder: workspaceDir, collectTeamSkills: skillExport(skillsHost).collectTeamSkills, skillFiles: skillsHost.readBotSkillFiles, access: () => pagesAccess(CLOUD_HOME), notOffered: () => pagesNotOffered(CLOUD_HOME), selfHosted: !CLOUD_HOME && !HOSTED_WORKSPACE && utilityParentPort === undefined, localFolders: !CLOUD_HOME && !HOSTED_WORKSPACE,
+ visibleBot: (auth) => (botId) => visibleTo(viewerFor(auth)).bot(botId), visibleRoutine: (auth) => (routine) => routineVisible(routine, visibleTo(viewerFor(auth))), patchMessage: (threadId, messageId, patch) => void store.patchMessage(threadId, messageId, patch), importDeps: async () => packageImportDeps(await defaultSelection()), publicBot, publicGroup: publicGroupState, broadcast, team: CLOUD_TEAM, personOf: (auth) => (CLOUD_TEAM && auth.kind === "session" ? personKey(auth.session) : null), who: (auth) => (auth.kind === "session" ? teamHost.personName(personKey(auth.session)) ?? auth.session.email ?? undefined : undefined), github: { cfg: () => cfg, composio, personApps: () => teamConnections.personApps(), appsAccess: (person) => teamConnections.people.appsAccess(person), appRefusal: (slug) => managedPolicy.appRefusal(slug) ?? null } }); ROUTES.push(share.routes);
ROUTES.push(createBrowserSiteRoutes({
target: (which, threadId) => signedInSitesTarget(which, threadId === null ? "team" : teamHost.browserAudience(threadId)),
list: (target) => listSignedInSites(target),
@@ -12898,7 +12898,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
throw Object.assign(new Error(TURN_ENDED_REFUSAL), { status: 401 });
}
};
- const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await lentMcp.route({ method, path, req, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS || await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await cloudComputerResets.internal({ method, path, res, json, sender: internalSender, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await meetingsHost.internal({ method, path, res, json, readBody: readInternalBody, bot: internalSender, threadId: internalCapability.threadId, active: () => internalCapabilityIsActive(internalCapability) }) !== PASS || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS || await share.tool({ method, path, res, json, readBody: readInternalBody, bot: internalSender, threadId: internalCapability.threadId, roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), personMessage: turnOrigin(internalCapability).kind === "user" ? store.messagesFor(internalCapability.threadId).find((line) => line.role === "user" && line.id === (directRequestOwners.get(internalCapability.threadId)?.messageId ?? roomRun(internalCapability.generation)?.requestMessageId))?.text ?? null : null, post: (text, template) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return source ? store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, template, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id : null; } }) !== PASS) return; const callSignal = turnCallSignals.signal(internalCapability, res); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: callSignal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle, bot: internalSender })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;
+ const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await lentMcp.route({ method, path, req, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS || await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await cloudComputerResets.internal({ method, path, res, json, sender: internalSender, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await meetingsHost.internal({ method, path, res, json, readBody: readInternalBody, bot: internalSender, threadId: internalCapability.threadId, active: () => internalCapabilityIsActive(internalCapability) }) !== PASS || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS || await share.tool({ method, path, res, json, readBody: readInternalBody, bot: internalSender, threadId: internalCapability.threadId, roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), actsForAdmin: teamConnections.actsForAdmin(internalCapability.threadId, internalCapability.generation), githubPerson: teamConnections.turnPerson(internalCapability.threadId, internalCapability.generation), actingName: CLOUD_TEAM ? teamHost.personName(actingPeople.requester(internalCapability.threadId, internalCapability.generation)) : undefined, personMessage: turnOrigin(internalCapability).kind === "user" ? store.messagesFor(internalCapability.threadId).find((line) => line.role === "user" && line.id === (directRequestOwners.get(internalCapability.threadId)?.messageId ?? roomRun(internalCapability.generation)?.requestMessageId))?.text ?? null : null, post: (text, template) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return source ? store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, template, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id : null; } }) !== PASS) return; const callSignal = turnCallSignals.signal(internalCapability, res); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: callSignal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle, bot: internalSender })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;
const delegatedThisTurn = (taskId: string) => {
(internalCapability.delegatedThisTurn ??= new Set()).add(taskId);
};
diff --git a/server/package-export.ts b/server/package-export.ts
index 9cf289a4cc..79a5c6b780 100644
--- a/server/package-export.ts
+++ b/server/package-export.ts
@@ -1,3 +1,4 @@
+import type { SkillFile } from "../shared/skill-files.ts";
import { parseBotPackage, type BotPackageDefinition, type BotPackagePlaybook, type BotPackageSkill, type ParsedBotPackage } from "./bot-package.ts";
import type { DefaultsPreset, PublishedLibrary } from "./presets.ts";
import type { PublishedTeam } from "./published-teams.ts";
@@ -70,11 +71,14 @@ export interface ExportablePackageSkill extends Omit<BotPackageSkill, "name" | "
name: string;
description: string;
enabled?: boolean;
+ /** The text files beside SKILL.md that travel with it. */
+ files?: SkillFile[];
}
function sameSkill(a: ExportablePackageSkill, b: ExportablePackageSkill): boolean {
return a.instructions === b.instructions && a.description === b.description &&
- a.source === b.source && a.license === b.license && a.compatibility === b.compatibility;
+ a.source === b.source && a.license === b.license && a.compatibility === b.compatibility &&
+ JSON.stringify(a.files ?? []) === JSON.stringify(b.files ?? []);
}
function assignPlaybooks(bots: readonly BotRecord[], idToKey: ReadonlyMap<string, string>) {
diff --git a/server/package-import.ts b/server/package-import.ts
index e80b85fdf2..fa50c35060 100644
--- a/server/package-import.ts
+++ b/server/package-import.ts
@@ -353,7 +353,7 @@ function runImport(source: ImportSource, options: PackageImportOptions, deps: Pa
const added = org
? deps.skills.installOrg!(created.id, `org:${org.ref}@${pkg!.release}`, skill.instructions,
{ installId: org.installId, key: skill.name, release: pkg!.release, ...pair(skill.instructions, skill.instructions) })
- : deps.skills.install(created.id, skill.source ?? `package:${pkg!.id}`, [{ path: "SKILL.md", content: skill.instructions }]);
+ : deps.skills.install(created.id, skill.source ?? `package:${pkg!.id}`, [{ path: "SKILL.md", content: skill.instructions }, ...(skill.files ?? [])]);
if ("error" in added) throw new Error(`Package skill "${skillName}" could not be imported: ${added.error}`);
}
for (const [path, text] of Object.entries(agent?.seed?.memory ?? {})) {
diff --git a/server/routes/share.ts b/server/routes/share.ts
index c986186f35..71acf20860 100644
--- a/server/routes/share.ts
+++ b/server/routes/share.ts
@@ -9,10 +9,12 @@ import { readShareFolder, SHARE_FOLDER_MAX_BYTES, type ShareFolder, type ShareFo
import type { WireBot, WireGroup } from "../../shared/wire.ts";
import type { json as sendJson } from "../harness/http.ts";
import { PackageImportError, importPackageDocument, importTeamManifest, type PackageImportDeps, type PackageImportResult } from "../package-import.ts";
-import type { RequestAuth } from "../request-auth.ts";
+import { ownerOrAdmin, type RequestAuth } from "../request-auth.ts";
import type { Routine } from "../routines.ts";
import { fetchGithubTemplate, GithubTemplateError } from "../share-github.ts";
+import { publishToRepo, readRepoFolder, repoFolder, repoFolderOf, repoName, type GithubConnection } from "../share-github-repo.ts";
import { cardText, readFolderFromDisk, ShareError, type ShareHost } from "../share.ts";
+import type { TeamTemplates } from "../team-templates.ts";
import { zipFolder } from "../share-zip.ts";
import type { BotRecord, GroupRecord } from "../store.ts";
import { parseTeamManifest } from "../team-manifest.ts";
@@ -30,9 +32,29 @@ export interface ShareRouteDeps {
publicGroup(group: GroupRecord): WireGroup;
broadcast(payload: Record<string, unknown>): void;
fetchTemplate?: typeof fetchGithubTemplate;
+ /** A Team Cloud's name and its own templates; absent anywhere else. */
+ library?: { team: string; templates: TeamTemplates } | null;
+ /** Who a request is, as the team's library names whoever added a template. */
+ who?(auth: RequestAuth): string | undefined;
+ /** A request's person on a Team Cloud, whose own GitHub a private link or their repository may use. */
+ personOf?(auth: RequestAuth): string | null;
+ /** The GitHub connection `person` (null: nobody in particular) may read and write through. */
+ github?(person: string | null): Promise<GithubConnection>;
}
-export type ImportSource = { url: string } | { path: string } | { files: ShareFolderFiles };
+export type ImportSource = { url: string } | { path: string } | { files: ShareFolderFiles } | { library: string };
+
+/** Where an import may read from, beyond the source itself. */
+export interface ImportReaders {
+ /** True on a desktop's own server: folders on this computer may be read. */
+ localFolders: boolean;
+ fetchTemplate?: typeof fetchGithubTemplate;
+ library?: TeamTemplates | null;
+ /** The GitHub connection a link that isn't public is read through. */
+ github?: () => Promise<GithubConnection>;
+}
+
+const NO_LIBRARY = "A team's own templates are on a Team Cloud.";
/** Words for an untrusted folder's refusal: the format's own sentence, else a plain one. */
function refusal(error: unknown): { status: number; error: string } | null {
@@ -45,8 +67,9 @@ function refusal(error: unknown): { status: number; error: string } | null {
/** `{url}`, `{path}` or `{files}`: exactly one, each checked for shape before anything is read. */
export function importSource(body: unknown): ImportSource | string {
const value = (body && typeof body === "object" && !Array.isArray(body) ? body : {}) as Record<string, unknown>;
- const given = ["url", "path", "files"].filter((key) => value[key] !== undefined);
+ const given = ["url", "path", "files", "library"].filter((key) => value[key] !== undefined);
if (given.length !== 1) return "Paste a GitHub link or choose a folder.";
+ if (value.library !== undefined) return typeof value.library === "string" && /^[a-z0-9][a-z0-9-]{0,47}$/.test(value.library) ? { library: value.library } : "Choose a template from the team's library.";
if (typeof value.url === "string") return value.url.trim() ? { url: value.url.trim().slice(0, 2_000) } : "Paste a GitHub link or choose a folder.";
if (typeof value.path === "string") return isAbsolute(value.path) ? { path: value.path } : "Choose a folder on this computer.";
const files = value.files;
@@ -62,10 +85,29 @@ export function importSource(body: unknown): ImportSource | string {
return { files: out };
}
-export async function readImport(source: ImportSource, localFolders: boolean, fetchTemplate = fetchGithubTemplate): Promise<ShareFolder> {
- if ("url" in source) return fetchTemplate(source.url);
+/** A public link through raw.githubusercontent.com; one GitHub says isn't there, through the GitHub connection. */
+async function readLink(url: string, readers: ImportReaders): Promise<ShareFolder> {
+ try {
+ return await (readers.fetchTemplate ?? fetchGithubTemplate)(url);
+ } catch (error) {
+ const at = error instanceof GithubTemplateError && error.status === 404 ? repoFolderOf(url) : null;
+ if (!at || !readers.github) throw error;
+ const connection = await readers.github();
+ if (!connection.ok) {
+ throw new GithubTemplateError(`${(error as GithubTemplateError).message} ${connection.reason === "not_connected" ? "If the repository is private, connect GitHub in Apps first." : connection.message}`, 404);
+ }
+ return readRepoFolder(connection, at);
+ }
+}
+
+export async function readImport(source: ImportSource, readers: ImportReaders): Promise<ShareFolder> {
+ if ("library" in source) {
+ if (!readers.library) throw new ShareError(NO_LIBRARY, 404);
+ return readShareFolder(readers.library.files(source.library));
+ }
+ if ("url" in source) return readLink(source.url, readers);
if ("path" in source) {
- if (!localFolders) throw new ShareError("Folders on this computer can only be imported in the desktop app.", 403);
+ if (!readers.localFolders) throw new ShareError("Folders on this computer can only be imported in the desktop app.", 403);
return readShareFolder(readFolderFromDisk(source.path));
}
return readShareFolder(source.files);
@@ -100,7 +142,34 @@ export function addTemplate(folder: ShareFolder, deps: PackageImportDeps, view:
};
}
-const TEMPLATE_PATH = /^\/api\/share\/([a-f0-9]{16})(\/publish|\/save|\/download)?$/;
+const TEMPLATE_PATH = /^\/api\/share\/([a-f0-9]{16})(\/publish|\/publish-repo|\/library|\/save|\/download)?$/;
+const LIBRARY_PATH = /^\/api\/share\/library\/([a-z0-9][a-z0-9-]{0,47})$/;
+
+/** Adds the template to the team's library, as its folder is now. */
+function addToLibrary(host: ShareHost, library: TeamTemplates, id: string, addedBy: string | undefined) {
+ const { card } = host.get(id);
+ const { slug, files } = host.files(id);
+ return library.add(slug, files, { name: card.name, scope: card.scope, tagline: card.tagline, ...(addedBy ? { addedBy } : {}) });
+}
+
+/** `{ repo: "owner/repo", folder?, direct? }`, checked; a sentence when it isn't one. */
+function repoTarget(body: unknown): { owner: string; repo: string; folder: string; direct: boolean } | string {
+ const value = (body && typeof body === "object" ? body : {}) as Record<string, unknown>;
+ const target = typeof value.repo === "string" ? repoName(value.repo) : null;
+ if (!target) return "Write the repository as owner/repo.";
+ const folder = repoFolder(typeof value.folder === "string" ? value.folder : undefined);
+ if (folder === null) return "The folder must be plain names separated by /.";
+ return { ...target, folder, direct: value.direct === true };
+}
+
+async function publishRepo(host: ShareHost, id: string, connection: Extract<GithubConnection, { ok: true }>, target: { owner: string; repo: string; folder: string; direct: boolean }) {
+ const { card } = host.get(id);
+ const { slug, files } = host.files(id);
+ return publishToRepo(connection, { ...target, slug, name: card.name, files });
+}
+
+const connectionRefusal = (connection: Extract<GithubConnection, { ok: false }>) =>
+ ({ status: connection.reason === "not_connected" ? 409 : connection.reason === "refused" ? 403 : 503, body: { error: connection.message, code: `github_${connection.reason}` } });
export function createShareRoutes(deps: ShareRouteDeps): RouteHandler {
const { host } = deps;
@@ -113,7 +182,30 @@ export function createShareRoutes(deps: ShareRouteDeps): RouteHandler {
const record = host.record(id);
return Boolean(record) && (record!.botId === undefined || deps.bots(auth).some((bot) => bot.id === record!.botId));
};
+ const readers = (auth: RequestAuth): ImportReaders => ({
+ localFolders: deps.localFolders, fetchTemplate: deps.fetchTemplate, library: deps.library?.templates ?? null,
+ ...(deps.github ? { github: () => deps.github!(deps.personOf?.(auth) ?? null) } : {}),
+ });
return async ({ req, res, url, path, method, auth, json, readBody }) => {
+ if (method === "GET" && path === "/api/share/library") {
+ if (!deps.library) return json(res, 404, { error: NO_LIBRARY });
+ return json(res, 200, { team: deps.library.team, templates: deps.library.templates.list() });
+ }
+ const removing = method === "DELETE" ? path.match(LIBRARY_PATH) : null;
+ if (removing) {
+ if (!deps.library) return json(res, 404, { error: NO_LIBRARY });
+ if (!ownerOrAdmin(auth)) return json(res, 403, { error: "Only the team's admins remove templates from its library." });
+ try {
+ deps.library.templates.remove(removing[1]!);
+ return json(res, 200, { ok: true });
+ } catch (error) {
+ return answer(res, json, error);
+ }
+ }
+ if (method === "GET" && path === "/api/share/github") {
+ const connection = deps.github ? await deps.github(deps.personOf?.(auth) ?? null) : null;
+ return json(res, 200, connection?.ok ? { connected: true } : { connected: false, reason: connection?.reason ?? "not_connected", error: connection?.message ?? "Connect GitHub in Apps first." });
+ }
if (method === "POST" && path === "/api/share/export") {
const body = await readBody(req) as Record<string, unknown>;
const bots = deps.bots(auth);
@@ -134,7 +226,7 @@ export function createShareRoutes(deps: ShareRouteDeps): RouteHandler {
const source = importSource(await readBody(req, SHARE_FOLDER_MAX_BYTES * 2));
if (typeof source === "string") return json(res, 400, { error: source });
try {
- const folder = await readImport(source, deps.localFolders, deps.fetchTemplate);
+ const folder = await readImport(source, readers(auth));
if (url.searchParams.get("preview") === "1") return json(res, 200, { details: host.preview(folder) });
return json(res, 201, addTemplate(folder, await deps.importDeps(auth), deps));
} catch (error) {
@@ -152,6 +244,21 @@ export function createShareRoutes(deps: ShareRouteDeps): RouteHandler {
return json(res, 200, { ok: true });
}
if (method === "POST" && m[2] === "/publish") return json(res, 200, await host.publish(id));
+ if (method === "POST" && m[2] === "/library") {
+ if (!deps.library) return json(res, 404, { error: NO_LIBRARY });
+ if (!ownerOrAdmin(auth)) return json(res, 403, { error: "Only the team's admins add templates to its library." });
+ return json(res, 201, addToLibrary(host, deps.library.templates, id, deps.who?.(auth)));
+ }
+ if (method === "POST" && m[2] === "/publish-repo") {
+ const target = repoTarget(await readBody(req));
+ if (typeof target === "string") return json(res, 400, { error: target });
+ const connection = deps.github ? await deps.github(deps.personOf?.(auth) ?? null) : { ok: false as const, reason: "not_connected" as const, message: "Connect GitHub in Apps first." };
+ if (!connection.ok) {
+ const refused = connectionRefusal(connection);
+ return json(res, refused.status, refused.body);
+ }
+ return json(res, 200, await publishRepo(host, id, connection, target));
+ }
if (method === "POST" && m[2] === "/save") {
if (!deps.localFolders) return json(res, 403, { error: "Saving to a folder works in the desktop app. Download the template instead." });
const body = await readBody(req) as Record<string, unknown>;
@@ -186,6 +293,12 @@ export interface ShareToolContext {
roots: readonly string[];
/** Puts a card in this conversation; its message id, or null when the conversation is gone. */
post(text: string, card: TemplateCard): string | null;
+ /** On a Team Cloud, whether the person this turn acts for is an owner or admin there; true anywhere else. */
+ actsForAdmin?: boolean;
+ /** The person whose own GitHub this turn may use (in their own chat), when each person on the team connects it. */
+ githubPerson?: string | null;
+ /** The name the team's library records for whoever this turn acts for. */
+ actingName?: string;
}
function within(root: string, path: string): boolean {
@@ -197,12 +310,19 @@ function within(root: string, path: string): boolean {
}
}
+const addedWords = (added: ReturnType<typeof addTemplate>) =>
+ `Added ${added.bots.map((bot) => bot.name).join(", ")}${added.section ? ` in a new department, ${added.section}` : ""}. Routines arrived paused${added.appsToConnect ? `, and ${added.appsToConnect} apps need the person's own accounts` : ""}.`;
+
const PRIVATE_DETAILS = "Before anyone publishes it, read the files and take out anything personal: people's names, emails, phone numbers, client names, private links or facts only this person should know. Keep the instructions general. Edit the files in that folder directly; Publish re-reads them.";
/** The `share` tool. Import needs the link or path in the person's own message this turn, so text the bot read
* elsewhere (a web page, an email) can't make it add bots. */
export function createShareToolRoute(deps: Omit<ShareRouteDeps, "bots"> & { bots(): readonly BotRecord[]; routines(): readonly Routine[]; importDeps(auth: null): Promise<PackageImportDeps> }) {
const { host } = deps;
+ const toolReaders = (ctx: ShareToolContext): ImportReaders => ({
+ localFolders: true, fetchTemplate: deps.fetchTemplate, library: deps.library?.templates ?? null,
+ ...(deps.github && ctx.actsForAdmin !== false ? { github: () => deps.github!(ctx.githubPerson ?? null) } : {}),
+ });
const shown = (ctx: ShareToolContext, card: TemplateCard) => {
const messageId = ctx.post(cardText(card), card);
if (messageId) host.shown(card.id, ctx.threadId, messageId);
@@ -244,12 +364,45 @@ export function createShareToolRoute(deps: Omit<ShareRouteDeps, "bots"> & { bots
return reply(403, "Import only what the person linked in their own message just now. Ask them to paste the link or folder path in the chat.");
}
if (path && !deps.localFolders && !ctx.roots.some((root) => within(root, path))) return reply(403, "That folder isn't one you can read here.");
- const folder = await readImport(link ? { url: link } : { path }, true, deps.fetchTemplate);
- const added = addTemplate(folder, await deps.importDeps(null), deps);
- const names = added.bots.map((bot) => bot.name).join(", ");
- return reply(201, `Added ${names}${added.section ? ` in a new department, ${added.section}` : ""}. Routines arrived paused${added.appsToConnect ? `, and ${added.appsToConnect} apps need the person's own accounts` : ""}.`);
+ const folder = await readImport(link ? { url: link } : { path }, toolReaders(ctx));
+ return reply(201, addedWords(addTemplate(folder, await deps.importDeps(null), deps)));
+ }
+ if (body.action === "list_team_library" || body.action === "add_to_team_library" || body.action === "import_from_team_library") {
+ if (!deps.library) return reply(404, "There is no team library here: a team's own templates are on a Team Cloud.");
+ if (!ctx.personMessage || ctx.actsForAdmin === false) return reply(403, "Only the team's owner or an admin can use the team's templates, in a request of their own. Tell the person.");
+ const { team, templates } = deps.library;
+ if (body.action === "list_team_library") {
+ const listed = templates.list();
+ if (!listed.length) return reply(200, `${team}'s library has no templates yet.`);
+ return reply(200, [`${team}'s templates (import one with share action import_from_team_library and its slug):`,
+ ...listed.map((one) => `- ${one.slug}: ${one.name} (${one.scope === "bot" ? "a bot" : "a department"})${one.tagline ? `, ${one.tagline}` : ""}; added${one.addedBy ? ` by ${one.addedBy}` : ""} ${new Date(one.addedAt).toISOString().slice(0, 10)}`)].join("\n"));
+ }
+ if (body.action === "add_to_team_library") {
+ const record = host.latest(ctx.bot.id, department ? "department" : "bot");
+ if (!record) return reply(404, "There is no template to add yet. Call share with action export first.");
+ const added = addToLibrary(host, templates, record.id, ctx.actingName);
+ return reply(201, `${added.replaced ? "Replaced" : "Added"} ${added.template.name} in ${team}'s templates${added.replaced ? "; the one it replaced is kept beside it" : ""}. Everyone who can add bots on ${team} finds it in Import.`);
+ }
+ const slug = typeof body.slug === "string" ? body.slug.trim() : "";
+ if (!templates.has(slug)) return reply(404, `${team}'s library has no template ${slug.slice(0, 48) || "with that slug"}. Call share with action list_team_library to see them.`);
+ return reply(201, addedWords(addTemplate(await readImport({ library: slug }, toolReaders(ctx)), await deps.importDeps(null), deps)));
+ }
+ if (body.action === "publish_to_repo") {
+ const target = repoTarget({ repo: body.repo, folder: body.path, direct: body.direct });
+ if (typeof target === "string") return reply(400, target);
+ if (!ctx.personMessage || !ctx.personMessage.toLowerCase().includes(`${target.owner}/${target.repo}`.toLowerCase())) {
+ return reply(403, "Publish only to a repository the person named (owner/repo) in their own message just now. Ask them which one.");
+ }
+ if (ctx.actsForAdmin === false) return reply(403, "Only the team's owner or an admin can publish its templates to a repository. Tell the person.");
+ const record = host.latest(ctx.bot.id, department ? "department" : "bot");
+ if (!record) return reply(404, "There is no template to publish yet. Call share with action export first.");
+ const connection = deps.github ? await deps.github(ctx.githubPerson ?? null) : null;
+ if (!connection?.ok) return reply(409, `${connection?.message ?? "Connect GitHub in Apps first."} Tell the person; the GitHub app is in Apps.`);
+ const done = await publishRepo(host, record.id, connection, target);
+ return reply(200, done.kind === "pull_request" ? `Opened a pull request in ${target.owner}/${target.repo}: ${done.url} (branch ${done.branch}). Import accepts ${done.link} once it is merged.`
+ : `Committed the template to ${target.owner}/${target.repo} on ${done.branch}: ${done.link}`);
}
- return reply(400, "action must be export, publish or import.");
+ return reply(400, "action must be export, publish, import, add_to_team_library, list_team_library, import_from_team_library or publish_to_repo.");
} catch (error) {
const known = refusal(error);
if (!known) throw error;
diff --git a/server/share-github-repo.ts b/server/share-github-repo.ts
new file mode 100644
index 0000000000..52c6228f10
--- /dev/null
+++ b/server/share-github-repo.ts
@@ -0,0 +1,250 @@
+// Template folders in a GitHub repository, read and written through a GitHub connection on the connected-apps service
+// (the person's own, or the team's): from the server, with the token kept by the service and nothing passing through a
+// model. Tool names, arguments and answer shapes follow Composio's GitHub toolkit documentation and are not yet checked
+// against the live service, so an answer of any other shape is an error in words, never an empty folder.
+// Security: owner, repository, ref and folder are plain path segments; only the files the manifest names are read, with
+// the public reader's caps; a link shown back must be on github.com under the repository asked for.
+import { randomBytes } from "node:crypto";
+
+import { decodeBase64 } from "../shared/package-format.ts";
+import { MANIFEST_NAMES, namedFolderFiles, readShareFolder, SHARE_FOLDER_MAX_BYTES, SHARE_FOLDER_MAX_FILES, type ShareFolder, type ShareFolderFiles } from "../shared/share-folder.ts";
+import type { TemplateRepoPublish } from "../shared/share-card.ts";
+import { toolData } from "./connected-reads.ts";
+import { parseMcpResponse } from "./connector-tools-list.ts";
+import { GithubTemplateError } from "./share-github.ts";
+
+export const GITHUB_TOOLS = {
+ repository: "GITHUB_GET_A_REPOSITORY",
+ content: "GITHUB_GET_REPOSITORY_CONTENT",
+ branch: "GITHUB_GET_A_BRANCH",
+ blob: "GITHUB_CREATE_A_BLOB",
+ tree: "GITHUB_CREATE_A_TREE",
+ commit: "GITHUB_CREATE_A_COMMIT",
+ createRef: "GITHUB_CREATE_A_REFERENCE",
+ updateRef: "GITHUB_UPDATE_A_REFERENCE",
+ pullRequest: "GITHUB_CREATE_A_PULL_REQUEST",
+} as const;
+
+export type GithubRelay = (payload: unknown, transportSessionId: string | undefined, signal: AbortSignal) =>
+ Promise<{ status: number; bytes: Uint8Array; transportSessionId?: string }>;
+
+/** A GitHub connection a request may use: the relay to its account, or why there is none. */
+export type GithubConnection =
+ | { ok: true; relay: GithubRelay; account?: string }
+ | { ok: false; reason: "not_connected" | "refused" | "unavailable"; message: string };
+
+export const CONNECT_GITHUB = "Connect GitHub in Apps first.";
+const MANIFEST_MAX_BYTES = 1_000_000;
+const MULTI_EXECUTE = "COMPOSIO_MULTI_EXECUTE_TOOL";
+const CALL_ID = "omb-share-github";
+const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
+const REPO = /^[A-Za-z0-9._-]{1,100}$/;
+const SEGMENT = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,99}$/;
+const NOT_THERE = /\b(?:not found|404|no commit found|does not exist)\b/i;
+const MISSING = Symbol("missing");
+
+export interface RepoFolder {
+ owner: string;
+ repo: string;
+ /** Absent: the repository's default branch. */
+ ref?: string;
+ /** "/"-separated, "" for the repository's root. */
+ path: string;
+}
+
+const record = (value: unknown): Record<string, unknown> | undefined =>
+ value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : undefined;
+/** A field of a tool's data, which the service may wrap once more. */
+function field(data: unknown, name: string): unknown {
+ for (const body of [record(data), record(record(data)?.details), record(record(data)?.response_data), record(record(data)?.data)]) {
+ if (body && name in body) return body[name];
+ }
+ return undefined;
+}
+const text = (data: unknown, name: string): string | undefined => {
+ const value = field(data, name);
+ return typeof value === "string" && value ? value : undefined;
+};
+
+export function repoName(value: string): { owner: string; repo: string } | null {
+ const [owner, repo, ...rest] = value.trim().replace(/^https:\/\/github\.com\//i, "").replace(/\.git$/i, "").replace(/\/+$/, "").split("/");
+ if (rest.length || !owner || !repo || !OWNER.test(owner) || !REPO.test(repo) || repo === "." || repo === "..") return null;
+ return { owner, repo };
+}
+
+/** A folder inside a repository, "" for its root; null when a part isn't a plain name. */
+export function repoFolder(value: string | undefined): string | null {
+ const parts = (value ?? "").trim().split("/").filter(Boolean);
+ return parts.length <= 6 && parts.every((part) => SEGMENT.test(part)) ? parts.join("/") : null;
+}
+
+/** Where a github.com link's template lives: a repository, a folder (tree), or a bot.md or team.md in one (blob). */
+export function repoFolderOf(link: string): RepoFolder | null {
+ let url: URL;
+ try {
+ url = new URL(link.trim());
+ } catch {
+ return null;
+ }
+ if (url.protocol !== "https:" || (url.hostname !== "github.com" && url.hostname !== "www.github.com") || url.username || url.password || url.port) return null;
+ let parts: string[];
+ try {
+ parts = url.pathname.split("/").filter(Boolean).map((part) => decodeURIComponent(part));
+ } catch {
+ return null;
+ }
+ const [owner, repo, kind, ref, ...path] = parts;
+ if (!owner || !repo || !OWNER.test(owner) || !REPO.test(repo) || !path.every((part) => SEGMENT.test(part))) return null;
+ if (!kind) return { owner, repo, path: "" };
+ if (!ref || !SEGMENT.test(ref)) return null;
+ if (kind === "tree") return { owner, repo, ref, path: path.join("/") };
+ if (kind === "blob" && (path.at(-1) === MANIFEST_NAMES.bot || path.at(-1) === MANIFEST_NAMES.department)) return { owner, repo, ref, path: path.slice(0, -1).join("/") };
+ return null;
+}
+
+/** One connection's GitHub calls, over one connected-apps session. */
+export function githubSession(connection: Extract<GithubConnection, { ok: true }>, timeoutMs = 60_000) {
+ let opened: Promise<string | undefined> | undefined;
+ const open = async (signal: AbortSignal) => {
+ const init = await connection.relay({
+ jsonrpc: "2.0", id: "omb-share-init", method: "initialize",
+ params: { protocolVersion: "2025-03-26", capabilities: {}, clientInfo: { name: "openmausbot-templates", version: "1" } },
+ }, undefined, signal);
+ if (init.status !== 200) throw new GithubTemplateError(`GitHub couldn't be reached through Apps (HTTP ${init.status}). Try again in a few minutes.`, 502);
+ await connection.relay({ jsonrpc: "2.0", method: "notifications/initialized" }, init.transportSessionId, signal).catch(() => undefined);
+ return init.transportSessionId;
+ };
+ /** The tool's data; `missing` (instead of an error) when GitHub says the thing asked for isn't there. */
+ async function call(slug: string, args: Record<string, unknown>): Promise<unknown> {
+ const signal = AbortSignal.timeout(timeoutMs);
+ try {
+ opened ??= open(signal).catch((error: unknown) => {
+ opened = undefined;
+ throw error;
+ });
+ const transport = await opened;
+ const answer = await connection.relay({
+ jsonrpc: "2.0", id: CALL_ID, method: "tools/call",
+ params: { name: MULTI_EXECUTE, arguments: { tools: [{ tool_slug: slug, arguments: args, ...(connection.account ? { account: connection.account } : {}) }] } },
+ }, transport, signal);
+ if (answer.status !== 200) throw new Error(`HTTP ${answer.status}`);
+ return toolData(slug, parseMcpResponse(new TextDecoder().decode(answer.bytes), CALL_ID));
+ } catch (error) {
+ if (error instanceof GithubTemplateError) throw error;
+ const words = error instanceof Error ? error.message : String(error);
+ if (NOT_THERE.test(words)) return MISSING;
+ if (/came back shortened/.test(words)) throw new GithubTemplateError("A file there is too large to read through Apps.", 413);
+ if (signal.aborted) throw new GithubTemplateError("GitHub didn't answer in time. Try again in a few minutes.", 504);
+ throw new GithubTemplateError(`GitHub refused: ${words.slice(0, 200)}`, 502);
+ }
+ }
+ return { call, missing: MISSING as unknown };
+}
+type Session = ReturnType<typeof githubSession>;
+
+async function defaultBranch(session: Session, owner: string, repo: string): Promise<{ branch: string; push?: boolean }> {
+ const data = await session.call(GITHUB_TOOLS.repository, { owner, repo });
+ if (data === session.missing) throw new GithubTemplateError(`${owner}/${repo} wasn't found, or your GitHub connection can't see it.`, 404);
+ const branch = text(data, "default_branch");
+ if (!branch) throw new GithubTemplateError("GitHub's answer about the repository had no default branch.", 502);
+ const push = record(field(data, "permissions"))?.push;
+ return { branch, ...(typeof push === "boolean" ? { push } : {}) };
+}
+
+/** A file's bytes, null when it isn't there. */
+async function fileBytes(session: Session, at: RepoFolder & { ref: string }, path: string, maxBytes: number): Promise<Uint8Array | null> {
+ const data = await session.call(GITHUB_TOOLS.content, { owner: at.owner, repo: at.repo, path: [at.path, path].filter(Boolean).join("/"), ref: at.ref });
+ if (data === session.missing) return null;
+ if (Array.isArray(data) || field(data, "type") === "dir") throw new GithubTemplateError(`${path} is a folder in that repository, not a file.`);
+ const size = field(data, "size");
+ if (typeof size === "number" && size > maxBytes) throw new GithubTemplateError("This template is larger than 4 MB.", 413);
+ const content = field(data, "content");
+ if (typeof content !== "string") throw new GithubTemplateError(`GitHub's answer for ${path} had no content. A file over 1 MB can't be read this way.`, 502);
+ const bytes = field(data, "encoding") === "base64" ? decodeBase64(content.replace(/\s+/g, "")) : new TextEncoder().encode(content);
+ if (!bytes) throw new GithubTemplateError(`GitHub's answer for ${path} couldn't be read.`, 502);
+ if (bytes.byteLength > maxBytes) throw new GithubTemplateError("This template is larger than 4 MB.", 413);
+ return bytes;
+}
+
+/** The template folder at `at`, through the connection, with the public reader's caps; nothing is added. */
+export async function readRepoFolder(connection: Extract<GithubConnection, { ok: true }>, at: RepoFolder): Promise<ShareFolder> {
+ const session = githubSession(connection);
+ const ref = at.ref ?? (await defaultBranch(session, at.owner, at.repo)).branch;
+ const where = { ...at, ref };
+ for (const name of [MANIFEST_NAMES.bot, MANIFEST_NAMES.department]) {
+ const manifest = await fileBytes(session, where, name, MANIFEST_MAX_BYTES);
+ if (!manifest) continue;
+ const manifestText = new TextDecoder().decode(manifest);
+ const files: ShareFolderFiles = { [name]: manifestText };
+ let total = manifest.byteLength;
+ const named = namedFolderFiles(manifestText);
+ if (named.length + 1 > SHARE_FOLDER_MAX_FILES) throw new GithubTemplateError("This folder has too many files to be a template.");
+ for (const path of named) {
+ const body = await fileBytes(session, where, path, SHARE_FOLDER_MAX_BYTES - total);
+ if (!body) continue;
+ total += body.byteLength;
+ files[path] = path.startsWith("avatars/") ? body : new TextDecoder().decode(body);
+ }
+ return readShareFolder(files);
+ }
+ throw new GithubTemplateError("No bot.md or team.md was found in that folder.", 404);
+}
+
+const toBase64 = (value: string | Uint8Array) => Buffer.from(typeof value === "string" ? new TextEncoder().encode(value) : value).toString("base64");
+
+/** Security: a link GitHub answers with is shown only when it is on github.com under the repository asked for. */
+function inRepository(value: unknown, owner: string, repo: string): string | null {
+ if (typeof value !== "string") return null;
+ try {
+ const url = new URL(value);
+ const prefix = `/${owner}/${repo}/`.toLowerCase();
+ return url.protocol === "https:" && url.hostname === "github.com" && url.pathname.toLowerCase().startsWith(prefix) ? url.href : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Commits the folder as <folder>/<slug> in one commit: on a new branch with a pull request, or straight on the
+ * default branch. Files already there under other names stay. */
+export async function publishToRepo(connection: Extract<GithubConnection, { ok: true }>, input: {
+ owner: string; repo: string; folder: string; slug: string; name: string; files: Record<string, string | Uint8Array>; direct: boolean;
+}): Promise<TemplateRepoPublish> {
+ const session = githubSession(connection);
+ const { owner, repo } = input;
+ const { branch: base, push } = await defaultBranch(session, owner, repo);
+ if (push === false) throw new GithubTemplateError(`Your GitHub connection can't write to ${owner}/${repo}.`, 403);
+ const head = await session.call(GITHUB_TOOLS.branch, { owner, repo, branch: base });
+ const headCommit = record(field(head, "commit"));
+ const headSha = typeof headCommit?.sha === "string" ? headCommit.sha : undefined;
+ const baseTree = record(record(headCommit?.commit)?.tree)?.sha;
+ if (!headSha || typeof baseTree !== "string") throw new GithubTemplateError(`GitHub's answer about ${base} had no commit.`, 502);
+ const dir = [input.folder, input.slug].filter(Boolean).join("/");
+ const tree: Array<{ path: string; mode: "100644"; type: "blob"; sha: string }> = [];
+ for (const [path, value] of Object.entries(input.files)) {
+ const blob = await session.call(GITHUB_TOOLS.blob, { owner, repo, content: toBase64(value), encoding: "base64" });
+ const sha = text(blob, "sha");
+ if (!sha) throw new GithubTemplateError("GitHub's answer for a file had no id.", 502);
+ tree.push({ path: `${dir}/${path}`, mode: "100644", type: "blob", sha });
+ }
+ const madeTree = text(await session.call(GITHUB_TOOLS.tree, { owner, repo, base_tree: baseTree, tree }), "sha");
+ if (!madeTree) throw new GithubTemplateError("GitHub's answer for the folder had no id.", 502);
+ const message = `Add the ${input.name} template from MausBot`;
+ const commit = text(await session.call(GITHUB_TOOLS.commit, { owner, repo, message, tree: madeTree, parents: [headSha] }), "sha");
+ if (!commit) throw new GithubTemplateError("GitHub's answer for the commit had no id.", 502);
+ const link = (branch: string) => `https://github.com/${owner}/${repo}/tree/${encodeURIComponent(branch)}/${dir}`;
+ if (input.direct) {
+ const moved = await session.call(GITHUB_TOOLS.updateRef, { owner, repo, ref: `heads/${base}`, sha: commit, force: false });
+ if (moved === session.missing) throw new GithubTemplateError(`${base} couldn't be updated. Try a pull request instead.`, 409);
+ return { kind: "commit", url: link(base), link: link(base), branch: base };
+ }
+ const branch = `mausbot-${input.slug}-${randomBytes(3).toString("hex")}`;
+ const made = await session.call(GITHUB_TOOLS.createRef, { owner, repo, ref: `refs/heads/${branch}`, sha: commit });
+ if (made === session.missing) throw new GithubTemplateError("The new branch couldn't be made.", 502);
+ const pull = await session.call(GITHUB_TOOLS.pullRequest, {
+ owner, repo, title: message, head: branch, base,
+ body: "A template made in MausBot: its instructions, skills and their scripts, and pictures. No chats, memory, keys or connections.",
+ });
+ const url = inRepository(field(pull, "html_url"), owner, repo);
+ if (!url) throw new GithubTemplateError("GitHub's answer for the pull request had no link.", 502);
+ return { kind: "pull_request", url, link: link(branch), branch };
+}
diff --git a/server/share-github.ts b/server/share-github.ts
index 4dacc4c795..5b9c969613 100644
--- a/server/share-github.ts
+++ b/server/share-github.ts
@@ -90,7 +90,7 @@ async function fetchFolder(base: string, names: readonly string[], fetcher: Fetc
let total = typeof manifest === "string" ? manifest.length : manifest.byteLength;
if (name === "bot.md" || name === "team.md") {
for (const path of namedFolderFiles(String(manifest))) {
- const body = await fetchBody(`${base}/${path}`, SHARE_FOLDER_MAX_BYTES - total, fetcher, !path.endsWith(".md"));
+ const body = await fetchBody(`${base}/${path}`, SHARE_FOLDER_MAX_BYTES - total, fetcher, path.startsWith("avatars/"));
if (body === null) continue;
total += typeof body === "string" ? body.length : body.byteLength;
files[path] = body;
diff --git a/server/share-skill-files.test.ts b/server/share-skill-files.test.ts
new file mode 100644
index 0000000000..b3b94fca6f
--- /dev/null
+++ b/server/share-skill-files.test.ts
@@ -0,0 +1,107 @@
+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { readShareFolder } from "../shared/share-folder.ts";
+import { admitSkillFiles, skillFilePathProblem as shareablePath } from "../shared/skill-files.ts";
+import { createCommunityPublisher, type CommunitySubmission } from "./share-publish.ts";
+import { createShareHost, readFolderFromDisk } from "./share.ts";
+import { prepareSkillFolder, skillFilePathProblem as storablePath } from "./skill-folder.ts";
+import type { BotRecord } from "./store.ts";
+
+const SKILL = "---\nname: report\ndescription: Weekly report.\n---\n\n# Report\n\nRun scripts/report.py.\n";
+const SCRIPT = "import os\ntoken = os.environ['REPORT_TOKEN']\nprint('ok')\n";
+const KEY = `ghp_${"a".repeat(36)}`;
+const folders: string[] = [];
+const scratch = () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-share-files-"));
+ folders.push(dir);
+ return dir;
+};
+afterEach(() => {
+ for (const dir of folders.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+const helper = { id: "bot-1", name: "Reporter", title: "Reports", color: "blue" } as BotRecord;
+
+function host(stored: Array<{ path: string; content: string | Uint8Array }> | null, submitted: CommunitySubmission[] = []) {
+ const dataDir = scratch(), botFolder = scratch();
+ const publisher = createCommunityPublisher({ access: () => ({ kind: "desktop", url: "https://admin.example.com/api/cloud/pages/token", token: "t" }) });
+ return createShareHost({
+ dataDir, bots: () => [helper], groups: () => [], routines: () => [], brief: () => undefined,
+ collectTeamSkills: () => ({ ok: true, skipped: [], skillsByBot: new Map([["bot-1", [{ name: "report", description: "Weekly report.", instructions: SKILL, enabled: true }]]]) }),
+ skillFiles: () => stored, picture: () => undefined, botFolder: (id) => join(botFolder, id),
+ publisher: { ...publisher, submit: async (submission) => {
+ submitted.push(submission);
+ return { ok: true, link: "https://github.com/milind-soni/openmausbot-teams/tree/main/teams/reporter", prUrl: "https://github.com/milind-soni/openmausbot-teams/pull/1" };
+ } },
+ patch: () => {},
+ });
+}
+
+describe("a skill's scripts in a template", () => {
+ it("are a subset of what a skill folder stores: whatever may travel is kept whole when it is added", () => {
+ const paths = ["run.py", "scripts/report.py", "a/b/c/d/e/f.txt", "a/b/c/d/e/f/g.txt", ".env", "x/.git/config", "node_modules/a.js", "venv/bin/x",
+ "__pycache__/a.pyc", "con", "nul.txt", "a:b", "a|b", "trailing.", "SKILL.md", `${"n".repeat(130)}.txt`, "id_rsa", "ok-file.md"];
+ for (const path of paths) if (shareablePath(path) === null) expect(storablePath(path), path).toBeNull();
+ const admitted = admitSkillFiles(paths.map((path) => ({ path, content: "text\n" })));
+ const prepared = prepareSkillFolder([{ path: "SKILL.md", content: SKILL }, ...admitted.files]);
+ if ("error" in prepared) throw new Error(prepared.error);
+ expect(prepared.files.map((file) => file.path).sort()).toEqual(admitted.files.map((file) => file.path).sort());
+ expect(prepared.skipped).toEqual([]);
+ });
+
+ it("travel on export, with what was left out and why named on the card", () => {
+ const share = host([
+ { path: "scripts/report.py", content: new TextEncoder().encode(SCRIPT) },
+ { path: "scripts/.env", content: "REPORT_TOKEN=abc" },
+ { path: "scripts/call.sh", content: `curl -H "authorization: token ${KEY}"` },
+ { path: "assets/logo.png", content: new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0, 0, 0]) },
+ { path: "prod.env", content: "A=1" },
+ ]);
+ const made = share.export({ scope: "bot", bot: helper }, []);
+ expect(readFileSync(join(made.dir, "skills", "report", "scripts", "report.py"), "utf8")).toBe(SCRIPT);
+ expect(made.card.skipped).toEqual(expect.arrayContaining([
+ "report/scripts/.env, which is hidden", "report/scripts/call.sh, which looks like it holds a key or password",
+ "report/assets/logo.png, which isn't a text file", "report/prod.env, which is named like a key or password file",
+ ]));
+ const folder = readShareFolder(readFolderFromDisk(made.dir));
+ if (folder.kind !== "package") throw new Error("not a package");
+ expect(folder.document.package.skills!.entries[0]!.files).toEqual([{ path: "scripts/report.py", content: SCRIPT }]);
+ expect(JSON.stringify(folder.document)).not.toContain(KEY);
+ });
+
+ it("stay home when they changed since they came in", () => {
+ const made = host(null).export({ scope: "bot", bot: helper }, []);
+ expect(made.card.skipped).toContain("the files beside skill report, which changed since they came in");
+ expect(readShareFolder(readFolderFromDisk(made.dir)).kind).toBe("package");
+ });
+
+ it("are read from a folder only when the manifest names them, never through a link", () => {
+ const made = host([{ path: "scripts/report.py", content: SCRIPT }]).export({ scope: "bot", bot: helper }, []);
+ writeFileSync(join(made.dir, "skills", "report", "notes.txt"), "not named");
+ expect(Object.keys(readFolderFromDisk(made.dir)).sort()).toEqual(["bot.md", "skills/report/SKILL.md", "skills/report/scripts/report.py"]);
+ const outside = scratch();
+ writeFileSync(join(outside, "secret.py"), "print('outside')\n");
+ rmSync(join(made.dir, "skills", "report", "scripts"), { recursive: true });
+ mkdirSync(join(made.dir, "skills", "report", "scripts"));
+ try {
+ symlinkSync(join(outside, "secret.py"), join(made.dir, "skills", "report", "scripts", "report.py"));
+ } catch {
+ return;
+ }
+ expect(readFolderFromDisk(made.dir)).not.toHaveProperty("skills/report/scripts/report.py");
+ expect(() => readShareFolder(readFolderFromDisk(made.dir))).toThrow(/but the file is missing/);
+ });
+
+ it("stay out of a community submission, whose check takes SKILL.md alone, and the published folder still reads", async () => {
+ const submitted: CommunitySubmission[] = [];
+ const share = host([{ path: "scripts/report.py", content: SCRIPT }], submitted);
+ const made = share.export({ scope: "bot", bot: helper }, []);
+ expect((await share.publish(made.card.id)).status).toBe("published");
+ expect(Object.keys(submitted[0]!.files).sort()).toEqual(["bot.md", "skills/report/SKILL.md"]);
+ expect(String(submitted[0]!.files["bot.md"])).not.toContain("skillFiles");
+ expect(share.files(made.card.id).files).toHaveProperty(["skills/report/scripts/report.py"]);
+ });
+});
diff --git a/server/share-team-templates.test.ts b/server/share-team-templates.test.ts
new file mode 100644
index 0000000000..add60a8e99
--- /dev/null
+++ b/server/share-team-templates.test.ts
@@ -0,0 +1,274 @@
+import { existsSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import type { IncomingMessage, ServerResponse } from "node:http";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { createShareGithubAccess } from "./host/share-github-access.ts";
+import type { RequestAuth } from "./request-auth.ts";
+import { createShareRoutes, createShareToolRoute, importSource, type ShareToolContext } from "./routes/share.ts";
+import { PASS } from "./routes/table.ts";
+import { GithubTemplateError } from "./share-github.ts";
+import { CONNECT_GITHUB, repoFolder, repoFolderOf, repoName, type GithubConnection } from "./share-github-repo.ts";
+import { createCommunityPublisher } from "./share-publish.ts";
+import { createShareHost } from "./share.ts";
+import type { BotRecord } from "./store.ts";
+import { createTeamTemplates, teamTemplatesFolder } from "./team-templates.ts";
+import { fakeGithubRepo } from "./testing/fake-composio-github.ts";
+
+const SKILL = "---\nname: report\ndescription: Weekly report.\n---\n\n# Report\n\nRun scripts/report.py.\n";
+const SCRIPT = "import os\nprint(os.environ.get('WEEK', 'this week'))\n";
+const TOKEN = `ghp_${"z".repeat(36)}`;
+const folders: string[] = [];
+const scratch = () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-team-templates-"));
+ folders.push(dir);
+ return dir;
+};
+afterEach(() => {
+ for (const dir of folders.splice(0)) rmSync(dir, { recursive: true, force: true });
+});
+
+const helper = { id: "bot-1", name: "Reporter", title: "Weekly reports", color: "blue" } as BotRecord;
+const ADMIN = { kind: "session", scopes: ["admin", "client"], via: "bearer", session: { id: "s1", email: "[email protected]" } } as unknown as RequestAuth;
+const MEMBER = { kind: "session", scopes: ["client"], via: "bearer", session: { id: "s2", email: "[email protected]" } } as unknown as RequestAuth;
+
+function setup(options: { team?: boolean; github?: GithubConnection; fetchTemplate?: () => Promise<never> } = {}) {
+ const dataDir = scratch(), botFolder = scratch();
+ const publisher = createCommunityPublisher({ access: () => null, selfHosted: true });
+ const host = createShareHost({
+ dataDir, bots: () => [helper], groups: () => [], routines: () => [], brief: () => undefined,
+ collectTeamSkills: () => ({ ok: true, skipped: [], skillsByBot: new Map([["bot-1", [{ name: "report", description: "Weekly report.", instructions: SKILL, enabled: true }]]]) }),
+ skillFiles: () => [{ path: "scripts/report.py", content: SCRIPT }], picture: () => undefined, botFolder: (id) => join(botFolder, id), publisher, patch: () => {},
+ });
+ let added = 0;
+ const library = options.team === false ? null : { team: "Acme", templates: createTeamTemplates(dataDir, () => 1_700_000_000_000 + added++) };
+ const view = { publicBot: (bot: BotRecord) => bot as never, publicGroup: (group: never) => group, broadcast: () => {} };
+ const importDeps = async () => { throw new Error("not added in this test"); };
+ const github = async () => options.github ?? { ok: false as const, reason: "not_connected" as const, message: CONNECT_GITHUB };
+ const fetchTemplate = options.fetchTemplate ?? (async () => { throw new GithubTemplateError("Nothing was found at that GitHub link.", 404); });
+ const routes = createShareRoutes({
+ host, localFolders: false, ...view, library, github, fetchTemplate, bots: () => [helper], routines: () => [], importDeps,
+ who: (auth) => (auth.kind === "session" ? auth.session.email : undefined), personOf: () => null,
+ });
+ const tool = createShareToolRoute({ host, localFolders: false, ...view, library, github, fetchTemplate, bots: () => [helper], routines: () => [], importDeps });
+ const request = async (auth: RequestAuth, method: string, path: string, body?: unknown) => {
+ let answer: { status: number; body: any } = { status: 0, body: null };
+ const url = new URL(`http://127.0.0.1${path}`);
+ const out = await routes({
+ req: {} as IncomingMessage, res: {} as ServerResponse, url, path: url.pathname, method, auth,
+ json: ((_res: unknown, status: number, value: unknown) => { answer = { status, body: value }; }) as never,
+ readBody: (async () => body) as never,
+ });
+ return out === PASS ? { status: 404, body: { error: "not routed" } } : answer;
+ };
+ const call = async (body: Record<string, unknown>, ctx: Partial<ShareToolContext> = {}) => {
+ let answer: { status: number; body: any } = { status: 0, body: null };
+ await tool({
+ method: "POST", path: "/api/internal/share", res: {} as ServerResponse, readBody: async () => body, bot: helper, threadId: "thread-1",
+ personMessage: "share yourself", roots: [], post: () => "message-1", actsForAdmin: true, githubPerson: null,
+ json: ((_res: unknown, status: number, value: unknown) => { answer = { status, body: value }; }) as never, ...ctx,
+ });
+ return answer;
+ };
+ return { host, dataDir, request, call, made: () => host.export({ scope: "bot", bot: helper }, []) };
+}
+
+describe("a team's own templates", () => {
+ it("an admin adds one under team-files/templates/<slug>/; adding again replaces it and keeps the old one as <slug>.previous/", async () => {
+ const { request, made, dataDir } = setup();
+ const card = made().card;
+ const first = await request(ADMIN, "POST", `/api/share/${card.id}/library`);
+ expect(first).toMatchObject({ status: 201, body: { replaced: false, template: { slug: "reporter", name: "Reporter", scope: "bot", addedBy: "[email protected]" } } });
+ const root = teamTemplatesFolder(dataDir);
+ expect(root).toBe(join(dataDir, "team-files", "templates"));
+ expect(readFileSync(join(root, "reporter", "skills", "report", "scripts", "report.py"), "utf8")).toBe(SCRIPT);
+ writeFileSync(join(root, "reporter", "marker.txt"), "first");
+ const again = await request(ADMIN, "POST", `/api/share/${card.id}/library`);
+ expect(again).toMatchObject({ status: 201, body: { replaced: true } });
+ expect(existsSync(join(root, "reporter.previous", "marker.txt"))).toBe(true);
+ expect(existsSync(join(root, "reporter", "marker.txt"))).toBe(false);
+ expect(readdirSync(root).sort()).toEqual(["reporter", "reporter.previous"]);
+ expect(JSON.stringify(readdirSync(join(root, "reporter"), { recursive: true }))).not.toMatch(/library|\.json/);
+ });
+
+ it("lists name, kind, who added it and when; imports from it through the folder reader; only an admin removes one", async () => {
+ const { request, made } = setup();
+ await request(ADMIN, "POST", `/api/share/${made().card.id}/library`);
+ const listed = await request(ADMIN, "GET", "/api/share/library");
+ expect(listed).toEqual({ status: 200, body: { team: "Acme", templates: [{ slug: "reporter", name: "Reporter", scope: "bot", tagline: "Weekly reports", addedBy: "[email protected]", addedAt: 1_700_000_000_000 }] } });
+ const preview = await request(ADMIN, "POST", "/api/share/import?preview=1", { library: "reporter" });
+ expect(preview).toMatchObject({ status: 200, body: { details: { scope: "bot", name: "Reporter", skills: [{ name: "report" }] } } });
+ expect(await request(MEMBER, "DELETE", "/api/share/library/reporter")).toMatchObject({ status: 403 });
+ expect(await request(MEMBER, "POST", `/api/share/${made().card.id}/library`)).toMatchObject({ status: 403 });
+ expect(await request(ADMIN, "DELETE", "/api/share/library/reporter")).toEqual({ status: 200, body: { ok: true } });
+ expect((await request(ADMIN, "GET", "/api/share/library")).body.templates).toEqual([]);
+ expect(await request(ADMIN, "POST", "/api/share/import?preview=1", { library: "reporter" })).toMatchObject({ status: 404 });
+ expect(await request(ADMIN, "DELETE", "/api/share/library/reporter")).toMatchObject({ status: 404 });
+ });
+
+ it("reads a library folder as untrusted: an edit that put a key in a script refuses the import", async () => {
+ const { request, made, dataDir } = setup();
+ await request(ADMIN, "POST", `/api/share/${made().card.id}/library`);
+ writeFileSync(join(teamTemplatesFolder(dataDir), "reporter", "skills", "report", "scripts", "report.py"), `TOKEN = "${TOKEN}"\n`);
+ const refused = await request(ADMIN, "POST", "/api/share/import?preview=1", { library: "reporter" });
+ expect(refused.status).toBe(400);
+ expect(refused.body.error).toMatch(/looks like it holds a key or password/);
+ });
+
+ it("is a Team Cloud's alone, and takes only plain slugs", async () => {
+ const { request, made } = setup({ team: false });
+ expect(await request(ADMIN, "GET", "/api/share/library")).toMatchObject({ status: 404 });
+ expect(await request(ADMIN, "POST", `/api/share/${made().card.id}/library`)).toMatchObject({ status: 404 });
+ for (const library of ["../x", "Reporter", "a/b", "", 5]) expect(importSource({ library })).toBeTypeOf("string");
+ expect(importSource({ library: "reporter" })).toEqual({ library: "reporter" });
+ const templates = createTeamTemplates(scratch());
+ expect(() => templates.add("../escape", {}, { name: "x", scope: "bot", tagline: "" })).toThrow();
+ });
+});
+
+describe("the share tool and the team's templates", () => {
+ it("adds, lists and imports for the team's owner or an admin only, in a request of their own", async () => {
+ const { call } = setup();
+ expect(await call({ action: "export" })).toMatchObject({ status: 200 });
+ expect(await call({ action: "add_to_team_library" }, { actsForAdmin: false })).toMatchObject({ status: 403 });
+ expect(await call({ action: "add_to_team_library" }, { personMessage: null })).toMatchObject({ status: 403 });
+ expect(await call({ action: "add_to_team_library" }, { actingName: "Olive" })).toMatchObject({ status: 201, body: { text: expect.stringContaining("Added Reporter in Acme's templates") } });
+ expect((await call({ action: "list_team_library" })).body.text).toContain("added by Olive");
+ expect(await call({ action: "add_to_team_library" })).toMatchObject({ status: 201, body: { text: expect.stringContaining("Replaced") } });
+ expect((await call({ action: "list_team_library" })).body.text).toMatch(/- reporter: Reporter \(a bot\), Weekly reports; added 2023-11-14/);
+ expect(await call({ action: "list_team_library" }, { actsForAdmin: false })).toMatchObject({ status: 403 });
+ expect(await call({ action: "import_from_team_library", slug: "nope" })).toMatchObject({ status: 404 });
+ expect(await call({ action: "import_from_team_library", slug: "reporter" }, { actsForAdmin: false })).toMatchObject({ status: 403 });
+ });
+
+ it("says there is no library off a Team Cloud", async () => {
+ const { call } = setup({ team: false });
+ expect(await call({ action: "list_team_library" })).toMatchObject({ status: 404, body: { error: expect.stringContaining("Team Cloud") } });
+ });
+});
+
+describe("GitHub through the connection", () => {
+ const connected = (repo: ReturnType<typeof fakeGithubRepo>): GithubConnection => ({ ok: true, relay: repo.relay });
+
+ it("parses owner/repo, folders and github.com links as plain names only", () => {
+ expect(repoName("acme/playbooks")).toEqual({ owner: "acme", repo: "playbooks" });
+ expect(repoName("https://github.com/acme/playbooks.git")).toEqual({ owner: "acme", repo: "playbooks" });
+ for (const bad of ["acme", "acme/play/books", "../x/y", "acme/..", "-x/y"]) expect(repoName(bad), bad).toBeNull();
+ expect(repoFolder(" templates/sales ")).toBe("templates/sales");
+ expect(repoFolder(undefined)).toBe("");
+ for (const bad of ["../x", "a/.git", "a/b/c/d/e/f/g"]) expect(repoFolder(bad), bad).toBeNull();
+ expect(repoFolderOf("https://github.com/acme/playbooks/tree/main/templates/reporter")).toEqual({ owner: "acme", repo: "playbooks", ref: "main", path: "templates/reporter" });
+ expect(repoFolderOf("https://github.com/acme/playbooks/blob/main/templates/reporter/bot.md")).toEqual({ owner: "acme", repo: "playbooks", ref: "main", path: "templates/reporter" });
+ expect(repoFolderOf("https://github.com/acme/playbooks")).toEqual({ owner: "acme", repo: "playbooks", path: "" });
+ for (const bad of ["http://github.com/a/b", "https://evil.test/a/b", "https://github.com/a/b/tree/main/a%2F..%2Fx", "https://u:[email protected]/a/b"]) expect(repoFolderOf(bad), bad).toBeNull();
+ });
+
+ it("opens a pull request in the person's repository with the scripts, then imports the private folder through the same connection", async () => {
+ const repo = fakeGithubRepo({ owner: "acme", repo: "playbooks", push: true });
+ const { request, made } = setup({ github: connected(repo) });
+ const card = made().card;
+ const published = await request(ADMIN, "POST", `/api/share/${card.id}/publish-repo`, { repo: "acme/playbooks", folder: "templates" });
+ expect(published.status, JSON.stringify(published.body)).toBe(200);
+ expect(published.body).toMatchObject({ kind: "pull_request", url: "https://github.com/acme/playbooks/pull/1", branch: expect.stringMatching(/^mausbot-reporter-[a-f0-9]{6}$/) });
+ expect(repo.pulls).toEqual([{ head: published.body.branch, base: "main", title: "Add the Reporter template from MausBot" }]);
+ const branch = repo.branches.get(published.body.branch)!;
+ expect([...branch.keys()].sort()).toEqual(["templates/reporter/bot.md", "templates/reporter/skills/report/SKILL.md", "templates/reporter/skills/report/scripts/report.py"]);
+ expect(repo.branches.get("main")!.size).toBe(0);
+ expect(JSON.stringify(repo.calls)).not.toMatch(/token|authorization|ghp_/i);
+ const link = published.body.link as string;
+ expect(link).toBe(`https://github.com/acme/playbooks/tree/${published.body.branch}/templates/reporter`);
+ const preview = await request(ADMIN, "POST", "/api/share/import?preview=1", { url: link });
+ expect(preview.status, JSON.stringify(preview.body)).toBe(200);
+ expect(preview.body.details).toMatchObject({ name: "Reporter", skills: [{ name: "report" }] });
+ });
+
+ it("commits straight to the default branch when asked and allowed, and says so when the connection can't write", async () => {
+ const repo = fakeGithubRepo({ owner: "acme", repo: "playbooks" });
+ const { request, made } = setup({ github: connected(repo) });
+ const card = made().card;
+ const direct = await request(ADMIN, "POST", `/api/share/${card.id}/publish-repo`, { repo: "acme/playbooks", direct: true });
+ expect(direct).toMatchObject({ status: 200, body: { kind: "commit", branch: "main", url: "https://github.com/acme/playbooks/tree/main/reporter" } });
+ expect(repo.branches.get("main")!.has("reporter/skills/report/scripts/report.py")).toBe(true);
+ const readOnly = fakeGithubRepo({ owner: "acme", repo: "playbooks", push: false });
+ const refused = await setup({ github: connected(readOnly) });
+ const answer = await refused.request(ADMIN, "POST", `/api/share/${refused.made().card.id}/publish-repo`, { repo: "acme/playbooks", direct: true });
+ expect(answer).toMatchObject({ status: 403, body: { error: "Your GitHub connection can't write to acme/playbooks." } });
+ expect(readOnly.calls.map((one) => one.slug)).toEqual(["GITHUB_GET_A_REPOSITORY"]);
+ });
+
+ it("never shows a pull request link outside the repository asked for", async () => {
+ const repo = fakeGithubRepo({ owner: "acme", repo: "playbooks", pullUrl: "https://github.com/evil/elsewhere/pull/1" });
+ const { request, made } = setup({ github: connected(repo) });
+ const answer = await request(ADMIN, "POST", `/api/share/${made().card.id}/publish-repo`, { repo: "acme/playbooks" });
+ expect(answer).toMatchObject({ status: 502, body: { error: "GitHub's answer for the pull request had no link." } });
+ });
+
+ it("without a GitHub connection: 'Connect GitHub in Apps first', and a private link's 404 says so", async () => {
+ const { request, made } = setup();
+ expect(await request(ADMIN, "GET", "/api/share/github")).toEqual({ status: 200, body: { connected: false, reason: "not_connected", error: CONNECT_GITHUB } });
+ expect(await request(ADMIN, "POST", `/api/share/${made().card.id}/publish-repo`, { repo: "acme/playbooks" })).toMatchObject({ status: 409, body: { error: CONNECT_GITHUB, code: "github_not_connected" } });
+ expect(await request(ADMIN, "POST", `/api/share/${made().card.id}/publish-repo`, { repo: "nope" })).toMatchObject({ status: 400 });
+ const missing = await request(ADMIN, "POST", "/api/share/import?preview=1", { url: "https://github.com/acme/private/tree/main/reporter" });
+ expect(missing).toMatchObject({ status: 404, body: { error: "Nothing was found at that GitHub link. If the repository is private, connect GitHub in Apps first." } });
+ });
+
+ it("reads a private folder only after the public read found nothing, with the same caps", async () => {
+ const repo = fakeGithubRepo({ owner: "acme", repo: "private" });
+ let publicReads = 0;
+ const big = fakeGithubRepo({ owner: "acme", repo: "big" });
+ big.put("main", "t/bot.md", `---\nbotmrr: 2\nname: Big\n---\n${"x".repeat(1_000_001)}`);
+ const { request } = setup({ github: { ok: true, relay: async (...args) => (String(JSON.stringify(args[0])).includes("\"big\"") ? big : repo).relay(...args) },
+ fetchTemplate: async () => { publicReads += 1; throw new GithubTemplateError("Nothing was found at that GitHub link.", 404); } });
+ expect(await request(ADMIN, "POST", "/api/share/import?preview=1", { url: "https://github.com/acme/private/tree/main/none" })).toMatchObject({ status: 404, body: { error: "No bot.md or team.md was found in that folder." } });
+ expect(publicReads).toBe(1);
+ expect(await request(ADMIN, "POST", "/api/share/import?preview=1", { url: "https://github.com/acme/big/tree/main/t" })).toMatchObject({ status: 413 });
+ });
+
+ it("the share tool reads a private link through GitHub only for the team's admins", async () => {
+ let asked = 0;
+ const repo = fakeGithubRepo({ owner: "acme", repo: "private" });
+ const { call } = setup({ github: { ok: true, relay: async (...args) => { asked += 1; return repo.relay(...args); } } });
+ const link = "https://github.com/acme/private/tree/main/reporter";
+ expect(await call({ action: "import", url: link }, { personMessage: `import ${link}`, actsForAdmin: false })).toMatchObject({ status: 404, body: { error: "Nothing was found at that GitHub link." } });
+ expect(asked).toBe(0);
+ expect(await call({ action: "import", url: link }, { personMessage: `import ${link}` })).toMatchObject({ status: 404, body: { error: "No bot.md or team.md was found in that folder." } });
+ expect(asked).toBeGreaterThan(0);
+ });
+
+ it("the share tool publishes only to a repository the person named, for the team's admins", async () => {
+ const repo = fakeGithubRepo({ owner: "acme", repo: "playbooks" });
+ const { call } = setup({ github: connected(repo) });
+ await call({ action: "export" });
+ expect(await call({ action: "publish_to_repo", repo: "acme/playbooks" }, { personMessage: "publish yourself to our repo" })).toMatchObject({ status: 403 });
+ expect(await call({ action: "publish_to_repo", repo: "acme/playbooks" }, { personMessage: "publish to acme/playbooks", actsForAdmin: false })).toMatchObject({ status: 403 });
+ expect(repo.calls).toEqual([]);
+ const done = await call({ action: "publish_to_repo", repo: "acme/playbooks", path: "bots" }, { personMessage: "publish to Acme/Playbooks please" });
+ expect(done.status, JSON.stringify(done.body)).toBe(200);
+ expect(done.body.text).toMatch(/^Opened a pull request in acme\/playbooks: https:\/\/github\.com\/acme\/playbooks\/pull\/1/);
+ expect([...repo.branches.values()].some((files) => files.has("bots/reporter/bot.md"))).toBe(true);
+ });
+});
+
+describe("which GitHub connection", () => {
+ const composio = (apps: Record<string, { connected: boolean; accounts: Array<{ id: string; status: string }> }>, seen: unknown[] = []) => ({
+ configured: () => true,
+ connectedServices: async (_cfg: unknown, as?: unknown) => { seen.push(as ?? "team"); return apps as never; },
+ relayMcp: async () => ({ status: 200, bytes: new Uint8Array(), contentType: "application/json" }),
+ });
+
+ it("is the team's, the person's own when each connects it, never one the Rules refuse", async () => {
+ const seen: unknown[] = [];
+ const github = { connected: true, pending: false, status: "ACTIVE", accounts: [{ id: "ca_1", status: "ACTIVE" }, { id: "ca_2", status: "ACTIVE" }] };
+ const team = createShareGithubAccess({ cfg: () => ({}) as never, composio: composio({ github }, seen) as never, personApps: () => [], appsAccess: () => null, appRefusal: () => null });
+ expect(await team(null)).toMatchObject({ ok: true, account: "ca_1" });
+ expect(seen).toEqual(["team"]);
+ const own = createShareGithubAccess({ cfg: () => ({}) as never, composio: composio({ github }) as never, personApps: () => ["github"], appsAccess: (person) => (person === "p_ada" ? { installationId: "i", token: "t" } as never : null), appRefusal: () => null });
+ expect(await own(null)).toMatchObject({ ok: false, reason: "not_connected", message: CONNECT_GITHUB });
+ expect(await own("p_ben")).toMatchObject({ ok: false, reason: "not_connected" });
+ const refused = createShareGithubAccess({ cfg: () => ({}) as never, composio: composio({ github }) as never, personApps: () => [], appsAccess: () => null, appRefusal: () => "GitHub is off on this team." });
+ expect(await refused(null)).toEqual({ ok: false, reason: "refused", message: "GitHub is off on this team." });
+ const none = createShareGithubAccess({ cfg: () => ({}) as never, composio: composio({}) as never, personApps: () => [], appsAccess: () => null, appRefusal: () => null });
+ expect(await none(null)).toMatchObject({ ok: false, reason: "not_connected" });
+ });
+});
diff --git a/server/share.ts b/server/share.ts
index 2a91b8c97a..23dbb46496 100644
--- a/server/share.ts
+++ b/server/share.ts
@@ -19,6 +19,9 @@ import type { TemplateAvatar, TemplateCard, TemplateDetails, TemplateScope } fro
import { manifestDetails, packageDetails } from "../shared/share-details.ts";
import {
isShareFolderPath,
+ isSkillFilePath,
+ namedFolderFiles,
+ MANIFEST_NAMES,
readShareFolder,
SHARE_FOLDER_MAX_BYTES,
SHARE_FOLDER_MAX_FILES,
@@ -26,6 +29,7 @@ import {
type ShareFolder,
type ShareFolderFiles,
} from "../shared/share-folder.ts";
+import { admitSkillFiles, skillFileRefusalWords } from "../shared/skill-files.ts";
import { writeFileAtomic } from "./atomic.ts";
import { createTeamPackageExport, TeamExportError, type ExportablePackageSkill, type TeamExportSkip } from "./package-export.ts";
import type { Routine } from "./routines.ts";
@@ -50,6 +54,9 @@ export interface ShareHostDeps {
collectTeamSkills(bots: readonly BotRecord[], selection: "all"):
| { ok: true; skillsByBot: Map<string, ExportablePackageSkill[]>; skipped: TeamExportSkip[] }
| { ok: false; error: string };
+ /** The files beside one of the bot's skills, before what may travel is picked from them; null when they changed since
+ * they came in. */
+ skillFiles?(bot: BotRecord, name: string): Array<{ path: string; content: string | Uint8Array }> | null;
/** The bot's picture as a data: URL, when it shows one instead of its mascot. */
picture(bot: BotRecord): string | undefined;
/** The bot's own folder, where a template it makes is written for it to read and edit. */
@@ -152,6 +159,14 @@ export function readFolderFromDisk(chosen: string): ShareFolderFiles {
if (isShareFolderPath(`avatars/${name}`)) take(join(prefix, "avatars", name));
}
}
+ const manifest = [MANIFEST_NAMES.bot, MANIFEST_NAMES.department].map((name) => files[prefix ? `${prefix}/${name}` : name]).find((value) => typeof value === "string");
+ let named: string[] = [];
+ try {
+ named = typeof manifest === "string" ? namedFolderFiles(manifest) : [];
+ } catch {
+ // The folder reader refuses a manifest it can't read, in its own words.
+ }
+ for (const path of named) if (isSkillFilePath(path)) take(join(prefix, ...path.split("/")));
};
collect("");
if (!Object.keys(files).some((path) => !path.includes("/"))) {
@@ -161,7 +176,7 @@ export function readFolderFromDisk(chosen: string): ShareFolderFiles {
return files;
}
-function writeFolder(dir: string, files: Record<string, string | Uint8Array>): void {
+export function writeFolder(dir: string, files: Record<string, string | Uint8Array>): void {
mkdirSync(dir, { recursive: true });
for (const [path, value] of Object.entries(files)) {
const target = join(dir, ...path.split("/"));
@@ -214,6 +229,14 @@ function templateDocument(document: PackageDocument, bots: readonly BotRecord[],
return { document: parsePackageDocument(redactedDocument, { trust: "file" }), redacted: redacted.length };
}
+/** The community repository's check takes SKILL.md alone in a skill's folder, so a template goes there without its
+ * skills' other files; a download, a team library and a person's own repository keep them. */
+export function withoutSkillFiles(document: PackageDocument): PackageDocument {
+ const skills = document.package.skills;
+ if (!skills?.entries.some((skill) => skill.files?.length)) return document;
+ return { ...document, package: { ...document.package, skills: { ...skills, entries: skills.entries.map(({ files: _files, ...skill }) => skill) } } };
+}
+
export function cardText(card: TemplateCard): string {
if (card.status === "gone") return `Deleted the template of ${card.name}.`;
if (card.status === "published" && card.link) return `Published the template of ${card.name}: ${card.link}`;
@@ -289,6 +312,19 @@ export function createShareHost(deps: ShareHostDeps) {
if (!bots.length) throw new ShareError("This department has no bots to share.");
const skills = deps.collectTeamSkills(bots, "all");
if (!skills.ok) throw new ShareError(skills.error);
+ const fileSkips = new Set<string>();
+ for (const bot of bots) {
+ for (const skill of skills.skillsByBot.get(bot.id) ?? []) {
+ const stored = deps.skillFiles ? deps.skillFiles(bot, skill.name) : [];
+ if (stored === null) {
+ fileSkips.add(`the files beside skill ${skill.name}, which changed since they came in`);
+ continue;
+ }
+ const admitted = admitSkillFiles(stored);
+ if (admitted.files.length) skill.files = admitted.files;
+ for (const refused of admitted.refused) fileSkips.add(`${skill.name}/${refused.path}, which ${skillFileRefusalWords(refused.reason)}`);
+ }
+ }
const avatars: Record<string, string> = {};
for (const bot of bots) {
const picture = deps.picture(bot);
@@ -331,7 +367,7 @@ export function createShareHost(deps: ShareHostDeps) {
...(agent.appearance.mascotBody ? { mascotBody: agent.appearance.mascotBody } : {}),
};
});
- return { document, redacted: redacted + exported.redacted.length, skipped: exported.skipped.map(skipWords), avatars: avatarsShown };
+ return { document, redacted: redacted + exported.redacted.length, skipped: [...exported.skipped.map(skipWords), ...fileSkips], avatars: avatarsShown };
}
return {
@@ -410,7 +446,7 @@ export function createShareHost(deps: ShareHostDeps) {
if (error instanceof ShareError) return update(record, { status: "failed", error: error.message });
throw error;
}
- const files = writeShareFolder(document, record.scope);
+ const files = writeShareFolder(withoutSkillFiles(document), record.scope);
const bytes = Object.values(files).reduce((sum, value) => sum + (typeof value === "string" ? Buffer.byteLength(value) : value.byteLength), 0);
if (Object.keys(files).length > COMMUNITY_MAX_FILES) return update(record, { status: "failed", error: `A template can have at most ${COMMUNITY_MAX_FILES} files.` }, document);
if (bytes > COMMUNITY_MAX_BYTES) return update(record, { status: "failed", error: "This template is bigger than 4 MB. Leave out large pictures or skills, then publish again." }, document);
diff --git a/server/skill-folder.ts b/server/skill-folder.ts
index 5be00f1db4..f1f7895a69 100644
--- a/server/skill-folder.ts
+++ b/server/skill-folder.ts
@@ -191,7 +191,7 @@ export function writeSkillFolder(
}
}
-function readNoFollow(path: string): Buffer | null {
+export function readNoFollow(path: string): Buffer | null {
let fd: number | null = null;
try {
fd = openSync(path, constants.O_RDONLY | (process.platform === "win32" ? 0 : constants.O_NOFOLLOW));
diff --git a/server/skill-side-files.ts b/server/skill-side-files.ts
new file mode 100644
index 0000000000..42039741b6
--- /dev/null
+++ b/server/skill-side-files.ts
@@ -0,0 +1,37 @@
+// The files beside a stored skill's SKILL.md, read for a template. Security: only the files its record lists, and only
+// while they still hash as they came in; never a walk of the folder, where a run may have left a cache, a lockfile or an
+// .env beside the skill.
+import { join } from "node:path";
+
+import { readNoFollow, skillFolderDigest } from "./skill-folder.ts";
+import { librarySkillDirectory, readSkillLibraryIndex, skillsLibraryRoot } from "./skill-library.ts";
+import { readManifest, readSkillReferences, skillDirectory } from "./skills.ts";
+
+/** The files, or null when they no longer match what came in. */
+export type StoredSkillFiles = Array<{ path: string; content: string | Uint8Array }> | null;
+
+function listedFiles(dir: string | null, paths: readonly string[] | undefined, sha256: string | undefined): StoredSkillFiles {
+ if (!paths?.length) return [];
+ if (!dir || !sha256 || skillFolderDigest(dir, paths) !== sha256) return null;
+ const files: Array<{ path: string; content: Uint8Array }> = [];
+ for (const path of paths) {
+ const bytes = readNoFollow(join(dir, ...path.split("/")));
+ if (bytes === null) return null;
+ files.push({ path, content: new Uint8Array(bytes) });
+ }
+ return files;
+}
+
+/** A bot's own skill: an import's files, or a learned skill's reviewed references. */
+export function ownSkillFiles(botId: string, name: string): StoredSkillFiles {
+ const entry = readManifest(botId)[name];
+ if (!entry) return [];
+ if (entry.files?.length) return listedFiles(skillDirectory(botId, name, entry), entry.files, entry.filesSha256);
+ return entry.referencesSha256 ? readSkillReferences(botId, name) : [];
+}
+
+/** A skill of the organization's library on this server. */
+export function librarySkillFiles(name: string, root: string = skillsLibraryRoot()): StoredSkillFiles {
+ const entry = readSkillLibraryIndex(root)[name];
+ return entry ? listedFiles(librarySkillDirectory(root, name), entry.files, entry.filesSha256) : [];
+}
diff --git a/server/skills.ts b/server/skills.ts
index 81bbc1addf..5366aa189c 100644
--- a/server/skills.ts
+++ b/server/skills.ts
@@ -52,7 +52,7 @@ export const INDEX_MAX_BYTES = 4_000;
const loggedIndexOmissions = new Map<string, string>();
export const MAX_STAGED_SKILLS = 20;
export const STAGED_GIST_MAX = 240;
-interface SkillManifestEntry {
+export interface SkillManifestEntry {
description: string;
enabled: boolean;
source: string;
@@ -82,7 +82,7 @@ export interface SkillPackageStamp {
via?: "preset";
}
-interface SkillManifest {
+export interface SkillManifest {
[name: string]: SkillManifestEntry;
}
@@ -142,7 +142,7 @@ function existingSkillDirectory(botId: string, name: string): string | null {
return directoryEntryState(directory) === "directory" ? directory : null;
}
-function skillDirectory(botId: string, name: string, entry: SkillManifestEntry): string | null {
+export function skillDirectory(botId: string, name: string, entry: SkillManifestEntry): string | null {
if (!entry.storageRevision) return existingSkillDirectory(botId, name);
const root = existingSkillsRoot(botId);
if (!root) return null;
@@ -211,7 +211,7 @@ function manifestFromFile(path: string): SkillManifest | null {
}
}
-function readManifest(botId: string): SkillManifest {
+export function readManifest(botId: string): SkillManifest {
const securePath = manifestPath(botId);
// Corrupt protected state fails closed; never fall back to the agent-writable legacy manifest.
if (existsSync(securePath)) return manifestFromFile(securePath) ?? {};
diff --git a/server/team-templates.ts b/server/team-templates.ts
new file mode 100644
index 0000000000..5e9375711c
--- /dev/null
+++ b/server/team-templates.ts
@@ -0,0 +1,117 @@
+// A Team Cloud's own templates: each a template folder at <dataDir>/team-files/templates/<slug>/, in the team's shared
+// files, with who added it and when kept apart in share/team-library.json. Adding a template with a slug already there
+// keeps the one it replaces as <slug>.previous/, and so does removing one.
+// Security: a folder here is read back through the template folder reader and the package gate at every import, never
+// trusted for having been written by this server; nothing outside templates/ is written or deleted.
+import { randomBytes } from "node:crypto";
+import { lstatSync, mkdirSync, readFileSync, rmSync } from "node:fs";
+import { join } from "node:path";
+import { z } from "zod";
+
+import type { TeamTemplate, TemplateScope } from "../shared/share-card.ts";
+import type { ShareFolderFiles } from "../shared/share-folder.ts";
+import { renameWithRetry, writeFileAtomic } from "./atomic.ts";
+import { readFolderFromDisk, ShareError, writeFolder } from "./share.ts";
+
+/** The team's shared files. Its templates are one folder of it. */
+export const TEAM_FILES_FOLDER = "team-files";
+export const teamTemplatesFolder = (dataDir: string): string => join(dataDir, TEAM_FILES_FOLDER, "templates");
+
+export const TEAM_TEMPLATE_SLUG = /^[a-z0-9][a-z0-9-]{0,47}$/;
+const MAX_TEMPLATES = 500;
+const GONE = "This template is no longer in the team's library.";
+
+const entrySchema = z.object({
+ name: z.string().min(1).max(100),
+ scope: z.enum(["bot", "department"]),
+ tagline: z.string().max(200),
+ addedBy: z.string().max(200).optional(),
+ addedAt: z.number().int().nonnegative(),
+});
+const fileSchema = z.object({ v: z.literal(1), templates: z.record(z.string().regex(TEAM_TEMPLATE_SLUG), entrySchema) });
+
+const isFolder = (path: string) => {
+ try {
+ return lstatSync(path).isDirectory();
+ } catch {
+ return false;
+ }
+};
+
+export function createTeamTemplates(dataDir: string, now: () => number = Date.now) {
+ const root = teamTemplatesFolder(dataDir);
+ const indexFile = join(dataDir, "share", "team-library.json");
+ const read = (): Record<string, z.output<typeof entrySchema>> => {
+ try {
+ const parsed = fileSchema.safeParse(JSON.parse(readFileSync(indexFile, "utf8")));
+ return parsed.success ? parsed.data.templates : {};
+ } catch {
+ return {};
+ }
+ };
+ const write = (templates: Record<string, z.output<typeof entrySchema>>) => {
+ mkdirSync(join(dataDir, "share"), { recursive: true, mode: 0o700 });
+ writeFileAtomic(indexFile, JSON.stringify({ v: 1, templates }), { mode: 0o600 });
+ };
+ const folderOf = (slug: string) => {
+ if (!TEAM_TEMPLATE_SLUG.test(slug)) throw new ShareError(GONE, 404);
+ return join(root, slug);
+ };
+ /** The folder at `slug` moves to <slug>.previous/, replacing an older one there. */
+ const keepPrevious = (slug: string) => {
+ const previous = join(root, `${slug}.previous`);
+ rmSync(previous, { recursive: true, force: true });
+ renameWithRetry(join(root, slug), previous);
+ };
+
+ return {
+ list(): TeamTemplate[] {
+ return Object.entries(read())
+ .filter(([slug]) => isFolder(join(root, slug)))
+ .map(([slug, entry]) => ({ slug, ...entry }))
+ .sort((a, b) => b.addedAt - a.addedAt);
+ },
+
+ /** Adds a template folder's files as <slug>, replacing one already there. */
+ add(slug: string, files: ShareFolderFiles, about: { name: string; scope: TemplateScope; tagline: string; addedBy?: string }): { template: TeamTemplate; replaced: boolean } {
+ const target = folderOf(slug);
+ const templates = read();
+ if (!templates[slug] && Object.keys(templates).length >= MAX_TEMPLATES) throw new ShareError(`The team's library holds at most ${MAX_TEMPLATES} templates. Remove one first.`, 409);
+ mkdirSync(root, { recursive: true, mode: 0o700 });
+ const incoming = join(root, `.incoming-${randomBytes(6).toString("hex")}`);
+ try {
+ writeFolder(incoming, files);
+ const replaced = isFolder(target);
+ if (replaced) keepPrevious(slug);
+ renameWithRetry(incoming, target);
+ const entry = { name: about.name.slice(0, 100), scope: about.scope, tagline: about.tagline.slice(0, 200), ...(about.addedBy ? { addedBy: about.addedBy.slice(0, 200) } : {}), addedAt: now() };
+ write({ ...templates, [slug]: entry });
+ return { template: { slug, ...entry }, replaced };
+ } finally {
+ rmSync(incoming, { recursive: true, force: true });
+ }
+ },
+
+ /** The template's files as they are on disk now, for the folder reader. */
+ files(slug: string): ShareFolderFiles {
+ const folder = folderOf(slug);
+ if (!read()[slug] || !isFolder(folder)) throw new ShareError(GONE, 404);
+ return readFolderFromDisk(folder);
+ },
+
+ has(slug: string): boolean {
+ return TEAM_TEMPLATE_SLUG.test(slug) && Boolean(read()[slug]) && isFolder(join(root, slug));
+ },
+
+ /** Takes the template out of the library; its folder stays as <slug>.previous/. */
+ remove(slug: string): void {
+ folderOf(slug);
+ const templates = read();
+ if (!templates[slug]) throw new ShareError(GONE, 404);
+ if (isFolder(join(root, slug))) keepPrevious(slug);
+ delete templates[slug];
+ write(templates);
+ },
+ };
+}
+export type TeamTemplates = ReturnType<typeof createTeamTemplates>;
diff --git a/server/testing/fake-composio-github.ts b/server/testing/fake-composio-github.ts
new file mode 100644
index 0000000000..95e9c35dc3
--- /dev/null
+++ b/server/testing/fake-composio-github.ts
@@ -0,0 +1,100 @@
+// A GitHub repository behind a fake connected-apps relay, for template tests: the MCP frames a template's GitHub reads
+// and writes send (initialize, then COMPOSIO_MULTI_EXECUTE_TOOL) answered from memory, with no network.
+import { createHash } from "node:crypto";
+
+import type { GithubRelay } from "../share-github-repo.ts";
+
+type Tree = Map<string, Uint8Array>;
+
+export interface FakeGithubRepo {
+ relay: GithubRelay;
+ /** Every tool call, by slug and arguments. */
+ calls: Array<{ slug: string; args: Record<string, unknown> }>;
+ branches: Map<string, Tree>;
+ pulls: Array<{ head: string; base: string; title: string }>;
+ /** Puts a file on a branch, as a person's own commit would. */
+ put(branch: string, path: string, content: string | Uint8Array): void;
+}
+
+const sha = (value: string) => createHash("sha1").update(value).digest("hex");
+
+export function fakeGithubRepo(options: { owner: string; repo: string; push?: boolean; pullUrl?: string }): FakeGithubRepo {
+ const branches = new Map<string, Tree>([["main", new Map()]]);
+ const blobs = new Map<string, Uint8Array>(), trees = new Map<string, Tree>(), commits = new Map<string, { tree: string; parents: string[] }>();
+ const heads = new Map<string, string>([["main", "c0"]]);
+ commits.set("c0", { tree: "t0", parents: [] });
+ trees.set("t0", new Map());
+ const calls: FakeGithubRepo["calls"] = [];
+ const pulls: FakeGithubRepo["pulls"] = [];
+ const ok = (data: unknown) => ({ successful: true, data });
+ const fail = (error: string) => ({ successful: false, error });
+ const mine = (args: Record<string, unknown>) => args.owner === options.owner && args.repo === options.repo;
+ const commitTo = (branch: string, commit: string) => {
+ heads.set(branch, commit);
+ branches.set(branch, new Map(trees.get(commits.get(commit)!.tree)!));
+ };
+
+ const tools: Record<string, (args: Record<string, unknown>) => unknown> = {
+ GITHUB_GET_A_REPOSITORY: () => ok({ default_branch: "main", ...(options.push === undefined ? {} : { permissions: { push: options.push } }) }),
+ GITHUB_GET_REPOSITORY_CONTENT: (args) => {
+ const file = branches.get(String(args.ref))?.get(String(args.path));
+ return file ? ok({ type: "file", encoding: "base64", size: file.byteLength, content: Buffer.from(file).toString("base64") }) : fail("Not Found");
+ },
+ GITHUB_GET_A_BRANCH: (args) => {
+ const head = heads.get(String(args.branch));
+ return head ? ok({ name: args.branch, commit: { sha: head, commit: { tree: { sha: commits.get(head)!.tree } } } }) : fail("Branch not found");
+ },
+ GITHUB_CREATE_A_BLOB: (args) => {
+ const bytes = new Uint8Array(Buffer.from(String(args.content), "base64"));
+ const id = sha(`blob:${Buffer.from(bytes).toString("hex")}`);
+ blobs.set(id, bytes);
+ return ok({ sha: id });
+ },
+ GITHUB_CREATE_A_TREE: (args) => {
+ const tree = new Map(trees.get(String(args.base_tree)) ?? []);
+ for (const entry of args.tree as Array<{ path: string; sha: string }>) tree.set(entry.path, blobs.get(entry.sha)!);
+ const id = sha(`tree:${[...tree.keys()].join(",")}:${trees.size}`);
+ trees.set(id, tree);
+ return ok({ sha: id });
+ },
+ GITHUB_CREATE_A_COMMIT: (args) => {
+ const id = sha(`commit:${String(args.tree)}:${commits.size}`);
+ commits.set(id, { tree: String(args.tree), parents: args.parents as string[] });
+ return ok({ sha: id });
+ },
+ GITHUB_CREATE_A_REFERENCE: (args) => {
+ commitTo(String(args.ref).replace(/^refs\/heads\//, ""), String(args.sha));
+ return ok({ ref: args.ref });
+ },
+ GITHUB_UPDATE_A_REFERENCE: (args) => {
+ if (options.push === false) return fail("Resource not accessible by integration");
+ commitTo(String(args.ref).replace(/^heads\//, ""), String(args.sha));
+ return ok({ ref: args.ref });
+ },
+ GITHUB_CREATE_A_PULL_REQUEST: (args) => {
+ pulls.push({ head: String(args.head), base: String(args.base), title: String(args.title) });
+ return ok({ number: pulls.length, html_url: options.pullUrl ?? `https://github.com/${options.owner}/${options.repo}/pull/${pulls.length}` });
+ },
+ };
+
+ const relay: GithubRelay = async (payload) => {
+ const frame = payload as { id?: string; method: string; params?: { name?: string; arguments?: { tools?: Array<{ tool_slug: string; arguments: Record<string, unknown> }> } } };
+ const answer = (body: unknown) => ({ status: 200, bytes: new TextEncoder().encode(JSON.stringify(body)), transportSessionId: "fake-session" });
+ if (frame.method === "initialize") return answer({ jsonrpc: "2.0", id: frame.id, result: { protocolVersion: "2025-03-26", capabilities: {} } });
+ if (frame.method !== "tools/call") return { status: 202, bytes: new Uint8Array() };
+ const results = (frame.params?.arguments?.tools ?? []).map((tool) => {
+ calls.push({ slug: tool.tool_slug, args: tool.arguments });
+ const run = tools[tool.tool_slug];
+ const response = !run ? fail(`Unknown tool ${tool.tool_slug}`) : mine(tool.arguments) ? run(tool.arguments) : fail("Not Found");
+ return { tool_slug: tool.tool_slug, response };
+ });
+ return answer({ jsonrpc: "2.0", id: frame.id, result: { content: [{ type: "text", text: JSON.stringify({ successful: true, data: { results } }) }] } });
+ };
+
+ return {
+ relay, calls, branches, pulls,
+ put(branch, path, content) {
+ branches.get(branch)!.set(path, typeof content === "string" ? new TextEncoder().encode(content) : content);
+ },
+ };
+}
diff --git a/shared/package-format.ts b/shared/package-format.ts
index c7075faba9..db3dd5f4ba 100644
--- a/shared/package-format.ts
+++ b/shared/package-format.ts
@@ -13,6 +13,7 @@ import { normalizeCronSchedule } from "./routine-schedule.ts";
import { isToolGroup } from "./tool-groups.ts";
import { MAUS_COLOR_NAMES } from "./wire.ts";
import { isSkillName, parseSkillMd, scanSkillText, SKILL_FILE_MAX_BYTES } from "./skill-md.ts";
+import { skillFilesSchema } from "./skill-files.ts";
export const PACKAGE_FORMAT = "openmaus.package";
/** The newest version this module reads and writes. */
@@ -61,7 +62,6 @@ export function utf8Bytes(value: string): number {
return encoder.encode(value).length;
}
-
export const requiredText = (max: number) =>
z.string({ error: "must be text" }).trim().min(1, { message: "is required" }).max(max, { message: "is too long" });
@@ -98,6 +98,7 @@ const portableSkillSchema = z.object({
license: optionalText(200),
compatibility: optionalText(200),
instructions: skillInstructions,
+ files: skillFilesSchema,
});
const soulSchema = z.string().refine((value) => utf8Bytes(value) <= BOT_PROFILE_LIMITS.soul, {
error: "standing instructions must be at most 24000 bytes",
@@ -262,7 +263,6 @@ const packageDocumentV1Schema = z.object({
export type PackageDocumentV1 = z.output<typeof packageDocumentV1Schema>;
-
const semver = z.string({ error: "must be text" }).regex(/^(0|[1-9]\d{0,5})\.(0|[1-9]\d{0,5})\.(0|[1-9]\d{0,5})$/, {
message: "must be a version like 1.2.3",
});
@@ -883,7 +883,7 @@ function visitText(document: PackageDocument, visit: TextVisitor): void {
if (!value || typeof value !== "object") return;
const record = value as Record<string, unknown>;
for (const name of Object.keys(record)) {
- if (part.endsWith(".appearance.avatar") && name === "data") continue;
+ if ((part.endsWith(".appearance.avatar") && name === "data") || (name === "content" && /^skills\[[^\]]*\]\.files\[\d+\]$/.test(part))) continue;
walk(record, name, part.endsWith(".seed.memory") ? `${part}[${JSON.stringify(name)}]` : `${part}.${name}`);
}
};
diff --git a/shared/share-folder.test.ts b/shared/share-folder.test.ts
index 5ceef441be..7fc5c8d762 100644
--- a/shared/share-folder.test.ts
+++ b/shared/share-folder.test.ts
@@ -70,7 +70,8 @@ describe("template folders", () => {
it("refuses unsafe paths and opens only the files a template has", () => {
for (const path of ["../bot.md", "/etc/passwd", "skills\\x\\SKILL.md", ".hidden/bot.md", "a/../bot.md", "a//b"]) expect(safeFolderPath(path)).toBeNull();
- const kept = normalizeShareFolder({ "bot.md": "x", "../team.md": "y", "skills/a/SKILL.md": "z", "skills/a/run.sh": "rm -rf", "avatars/a.svg": "<svg/>", "memory/notes.md": "secret" });
+ const kept = normalizeShareFolder({ "bot.md": "x", "../team.md": "y", "skills/a/SKILL.md": "z", "skills/a/run.sh": "rm -rf", "skills/a/.env": "KEY=1",
+ "skills/a/node_modules/x.js": "x", "avatars/a.svg": "<svg/>", "memory/notes.md": "secret" });
expect(Object.keys(kept).sort()).toEqual(["bot.md", "skills/a/SKILL.md"]);
});
diff --git a/shared/share-folder.ts b/shared/share-folder.ts
index bd34dff387..e6c38e99e5 100644
--- a/shared/share-folder.ts
+++ b/shared/share-folder.ts
@@ -1,6 +1,7 @@
// A template folder, the one format a shared bot or department travels in:
// bot.md | team.md BotMRR Markdown v2: YAML frontmatter with the package fields, and a readable body
// skills/<name>/SKILL.md each skill the frontmatter names
+// skills/<name>/<path> the text files beside it that the frontmatter's skillFiles names
// avatars/<key>.<png|jpg|webp> each picture the frontmatter names
// README.md optional, for people browsing GitHub; never read back
// Pure (no node:*): the server, the renderer and the Admin's submission check read folders with the same rules, and
@@ -20,6 +21,7 @@ import {
type PackageDocument,
} from "./package-format.ts";
import type { TemplateScope } from "./share-card.ts";
+import { skillFilePathProblem, type SkillFile } from "./skill-files.ts";
import { isSkillName, parseSkillMd, SKILL_FILE_MAX_BYTES } from "./skill-md.ts";
export type ShareFolderFiles = Record<string, string | Uint8Array>;
@@ -35,6 +37,13 @@ const PICTURE_TYPES = { png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg",
const PICTURE_EXTENSIONS: Record<string, string> = { "image/png": "png", "image/jpeg": "jpg", "image/webp": "webp" };
const SKILL_PATH = /^skills\/([a-z0-9][a-z0-9-]{0,63})\/SKILL\.md$/;
const PICTURE_PATH = /^avatars\/([a-z0-9][a-z0-9_-]{0,63})\.(png|jpg|jpeg|webp)$/;
+const SKILL_FILE_PATH = /^skills\/([a-z0-9][a-z0-9-]{0,63})\/(.+)$/;
+
+/** A file beside a skill's SKILL.md: skills/<name>/<path>, with a path a skill folder can hold. */
+export function isSkillFilePath(path: string): boolean {
+ const match = path.match(SKILL_FILE_PATH);
+ return Boolean(match) && match![2] !== "SKILL.md" && skillFilePathProblem(match![2]!) === null;
+}
export type ShareFolder =
| { kind: "package"; scope: TemplateScope; document: PackageDocument }
@@ -51,10 +60,11 @@ export function safeFolderPath(path: string): string | null {
return parts.every((part) => part && part !== "." && part !== ".." && !part.startsWith(".")) ? clean : null;
}
-/** Whether the reader ever opens this path: the manifest, a skill or a picture. Everything else in a folder is ignored. */
+/** Whether the reader ever opens this path: the manifest, a skill, a file beside one or a picture. Everything else in a
+ * folder is ignored. */
export function isShareFolderPath(path: string): boolean {
return path === MANIFEST_NAMES.bot || path === MANIFEST_NAMES.department || path === LEGACY_MARKDOWN || path === LEGACY_MANIFEST ||
- /^[\w.-]+\.openmaus\.json$/.test(path) || SKILL_PATH.test(path) || PICTURE_PATH.test(path);
+ /^[\w.-]+\.openmaus\.json$/.test(path) || SKILL_PATH.test(path) || PICTURE_PATH.test(path) || isSkillFilePath(path);
}
function textOf(value: string | Uint8Array | undefined): string | undefined {
@@ -68,6 +78,17 @@ function bytesOf(value: string | Uint8Array): Uint8Array | null {
return data ? decodeBase64(data[1]!) : null;
}
+/** The skill files the folder's bot.md or team.md names: only those are read, or counted against the folder's caps. */
+function namedSkillFiles(files: ReadonlyArray<readonly [string, string | Uint8Array]>): Set<string> {
+ const manifest = files.find(([path]) => path === MANIFEST_NAMES.bot || path === MANIFEST_NAMES.department)?.[1];
+ if (manifest === undefined) return new Set();
+ try {
+ return new Set(namedFolderFiles(textOf(manifest)!).filter(isSkillFilePath));
+ } catch {
+ return new Set();
+ }
+}
+
/** The folder's files keyed by their path inside it: a single top folder (a browser's folder upload, a saved folder
* picked one level up) is looked through. Unsafe paths and files the reader never opens are dropped. */
export function normalizeShareFolder(files: ShareFolderFiles): ShareFolderFiles {
@@ -84,12 +105,12 @@ export function normalizeShareFolder(files: ShareFolderFiles): ShareFolderFiles
const top = tops.size === 1 ? [...tops][0]! : "";
if (top && safe.some(([path]) => path.includes("/") && atRoot(path.slice(top.length + 1)))) prefix = `${top}/`;
}
+ const inside = safe.flatMap(([path, value]) => (path.startsWith(prefix) && isShareFolderPath(path.slice(prefix.length)) ? [[path.slice(prefix.length), value] as const] : []));
+ const named = namedSkillFiles(inside);
const kept: ShareFolderFiles = {};
let total = 0, count = 0;
- for (const [path, value] of safe) {
- if (!path.startsWith(prefix)) continue;
- const inner = path.slice(prefix.length);
- if (!isShareFolderPath(inner)) continue;
+ for (const [inner, value] of inside) {
+ if (isSkillFilePath(inner) && !named.has(inner)) continue;
total += typeof value === "string" ? utf8Bytes(value) : value.byteLength;
if (++count > SHARE_FOLDER_MAX_FILES) throw refuse("This folder has too many files to be a template.");
if (total > SHARE_FOLDER_MAX_BYTES) throw new PackageFormatError("too_large", "This folder is larger than 4 MB.");
@@ -112,7 +133,18 @@ function frontmatterOf(markdown: string): { metadata: Record<string, unknown> }
return { metadata: metadata as Record<string, unknown> };
}
-function folderSkill(files: ShareFolderFiles, name: unknown) {
+/** The skill's own files the frontmatter names, each required. Their rules are the package gate's (skillFilesSchema). */
+function folderSkillFiles(files: ShareFolderFiles, name: string, listed: unknown): SkillFile[] | undefined {
+ if (listed === undefined) return undefined;
+ if (!Array.isArray(listed) || listed.some((path) => typeof path !== "string")) throw refuse(`skillFiles for ${name} must be a list of paths.`);
+ return (listed as string[]).map((path) => {
+ const text = textOf(files[`skills/${name}/${path}`]);
+ if (text === undefined) throw refuse(`This template names skills/${name}/${path.slice(0, 120)}, but the file is missing.`);
+ return { path, content: text };
+ });
+}
+
+function folderSkill(files: ShareFolderFiles, name: unknown, listed?: unknown) {
if (typeof name !== "string" || !isSkillName(name)) throw refuse(`A skill name in this template is not valid: ${String(name).slice(0, 80)}`);
const text = textOf(files[`skills/${name}/SKILL.md`]);
if (text === undefined) throw refuse(`This template names the skill ${name}, but skills/${name}/SKILL.md is missing.`);
@@ -120,9 +152,11 @@ function folderSkill(files: ShareFolderFiles, name: unknown) {
const parsed = parseSkillMd(text);
if ("error" in parsed) throw refuse(`skills/${name}/SKILL.md: ${parsed.error}`);
if (parsed.name !== name) throw refuse(`skills/${name}/SKILL.md is named ${parsed.name} inside.`);
+ const beside = folderSkillFiles(files, name, listed);
return {
name, description: parsed.description, instructions: text,
...(parsed.license ? { license: parsed.license } : {}), ...(parsed.compatibility ? { compatibility: parsed.compatibility } : {}),
+ ...(beside?.length ? { files: beside } : {}),
};
}
@@ -141,14 +175,15 @@ function folderPicture(files: ShareFolderFiles, value: unknown, crop: unknown) {
}
function packageFromFolder(metadata: Record<string, unknown>, files: ShareFolderFiles): unknown {
- const { botmrr: _version, skills: skillNames, ...definition } = metadata;
+ const { botmrr: _version, skills: skillNames, skillFiles, ...definition } = metadata;
+ const listedFiles = (skillFiles && typeof skillFiles === "object" && !Array.isArray(skillFiles) ? skillFiles : {}) as Record<string, unknown>;
const agents = Array.isArray(definition.agents) ? definition.agents : [];
const named = new Set<unknown>(Array.isArray(skillNames) ? skillNames : []);
for (const agent of agents) {
const skills = (agent as { skills?: unknown })?.skills;
if (Array.isArray(skills)) for (const name of skills) named.add(name);
}
- const entries = [...named].map((name) => folderSkill(files, name));
+ const entries = [...named].map((name) => folderSkill(files, name, typeof name === "string" && Object.hasOwn(listedFiles, name) ? listedFiles[name] : undefined));
const withPictures = agents.map((raw) => {
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return raw;
const agent = raw as Record<string, unknown>;
@@ -190,7 +225,7 @@ export function readShareFolder(input: ShareFolderFiles): ShareFolder {
throw new PackageFormatError("not_a_package", "This folder has no bot.md or team.md.");
}
-/** The paths a manifest names besides itself: its skills and pictures, the only files a remote reader fetches. */
+/** The paths a manifest names besides itself: its skills, their files and its pictures, the only files a reader opens. */
export function namedFolderFiles(manifest: string): string[] {
const { metadata } = frontmatterOf(manifest);
if (metadata.botmrr !== BOTMRR_FOLDER_VERSION) return [];
@@ -203,6 +238,11 @@ export function namedFolderFiles(manifest: string): string[] {
const picture = record.appearance?.avatar;
if (typeof picture === "string" && PICTURE_PATH.test(picture)) names.add(picture);
}
+ const listed = metadata.skillFiles && typeof metadata.skillFiles === "object" && !Array.isArray(metadata.skillFiles) ? metadata.skillFiles as Record<string, unknown> : {};
+ for (const [skill, paths] of Object.entries(listed)) {
+ if (!names.has(`skills/${skill}/SKILL.md`) || !Array.isArray(paths)) continue;
+ for (const path of paths) if (typeof path === "string" && isSkillFilePath(`skills/${skill}/${path}`)) names.add(`skills/${skill}/${path}`);
+ }
return [...names].slice(0, SHARE_FOLDER_MAX_FILES);
}
@@ -252,10 +292,15 @@ export function writeShareFolder(document: PackageDocument, scope: TemplateScope
const { avatar: _picture, ...look } = agent.appearance;
return { ...agent, appearance: { ...look, avatar: path, ...(avatar.crop === "circle" ? {} : { avatarCrop: avatar.crop }) } };
});
- for (const skill of pkg.skills?.entries ?? []) files[`skills/${skill.name}/SKILL.md`] = skill.instructions;
+ const skillFiles: Record<string, string[]> = {};
+ for (const skill of pkg.skills?.entries ?? []) {
+ files[`skills/${skill.name}/SKILL.md`] = skill.instructions;
+ for (const file of skill.files ?? []) files[`skills/${skill.name}/${file.path}`] = file.content;
+ if (skill.files?.length) skillFiles[skill.name] = skill.files.map((file) => file.path);
+ }
const skills = (pkg.skills?.entries ?? []).map((skill) => skill.name);
const { skills: _skills, agents: _agents, ...rest } = pkg;
- const metadata = { botmrr: BOTMRR_FOLDER_VERSION, ...rest, agents, ...(skills.length ? { skills } : {}) };
+ const metadata = { botmrr: BOTMRR_FOLDER_VERSION, ...rest, agents, ...(skills.length ? { skills } : {}), ...(Object.keys(skillFiles).length ? { skillFiles } : {}) };
files[MANIFEST_NAMES[scope]] = `---\n${stringifyYaml(metadata, { lineWidth: 0 }).trimEnd()}\n---\n\n${readableBody(document, scope)}\n`;
return files;
}
diff --git a/shared/skill-files.test.ts b/shared/skill-files.test.ts
new file mode 100644
index 0000000000..d7f16a8896
--- /dev/null
+++ b/shared/skill-files.test.ts
@@ -0,0 +1,104 @@
+import { describe, expect, it } from "vitest";
+
+import { canonicalJson, PackageFormatError, packageSecretFindings, parsePackageDocument, redactPackageSecrets } from "./package-format.ts";
+import { namedFolderFiles, normalizeShareFolder, readShareFolder, writeShareFolder } from "./share-folder.ts";
+import { admitSkillFiles, SKILL_FILE_LIMITS, skillFilePathProblem, skillFileProblem, skillFileText } from "./skill-files.ts";
+
+const skillMd = (name: string) => `---\nname: ${name}\ndescription: ${name} steps.\n---\n\n# ${name}\n\nRun scripts/report.py.\n`;
+const SCRIPT = "import os\ntoken = os.environ['REPORT_TOKEN']\nprint('report')\n";
+const KEY = `sk-ant-api03-${"A".repeat(40)}`;
+
+function withFiles(files: Array<{ path: string; content: string }>) {
+ return {
+ format: "openmaus.package", version: 2,
+ package: {
+ id: "reporter", release: "1.0.0", name: "Reporter", tagline: "Writes reports.", summary: "Writes reports.", category: "Community",
+ author: { name: "MausBot user" }, license: "Unspecified", outcomes: ["Reports."], setupMinutes: 2,
+ requirements: { apps: [], capabilities: [] }, team: { name: "Reporter" },
+ agents: [{ key: "reporter", name: "Reporter", appearance: { color: "blue" }, skills: ["report"] }],
+ skills: { version: 1, entries: [{ name: "report", description: "report steps.", instructions: skillMd("report"), files }] },
+ },
+ };
+}
+
+describe("files beside a skill", () => {
+ it("takes plain relative paths and refuses hidden, generated, deep, odd and key-file names", () => {
+ for (const path of ["run.py", "scripts/report.py", "references/guide.md", "templates/a/b/c/d.txt", "Makefile"]) expect(skillFilePathProblem(path), path).toBeNull();
+ expect(skillFilePathProblem(".env")).toBe("hidden");
+ expect(skillFilePathProblem("scripts/.cache/x")).toBe("hidden");
+ expect(skillFilePathProblem("node_modules/x/index.js")).toBe("generated");
+ expect(skillFilePathProblem("scripts/__pycache__/a.pyc")).toBe("generated");
+ expect(skillFilePathProblem("a/b/c/d/e/f/g.txt")).toBe("deep");
+ for (const path of ["../x", "a//b", "/abs", "a\\b", "con.txt", "x.", "SKILL.md", "docs/skill.md", "a:b"]) expect(skillFilePathProblem(path), path).toBe("name");
+ for (const path of ["prod.env", "env", "env.local", "id_rsa", "server.pem", "api.key", "credentials.json", "secrets.yaml", "app-secrets.json", "tokens.json",
+ "service-account-prod.json", "auth.json", "cert.p12"]) expect(skillFilePathProblem(path), path).toBe("secret_name");
+ });
+
+ it("keeps text only, under the size cap, and refuses a file holding a credential", () => {
+ expect(skillFileText(new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x00]))).toBeNull();
+ expect(skillFileText(new TextEncoder().encode(SCRIPT))).toBe(SCRIPT);
+ expect(skillFileProblem("scripts/report.py", SCRIPT)).toBeNull();
+ expect(skillFileProblem("logo.png", new Uint8Array([0xff, 0xd8, 0xff, 0x00]))).toBe("binary");
+ expect(skillFileProblem("big.txt", "x".repeat(SKILL_FILE_LIMITS.fileBytes + 1))).toBe("large");
+ expect(skillFileProblem("scripts/call.sh", `curl -H "x-api-key: ${KEY}" https://api.example.test`)).toBe("secret");
+ expect(skillFileProblem("deploy.sh", "-----BEGIN OPENSSH PRIVATE KEY-----\nabc\n-----END OPENSSH PRIVATE KEY-----\n")).toBe("secret");
+ });
+
+ it("admits shallow files first within the per-skill file and byte caps", () => {
+ const many = Array.from({ length: SKILL_FILE_LIMITS.files + 3 }, (_, index) => ({ path: `deep/f${String(index).padStart(2, "0")}.txt`, content: "x" }));
+ const admitted = admitSkillFiles([{ path: "z.txt", content: "top" }, ...many, { path: "Z.TXT", content: "dup" }, { path: ".env", content: "A=1" }]);
+ expect(admitted.files[0]).toEqual({ path: "Z.TXT", content: "dup" });
+ expect(admitted.files).toHaveLength(SKILL_FILE_LIMITS.files);
+ expect(admitted.refused).toContainEqual({ path: "z.txt", reason: "duplicate" });
+ expect(admitted.refused).toContainEqual({ path: ".env", reason: "hidden" });
+ expect(admitted.refused.filter((one) => one.reason === "full")).toHaveLength(4);
+ const heavy = Array.from({ length: 5 }, (_, index) => ({ path: `h${index}.txt`, content: "y".repeat(SKILL_FILE_LIMITS.fileBytes) }));
+ expect(admitSkillFiles(heavy).files).toHaveLength(SKILL_FILE_LIMITS.bytes / SKILL_FILE_LIMITS.fileBytes);
+ });
+
+ it("the package gate refuses a skill file that breaks a rule, and never rewrites a script's code as a secret", () => {
+ const ok = parsePackageDocument(withFiles([{ path: "scripts/report.py", content: SCRIPT }]), { trust: "file" });
+ expect(ok.package.skills!.entries[0]!.files).toEqual([{ path: "scripts/report.py", content: SCRIPT }]);
+ expect(packageSecretFindings(ok)).toEqual([]);
+ expect(redactPackageSecrets(ok).document.package.skills!.entries[0]!.files![0]!.content).toBe(SCRIPT);
+ for (const files of [[{ path: ".env", content: "A=1" }], [{ path: "x.pem", content: "x" }], [{ path: "call.sh", content: KEY }], [{ path: "../up.sh", content: "x" }]]) {
+ expect(() => parsePackageDocument(withFiles(files), { trust: "file" }), JSON.stringify(files)).toThrow(PackageFormatError);
+ }
+ });
+
+ it("a folder carries them as skills/<name>/<path>, names them in skillFiles and reads them back", () => {
+ const document = parsePackageDocument(withFiles([{ path: "scripts/report.py", content: SCRIPT }, { path: "references/style.md", content: "# Style\n" }]), { trust: "file" });
+ const files = writeShareFolder(document, "bot");
+ expect(Object.keys(files).sort()).toEqual(["bot.md", "skills/report/SKILL.md", "skills/report/references/style.md", "skills/report/scripts/report.py"]);
+ expect(String(files["bot.md"])).toMatch(/\nskillFiles:\n {2}report:\n/);
+ expect(namedFolderFiles(String(files["bot.md"])).sort()).toEqual(["skills/report/SKILL.md", "skills/report/references/style.md", "skills/report/scripts/report.py"]);
+ const back = readShareFolder({ ...files, "skills/report/scripts/unlisted.sh": "echo hi" });
+ if (back.kind !== "package") throw new Error("not a package");
+ expect(canonicalJson(back.document)).toBe(canonicalJson(document));
+ const { "skills/report/scripts/report.py": _gone, ...without } = files;
+ expect(() => readShareFolder(without)).toThrow(/scripts\/report\.py, but the file is missing/);
+ expect(() => readShareFolder({ ...files, "skills/report/scripts/report.py": `token=${KEY}` })).toThrow(PackageFormatError);
+ expect(() => readShareFolder({ ...files, "skills/report/scripts/report.py": new Uint8Array([0xff, 0xfe, 0x00, 0x01]) })).toThrow(/isn't a text file/);
+ });
+
+ it("files a manifest doesn't name are dropped before the folder's caps count them", () => {
+ const document = parsePackageDocument(withFiles([{ path: "run.sh", content: "echo hi\n" }]), { trust: "file" });
+ const files = writeShareFolder(document, "bot");
+ const clutter = Object.fromEntries(Array.from({ length: 400 }, (_, index) => [`skills/report/cache/f${index}.txt`, "x".repeat(20_000)]));
+ const kept = normalizeShareFolder({ ...files, ...clutter });
+ expect(Object.keys(kept).sort()).toEqual(["bot.md", "skills/report/SKILL.md", "skills/report/run.sh"]);
+ expect(readShareFolder({ ...files, ...clutter }).kind).toBe("package");
+ });
+
+ it("an older reader's folder (no skillFiles) still reads, and one naming a file outside the skill opens nothing", () => {
+ const document = parsePackageDocument(withFiles([{ path: "run.sh", content: "echo hi\n" }]), { trust: "file" });
+ const files = writeShareFolder(document, "bot");
+ const bare = String(files["bot.md"]).replace(/skillFiles:\n {2}report:\n\s*- run\.sh\n/, "");
+ expect(bare).not.toContain("skillFiles");
+ const back = readShareFolder({ ...files, "bot.md": bare });
+ if (back.kind !== "package") throw new Error("not a package");
+ expect(back.document.package.skills!.entries[0]!.files).toBeUndefined();
+ const sneaky = String(files["bot.md"]).replace("- run.sh", "- ../../memory/notes.md");
+ expect(namedFolderFiles(sneaky)).not.toContain("skills/report/../../memory/notes.md");
+ });
+});
diff --git a/shared/skill-files.ts b/shared/skill-files.ts
new file mode 100644
index 0000000000..3c810c498a
--- /dev/null
+++ b/shared/skill-files.ts
@@ -0,0 +1,124 @@
+// The files beside a skill's SKILL.md that travel in a template: its scripts, references and small text assets, as
+// skills/<name>/<path> in the folder and `files` on the package's skill entry. Pure (no node:*): the folder reader, the
+// writer and the package gate apply the same rules, on the server, in the renderer and at the Admin.
+// Security: plain relative paths only (nothing hidden, no generated folders, nothing a skill folder can't hold), text
+// only, size-capped, and never a file named like a credential store or holding a credential's shape. Their text is not
+// passed through redactSecretsInText, which would rewrite ordinary code (`token = os.environ[...]`): a credential in
+// one refuses that file instead.
+import { z } from "zod";
+
+import { holdsCredential, scrubHeldSecrets } from "./redact.ts";
+
+/** Per skill: how many files beside SKILL.md, the bytes of each and of all together, and how deep a path may go. */
+export const SKILL_FILE_LIMITS = { files: 30, fileBytes: 128 * 1024, bytes: 512 * 1024, depth: 6, segmentBytes: 120 } as const;
+
+export type SkillFileRefusal = "name" | "hidden" | "generated" | "deep" | "secret_name" | "binary" | "large" | "secret" | "duplicate" | "full";
+
+export interface SkillFile {
+ /** Relative to the skill's folder, "/"-separated. */
+ path: string;
+ content: string;
+}
+
+const GENERATED = new Set(["node_modules", "__pycache__", "venv"]);
+const WINDOWS_DEVICE = /^(?:con|prn|aux|nul|com[0-9¹²³]|lpt[0-9¹²³])(?:\..*)?$/i;
+const SECRET_NAME = /^(?:.+\.(?:env|pem|key|p12|pfx|keystore|jks|kdbx|ppk|gpg|asc|crt|cer|der)|env(?:\..*)?|id_(?:rsa|dsa|ecdsa|ed25519)(?:\.pub)?|credentials?(?:\..*)?|secrets?(?:\..*)?|.+[-_.]secrets?\.[a-z]+|tokens?\.(?:json|txt|ya?ml)|auth\.json|service[-_]?account.*\.json|netrc|npmrc|pypirc)$/i;
+const encoder = new TextEncoder();
+const bytesOf = (text: string) => encoder.encode(text).length;
+const unsafeCharacter = (char: string) => char < " " || char === "\u007f" || '<>:"|?*\\'.includes(char);
+
+/** Why `path` can't be a file beside SKILL.md, by its name alone; null when it can. At least as strict as the rule a
+ * skill folder is stored by, so whatever passes here is stored whole when it is added. */
+export function skillFilePathProblem(path: string): SkillFileRefusal | null {
+ if (!path || path.length > 300) return "name";
+ const parts = path.split("/");
+ for (const part of parts) {
+ if (!part || part === "." || part === ".." || [...part].some(unsafeCharacter) || /[. ]$/.test(part) ||
+ WINDOWS_DEVICE.test(part) || bytesOf(part) > SKILL_FILE_LIMITS.segmentBytes) return "name";
+ if (part.startsWith(".")) return "hidden";
+ if (GENERATED.has(part.toLowerCase())) return "generated";
+ if (part.toLowerCase() === "skill.md") return "name";
+ }
+ if (parts.length > SKILL_FILE_LIMITS.depth) return "deep";
+ return SECRET_NAME.test(parts.at(-1)!) ? "secret_name" : null;
+}
+
+const strictText = new TextDecoder("utf-8", { fatal: true });
+
+/** The file's text, or null for one that is not UTF-8 text (a picture, an archive, a compiled file). */
+export function skillFileText(content: string | Uint8Array): string | null {
+ let text: string;
+ if (typeof content === "string") text = content;
+ else {
+ try {
+ text = strictText.decode(content);
+ } catch {
+ return null;
+ }
+ }
+ return text.includes("\u0000") || text.includes("�") ? null : text;
+}
+
+/** Why one file can't travel; null when it can. */
+export function skillFileProblem(path: string, content: string | Uint8Array): SkillFileRefusal | null {
+ const named = skillFilePathProblem(path);
+ if (named) return named;
+ const text = skillFileText(content);
+ if (text === null) return "binary";
+ if (bytesOf(text) > SKILL_FILE_LIMITS.fileBytes) return "large";
+ return holdsCredential(text) || scrubHeldSecrets(text) !== text ? "secret" : null;
+}
+
+const WORDS: Record<SkillFileRefusal, string> = {
+ name: "has a name a skill folder can't hold",
+ hidden: "is hidden",
+ generated: "is in a generated folder",
+ deep: "is too deep in folders",
+ secret_name: "is named like a key or password file",
+ binary: "isn't a text file",
+ large: `is larger than ${SKILL_FILE_LIMITS.fileBytes / 1024} KB`,
+ secret: "looks like it holds a key or password",
+ duplicate: "has the same name as another file",
+ full: "is past the skill's file limit",
+};
+export const skillFileRefusalWords = (reason: SkillFileRefusal): string => WORDS[reason];
+
+/** What of a skill's files can travel, shallow files first, within SKILL_FILE_LIMITS; the rest with why. */
+export function admitSkillFiles(files: ReadonlyArray<{ path: string; content: string | Uint8Array }>): {
+ files: SkillFile[];
+ refused: Array<{ path: string; reason: SkillFileRefusal }>;
+} {
+ const ordered = [...files].sort((a, b) => a.path.split("/").length - b.path.split("/").length || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
+ const kept: SkillFile[] = [];
+ const refused: Array<{ path: string; reason: SkillFileRefusal }> = [];
+ const held = new Set<string>();
+ let total = 0;
+ for (const file of ordered) {
+ const problem = skillFileProblem(file.path, file.content);
+ if (problem) {
+ refused.push({ path: file.path, reason: problem });
+ continue;
+ }
+ const text = skillFileText(file.content)!;
+ const size = bytesOf(text);
+ const key = file.path.normalize("NFC").toLowerCase();
+ if (held.has(key)) refused.push({ path: file.path, reason: "duplicate" });
+ else if (kept.length >= SKILL_FILE_LIMITS.files || total + size > SKILL_FILE_LIMITS.bytes) refused.push({ path: file.path, reason: "full" });
+ else {
+ held.add(key);
+ kept.push({ path: file.path, content: text });
+ total += size;
+ }
+ }
+ return { files: kept, refused };
+}
+
+/** A skill entry's `files` in the package gate: every file must pass, as admitSkillFiles would keep it. */
+export const skillFilesSchema = z
+ .array(z.object({ path: z.string({ error: "must be text" }), content: z.string({ error: "must be text" }) }))
+ .max(SKILL_FILE_LIMITS.files, { message: `must have at most ${SKILL_FILE_LIMITS.files} files` })
+ .superRefine((files, ctx) => {
+ const { refused } = admitSkillFiles(files);
+ for (const { path, reason } of refused) ctx.addIssue({ code: "custom", message: `${path.slice(0, 120)} ${skillFileRefusalWords(reason)}` });
+ })
+ .optional();
diff --git a/src/components/ImportDialog.test.ts b/src/components/ImportDialog.test.ts
index ad77db6c89..409663f2ea 100644
--- a/src/components/ImportDialog.test.ts
+++ b/src/components/ImportDialog.test.ts
@@ -7,11 +7,14 @@ import type { TemplateCard, TemplateDetails } from "../../shared/share-card";
const dispatch = vi.fn();
const api = vi.fn(async (_path: string, _init?: RequestInit): Promise<unknown> => ({}));
+const place: { state: { config?: { team?: { id: string; name: string } } }; admin: boolean | null } = { state: {}, admin: null };
vi.mock("@/state/store", async () => {
const { createContext } = await import("react");
- return { StoreContext: createContext(null), useStore: () => ({ state: {}, dispatch }), api: (path: string, init?: RequestInit) => api(path, init) };
+ return { StoreContext: createContext(null), useStore: () => ({ state: place.state, dispatch }), api: (path: string, init?: RequestInit) => api(path, init) };
});
-vi.mock("@/lib/app-links", () => ({ openExternalLink: async () => {} }));
+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => place.admin }));
+const openLink = vi.fn(async (_url: string) => {});
+vi.mock("@/lib/app-links", () => ({ openExternalLink: (url: string) => openLink(url) }));
const { ImportDialog } = await import("./ImportDialog");
const { ShareDepartmentDialog } = await import("./ShareDepartmentDialog");
@@ -34,7 +37,8 @@ const typeInto = (input: HTMLInputElement, value: string) => {
input.dispatchEvent(new Event("input", { bubbles: true }));
};
-afterEach(() => { vi.clearAllMocks(); delete (window as { ogb?: unknown }).ogb; document.body.innerHTML = ""; });
+afterEach(() => { vi.clearAllMocks(); delete (window as { ogb?: unknown }).ogb; document.body.innerHTML = ""; place.state = {}; place.admin = null; });
+const onTeam = () => { place.state = { config: { team: { id: "t1", name: "Acme" } } }; place.admin = true; };
describe("Import", () => {
it("previews a pasted GitHub link, then adds it and says how many apps to connect", async () => {
@@ -68,6 +72,42 @@ describe("Import", () => {
} finally { view.unmount(); }
});
+ it("lists the team's templates for its admins: name, kind, who added it; opens one and removes one", async () => {
+ onTeam();
+ const listed = [
+ { slug: "quill", name: "Quill", scope: "bot", tagline: "Writes outreach.", addedBy: "Olive", addedAt: Date.now() - 2 * 3_600_000 },
+ { slug: "sales-desk", name: "Sales desk", scope: "department", tagline: "", addedAt: Date.now() - 30_000 },
+ ];
+ api.mockImplementation(async (path: string) => path === "/api/share/library" ? { team: "Acme", templates: listed }
+ : path.startsWith("/api/share/library/") ? { ok: true } : { details });
+ const view = mount(createElement(ImportDialog, { onClose: vi.fn(), onAdded: vi.fn() }));
+ try {
+ await vi.waitFor(() => expect(document.body.textContent).toContain("From Acme's templates"));
+ const row = document.querySelector("[data-team-template=quill]")!;
+ expect(row.textContent).toContain("Quill");
+ expect(row.textContent).toContain("Bot");
+ expect(row.textContent).toContain("Added by Olive · 2 hr ago");
+ expect(document.querySelector("[data-team-template=sales-desk]")!.textContent).toContain("Department");
+ document.querySelector<HTMLButtonElement>("[aria-label='Remove Sales desk']")!.click();
+ await vi.waitFor(() => expect(document.querySelector("[data-team-template=sales-desk]")).toBeNull());
+ expect(api).toHaveBeenCalledWith("/api/share/library/sales-desk", { method: "DELETE" });
+ (row.querySelector("button") as HTMLButtonElement).click();
+ await vi.waitFor(() => expect(api).toHaveBeenCalledWith("/api/share/import?preview=1", { method: "POST", body: JSON.stringify({ library: "quill" }) }));
+ await vi.waitFor(() => expect(document.body.textContent).toContain("Apps to connect"));
+ } finally { view.unmount(); }
+ });
+
+ it("shows no team list off a Team Cloud or to someone who isn't its owner or an admin", async () => {
+ place.state = { config: { team: { id: "t1", name: "Acme" } } };
+ place.admin = false;
+ const view = mount(createElement(ImportDialog, { onClose: vi.fn(), onAdded: vi.fn() }));
+ try {
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(document.querySelector("[data-team-templates]")).toBeNull();
+ expect(api).not.toHaveBeenCalledWith("/api/share/library", undefined);
+ } finally { view.unmount(); }
+ });
+
it("reads a folder the desktop app picks by its path", async () => {
(window as { ogb?: unknown }).ogb = { pickFolder: async () => "/Users/sam/quill" };
api.mockResolvedValue({ details });
@@ -101,6 +141,80 @@ describe("a department's Share", () => {
} finally { view.unmount(); }
});
+ it("adds it to the team's templates for an admin, and says when it replaced one", async () => {
+ onTeam();
+ let replaced = false;
+ api.mockImplementation(async (path: string) => {
+ if (path === "/api/share/export") return card;
+ const answer = { template: { slug: "sales-desk", name: "Sales desk", scope: "department", tagline: "", addedAt: 1 }, replaced };
+ replaced = true;
+ return answer;
+ });
+ const view = mount(createElement(ShareDepartmentDialog, { department: "Sales desk", onClose: vi.fn() }));
+ try {
+ await vi.waitFor(() => expect(button("Add to Acme's templates")).toBeTruthy());
+ button("Add to Acme's templates")!.click();
+ await vi.waitFor(() => expect(document.body.textContent).toContain("Added to Acme's templates"));
+ expect(api).toHaveBeenCalledWith("/api/share/tpl2/library", { method: "POST", body: "{}" });
+ button("Add to Acme's templates")!.click();
+ await vi.waitFor(() => expect(document.body.textContent).toContain("Replaced in Acme's templates. The previous one is kept."));
+ } finally { view.unmount(); }
+ });
+
+ it("publishes to the person's own repository as a pull request, or says to connect GitHub in Apps first", async () => {
+ let connected = false;
+ api.mockImplementation(async (path: string) => path === "/api/share/export" ? card
+ : path === "/api/share/github" ? (connected ? { connected: true } : { connected: false, reason: "not_connected", error: "Connect GitHub in Apps first." })
+ : { kind: "pull_request", url: "https://github.com/acme/playbooks/pull/3", link: "https://github.com/acme/playbooks/tree/mausbot-sales-desk-abc123/sales-desk", branch: "mausbot-sales-desk-abc123" });
+ const view = mount(createElement(ShareDepartmentDialog, { department: "Sales desk", onClose: vi.fn() }));
+ try {
+ await vi.waitFor(() => expect(button("Your GitHub repo…")).toBeTruthy());
+ expect(button("Add to Acme's templates")).toBeUndefined();
+ button("Your GitHub repo…")!.click();
+ await vi.waitFor(() => expect(document.body.textContent).toContain("Connect GitHub in Apps first."));
+ button("Open Apps")!.click();
+ expect(dispatch).toHaveBeenCalledWith({ type: "togglePlugins", open: true });
+ await vi.waitFor(() => expect(document.querySelector("[data-template-repo=tpl2]")).toBeNull());
+ connected = true;
+ button("Your GitHub repo…")!.click();
+ await vi.waitFor(() => expect(document.querySelector("[data-template-repo] form")).toBeTruthy());
+ const [repo, folder] = [...document.querySelectorAll<HTMLInputElement>("[data-template-repo] input:not([type=checkbox])")];
+ typeInto(repo!, "acme/playbooks");
+ typeInto(folder!, "templates");
+ await vi.waitFor(() => expect(button("Open pull request")!.disabled).toBe(false));
+ button("Open pull request")!.click();
+ await vi.waitFor(() => expect(document.body.textContent).toContain("Pull request opened from the branch mausbot-sales-desk-abc123."));
+ expect(api).toHaveBeenCalledWith("/api/share/tpl2/publish-repo", { method: "POST", body: JSON.stringify({ repo: "acme/playbooks", folder: "templates", direct: false }) });
+ [...document.querySelectorAll("button")].find((each) => each.textContent?.includes("View pull request") && each.closest("footer"))!.click();
+ expect(openLink).toHaveBeenCalledWith("https://github.com/acme/playbooks/pull/3");
+ } finally { view.unmount(); }
+ });
+
+ it("shows the server's own sentence when GitHub is refused here, with no Open Apps", async () => {
+ api.mockImplementation(async (path: string) => path === "/api/share/export" ? card
+ : { connected: false, reason: "refused", error: "Acme's rules turn GitHub off." });
+ const view = mount(createElement(ShareDepartmentDialog, { department: "Sales desk", onClose: vi.fn() }));
+ try {
+ await vi.waitFor(() => expect(button("Your GitHub repo…")).toBeTruthy());
+ button("Your GitHub repo…")!.click();
+ await vi.waitFor(() => expect(document.body.textContent).toContain("Acme's rules turn GitHub off."));
+ expect(button("Open Apps")).toBeUndefined();
+ expect(document.body.textContent).not.toContain("Connect GitHub in Apps first.");
+ } finally { view.unmount(); }
+ });
+
+ it("offers no repository or team library to a team member", async () => {
+ place.state = { config: { team: { id: "t1", name: "Acme" } } };
+ place.admin = false;
+ api.mockResolvedValue(card);
+ const view = mount(createElement(ShareDepartmentDialog, { department: "Sales desk", onClose: vi.fn() }));
+ try {
+ await vi.waitFor(() => expect(button("Publish to community")).toBeTruthy());
+ expect(button("Your GitHub repo…")).toBeUndefined();
+ expect(button("Add to Acme's templates")).toBeUndefined();
+ } finally { view.unmount(); }
+ });
+
it("says why it couldn't be made, with Try again", async () => {
api.mockRejectedValueOnce(new Error("This department has no bots to share.")).mockResolvedValueOnce(card);
const view = mount(createElement(ShareDepartmentDialog, { department: "Empty", onClose: vi.fn() }));
diff --git a/src/components/ImportDialog.tsx b/src/components/ImportDialog.tsx
index 661327dfcc..8233e0cc7e 100644
--- a/src/components/ImportDialog.tsx
+++ b/src/components/ImportDialog.tsx
@@ -1,11 +1,64 @@
import { useEffect, useId, useRef, useState } from "react";
-import { FolderOpen, Loader2 } from "lucide-react";
+import { FolderOpen, Loader2, Trash2 } from "lucide-react";
-import type { TemplateDetails } from "../../shared/share-card";
+import type { TeamTemplate, TemplateDetails } from "../../shared/share-card";
import { t } from "@/lib/i18n";
-import { addImport, addedLine, folderFiles, previewImport, type ImportSource } from "@/lib/template-share";
+import { relativeTime } from "@/lib/memory";
+import { addImport, addedLine, folderFiles, previewImport, removeTeamTemplate, teamTemplates, type ImportSource } from "@/lib/template-share";
import { useStore } from "@/state/store";
-import { TemplateDetailsBody, TemplateModal } from "./TemplateCard";
+import { TemplateDetailsBody, TemplateModal, useTeamTemplatesOwner } from "./TemplateCard";
+
+/** "From Acme's templates": each one's name, kind, who added it and when; opening one previews it, and its owner or an
+ * admin can remove it. */
+function TeamTemplateList({ team, onOpen, disabled }: { team: string; onOpen: (slug: string) => void; disabled: boolean }) {
+ const [templates, setTemplates] = useState<TeamTemplate[] | null>(null);
+ const [error, setError] = useState("");
+ const [removing, setRemoving] = useState<string | null>(null);
+ const headingId = useId();
+ useEffect(() => {
+ let live = true;
+ teamTemplates().then((answer) => { if (live) setTemplates(answer.templates); }, () => { if (live) setTemplates([]); });
+ return () => { live = false; };
+ }, []);
+ const remove = async (slug: string) => {
+ setRemoving(slug);
+ setError("");
+ try {
+ await removeTeamTemplate(slug);
+ setTemplates((current) => (current ?? []).filter((one) => one.slug !== slug));
+ } catch (cause) {
+ setError(cause instanceof Error && cause.message ? cause.message : t("templateImport.failed"));
+ } finally {
+ setRemoving(null);
+ }
+ };
+ if (!templates?.length) return null;
+ return (
+ <section aria-labelledby={headingId} data-team-templates className="mt-4">
+ <h3 id={headingId} dir="auto" className="text-[13px] font-medium text-ink">{t("templateImport.fromTeam", { team })}</h3>
+ <ul className="mt-1.5 flex flex-col">
+ {templates.map((one) => (
+ <li key={one.slug} data-team-template={one.slug} className="group flex min-w-0 items-center gap-1 rounded-md hover:bg-ink/[0.06]">
+ <button type="button" onClick={() => onOpen(one.slug)} disabled={disabled || removing !== null} className="min-w-0 flex-1 px-1.5 py-1.5 text-start">
+ <span className="flex min-w-0 items-center gap-2">
+ <span dir="auto" className="min-w-0 truncate text-[13px] text-ink">{one.name}</span>
+ <span className="ui-chip shrink-0 bg-ink/[0.06] text-ink-secondary">{t(one.scope === "bot" ? "templateImport.kindBot" : "templateImport.kindDepartment")}</span>
+ </span>
+ <span dir="auto" className="block truncate text-[12px] text-ink-tertiary">
+ {one.addedBy ? t("templateImport.addedBy", { name: one.addedBy, when: relativeTime(one.addedAt) }) : t("templateImport.addedAt", { when: relativeTime(one.addedAt) })}
+ </span>
+ </button>
+ <button type="button" onClick={() => void remove(one.slug)} disabled={disabled || removing !== null} aria-label={t("templateImport.remove", { name: one.name })} title={t("templateImport.remove", { name: one.name })}
+ className="flex size-7 shrink-0 items-center justify-center rounded-md text-ink-tertiary hover:text-ink">
+ {removing === one.slug ? <Loader2 size={14} aria-hidden="true" className="animate-spin motion-reduce:animate-none" /> : <Trash2 size={14} aria-hidden="true" />}
+ </button>
+ </li>
+ ))}
+ </ul>
+ {error && <p role="alert" dir="auto" className="mt-1.5 text-[12px] text-danger">{error}</p>}
+ </section>
+ );
+}
/** Import: paste a GitHub link or choose a folder, see what it brings, then Add. `onAdded` gets the line to show. */
export function ImportDialog({ initialUrl, onClose, onAdded }: { initialUrl?: string; onClose: () => void; onAdded: (line: string) => void }) {
@@ -19,6 +72,7 @@ export function ImportDialog({ initialUrl, onClose, onAdded }: { initialUrl?: st
const titleId = useId();
const fieldId = useId();
const pick = window.ogb?.remoteClient?.active ? undefined : window.ogb?.pickFolder;
+ const team = useTeamTemplatesOwner();
const preview = async (next: ImportSource) => {
setBusy("preview");
@@ -91,6 +145,7 @@ export function ImportDialog({ initialUrl, onClose, onAdded }: { initialUrl?: st
void folderFiles(files).then((read) => preview({ files: read }), (cause: unknown) => setError(cause instanceof Error ? cause.message : t("templateImport.failed")));
event.currentTarget.value = "";
}} />
+ {team && <TeamTemplateList team={team} disabled={busy !== null} onOpen={(slug) => void preview({ library: slug })} />}
</form>
)}
{error && <p role="alert" dir="auto" className="mt-3 text-[13px] text-danger">{error}</p>}
diff --git a/src/components/ShareDepartmentDialog.tsx b/src/components/ShareDepartmentDialog.tsx
index 250fd528f2..7aed86167f 100644
--- a/src/components/ShareDepartmentDialog.tsx
+++ b/src/components/ShareDepartmentDialog.tsx
@@ -4,10 +4,13 @@ import { Loader2 } from "lucide-react";
import type { TemplateCard } from "../../shared/share-card";
import { t } from "@/lib/i18n";
import { exportDepartment } from "@/lib/template-share";
-import { TemplateButtons, TemplateCardBody, TemplateModal, TemplateNotes, useTemplateActions } from "./TemplateCard";
+import { TemplateButtons, TemplateCardBody, TemplateModal, TemplateNotes, TemplateRepoPublishDialog, useRepoPublishOffered, useTeamTemplatesOwner, useTemplateActions } from "./TemplateCard";
function Shared({ card }: { card: TemplateCard }) {
const actions = useTemplateActions(card);
+ const team = useTeamTemplatesOwner();
+ const repoOffered = useRepoPublishOffered();
+ const [repo, setRepo] = useState(false);
return <>
<div className="rounded-xl border border-hairline/40 px-3 py-2.5">
<TemplateCardBody card={actions.card} />
@@ -15,12 +18,19 @@ function Shared({ card }: { card: TemplateCard }) {
{!actions.card.fallback && actions.card.status !== "published" && <p className="mt-2 text-[12px] text-ink-secondary">{t("template.publicNote")}</p>}
<TemplateButtons actions={actions} primary={t("template.publishToCommunity")}
view={{ label: t("template.viewPullRequest"), url: actions.card.prUrl ?? actions.card.link }}
- extra={actions.card.fallback || actions.card.status === "gone" ? null : (
- <button type="button" data-template-save onClick={() => void actions.save()} disabled={actions.busy !== null} className="ui-button ui-button-md">
+ extra={actions.card.status === "gone" ? null : <>
+ {repoOffered && <button type="button" data-template-repo onClick={() => setRepo(true)} disabled={actions.busy !== null} className="ui-button ui-button-md">
+ {t("template.publishToRepo")}
+ </button>}
+ {team && <button type="button" data-template-team onClick={() => void actions.addToTeam(team)} disabled={actions.busy !== null} className="ui-button ui-button-md">
+ {actions.busy === "team" && <Loader2 size={14} aria-hidden="true" className="animate-spin motion-reduce:animate-none" />}{t("template.addToTeam", { team })}
+ </button>}
+ {!actions.card.fallback && <button type="button" data-template-save onClick={() => void actions.save()} disabled={actions.busy !== null} className="ui-button ui-button-md">
{t("template.saveFolder")}
- </button>
- )} />
+ </button>}
+ </>} />
<TemplateNotes actions={actions} />
+ {repo && <TemplateRepoPublishDialog card={actions.card} onClose={() => setRepo(false)} />}
</>;
}
diff --git a/src/components/TemplateCard.test.ts b/src/components/TemplateCard.test.ts
index d5662f44cc..3e6562b336 100644
--- a/src/components/TemplateCard.test.ts
+++ b/src/components/TemplateCard.test.ts
@@ -9,10 +9,12 @@ import type { Message } from "@/state/store";
const dispatch = vi.fn();
const api = vi.fn(async (_path: string, _init?: RequestInit): Promise<unknown> => ({ ok: true }));
+const place: { state: { config?: { team?: { id: string; name: string } } }; admin: boolean | null } = { state: {}, admin: null };
vi.mock("@/state/store", async () => {
const { createContext } = await import("react");
- return { StoreContext: createContext(null), useStore: () => ({ state: {}, dispatch }), api: (path: string, init?: RequestInit) => api(path, init) };
+ return { StoreContext: createContext(null), useStore: () => ({ state: place.state, dispatch }), api: (path: string, init?: RequestInit) => api(path, init) };
});
+vi.mock("@/lib/use-owner-or-admin", () => ({ useOwnerOrAdmin: () => place.admin }));
const openExternalLink = vi.fn(async (_url: string) => {});
vi.mock("@/lib/app-links", () => ({ openExternalLink: (url: string) => openExternalLink(url) }));
const { TemplateChatCard, TemplateDetailsBody } = await import("./TemplateCard");
@@ -35,7 +37,7 @@ function render(card: TemplateCard) {
}
const button = (container: HTMLElement, label: string) => [...container.querySelectorAll("button")].find((each) => each.textContent?.trim() === label);
-afterEach(() => { vi.clearAllMocks(); delete (window as { ogb?: unknown }).ogb; });
+afterEach(() => { vi.clearAllMocks(); delete (window as { ogb?: unknown }).ogb; place.state = {}; place.admin = null; document.body.innerHTML = ""; });
describe("a template's chat card", () => {
it("shows a draft with its counts, Publish and Details, and says nothing private travels", () => {
@@ -122,6 +124,40 @@ describe("a template's chat card", () => {
});
});
+describe("a template's chat card on a Team Cloud", () => {
+ const menuItems = async (container: HTMLElement) => {
+ container.querySelector<HTMLElement>("[aria-label='More']")!.click();
+ await vi.waitFor(() => expect(document.querySelectorAll("[role=menuitem]").length).toBeGreaterThan(0));
+ return [...document.querySelectorAll<HTMLElement>("[role=menuitem]")];
+ };
+
+ it("offers Add to the team's templates and Your GitHub repo… to its owner or an admin", async () => {
+ place.state = { config: { team: { id: "t1", name: "Acme" } } };
+ place.admin = true;
+ api.mockResolvedValueOnce({ template: { slug: "quill", name: "Quill", scope: "bot", tagline: "", addedAt: 1 }, replaced: false });
+ const { container, unmount } = render(draft);
+ try {
+ const items = await menuItems(container);
+ expect(items.map((item) => item.textContent?.trim())).toEqual(expect.arrayContaining(["Add to Acme's templates", "Your GitHub repo…"]));
+ items.find((item) => item.textContent?.trim() === "Add to Acme's templates")!.click();
+ await vi.waitFor(() => expect(container.textContent).toContain("Added to Acme's templates"));
+ expect(api).toHaveBeenCalledWith("/api/share/tpl1/library", { method: "POST", body: "{}" });
+ } finally { unmount(); }
+ });
+
+ it("leaves the team's templates and its repositories out for a member", async () => {
+ place.state = { config: { team: { id: "t1", name: "Acme" } } };
+ place.admin = false;
+ const { container, unmount } = render(draft);
+ try {
+ const items = (await menuItems(container)).map((item) => item.textContent?.trim());
+ expect(items).toContain("Delete");
+ expect(items).not.toContain("Your GitHub repo…");
+ expect(items).not.toContain("Add to Acme's templates");
+ } finally { unmount(); }
+ });
+});
+
describe("a template's details", () => {
const details: TemplateDetails = {
scope: "department", name: "Sales desk", tagline: "Leads in, replies out.", summary: "A small sales team.",
diff --git a/src/components/TemplateCard.tsx b/src/components/TemplateCard.tsx
index 7c4614f9aa..f6773ee61b 100644
--- a/src/components/TemplateCard.tsx
+++ b/src/components/TemplateCard.tsx
@@ -2,16 +2,17 @@
// (the Details sheet, also Import's preview), and the card's actions.
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";
-import { ArrowUpRight, Check, ChevronDown, Copy, FolderDown, Github, Loader2, MoreHorizontal, RefreshCw, Trash2, Upload } from "lucide-react";
+import { ArrowUpRight, Check, ChevronDown, Copy, FolderDown, Github, Library, Loader2, MoreHorizontal, RefreshCw, Trash2, Upload } from "lucide-react";
-import { COMMUNITY_UPLOAD_URL, TEMPLATE_UPDATE_MESSAGE, type TemplateAvatar, type TemplateCard, type TemplateDetails } from "../../shared/share-card";
+import { COMMUNITY_UPLOAD_URL, TEMPLATE_UPDATE_MESSAGE, type TemplateAvatar, type TemplateCard, type TemplateDetails, type TemplateRepoPublish } from "../../shared/share-card";
import { botBodyId } from "../../shared/bot-body";
import { MAUS_COLOR_NAMES, type MausColor } from "../../shared/wire";
import { openExternalLink } from "@/lib/app-links";
import { cn } from "@/lib/cn";
import { useCopyFeedback } from "@/lib/copy-text";
import { t } from "@/lib/i18n";
-import { askBot, countsLine, deleteTemplate, publishTemplate, saveTemplateFolder, templateDetails } from "@/lib/template-share";
+import { addToTeamTemplates, askBot, countsLine, deleteTemplate, githubConnection, publishTemplate, publishToRepo, saveTemplateFolder, templateDetails } from "@/lib/template-share";
+import { useOwnerOrAdmin } from "@/lib/use-owner-or-admin";
import { useModalDialog } from "@/hooks/use-modal-dialog";
import { useStore, type Message } from "@/state/store";
import { ASK_CHIP, ASK_CHIP_IDLE, ASK_PRIMARY_BUTTON } from "./AskCard";
@@ -73,9 +74,10 @@ export function TemplateCardBody({ card }: { card: TemplateCard }) {
/** What the card's buttons do. The card shown is the latest the server answered, until the message brings a newer one. */
export function useTemplateActions(initial: TemplateCard) {
const [card, setCard] = useState(initial);
- const [busy, setBusy] = useState<"publish" | "save" | "delete" | null>(null);
+ const [busy, setBusy] = useState<"publish" | "save" | "delete" | "team" | null>(null);
const [error, setError] = useState("");
const [saved, setSaved] = useState<string | null>(null);
+ const [teamNote, setTeamNote] = useState<string | null>(null);
useEffect(() => setCard(initial), [initial]);
const run = async (kind: NonNullable<typeof busy>, work: () => Promise<void>) => {
if (busy) return;
@@ -90,7 +92,13 @@ export function useTemplateActions(initial: TemplateCard) {
}
};
return {
- card, busy, error, saved,
+ card, busy, error, saved, teamNote,
+ /** Adds it to the Team Cloud's own templates, replacing one of the same name there. */
+ addToTeam: (team: string) => run("team", async () => {
+ setTeamNote(null);
+ const added = await addToTeamTemplates(card.id);
+ setTeamNote(t(added.replaced ? "template.replacedInTeam" : "template.addedToTeam", { team }));
+ }),
publish: () => run("publish", async () => {
setCard((current) => ({ ...current, status: "publishing", error: undefined }));
try {
@@ -161,23 +169,44 @@ export function TemplateButtons({ actions, primary, view, extra }: {
/** One line under the buttons: why Publish isn't offered, the publish error, the last action's error, or where the folder went. */
export function TemplateNotes({ actions }: { actions: TemplateActions }) {
- const { card, error, saved } = actions;
+ const { card, error, saved, teamNote } = actions;
return <>
{card.fallback && <p className="mt-1.5 text-[12px] text-ink-secondary">{t(card.fallback === "sign_in" ? "template.signInToPublish" : "template.publishUnavailable")}</p>}
{card.status === "failed" && card.error && <p role="alert" dir="auto" className="mt-1.5 text-[12px] text-danger">{card.error}</p>}
{error && <p role="alert" dir="auto" className="mt-1.5 text-[12px] text-danger">{error}</p>}
{saved && <p role="status" dir="auto" className="mt-1.5 truncate text-[12px] text-ink-secondary" title={saved}>{t("template.savedTo", { path: saved })}</p>}
+ {teamNote && <p role="status" dir="auto" className="mt-1.5 text-[12px] text-ink-secondary">{teamNote}</p>}
</>;
}
+/** On a Team Cloud, its name when the person is its owner or an admin, who add templates to its library; else null. */
+export function useTeamTemplatesOwner(): string | null {
+ const { state } = useStore();
+ const admin = useOwnerOrAdmin();
+ const team = state.config?.team?.name;
+ return team && admin === true ? team : null;
+}
+
+/** Publishing to one's own repository goes through Share's routes, which a Team Cloud keeps for its owner and admins. */
+export function useRepoPublishOffered(): boolean {
+ const { state } = useStore();
+ const admin = useOwnerOrAdmin();
+ return !state.config?.team || admin === true;
+}
+
/** The template card a bot posts in its chat. `botId` and `threadId` are this chat's, for Update; a group chat leaves them out. */
export function TemplateChatCard({ message, botId, threadId }: { message: Message; botId?: string; threadId?: string }) {
const { dispatch } = useStore();
const actions = useTemplateActions(message.template!);
const [details, setDetails] = useState(false);
+ const [repo, setRepo] = useState(false);
+ const team = useTeamTemplatesOwner();
+ const repoOffered = useRepoPublishOffered();
const { card } = actions;
const overflow: SidebarMenuItem[] = card.status === "gone" ? [] : [
...(botId ? [{ key: "update", label: t("template.update"), icon: <RefreshCw size={16} />, onSelect: () => askBot(dispatch, botId, threadId, TEMPLATE_UPDATE_MESSAGE) }] : []),
+ ...(team ? [{ key: "team", label: t("template.addToTeam", { team }), icon: <Library size={16} />, onSelect: () => void actions.addToTeam(team) }] : []),
+ ...(repoOffered ? [{ key: "repo", label: t("template.publishToRepo"), icon: <Github size={16} />, onSelect: () => setRepo(true) }] : []),
...(card.fallback ? [] : [{ key: "save", label: t("template.saveFolder"), icon: <FolderDown size={16} />, onSelect: () => void actions.save() }]),
{ key: "delete", label: t("template.delete"), icon: <Trash2 size={16} />, separatorBefore: true, onSelect: () => void actions.remove() },
];
@@ -193,6 +222,7 @@ export function TemplateChatCard({ message, botId, threadId }: { message: Messag
</>} />
<TemplateNotes actions={actions} />
{details && <TemplateDetailsSheet id={card.id} name={card.name} onClose={() => setDetails(false)} />}
+ {repo && <TemplateRepoPublishDialog card={card} onClose={() => setRepo(false)} />}
</div>
);
}
@@ -300,3 +330,100 @@ export function TemplateDetailsSheet({ id, name, onClose }: { id: string; name:
</TemplateModal>
);
}
+
+/** Share's second GitHub target: the person's own repository, through the GitHub connection in Apps. A pull request from
+ * a new branch, or one commit on the default branch when they tick it. */
+
+/** `missing`: connect GitHub in Apps; `refused`: the server's own sentence (the team's Rules, Apps unreachable, no access). */
+type Connection = { state: "checking" } | { state: "connected" } | { state: "missing" } | { state: "refused"; error: string };
+
+const repoField = "h-8 w-full min-w-0 rounded-lg border border-hairline bg-inset px-2.5 text-[13px] text-ink focus:border-focus focus:outline-none";
+const repoSpinner = <Loader2 size={14} aria-hidden="true" className="animate-spin motion-reduce:animate-none" />;
+
+export function TemplateRepoPublishDialog({ card, onClose }: { card: Pick<TemplateCard, "id" | "name">; onClose: () => void }) {
+ const { dispatch } = useStore();
+ const [connection, setConnection] = useState<Connection>({ state: "checking" });
+ const [repo, setRepo] = useState("");
+ const [folder, setFolder] = useState("");
+ const [direct, setDirect] = useState(false);
+ const [busy, setBusy] = useState(false);
+ const [error, setError] = useState("");
+ const [done, setDone] = useState<TemplateRepoPublish | null>(null);
+ const titleId = useId(), repoId = useId(), folderId = useId();
+
+ useEffect(() => {
+ let live = true;
+ githubConnection().then((answer) => {
+ if (!live) return;
+ setConnection(answer.connected ? { state: "connected" } : answer.reason === "not_connected" || !answer.error ? { state: "missing" } : { state: "refused", error: answer.error });
+ }, (cause: unknown) => { if (live) setConnection({ state: "refused", error: cause instanceof Error && cause.message ? cause.message : t("template.failed") }); });
+ return () => { live = false; };
+ }, []);
+
+ const publish = async () => {
+ if (busy || !repo.trim()) return;
+ setBusy(true);
+ setError("");
+ try {
+ setDone(await publishToRepo(card.id, { repo: repo.trim(), ...(folder.trim() ? { folder: folder.trim() } : {}), direct }));
+ } catch (cause) {
+ setError(cause instanceof Error && cause.message ? cause.message : t("template.failed"));
+ } finally {
+ setBusy(false);
+ }
+ };
+
+ const openApps = () => {
+ dispatch({ type: "togglePlugins", open: true });
+ onClose();
+ };
+
+ const footer = done ? <>
+ <button type="button" className="ui-button ui-button-md" onClick={onClose}>{t("common.close")}</button>
+ <button type="button" className="ui-button ui-button-md ui-button-primary" onClick={() => void openExternalLink(done.url).catch(() => {})}>
+ <ArrowUpRight size={14} aria-hidden="true" />{t(done.kind === "pull_request" ? "template.viewPullRequest" : "template.viewOnGithub")}
+ </button>
+ </> : connection.state === "missing" ? <>
+ <button type="button" className="ui-button ui-button-md" onClick={onClose}>{t("common.cancel")}</button>
+ <button type="button" data-template-open-apps className="ui-button ui-button-md ui-button-primary" onClick={openApps}>{t("template.repo.openApps")}</button>
+ </> : connection.state === "refused" ? (
+ <button type="button" className="ui-button ui-button-md" onClick={onClose}>{t("common.close")}</button>
+ ) : <>
+ <button type="button" className="ui-button ui-button-md" onClick={onClose} disabled={busy}>{t("common.cancel")}</button>
+ <button type="submit" form={titleId} data-template-repo-publish className="ui-button ui-button-md ui-button-primary" disabled={busy || connection.state !== "connected" || !repo.trim()}>
+ {busy && repoSpinner}{t(busy ? "template.repo.working" : direct ? "template.repo.commit" : "template.repo.openPullRequest")}
+ </button>
+ </>;
+
+ return (
+ <TemplateModal title={t("template.repo.title")} labelledBy={`${titleId}-title`} onClose={() => { if (!busy) onClose(); }} footer={footer}>
+ <div data-template-repo={card.id}>
+ {done ? (
+ <p role="status" dir="auto" className="text-[13px] text-ink-secondary">{t(done.kind === "pull_request" ? "template.repo.pullRequestOpened" : "template.repo.committed", { branch: done.branch })}</p>
+ ) : connection.state === "checking" ? (
+ <p role="status" className="flex items-center gap-2 text-[13px] text-ink-secondary">{repoSpinner}{t("template.repo.checking")}</p>
+ ) : connection.state === "missing" ? (
+ <p role="alert" dir="auto" className="text-[13px] text-ink-secondary">{t("template.repo.connectFirst")}</p>
+ ) : connection.state === "refused" ? (
+ <p role="alert" dir="auto" className="text-[13px] text-ink-secondary">{connection.error}</p>
+ ) : (
+ <form id={titleId} onSubmit={(event) => { event.preventDefault(); void publish(); }} className="flex flex-col gap-3">
+ <div>
+ <label htmlFor={repoId} className="text-[13px] font-medium text-ink">{t("template.repo.repoLabel")}</label>
+ <input id={repoId} dir="ltr" autoFocus value={repo} onChange={(event) => setRepo(event.target.value)} placeholder={t("template.repo.repoPlaceholder")} spellCheck={false} className={`mt-1.5 ${repoField}`} />
+ </div>
+ <div>
+ <label htmlFor={folderId} className="text-[13px] font-medium text-ink">{t("template.repo.folderLabel")}</label>
+ <input id={folderId} dir="ltr" value={folder} onChange={(event) => setFolder(event.target.value)} spellCheck={false} className={`mt-1.5 ${repoField}`} />
+ </div>
+ <label className="flex items-center gap-2 text-[13px] text-ink">
+ <input type="checkbox" checked={direct} onChange={(event) => setDirect(event.target.checked)} />{t("template.repo.direct")}
+ </label>
+ <p className="text-[12px] text-ink-tertiary">{t("template.repo.note")}</p>
+ </form>
+ )}
+ {error && <p role="alert" dir="auto" className="mt-3 text-[13px] text-danger">{error}</p>}
+ </div>
+ </TemplateModal>
+ );
+}
diff --git a/src/lib/template-share.ts b/src/lib/template-share.ts
index 92b719c5b7..b39fc2d0c9 100644
--- a/src/lib/template-share.ts
+++ b/src/lib/template-share.ts
@@ -1,4 +1,5 @@
-import type { TemplateCard, TemplateDetails } from "../../shared/share-card";
+import type { TeamTemplate, TemplateCard, TemplateDetails, TemplateRepoPublish } from "../../shared/share-card";
+import { SKILL_FILE_LIMITS, skillFilePathProblem } from "../../shared/skill-files";
import { t } from "./i18n";
import { api, type Action, type Bot, type Group } from "@/state/store";
import type { Routine } from "@/lib/routines";
@@ -7,6 +8,13 @@ import type { Routine } from "@/lib/routines";
export const TEMPLATE_FOLDER_MAX_BYTES = 4 * 1024 * 1024;
const PICTURE = /\.(png|jpe?g|webp)$/i;
const TEXT = /\.(md|json|txt)$/i;
+const SKILL_FILE = /(?:^|\/)skills\/[a-z0-9][a-z0-9-]{0,63}\/(.+)$/;
+
+/** A file beside a skill's SKILL.md that may travel with it, judged by its path and size before it is read. */
+function skillFileOf(file: File): boolean {
+ const inner = ((file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name).match(SKILL_FILE)?.[1];
+ return inner !== undefined && inner !== "SKILL.md" && skillFilePathProblem(inner) === null && file.size <= SKILL_FILE_LIMITS.fileBytes;
+}
export interface ImportedTemplate {
name: string;
@@ -24,7 +32,18 @@ export const templateDetails = (id: string) => api<{ card: TemplateCard; details
export const publishTemplate = (id: string) => api<TemplateCard>(`/api/share/${encodeURIComponent(id)}/publish`, post({}));
export const deleteTemplate = (id: string) => api<{ ok: true }>(`/api/share/${encodeURIComponent(id)}`, { method: "DELETE" });
-export type ImportSource = { url: string } | { path: string } | { files: Record<string, string> };
+export type ImportSource = { url: string } | { path: string } | { files: Record<string, string> } | { library: string };
+
+/** A Team Cloud's own templates, for its owner and admins. */
+export const teamTemplates = () => api<{ team: string; templates: TeamTemplate[] }>("/api/share/library");
+export const addToTeamTemplates = (id: string) =>
+ api<{ template: TeamTemplate; replaced: boolean }>(`/api/share/${encodeURIComponent(id)}/library`, post({}));
+export const removeTeamTemplate = (slug: string) => api<{ ok: true }>(`/api/share/library/${encodeURIComponent(slug)}`, { method: "DELETE" });
+
+/** Whether a GitHub connection is there to publish to the person's own repository through. */
+export const githubConnection = () => api<{ connected: boolean; reason?: "not_connected" | "refused" | "unavailable"; error?: string }>("/api/share/github");
+export const publishToRepo = (id: string, target: { repo: string; folder?: string; direct?: boolean }) =>
+ api<TemplateRepoPublish>(`/api/share/${encodeURIComponent(id)}/publish-repo`, post(target));
export const previewImport = (source: ImportSource) =>
api<{ details: TemplateDetails }>("/api/share/import?preview=1", post(source)).then((answer) => answer.details);
@@ -89,15 +108,15 @@ const readDataUrl = (file: File) => new Promise<string>((resolve, reject) => {
reader.readAsDataURL(file);
});
-/** A folder chosen in a browser, as the import route takes it: Markdown and JSON as text, pictures as data: URLs, and
- * nothing else. Refuses a folder over the size cap before reading it. */
+/** A folder chosen in a browser, as the import route takes it: Markdown, JSON and the files beside a skill as text,
+ * pictures as data: URLs, and nothing else. Refuses a folder over the size cap before reading it. */
export async function folderFiles(files: ArrayLike<File>): Promise<Record<string, string>> {
- const kept = Array.from(files).filter((file) => TEXT.test(file.name) || PICTURE.test(file.name));
+ const kept = Array.from(files).filter((file) => TEXT.test(file.name) || PICTURE.test(file.name) || skillFileOf(file));
if (kept.reduce((total, file) => total + file.size, 0) > TEMPLATE_FOLDER_MAX_BYTES) throw new Error(t("templateImport.tooLarge"));
const out: Record<string, string> = {};
for (const file of kept) {
const path = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
- out[path] = PICTURE.test(file.name) ? await readDataUrl(file) : await readText(file);
+ out[path] = PICTURE.test(file.name) && !skillFileOf(file) ? await readDataUrl(file) : await readText(file);
}
return out;
}
diff --git a/src/locales/en.json b/src/locales/en.json
index 3cd4ae1bec..8eedb385af 100644
--- a/src/locales/en.json
+++ b/src/locales/en.json
@@ -10975,6 +10975,24 @@
"template.publicNote": "Publishing makes it public on GitHub.",
"template.shareDepartment": "Share {name}",
"template.shareAsTemplate": "Share as template",
+ "template.addToTeam": "Add to {team}'s templates",
+ "template.addedToTeam": "Added to {team}'s templates",
+ "template.replacedInTeam": "Replaced in {team}'s templates. The previous one is kept.",
+ "template.publishToRepo": "Your GitHub repo…",
+ "template.repo.title": "Publish to your GitHub repo",
+ "template.repo.repoLabel": "Repository",
+ "template.repo.repoPlaceholder": "owner/repo",
+ "template.repo.folderLabel": "Folder (optional)",
+ "template.repo.direct": "Commit directly to the default branch",
+ "template.repo.openPullRequest": "Open pull request",
+ "template.repo.commit": "Commit",
+ "template.repo.working": "Publishing…",
+ "template.repo.checking": "Checking your GitHub connection…",
+ "template.repo.connectFirst": "Connect GitHub in Apps first.",
+ "template.repo.openApps": "Open Apps",
+ "template.repo.pullRequestOpened": "Pull request opened from the branch {branch}.",
+ "template.repo.committed": "Committed to {branch}.",
+ "template.repo.note": "Skills travel with their scripts. Chats, memory and keys never do.",
"templateImport.title": "Import",
"templateImport.linkLabel": "Paste a GitHub link",
"templateImport.open": "Open",
@@ -10990,6 +11008,12 @@
"templateImport.folderUnreadable": "This folder couldn't be read. Choose it again.",
"templateImport.failed": "That couldn't be imported. Check the link and try again.",
"templateImport.notATemplate": "This isn't a template. Choose another one.",
+ "templateImport.fromTeam": "From {team}'s templates",
+ "templateImport.kindBot": "Bot",
+ "templateImport.kindDepartment": "Department",
+ "templateImport.addedBy": "Added by {name} · {when}",
+ "templateImport.addedAt": "Added {when}",
+ "templateImport.remove": "Remove {name}",
"sidebar.addDepartment": "Add department",
"sidebar.import": "Import…",
"team.shareDepartment": "Share"
diff --git a/src/locales/pt-br.json b/src/locales/pt-br.json
index d1ec2b17d6..1c8e1c7cbd 100644
--- a/src/locales/pt-br.json
+++ b/src/locales/pt-br.json
@@ -10975,6 +10975,24 @@
"template.publicNote": "Publicar deixa o modelo público no GitHub.",
"template.shareDepartment": "Compartilhar {name}",
"template.shareAsTemplate": "Compartilhar como modelo",
+ "template.addToTeam": "Adicionar aos modelos de {team}",
+ "template.addedToTeam": "Adicionado aos modelos de {team}",
+ "template.replacedInTeam": "Substituído nos modelos de {team}. O anterior foi mantido.",
+ "template.publishToRepo": "Seu repositório no GitHub…",
+ "template.repo.title": "Publicar no seu repositório do GitHub",
+ "template.repo.repoLabel": "Repositório",
+ "template.repo.repoPlaceholder": "dono/repositório",
+ "template.repo.folderLabel": "Pasta (opcional)",
+ "template.repo.direct": "Fazer o commit direto no branch padrão",
+ "template.repo.openPullRequest": "Abrir pull request",
+ "template.repo.commit": "Fazer commit",
+ "template.repo.working": "Publicando…",
+ "template.repo.checking": "Verificando sua conexão com o GitHub…",
+ "template.repo.connectFirst": "Conecte o GitHub em Apps primeiro.",
+ "template.repo.openApps": "Abrir Apps",
+ "template.repo.pullRequestOpened": "Pull request aberto a partir do branch {branch}.",
+ "template.repo.committed": "Commit feito em {branch}.",
+ "template.repo.note": "As skills vão com seus scripts. Chats, memória e chaves nunca vão.",
"templateImport.title": "Importar",
"templateImport.linkLabel": "Cole um link do GitHub",
"templateImport.open": "Abrir",
@@ -10990,6 +11008,12 @@
"templateImport.folderUnreadable": "Não foi possível ler esta pasta. Escolha de novo.",
"templateImport.failed": "Não foi possível importar. Confira o link e tente de novo.",
"templateImport.notATemplate": "Isto não é um modelo. Escolha outro.",
+ "templateImport.fromTeam": "Dos modelos de {team}",
+ "templateImport.kindBot": "Bot",
+ "templateImport.kindDepartment": "Departamento",
+ "templateImport.addedBy": "Adicionado por {name} · {when}",
+ "templateImport.addedAt": "Adicionado {when}",
+ "templateImport.remove": "Remover {name}",
"sidebar.addDepartment": "Adicionar equipe",
"sidebar.import": "Importar…",
"team.shareDepartment": "Compartilhar"