Skip to content

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

Move the phone's wire, card, widget, mascot and pairing code into packages/phone-protocol (#5759)

Milind Soni1c3f9d1e0e87
diff --git a/.gitattributes b/.gitattributes
index 1461605eb9..ab0c99a654 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -3,7 +3,7 @@
# compares the result to what is checked in, so if git hands Windows a CRLF
# checkout every line differs and the drift guard fails for a reason that has
# nothing to do with drift. Pin them to LF on every platform.
-shared/mascot-bodies.ts text eol=lf
+packages/phone-protocol/src/mascot-bodies.ts text eol=lf
# git runs hooks through sh; a CRLF shebang line is "/bin/sh^M: bad interpreter" on every platform.
scripts/git-hooks/* text eol=lf
deploy/podman/*.sh text eol=lf
diff --git a/.oxlintrc.json b/.oxlintrc.json
index 583ad9bd8c..e60f86a17e 100644
--- a/.oxlintrc.json
+++ b/.oxlintrc.json
@@ -19,5 +19,19 @@
"release/**",
"third_party/**",
"electron/resources/**"
+ ],
+ "overrides": [
+ {
+ "files": ["packages/phone-protocol/**"],
+ "rules": {
+ "no-restricted-imports": ["error", {
+ "patterns": [{ "group": ["node:*"], "message": "The phone imports this package: no Node modules." }]
+ }],
+ "no-restricted-globals": ["error",
+ { "name": "window", "message": "The phone imports this package: no DOM." },
+ { "name": "document", "message": "The phone imports this package: no DOM." }
+ ]
+ }
+ }
]
}
diff --git a/companion/test/phone-protocol.test.ts b/companion/test/phone-protocol.test.ts
new file mode 100644
index 0000000000..1551ac5ee2
--- /dev/null
+++ b/companion/test/phone-protocol.test.ts
@@ -0,0 +1,17 @@
+import { describe, expectTypeOf, it } from "vitest";
+
+import type { CompanionEndpointsSnapshot, PairResponse, ServerFrame } from "../../packages/phone-protocol/src/wire.ts";
+import type { PublicDevice } from "../src/devices.ts";
+import type { E2EDescriptor } from "../src/e2e/descriptor.ts";
+import type { CompanionEndpoint } from "../src/endpoints.ts";
+import type { CompanionEndpointSnapshot } from "../src/proxy.ts";
+
+describe("the phone protocol's types", () => {
+ it("cover what the companion sends a phone", () => {
+ type Endpoints = CompanionEndpointSnapshot & { version?: string; e2e?: E2EDescriptor };
+ expectTypeOf<Endpoints>().toExtend<CompanionEndpointsSnapshot>();
+ expectTypeOf<{ kind: "companion.endpoints" } & Endpoints>().toExtend<ServerFrame>();
+ type Paired = { device: PublicDevice; token: string } & { serverName: string; hosts?: string[]; endpoints?: CompanionEndpoint[]; e2e?: E2EDescriptor };
+ expectTypeOf<Paired>().toExtend<PairResponse>();
+ });
+});
diff --git a/package.json b/package.json
index 70fa887aef..285146e35b 100644
--- a/package.json
+++ b/package.json
@@ -39,7 +39,7 @@
"eval": "node --experimental-strip-types evals/runners/run-evals.ts",
"dev:desktop": "node scripts/prepare-cloudflared.mjs --current && electron .",
"build": "tsc -b && tsc -p tsconfig.server.json && vite build",
- "typecheck": "tsc -b && tsc -p tsconfig.server.json",
+ "typecheck": "tsc -b && tsc -p tsconfig.server.json && tsc -p packages/phone-protocol/tsconfig.json",
"test": "vitest run && pnpm broker:test && pnpm test:electron && pnpm test:packaged-server",
"test:electron": "node --test \"electron/*.node-test.mjs\"",
"bench:observation": "node --experimental-strip-types scripts/bench-observation.ts",
diff --git a/packages/phone-protocol/package.json b/packages/phone-protocol/package.json
new file mode 100644
index 0000000000..43c0614a24
--- /dev/null
+++ b/packages/phone-protocol/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@openmausbot/phone-protocol",
+ "private": true,
+ "version": "0.0.0",
+ "description": "The wire contract a MausBot phone app shares with the desktop: frame and response types, cards, widgets, mascot and pairing.",
+ "license": "Apache-2.0",
+ "type": "module",
+ "exports": {
+ "./*": "./src/*"
+ },
+ "peerDependencies": {
+ "croner": "10.0.1",
+ "zod": "4.6.7"
+ }
+}
diff --git a/packages/phone-protocol/portable-globals.d.ts b/packages/phone-protocol/portable-globals.d.ts
new file mode 100644
index 0000000000..a3f77fd131
--- /dev/null
+++ b/packages/phone-protocol/portable-globals.d.ts
@@ -0,0 +1,45 @@
+// The only globals beyond ES2022 this package may use: web-platform APIs that Node 24 and browsers have and a React
+// Native app provides (Hermes, or a polyfill the phone app installs). Anything else is a compile error here, which keeps
+// the package free of DOM and Node APIs.
+
+interface URLSearchParams {
+ get(name: string): string | null;
+ has(name: string): boolean;
+ toString(): string;
+}
+declare var URLSearchParams: {
+ prototype: URLSearchParams;
+ new (init?: string | Record<string, string>): URLSearchParams;
+};
+
+interface URL {
+ hash: string;
+ host: string;
+ hostname: string;
+ href: string;
+ readonly origin: string;
+ password: string;
+ pathname: string;
+ port: string;
+ protocol: string;
+ search: string;
+ readonly searchParams: URLSearchParams;
+ username: string;
+ toString(): string;
+}
+declare var URL: {
+ prototype: URL;
+ new (url: string, base?: string | URL): URL;
+};
+
+interface TextEncoder {
+ encode(input?: string): Uint8Array;
+}
+declare var TextEncoder: {
+ prototype: TextEncoder;
+ new (): TextEncoder;
+};
+
+declare function atob(data: string): string;
+declare function btoa(data: string): string;
+declare function structuredClone<T>(value: T): T;
diff --git a/packages/phone-protocol/src/activity.ts b/packages/phone-protocol/src/activity.ts
new file mode 100644
index 0000000000..575d5b636a
--- /dev/null
+++ b/packages/phone-protocol/src/activity.ts
@@ -0,0 +1,40 @@
+import type { ServerTextParams } from "./server-text.ts";
+// The shape of one line in a bot's activity log, shared by the harness reader
+// and the panel that renders it.
+
+export type ActivityOutcome =
+ /** the tool finished and reported success */
+ | "ran"
+ /** the tool finished and reported failure */
+ | "failed"
+ /** started, no completion seen yet */
+ | "running"
+ /** approved, but no matching tool run was found in the thread's events */
+ | "allowed"
+ /** a person or reviewer said no; nothing ran */
+ | "denied"
+ /** a card is open and nobody has answered it */
+ | "waiting";
+
+export interface ActivityRow {
+ /** when it started (a tool) or was asked (a request) */
+ at: string;
+ threadId: string;
+ turnId?: string;
+ requestId?: string;
+ tool: string;
+ /** the connected app or surface it touched, when there is one */
+ app: string | null;
+ /** the action, in words */
+ label: string;
+ /** `label` as an `activity.tool.*` catalog key, for a client to say in its own language */
+ labelKey?: string;
+ /** `app` as an `activity.app.*` catalog key, only for the app's own surfaces (Team, Computer, Research) */
+ appKey?: string;
+ /** the arguments the decision log recorded, already redacted */
+ summary?: string;
+ /** Fixed summary words; the English remains authoritative. */
+ summaryCode?: string;
+ summaryParams?: ServerTextParams;
+ outcome: ActivityOutcome;
+}
diff --git a/packages/phone-protocol/src/agents-tool-names.ts b/packages/phone-protocol/src/agents-tool-names.ts
new file mode 100644
index 0000000000..46de64ad2a
--- /dev/null
+++ b/packages/phone-protocol/src/agents-tool-names.ts
@@ -0,0 +1,99 @@
+// The agents tools that each do several things, and the name each of their calls goes by: its member name, the name
+// that call has as a tool of its own. A tool selection and the call path read a call by that name, so a selector or a
+// saved skill naming a member means exactly those calls. Security: an engine may remember "always allow" by a tool's
+// name, so a tool never does anything more destructive than each of its members did alone: deleting a trigger is a
+// tool of its own.
+type Args = Record<string, unknown>;
+
+const given = (args: Args, key: string) => args[key] !== undefined && args[key] !== null;
+
+function record(value: unknown): value is Args {
+ return value !== null && typeof value === "object" && !Array.isArray(value);
+}
+
+export interface AgentsActionTool {
+ /** Every member, the tool's own name first when its plain calls keep it. */
+ members: readonly string[];
+ member(args: Args): string;
+}
+
+export const AGENTS_ACTION_TOOLS: Readonly<Record<string, AgentsActionTool>> = {
+ trigger_info: { members: ["list_triggers", "list_trigger_events"], member: (args) => args.action === "events" ? "list_trigger_events" : "list_triggers" },
+ trigger: { members: ["create_trigger", "manage_trigger"], member: (args) => args.action === "create" ? "create_trigger" : "manage_trigger" },
+ delete_trigger: { members: ["manage_trigger"], member: () => "manage_trigger" },
+ manage_room: { members: ["manage_room", "create_room"], member: (args) => args.action === "create" ? "create_room" : "manage_room" },
+ session_search: { members: ["session_search", "session_read"], member: (args) => given(args, "thread_id") || given(args, "message_id") ? "session_read" : "session_search" },
+ show_widget: { members: ["show_widget", "update_widget"], member: (args) => given(args, "widget_id") ? "update_widget" : "show_widget" },
+ show_html: { members: ["show_html", "update_html"], member: (args) => given(args, "app_id") ? "update_html" : "show_html" },
+ x_search: {
+ members: ["x_search", "x_user_posts", "x_post", "x_profile"],
+ member: (args) => args.action === "user_posts" ? "x_user_posts" : args.action === "post" ? "x_post" : args.action === "profile" ? "x_profile" : "x_search",
+ },
+};
+
+/** A member name that is not a listed tool, still answered as a call: an engine session that saw it, a saved skill or
+ * memory, or an external runtime may use one. It runs as the call `resolve` gives, to one of `tools`. */
+export interface AgentsAlias {
+ tools: readonly string[];
+ resolve(args: Args): { name: string; arguments: Args };
+}
+
+const as = (name: string, args: Args) => ({ name, arguments: args });
+/** An id the call must carry to mean an update: empty when it was left out, so the tool refuses rather than creates. */
+const required = (args: Args, key: string): Args => ({ ...args, [key]: args[key] ?? "" });
+
+export const AGENTS_TOOL_ALIASES: Readonly<Record<string, AgentsAlias>> = {
+ list_triggers: { tools: ["trigger_info"], resolve: (args) => as("trigger_info", { ...args, action: "list" }) },
+ list_trigger_events: { tools: ["trigger_info"], resolve: (args) => as("trigger_info", { ...args, action: "events" }) },
+ create_trigger: { tools: ["trigger"], resolve: (args) => as("trigger", { ...args, action: "create" }) },
+ manage_trigger: {
+ tools: ["trigger", "delete_trigger"],
+ resolve: ({ changes, ...args }) => {
+ const fields = record(changes) ? changes : {};
+ if (args.action === "delete") {
+ const { action: _delete, ...target } = args;
+ return as("delete_trigger", { ...fields, ...target });
+ }
+ return as("trigger", { ...fields, ...args, action: args.action === "create" ? undefined : args.action });
+ },
+ },
+ create_room: { tools: ["manage_room"], resolve: (args) => as("manage_room", { ...args, action: "create" }) },
+ session_read: { tools: ["session_search"], resolve: (args) => as("session_search", required(required(args, "thread_id"), "message_id")) },
+ update_widget: { tools: ["show_widget"], resolve: (args) => as("show_widget", required(args, "widget_id")) },
+ update_html: { tools: ["show_html"], resolve: (args) => as("show_html", required(args, "app_id")) },
+ x_user_posts: { tools: ["x_search"], resolve: (args) => as("x_search", { ...args, action: "user_posts" }) },
+ x_post: { tools: ["x_search"], resolve: (args) => as("x_search", { ...args, action: "post" }) },
+ x_profile: { tools: ["x_search"], resolve: (args) => as("x_search", { ...args, action: "profile" }) },
+};
+
+const aliasOf = (name: string) => Object.hasOwn(AGENTS_TOOL_ALIASES, name) ? AGENTS_TOOL_ALIASES[name] : undefined;
+const actionToolOf = (name: string) => Object.hasOwn(AGENTS_ACTION_TOOLS, name) ? AGENTS_ACTION_TOOLS[name] : undefined;
+
+/** The tool a call runs and its arguments: an alias as its action tool's call, any other name as it came. */
+export function resolveAgentsCall(name: string, args: Args): { name: string; arguments: Args } {
+ return aliasOf(name)?.resolve(args) ?? { name, arguments: args };
+}
+
+/** The member name a call to `tool` with `args` goes by; the tool's own name when it does one thing. */
+export function agentsCallMember(tool: string, args: unknown): string {
+ return actionToolOf(tool)?.member(record(args) ? args : {}) ?? tool;
+}
+
+/** A call's names in a selection: its member name, and its tool's name when that is not itself a member. */
+function named(tool: string, member: string): string[] {
+ return actionToolOf(tool)?.members.includes(tool) ? [member] : [tool, member];
+}
+
+/** The names that identify an agents call in a tool selection. With no arguments (a tool being listed), one set per
+ * call the name can make. */
+export function agentsCallIdentities(name: string, args?: unknown): string[][] {
+ const alias = aliasOf(name);
+ if (alias) {
+ if (args === undefined) return alias.tools.map((tool) => named(tool, name));
+ const call = alias.resolve(record(args) ? args : {});
+ return [named(call.name, agentsCallMember(call.name, call.arguments))];
+ }
+ const tool = actionToolOf(name);
+ if (!tool) return [[name]];
+ return args === undefined ? tool.members.map((member) => named(name, member)) : [named(name, tool.member(record(args) ? args : {}))];
+}
diff --git a/packages/phone-protocol/src/app-settings.ts b/packages/phone-protocol/src/app-settings.ts
new file mode 100644
index 0000000000..1287447a7b
--- /dev/null
+++ b/packages/phone-protocol/src/app-settings.ts
@@ -0,0 +1,86 @@
+// The app_settings tool's wire shapes: a setting's tier (the whole policy), the applied card a change rides on, and the
+// preferences that live in the window's localStorage, which the server reaches through an SSE frame.
+import { z } from "zod";
+
+export type SettingTier = "safe" | "secret" | "owner-only";
+
+/** On a card: display values only, never a key. */
+export interface AppSettingRequest {
+ settingId: string;
+ label: string;
+ before?: string;
+ after: string;
+ tier: SettingTier;
+}
+export interface AppSettingCardField {
+ /** A bot's change to one of the app's own settings, applied with Undo. */
+ appSettingRequest?: AppSettingRequest;
+}
+
+export const SKIN_IDS = [
+ "midnight",
+ "atelier",
+ "foundry",
+ "lagoon",
+ "graphite",
+ "linen",
+ "dusk",
+ "daylight",
+ "meadow",
+ "pop",
+ "halloween",
+ "diwali",
+ "aurora",
+] as const;
+export const FONT_IDS = ["skin", "system", "inter", "poppins", "serif"] as const;
+export const CHAT_WIDTH_IDS = ["standard", "wide", "full"] as const;
+/** The Enter-adds-a-line modes are for input methods that confirm a conversion with Enter (Japanese). */
+export const SEND_KEYS = ["enter", "shift-enter", "mod-enter"] as const;
+export const PLACE_SWATCHES = ["blue", "green", "amber", "rose", "violet", "slate"] as const;
+export const TALK_KEYS = ["ctrl-opt-space", "ctrl-shift-space", "opt-shift-space"] as const;
+const pinnedPage = z.object({ name: z.string().trim().min(1).max(40), url: z.string().trim().max(2048).regex(/^https?:\/\/\S+$/, "an http(s) address") }).strict();
+
+/** Preferences kept in the window or behind the desktop app's own bridge, by setting id; the renderer applies a frame with
+ * the matching setter. */
+export const WINDOW_PREFS = {
+ "appearance.skin": z.enum([...SKIN_IDS, "system"]),
+ "appearance.advanced": z.boolean(),
+ "appearance.font": z.enum(FONT_IDS),
+ "appearance.chatWidth": z.enum(CHAT_WIDTH_IDS),
+ "general.sendKey": z.enum(SEND_KEYS),
+ "general.notificationSounds": z.boolean(),
+ "appearance.userBubbles": z.boolean(),
+ "appearance.runCard": z.boolean(),
+ "appearance.showThreads": z.boolean(),
+ "appearance.toolsLayout": z.enum(["rows", "toolbar"]),
+ "appearance.pinnedCircles": z.boolean(),
+ "appearance.universalPins": z.boolean(),
+ "appearance.pinnedPages": z.array(pinnedPage).max(6),
+ "appearance.showComputers": z.boolean(),
+ "appearance.windowFrame": z.boolean(),
+ "appearance.sidebarColor": z.enum([...PLACE_SWATCHES, "none"]),
+ "general.followUp": z.enum(["steer", "queue"]),
+ "general.finishedNotifications": z.boolean(),
+ "general.notificationFeed": z.boolean(),
+ "general.analytics": z.boolean(),
+ "general.openAtLogin": z.boolean(),
+ "general.talkShortcut": z.object({ enabled: z.boolean(), key: z.enum(TALK_KEYS) }).strict(),
+ "account.productEmails": z.boolean(),
+ "remote.wifi": z.boolean(),
+ "remote.relay": z.boolean(),
+ "remote.tailscale": z.boolean(),
+ "remote.keepAwake": z.boolean(),
+} as const;
+export type WindowPrefId = keyof typeof WINDOW_PREFS;
+export type WindowPrefValue<I extends WindowPrefId> = z.infer<(typeof WINDOW_PREFS)[I]>;
+export const WINDOW_PREF_IDS = Object.keys(WINDOW_PREFS) as WindowPrefId[];
+export const isWindowPrefId = (id: string): id is WindowPrefId => Object.hasOwn(WINDOW_PREFS, id);
+
+export interface WindowPrefFrame {
+ kind: "window-pref";
+ id: WindowPrefId;
+ value: unknown;
+}
+
+/** What the window reports as its current values (PUT /api/window-prefs). */
+export const windowPrefReportSchema = z.object({ values: z.record(z.string(), z.unknown()) }).strict();
diff --git a/packages/phone-protocol/src/app-triggers.ts b/packages/phone-protocol/src/app-triggers.ts
new file mode 100644
index 0000000000..d4fe680177
--- /dev/null
+++ b/packages/phone-protocol/src/app-triggers.ts
@@ -0,0 +1,187 @@
+/** App-event automations: "when something happens in a connected app, a bot does something". Wire shapes for the
+ * REST snapshot (`/api/app-triggers`), the `app-trigger*` live frames and the chat card a bot's change leaves. */
+import type { ConnectorToolGrant } from "./wire.ts";
+import type { RoutineRunOn } from "./routines.ts";
+
+/** Plain words a person or bot gives. Gmail turns them into its own search, so other mail never arrives at all; other
+ * apps match them, case-insensitively, against the event's fields. */
+export interface AppTriggerFilter {
+ from?: string;
+ /** The subject (or title) contains this. */
+ subject?: string;
+ label?: string;
+ /** Anywhere in the event. */
+ text?: string;
+}
+
+/** "instant": the app pushes each event; "poll": Composio checks on its interval (15 minutes on managed sign-ins). */
+export type AppTriggerDelivery = "instant" | "poll";
+
+export type AppTriggerProblem =
+ | { kind: "reconnect"; at: number }
+ | { kind: "error"; text: string; at: number };
+
+/** Events Composio sent but the connected-apps service did not keep, today (UTC, as the service counts its limit). */
+export interface AppTriggerSkipped {
+ day: string;
+ dailyLimit: number;
+ queueFull: number;
+ expired: number;
+ /** Kept back here because this automation already had its limit of waiting runs. */
+ tooMany: number;
+}
+
+export interface AppTrigger {
+ id: string;
+ name: string;
+ prompt: string;
+ botId: string;
+ runOn: RoutineRunOn;
+ enabled: boolean;
+ /** Composio toolkit slug, e.g. `gmail`. */
+ app: string;
+ appName: string;
+ /** Composio trigger type slug, e.g. `GMAIL_NEW_GMAIL_MESSAGE`. */
+ event: string;
+ eventName: string;
+ delivery: AppTriggerDelivery;
+ accountId: string;
+ accountLabel?: string;
+ /** Composio trigger config, with a Gmail filter already folded into `query`. */
+ config: Record<string, unknown>;
+ filter?: AppTriggerFilter;
+ /** The connected-apps service's copy. `pending` is retried on its own until it holds. */
+ remote: { triggerId?: string; state: "active" | "pending" | "error"; error?: string; syncedAt?: number };
+ problem?: AppTriggerProblem;
+ sourceThreadId?: string;
+ /** Each run continues this automation's previous run conversation instead of starting a new one. */
+ sameConversation?: boolean;
+ /** Events that started a run or joined one. */
+ received: number;
+ filtered: number;
+ skipped?: AppTriggerSkipped;
+ lastEventAt?: number;
+ lastRunId?: string;
+ createdAt: number;
+ updatedAt: number;
+}
+
+export type AppEventOutcome = "started" | "joined" | "filtered" | "duplicate" | "skipped" | "rejected";
+
+export interface AppEventAttempt {
+ id: string;
+ triggerId: string;
+ eventId: string;
+ at: number;
+ outcome: AppEventOutcome;
+ reason?: string;
+ runId?: string;
+ /** One line: who it is from and what it is about, when the event says. */
+ preview?: string;
+}
+
+export interface AppTriggerService {
+ /** "self-hosted": this server uses its own Composio key, which app events do not support. "off": OMB_COMPOSIO_BROKER=off. */
+ available: boolean;
+ reason?: "self-hosted" | "unavailable" | "off";
+ plan?: "desktop" | "cloud";
+ eventsPerDay?: number;
+ eventsToday?: number;
+}
+
+export interface AppTriggersSnapshot {
+ triggers: AppTrigger[];
+ attempts: AppEventAttempt[];
+ service: AppTriggerService;
+}
+
+/** One event type a connected app offers, as the picker and `trigger_info` events show it. */
+export interface AppEventType {
+ event: string;
+ name: string;
+ description: string;
+ delivery: AppTriggerDelivery;
+ configFields: Array<{ name: string; type: string; required: boolean; description?: string; default?: unknown }>;
+ filterFields: string[];
+}
+
+export interface AppEventCatalog {
+ apps: Array<{ app: string; name: string; accounts: Array<{ id: string; alias?: string }>; events: AppEventType[]; error?: string }>;
+ /** Popular apps with events that are not connected yet. */
+ notConnected: Array<{ app: string; name: string }>;
+ unavailable?: string;
+}
+
+export interface AppTriggerDefinition {
+ name: string;
+ instructions: string;
+ app: string;
+ event: string;
+ /** Connected account id or alias; needed only when the person has more than one for this app. */
+ account?: string;
+ filter?: AppTriggerFilter;
+ config?: Record<string, unknown>;
+ runOn?: RoutineRunOn;
+ /** Each run continues the automation's previous run conversation. */
+ sameConversation?: boolean;
+}
+
+export type AppTriggerChange = Partial<Pick<AppTriggerDefinition, "name" | "instructions" | "filter" | "config" | "runOn" | "sameConversation">>;
+
+export type AppTriggerRequestOperation =
+ | { action: "create"; trigger: AppTriggerDefinition; forBot?: { botId: string; name: string } }
+ | { action: "update"; triggerId: string; changes: AppTriggerChange; forBot?: { botId: string; name: string } }
+ | { action: "pause" | "resume" | "run_now" | "delete"; triggerId: string; forBot?: { botId: string; name: string } };
+
+/** Durable payload of an app-event automation a bot made or changed from chat: a receipt with what Undo needs. */
+export interface AppTriggerRequestCardData {
+ version: 1;
+ requestId: string;
+ botId: string;
+ threadId: string;
+ createdAt: number;
+ operation: AppTriggerRequestOperation;
+ resultId?: string;
+ undo?: {
+ name: string;
+ /** The automation's revision right after the change; Undo refuses once it moved. */
+ appliedUpdatedAt?: number;
+ before?: { name: string; prompt: string; runOn: RoutineRunOn; enabled: boolean; filter?: AppTriggerFilter; config: Record<string, unknown>; sameConversation?: boolean };
+ };
+}
+
+export const APP_FILTER_MAX = 200;
+export const GMAIL_APP = "gmail";
+export const GMAIL_NEW_MESSAGE = "GMAIL_NEW_GMAIL_MESSAGE";
+
+const quoted = (value: string) => {
+ const clean = value.replace(/["\\]/g, " ").replace(/\s+/g, " ").trim();
+ return /\s/.test(clean) ? `"${clean}"` : clean;
+};
+
+/** Gmail search syntax for a plain filter: from:, subject:, label: and free words, so filtering happens at the source. */
+export function gmailSearchQuery(filter: AppTriggerFilter | undefined): string {
+ if (!filter) return "";
+ return [
+ filter.from && `from:${quoted(filter.from)}`,
+ filter.subject && `subject:(${filter.subject.replace(/[()\\]/g, " ").replace(/\s+/g, " ").trim()})`,
+ filter.label && `label:${quoted(filter.label).replace(/\s+/g, "-")}`,
+ filter.text && quoted(filter.text),
+ ].filter(Boolean).join(" ");
+}
+
+/** Whether Composio filters this app's events itself from the plain filter (its config), or OpenMausBot does on arrival. */
+export function filtersAtSource(app: string): boolean {
+ return app === GMAIL_APP;
+}
+
+/** A bot may watch an app its connected-app settings let it use: the same grants and scopes its tool calls meet. */
+export function botMayWatchApp(
+ bot: { composio?: boolean; connectorTools?: Record<string, ConnectorToolGrant>; connectorScopes?: { apps: Record<string, "read" | "write"> } },
+ app: string,
+): boolean {
+ if (bot.composio === false) return false;
+ if (bot.connectorTools !== undefined && !Object.hasOwn(bot.connectorTools, app)) return false;
+ if (bot.connectorScopes !== undefined && !Object.hasOwn(bot.connectorScopes.apps, app)) return false;
+ return true;
+}
diff --git a/packages/phone-protocol/src/app.ts b/packages/phone-protocol/src/app.ts
new file mode 100644
index 0000000000..b16e4c0a5c
--- /dev/null
+++ b/packages/phone-protocol/src/app.ts
@@ -0,0 +1,418 @@
+// Chat apps: HTML in a sandboxed frame inside a chat row, speaking the MCP Apps bridge
+// (io.modelcontextprotocol/ui, SEP-1865). Bot HTML (show_html) and an MCP server's UI
+// (_meta.ui.resourceUri) share the one wire kind, `app`.
+
+export const APP_MIME = "text/html;profile=mcp-app";
+export const APP_PROTOCOL_VERSION = "2026-01-26";
+export const APP_EXTENSION_KEY = "io.modelcontextprotocol/ui";
+
+export const APP_LIMITS = {
+ /** show_html `html` or `jsx`, UTF-8 bytes after trimming. */
+ htmlBytes: 256 * 1024,
+ title: 80,
+ fallback: 1_500,
+ fallbackExcerpt: 600,
+ heightMin: 80,
+ heightMax: 720,
+ /** ui/message text, and the appMessage on the send route. */
+ messageText: 4_000,
+ /** ui/update-model-context text, stored per row. */
+ contextText: 4_000,
+ /** The result line of an app row's "Done" note. */
+ doneText: 300,
+ /** An MCP server's UI resource, decoded. */
+ mcpHtmlBytes: 2 * 1024 * 1024,
+ /** tools/call arguments on the rpc route. */
+ rpcArgumentsBytes: 64 * 1024,
+ /** resources/read through the rpc route. */
+ rpcResourceBytes: 8 * 1024 * 1024,
+ /** appMessage sends per app row per hour. */
+ messagesPerHour: 20,
+ /** rpc calls per app row per minute. */
+ rpcPerMinute: 60,
+} as const;
+
+/** Versions of one bot page kept for stepping back, the current one included. */
+export const APP_PAGE_VERSIONS = 10;
+
+export type AppSource = "html" | "mcp";
+
+/** Origins a frame may reach, after the host's filter. `refused`: what a server asked for and the
+ * filter dropped. */
+export interface AppNetwork {
+ connect: string[];
+ resources: string[];
+ refused?: string[];
+}
+
+/** The latest ui/update-model-context of one app row, delivered with the person's next message in
+ * its thread. */
+export interface AppContextState {
+ text: string;
+ at: number;
+ delivered: boolean;
+}
+
+/** The last change an MCP app made from its own card: a tool the bot could call too, not read-only, that did
+ * not fail. Shown under the card, so a reopened conversation does not look as if it was never sent. */
+export interface AppDoneState {
+ /** the tool's title, else its name */
+ tool: string;
+ /** the result's plain text, one line */
+ text?: string;
+ /** an https link the result names (html_url, else url) */
+ url?: string;
+ at: number;
+}
+
+export interface AppMcpRef {
+ /** the mount name in config.json mcpServers */
+ server: string;
+ /** initialize serverInfo.title ?? name */
+ serverTitle?: string;
+ tool: string;
+ /** ui://... */
+ resourceUri: string;
+ isError?: boolean;
+}
+
+/** Never carries the HTML: a client fetches the AppDocument when it mounts the frame. */
+export interface AppPayload {
+ v: 1;
+ source: AppSource;
+ /** Header title, one line, ≤ 80 chars. Bot HTML: the bot's title. MCP:
+ * the tool's title, else its name. */
+ title: string;
+ /** Content id of the stored document; a new value means the frame must reload. Empty when nothing
+ * could be stored (`blocked`): the row then shows only its text. */
+ doc: string;
+ /** 0, bumped each time show_html replaces the page. */
+ rev: number;
+ /** Content ids of the versions before `doc`, oldest first, at most APP_PAGE_VERSIONS - 1: the last one is
+ * rev - 1. */
+ history?: string[];
+ /** Bot HTML whose document is a React component file (show_html `jsx`), wrapped in the page shell when served. */
+ format?: "jsx";
+ /** UTF-8 bytes of the HTML, for the info popover. */
+ bytes: number;
+ /** Initial height in px before the frame reports its own (show_html
+ * `height`, clamped 80..720). */
+ height?: number;
+ /** Draw the host's border and background (MCP prefersBorder; bot HTML: true). */
+ border: boolean;
+ /** Origins the frame may reach, after the host's filter, for the info popover. */
+ network: AppNetwork;
+ mcp?: AppMcpRef;
+ /** The latest ui/update-model-context, delivered with the person's next
+ * message in this thread. */
+ context?: AppContextState;
+ done?: AppDoneState;
+ /** Why the document could not be stored or read when the row was written
+ * (`too-large`, or an MCP server that was signed out or unreachable). The
+ * row is still written, with its text. */
+ blocked?: AppBlockedReason;
+ /** A page from a folder that reloads in place when a file in its folder changes (show_html `live`). */
+ live?: true;
+}
+
+/** A user row an app's ui/message sent. */
+export interface AppFromRef {
+ messageId: string;
+ title: string;
+}
+
+/** One part of a bot's page the person pointed at, as its chip on their message reads. `label` is the page's own
+ * words. */
+export interface AppPointedRef {
+ appId: string;
+ label: string;
+}
+
+/** Why an app's server calls are off, or why its document is missing. `unavailable`: the UI resource
+ * could not be read when the row was written (offline, wrong mime type). */
+export type AppBlockedReason = "signed-out" | "server-removed" | "server-disabled" | "apps-off" | "too-large" | "unavailable";
+
+/** What the frame may do right now; hostCapabilities is built from this. */
+export interface AppCan {
+ serverTools: boolean;
+ serverResources: boolean;
+ message: boolean;
+ openLinks: boolean;
+ modelContext: boolean;
+}
+
+export interface AppToolDefinition {
+ name: string;
+ title?: string;
+ description?: string;
+ inputSchema?: object;
+ annotations?: object;
+ _meta?: object;
+}
+
+export interface AppToolResult {
+ content: unknown[];
+ structuredContent?: unknown;
+ _meta?: Record<string, unknown>;
+ isError?: boolean;
+}
+
+/** What a client fetches to mount a frame (GET /api/threads/:threadId/messages/:messageId/app), never
+ * part of a thread load. A document with `tool` is an MCP app; one without is bot HTML. */
+export interface AppDocument {
+ v: 1;
+ messageId: string;
+ rev: number;
+ /** Set verbatim as the iframe's srcdoc. Starts with
+ * `<!DOCTYPE html><meta http-equiv="Content-Security-Policy" content="…">`. */
+ srcdoc: string;
+ /** The policy in that meta, repeated for phone network enforcement. */
+ csp: string;
+ network: { connect: string[]; resources: string[] };
+ /** MCP only: hostContext.toolInfo.tool, and the two notifications. */
+ tool?: AppToolDefinition;
+ toolInput?: Record<string, unknown>;
+ toolResult?: AppToolResult;
+ can: AppCan;
+ /** Why serverTools/serverResources are off: drawn as a strip under the frame. */
+ blocked?: { reason: AppBlockedReason; text: string };
+ /** Shown in a room, to everyone who can see it: view-only. `can` has message, modelContext, serverTools and
+ * serverResources off, and a bot's page reads `mausbot.room === true`. */
+ room?: true;
+}
+
+/** Why a room refuses what an app or a widget would do for the person: nobody in a room speaks for the others. */
+export const ROOM_VIEW_ONLY = "In a room, pages, apps and widgets are view-only: they cannot send messages or tell a bot what anyone sees.";
+
+/** Exactly one of `html` (wrapped when it was a fragment), `jsx` and `path` (a folder with index.html, or an .html
+ * file, in the bot's own folders), none yet scrubbed of secrets. */
+export interface ShowHtmlInput {
+ html?: string;
+ jsx?: string;
+ path?: string;
+ title: string;
+ height?: number;
+ fallbackText?: string;
+ /** Show the page without the card frame (still in its sandboxed frame). */
+ frameless?: boolean;
+ /** Reload the page in place whenever a file in its folder changes; only with `path`. */
+ live?: boolean;
+}
+
+export interface UpdateHtmlInput {
+ appId: string;
+ html?: string;
+ jsx?: string;
+ path?: string;
+ title?: string;
+ /** Change whether the page has the card frame; kept as it was when omitted. */
+ frameless?: boolean;
+ /** Turn reloading on folder changes on (only with `path`) or off; kept as it was when omitted. */
+ live?: boolean;
+}
+
+export type AppInputResult<T> = { ok: true; value: T } | { ok: false; error: string };
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+export function utf8Bytes(text: string): number {
+ let bytes = 0;
+ for (let index = 0; index < text.length; index += 1) {
+ const code = text.charCodeAt(index);
+ if (code < 0x80) bytes += 1;
+ else if (code < 0x800) bytes += 2;
+ else if (code >= 0xd800 && code <= 0xdbff && index + 1 < text.length) {
+ const next = text.charCodeAt(index + 1);
+ if (next >= 0xdc00 && next <= 0xdfff) { bytes += 4; index += 1; } else bytes += 3;
+ } else bytes += 3;
+ }
+ return bytes;
+}
+
+export function oneLine(text: string): string {
+ return text.replace(/\s+/g, " ").trim();
+}
+
+/** A fragment gets a minimal document, so the CSP meta can lead its head. */
+export function wrapHtmlFragment(html: string): string {
+ if (/<(?:html|body)[\s>/]/i.test(html) || /<(?:html|body)$/i.test(html)) return html;
+ return `<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>${html}</body></html>`;
+}
+
+function checkHtml(value: unknown): AppInputResult<string> {
+ if (typeof value !== "string") return { ok: false, error: "html: must be a string holding one HTML document." };
+ const html = value.trim();
+ if (!html) return { ok: false, error: "html: is empty; send one HTML document with inline style and script." };
+ const bytes = utf8Bytes(html);
+ if (bytes > APP_LIMITS.htmlBytes) {
+ return { ok: false, error: `html: is ${bytes} bytes, over the ${APP_LIMITS.htmlBytes}-byte limit; load libraries from a CDN and embed less data.` };
+ }
+ return { ok: true, value: wrapHtmlFragment(html) };
+}
+
+function checkJsx(value: unknown): AppInputResult<string> {
+ if (typeof value !== "string") return { ok: false, error: "jsx: must be a string holding one React component file." };
+ const jsx = value.trim();
+ if (!jsx) return { ok: false, error: "jsx: is empty; send one React component file with a default export." };
+ const bytes = utf8Bytes(jsx);
+ if (bytes > APP_LIMITS.htmlBytes) return { ok: false, error: `jsx: is ${bytes} bytes, over the ${APP_LIMITS.htmlBytes}-byte limit; embed less data.` };
+ if (!/\bexport\s+default\b/.test(jsx)) return { ok: false, error: "jsx: needs `export default` of the page's component." };
+ return { ok: true, value: jsx };
+}
+
+function checkPage(input: Record<string, unknown>): AppInputResult<{ html: string } | { jsx: string } | { path: string }> {
+ const given = (value: unknown) => value !== undefined && value !== null;
+ if ([input.html, input.jsx, input.path].filter(given).length > 1) return { ok: false, error: "Send one of html, jsx or path." };
+ if (given(input.path)) {
+ const path = typeof input.path === "string" ? input.path.trim() : "";
+ if (!path || path.length > 4_096) return { ok: false, error: "path: the folder with index.html, or the .html file, in your working folder." };
+ return { ok: true, value: { path } };
+ }
+ if (given(input.jsx)) {
+ const jsx = checkJsx(input.jsx);
+ return jsx.ok ? { ok: true, value: { jsx: jsx.value } } : jsx;
+ }
+ const html = checkHtml(input.html);
+ return html.ok ? { ok: true, value: { html: html.value } } : html;
+}
+
+function checkTitle(value: unknown): AppInputResult<string> {
+ if (typeof value !== "string") return { ok: false, error: "title: must be a string of 1 to 80 characters." };
+ const title = oneLine(value);
+ if (!title || title.length > APP_LIMITS.title) return { ok: false, error: "title: must be 1 to 80 characters on one line." };
+ return { ok: true, value: title };
+}
+
+function checkFrameless(value: unknown): AppInputResult<boolean | undefined> {
+ if (value === undefined || value === null) return { ok: true, value: undefined };
+ if (typeof value !== "boolean") return { ok: false, error: "frameless: must be true or false." };
+ return { ok: true, value };
+}
+
+function checkLive(value: unknown, path: string | undefined): AppInputResult<boolean | undefined> {
+ if (value === undefined || value === null) return { ok: true, value: undefined };
+ if (typeof value !== "boolean") return { ok: false, error: "live: must be true or false." };
+ if (value && path === undefined) return { ok: false, error: "live: only a page from a folder (path) can be live." };
+ return { ok: true, value };
+}
+
+export function parseShowHtmlInput(input: unknown): AppInputResult<ShowHtmlInput> {
+ if (!isRecord(input)) return { ok: false, error: "show_html needs {html, jsx or path, title, height?, fallback_text?}." };
+ const page = checkPage(input);
+ if (!page.ok) return page;
+ const title = checkTitle(input.title);
+ if (!title.ok) return title;
+ const out: ShowHtmlInput = { ...page.value, title: title.value };
+ const frameless = checkFrameless(input.frameless);
+ if (!frameless.ok) return frameless;
+ if (frameless.value) out.frameless = true;
+ const live = checkLive(input.live, out.path);
+ if (!live.ok) return live;
+ if (live.value) out.live = true;
+ if (input.height !== undefined && input.height !== null) {
+ if (typeof input.height !== "number" || !Number.isFinite(input.height)) return { ok: false, error: "height: must be a number of pixels, 80 to 720." };
+ out.height = Math.round(Math.min(APP_LIMITS.heightMax, Math.max(APP_LIMITS.heightMin, input.height)));
+ }
+ if (input.fallback_text !== undefined && input.fallback_text !== null) {
+ if (typeof input.fallback_text !== "string") return { ok: false, error: "fallback_text: must be a string." };
+ const fallback = input.fallback_text.trim();
+ if (fallback.length > APP_LIMITS.fallback) return { ok: false, error: `fallback_text: must be at most ${APP_LIMITS.fallback} characters.` };
+ if (fallback) out.fallbackText = fallback;
+ }
+ return { ok: true, value: out };
+}
+
+export function parseUpdateHtmlInput(input: unknown): AppInputResult<UpdateHtmlInput> {
+ if (!isRecord(input)) return { ok: false, error: "Replacing a page needs {app_id, html, jsx or path, title?}." };
+ if (typeof input.app_id !== "string" || !/^[\w-]{1,128}$/.test(input.app_id.trim())) {
+ return { ok: false, error: "app_id: is required, the id show_html returned." };
+ }
+ const page = checkPage(input);
+ if (!page.ok) return page;
+ const out: UpdateHtmlInput = { appId: input.app_id.trim(), ...page.value };
+ const frameless = checkFrameless(input.frameless);
+ if (!frameless.ok) return frameless;
+ if (frameless.value !== undefined) out.frameless = frameless.value;
+ const live = checkLive(input.live, out.path);
+ if (!live.ok) return live;
+ if (live.value !== undefined) out.live = live.value;
+ if (input.title !== undefined && input.title !== null) {
+ const title = checkTitle(input.title);
+ if (!title.ok) return title;
+ out.title = title.value;
+ }
+ return { ok: true, value: out };
+}
+
+const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: "\"", apos: "'", nbsp: " ", "#39": "'" };
+
+/** A preview, not a parser or a sanitizer: it only ever feeds the row's readable fallback. */
+export function htmlVisibleText(html: string): string {
+ return html
+ .replace(/<!--[\s\S]*?(?:-->|$)/g, " ")
+ .replace(/<(script|style|template|noscript|title|head)\b[\s\S]*?(?:<\/\1\s*>|$)/gi, " ")
+ .replace(/<[^>]*>?/g, " ")
+ .replace(/&(#\d+|#x[\da-f]+|[a-z]+\d*);/gi, (whole, name: string) => {
+ const lower = name.toLowerCase();
+ if (ENTITIES[lower] !== undefined) return ENTITIES[lower]!;
+ const code = lower.startsWith("#x") ? Number.parseInt(lower.slice(2), 16) : lower.startsWith("#") ? Number.parseInt(lower.slice(1), 10) : NaN;
+ return Number.isFinite(code) && code > 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff) ? String.fromCodePoint(code) : whole;
+ })
+ .replace(/\s+/g, " ")
+ .trim();
+}
+
+function clip(text: string, limit: number): string {
+ return text.length <= limit ? text : `${text.slice(0, limit - 1).trimEnd()}…`;
+}
+
+export function htmlFallbackText(title: string, html: string, fallbackText?: string): string {
+ const given = fallbackText?.trim();
+ if (given) return clip(given, APP_LIMITS.fallback);
+ const visible = clip(htmlVisibleText(html), APP_LIMITS.fallbackExcerpt);
+ return clip(visible ? `[App] ${title}\n${visible}` : `[App] ${title}`, APP_LIMITS.fallback);
+}
+
+export function mcpAppFallbackText(serverTitle: string, toolTitle: string, result: { content?: unknown } | undefined): string {
+ const texts = Array.isArray(result?.content)
+ ? result.content.flatMap((block) => (isRecord(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []))
+ : [];
+ const excerpt = clip(oneLine(texts.join(" ")), APP_LIMITS.fallbackExcerpt);
+ const head = `${oneLine(serverTitle)} · ${oneLine(toolTitle)}`;
+ return clip(excerpt ? `${head}\n${excerpt}` : head, APP_LIMITS.fallback);
+}
+
+const httpsLink = (value: unknown): string | undefined =>
+ typeof value === "string" && value.length <= 2_048 && /^https:\/\/[^\s"'<>]+$/.test(value) ? value : undefined;
+const namedLink = (value: unknown): string | undefined => (isRecord(value) ? httpsLink(value.html_url) ?? httpsLink(value.url) : undefined);
+
+/** A JSON text block gives only its link; plain text gives the note's line and, failing a named link, its first
+ * https link. */
+export function appDoneOf(tool: string, result: { content?: unknown; structuredContent?: unknown }, at: number): AppDoneState {
+ let url = namedLink(result.structuredContent);
+ let text: string | undefined;
+ for (const block of Array.isArray(result.content) ? result.content : []) {
+ if (!isRecord(block) || block.type !== "text" || typeof block.text !== "string") continue;
+ const raw = block.text.trim();
+ let parsed: unknown;
+ try { parsed = /^[{[]/.test(raw) ? JSON.parse(raw) : undefined; } catch { parsed = undefined; }
+ if (parsed !== undefined) { url ??= namedLink(parsed); continue; }
+ url ??= httpsLink(/https:\/\/[^\s"'<>)\]]+/.exec(raw)?.[0]);
+ text ??= clip(oneLine(raw), APP_LIMITS.doneText) || undefined;
+ }
+ return { tool, ...(text ? { text } : {}), ...(url ? { url } : {}), at };
+}
+
+export function appBlockedText(reason: AppBlockedReason, server?: string): string {
+ const name = server?.trim() || "This app's server";
+ switch (reason) {
+ case "signed-out": return `Sign in to ${name} again`;
+ case "server-removed": return `${name} is no longer connected`;
+ case "server-disabled": return `${name} is switched off in Settings`;
+ case "apps-off": return `Apps from ${name} are switched off in Settings`;
+ case "too-large": return "This app is too large to store";
+ case "unavailable": return `${name} did not send this app's page`;
+ }
+}
diff --git a/packages/phone-protocol/src/approval-mode.ts b/packages/phone-protocol/src/approval-mode.ts
new file mode 100644
index 0000000000..029ad4e3c6
--- /dev/null
+++ b/packages/phone-protocol/src/approval-mode.ts
@@ -0,0 +1,112 @@
+/** The approval levels exposed by the app. Each one is a provider's own
+ * permission mode, passed through: OpenMausBot never decides a permission
+ * itself (Full access aside, which answers residual prompts because that is
+ * what the person granted). The order is the order the selector shows. */
+export const APPROVAL_MODES = ["ask", "edits", "auto", "full", "custom"] as const;
+
+export type ApprovalMode = (typeof APPROVAL_MODES)[number];
+
+/** Whether work at `level` lets nothing through that `limit` would stop; "custom" is comparable only to itself. */
+export const levelWithin = (level: ApprovalMode, limit: ApprovalMode): boolean =>
+ level === limit || (level !== "custom" && limit !== "custom" && APPROVAL_MODES.indexOf(level) < APPROVAL_MODES.indexOf(limit));
+
+/** Only providers with an implemented permission mapping may expose a level.
+ * `edits` (auto-accept edits) exists where the engine has such a mode:
+ * Claude and Grok `acceptEdits`, Antigravity `auto_edit`, Qwen `auto-edit`,
+ * Gemini `auto_edit`. Codex's Ask already runs `workspace-write`, so an edits
+ * level would change nothing there. Full access, the default level, runs on
+ * every engine: in the engine's own most permissive mode, or, where it has
+ * none, with the harness answering the permission requests it leaves (the
+ * chat-completions family, ACP agents such as Kimi or Hermes, Pi's computer
+ * confirms). */
+export function supportsApprovalMode(driverKind: string | undefined, mode: ApprovalMode): boolean {
+ if (mode === "custom") return driverKind === "codex";
+ if (mode === "edits") return ["claudeAgent", "grokAgent", "antigravityAgent", "qwenAgent", "geminiAgent"].includes(driverKind ?? "");
+ return true;
+}
+
+/** Whether switching engines must first drop this level to Ask. A Custom
+ * grant's rules belong to one provider's tool semantics, so it never crosses
+ * engines; Full carries silently to any engine; Auto-accept edits stops at an
+ * engine without it.
+ * Adapted from tahodev's provider-switch guard. */
+export function modelSwitchNeedsAsk(
+ mode: ApprovalMode,
+ fromDriver: string | undefined,
+ toDriver: string | undefined,
+): boolean {
+ return !supportsApprovalMode(toDriver, mode) || (mode === "custom" && fromDriver !== toDriver);
+}
+
+export function hasNativeAutoReview(driverKind: string | undefined): boolean {
+ // Qwen Code's `--approval-mode auto` is an LLM classifier that approves
+ // safe actions and blocks risky ones — a reviewer, not a rubber stamp.
+ return ["codex", "claudeAgent", "cursorAgent", "grokAgent", "qwenAgent"].includes(driverKind ?? "");
+}
+
+const APPROVAL_RANK: Record<ApprovalMode, number> = { ask: 0, edits: 1, auto: 2, full: 3, custom: 4 };
+
+export interface ApprovalFields {
+ approvalMode?: ApprovalMode;
+ autoApprove?: boolean;
+ alwaysAllow?: string[];
+}
+
+export function threadApproval(thread: ApprovalFields, bot: ApprovalFields): ApprovalFields {
+ return {
+ approvalMode: thread.approvalMode ?? (thread.autoApprove === undefined ? bot.approvalMode : undefined),
+ autoApprove: thread.autoApprove ?? bot.autoApprove,
+ alwaysAllow: structuredClone(thread.alwaysAllow ?? bot.alwaysAllow),
+ };
+}
+
+export function approvalModeWidens(from: ApprovalMode, to: ApprovalMode): boolean {
+ return APPROVAL_RANK[to] > APPROVAL_RANK[from];
+}
+
+export function isApprovalMode(value: unknown): value is ApprovalMode {
+ return typeof value === "string" && (APPROVAL_MODES as readonly string[]).includes(value);
+}
+
+/** The level a bot or conversation runs at until a person picks one: Full
+ * access, as in t3code (its DEFAULT_RUNTIME_MODE). Each provider maps it to
+ * its own most permissive mode; a real question or a missing credential
+ * still reaches a person. */
+export const DEFAULT_APPROVAL_MODE: ApprovalMode = "full";
+
+let defaultApprovalMode: ApprovalMode = DEFAULT_APPROVAL_MODE;
+
+/** On a shared company workspace Full access comes only from the operator's
+ * own policy, so its server makes Ask the default once, at startup. */
+export function setDefaultApprovalMode(mode: ApprovalMode): void {
+ defaultApprovalMode = mode;
+}
+
+/** An unset level runs at the default, the pre-approvalMode Auto bit reads as
+ * safe Auto, and an unknown persisted value fails closed to Ask. */
+export function approvalModeFor(bot: {
+ approvalMode?: unknown;
+ autoApprove?: unknown;
+ /** Server-only two-phase grant marker. Until Electron confirms it, the
+ * stored elevated selection is deliberately executable only as Ask. */
+ approvalGrant?: unknown;
+ threadId?: string;
+}): ApprovalMode {
+ const grant = bot.approvalGrant;
+ const otherThread = grant && typeof grant === "object" && "threadOnly" in grant && grant.threadOnly === true &&
+ "threadId" in grant && typeof grant.threadId === "string" && typeof bot.threadId === "string" && grant.threadId !== bot.threadId;
+ if (grant && !otherThread) return "ask";
+ if (isApprovalMode(bot.approvalMode)) return bot.approvalMode;
+ if (bot.autoApprove === true) return "auto";
+ return bot.approvalMode === undefined ? defaultApprovalMode : "ask";
+}
+
+/** A private late-grant recovery may revoke an elevated mode even after a
+ * turn began. It can only move to the fail-closed Ask mode, and it also stops
+ * the running turn, which a native engine would otherwise finish elevated. */
+export function isEmergencyApprovalDowngrade(
+ current: ApprovalMode,
+ next: ApprovalMode,
+): boolean {
+ return next === "ask" && (current === "full" || current === "custom");
+}
diff --git a/packages/phone-protocol/src/ask-question.ts b/packages/phone-protocol/src/ask-question.ts
new file mode 100644
index 0000000000..a767596187
--- /dev/null
+++ b/packages/phone-protocol/src/ask-question.ts
@@ -0,0 +1,400 @@
+/**
+ * Structured questions from a provider's own "ask the human" tool, Claude
+ * Code's `AskUserQuestion`. The CLI routes it through --permission-prompt-tool
+ * like any tool use, so it is re-read here into the questions posed. The
+ * payload is bot-authored: validated rather than cast, and capped.
+ */
+
+export const ASK_USER_QUESTION_TOOL = "AskUserQuestion";
+export const QUESTION_DISMISS_MESSAGE = "The user closed this question without answering. Use your best judgment and continue.";
+
+/** Claude Code's own limits are 1-4 questions and 2-4 options; these leave
+ * room for a provider that widens them. */
+export const MAX_QUESTIONS = 6;
+export const MAX_OPTIONS = 12;
+export const MAX_QUESTION_TEXT = 8_000;
+const MAX_LABEL = 120;
+const MAX_DESCRIPTION = 400;
+export const MAX_CUSTOM_ANSWER = 2000;
+
+export interface AskQuestionOption {
+ label: string;
+ description?: string;
+}
+
+export interface AskQuestion {
+ question: string;
+ /** Short tab label the model gives each question ("Schedule", "Model"). */
+ header?: string;
+ multiSelect?: boolean;
+ options: AskQuestionOption[];
+ /** false when the provider can only take an option back (an ACP
+ * permission-style question answers with an option id): no free text. */
+ custom?: false;
+}
+
+export interface QuestionRequestCardData {
+ version: 1;
+ questions: AskQuestion[];
+ /** "tool" (or absent): a real tool call; "output": a block parsed from
+ * model-authored output. Only drives the agent-composed badge. */
+ origin?: "tool" | "output";
+}
+
+/** Excludes the other durable proposal card kinds that share requestId. */
+export function isPersistentQuestionCard(card?: {
+ requestType?: "permission" | "question";
+ questionRequest?: unknown;
+ tool?: string;
+ routineRequest?: unknown;
+ skillRequest?: unknown;
+ profileRequest?: unknown;
+ modelRequest?: unknown;
+ teamSetupRequest?: unknown;
+} | null): boolean {
+ return Boolean(card && (
+ card.requestType === "question" || card.questionRequest ||
+ (!card.requestType && !card.tool && !card.routineRequest && !card.skillRequest && !card.profileRequest &&
+ !card.modelRequest && !card.teamSetupRequest)
+ ));
+}
+
+/** System/provider completion ends the live run, not the human's question. */
+export function shouldSettleRequestCard(card: Parameters<typeof isPersistentQuestionCard>[0], source: "user" | "auto" | "timeout" | "system" | "unavailable" | "peer"): boolean {
+ return !isPersistentQuestionCard(card) || source === "user";
+}
+
+function text(value: unknown, limit: number): string | undefined {
+ if (typeof value !== "string") return undefined;
+ const trimmed = value.trim();
+ return trimmed ? trimmed.slice(0, limit).trim() : undefined;
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return typeof value === "object" && value !== null && !Array.isArray(value);
+}
+
+function parseOption(value: unknown): AskQuestionOption | null {
+ // Not the documented shape, but accepted.
+ if (typeof value === "string") {
+ const label = text(value, MAX_LABEL);
+ return label ? { label } : null;
+ }
+ if (!isRecord(value)) return null;
+ const label = text(value.label, MAX_LABEL);
+ if (!label) return null;
+ const description = text(value.description, MAX_DESCRIPTION);
+ return description ? { label, description } : { label };
+}
+
+function parseQuestion(value: unknown): AskQuestion | null {
+ if (!isRecord(value)) return null;
+ const question = text(value.question, MAX_QUESTION_TEXT);
+ if (!question) return null;
+ const options: AskQuestionOption[] = [];
+ const seen = new Set<string>();
+ for (const raw of Array.isArray(value.options) ? value.options : []) {
+ const option = parseOption(raw);
+ // Duplicate labels: the answer text could not say which row was picked.
+ if (!option || seen.has(option.label)) continue;
+ seen.add(option.label);
+ options.push(option);
+ if (options.length === MAX_OPTIONS) break;
+ }
+ // An empty option list is kept: the card always offers free text.
+ const header = text(value.header, MAX_LABEL);
+ return {
+ question,
+ ...(header ? { header } : {}),
+ ...(value.multiSelect === true ? { multiSelect: true } : {}),
+ options,
+ // only meaningful beside options: with none, free text is the only answer
+ ...(value.custom === false && options.length ? { custom: false as const } : {}),
+ };
+}
+
+/** null when the payload is not one; a malformed call gets the ordinary card. */
+export function parseAskQuestions(input: unknown): AskQuestion[] | null {
+ if (!isRecord(input) || !Array.isArray(input.questions)) return null;
+ const questions: AskQuestion[] = [];
+ for (const raw of input.questions) {
+ const question = parseQuestion(raw);
+ if (!question) continue;
+ questions.push(question);
+ if (questions.length === MAX_QUESTIONS) break;
+ }
+ return questions.length ? questions : null;
+}
+
+/** Codex request_user_input_async's `{ title, options: string[] | null }` entries in the card's shape. Null unless one
+ * offers an option: a bare question already reads in the message text. */
+export function parseAsyncQuestions(entries: unknown): AskQuestion[] | null {
+ if (!Array.isArray(entries)) return null;
+ const questions = parseAskQuestions({
+ questions: entries.map((entry) => (isRecord(entry) ? { question: entry.title, options: entry.options } : null)),
+ });
+ return questions?.some((question) => question.options.length > 0) ? questions : null;
+}
+
+/** The one line the card subtitle and a spoken prompt show. */
+export function askQuestionSummary(questions: readonly AskQuestion[]): string {
+ const first = questions[0]?.question ?? "";
+ const rest = questions.length - 1;
+ return rest > 0 ? `${first} (+${rest} more question${rest > 1 ? "s" : ""})` : first;
+}
+
+/** The tool advertises "2-5 suggested answers". */
+export const MAX_CHOICES = 5;
+
+/**
+ * A model that has seen AskUserQuestion may hand over `{ label, description }`
+ * rows instead of strings (MiniMax M3 does). Anything else is dropped: React
+ * refuses a non-string child.
+ */
+export function parseChoices(input: unknown, limit = MAX_CHOICES): string[] | undefined {
+ if (!Array.isArray(input)) return undefined;
+ const choices: string[] = [];
+ const seen = new Set<string>();
+ for (const raw of input) {
+ const label = typeof raw === "string" ? text(raw, MAX_LABEL) : isRecord(raw) ? text(raw.label, MAX_LABEL) : undefined;
+ if (!label || seen.has(label)) continue;
+ seen.add(label);
+ choices.push(label);
+ if (choices.length === limit) break;
+ }
+ return choices.length ? choices : undefined;
+}
+
+/** For clients that only render a list of choices: only a single question can
+ * be answered that way. */
+export function questionChoices(questions: readonly AskQuestion[]): string[] | undefined {
+ if (questions.length !== 1) return undefined;
+ const only = questions[0]!;
+ if (only.multiSelect || only.options.length < 2) return undefined;
+ return only.options.map((option) => option.label);
+}
+
+/** The chat runtime's ask tool. Named ask_user so the ASKS_A_PERSON backstop
+ * covers it: no auto mode may answer a question. */
+export const ASK_USER_TOOL = "ask_user";
+
+/** Shaped for an OpenAI function-calling tool list. The parser enforces the caps
+ * again: a model-authored argument is not a guarantee it followed the schema. */
+export const ASK_USER_TOOL_DEFINITION = {
+ type: "function",
+ function: {
+ name: ASK_USER_TOOL,
+ description:
+ "Ask the person questions when the decision is theirs. Offer concrete options where they exist; they can always answer in their own words. Ask up to six questions in one call rather than one at a time.",
+ parameters: {
+ type: "object",
+ properties: {
+ questions: {
+ type: "array",
+ minItems: 1,
+ maxItems: MAX_QUESTIONS,
+ items: {
+ type: "object",
+ properties: {
+ question: { type: "string", description: "The question to show the person." },
+ header: { type: "string", description: "A short label for the question's tab." },
+ multiSelect: { type: "boolean", description: "Whether several options may be picked." },
+ options: {
+ type: "array",
+ maxItems: MAX_OPTIONS,
+ description: "Suggested answers; the person may always write their own.",
+ items: {
+ type: "object",
+ properties: {
+ label: { type: "string" },
+ description: { type: "string" },
+ },
+ required: ["label"],
+ additionalProperties: false,
+ },
+ },
+ },
+ required: ["question"],
+ additionalProperties: false,
+ },
+ },
+ },
+ required: ["questions"],
+ additionalProperties: false,
+ },
+ },
+} as const;
+
+/** The answer is delivered on the deny channel, so it says what it is; the card
+ * strips it back off for display. */
+export const ANSWER_PREAMBLE = "The user answered your questions.";
+const JSON_ANSWERS_PREFIX = `${ANSWER_PREAMBLE}\n\nAnswers (JSON):\n`;
+
+/** Arrives as the tool's result, so it names each question and what was picked. */
+export function formatQuestionAnswers(
+ questions: readonly AskQuestion[],
+ answers: readonly (readonly string[])[],
+): string {
+ const pairs: [string, string][] = [];
+ questions.forEach((question, index) => {
+ const picked = (answers[index] ?? []).map((value) => value.trim()).filter(Boolean);
+ if (!picked.length) return;
+ pairs.push([question.question, picked.join(", ")]);
+ });
+ if (!pairs.length) return "";
+ // Newlines can contain Q:/A: headers; JSON preserves them as answer text.
+ if (pairs.some(pair => pair.some(value => /[\r\n]/.test(value)))) {
+ return JSON_ANSWERS_PREFIX + JSON.stringify(pairs);
+ }
+ return `${ANSWER_PREAMBLE}\n\n${pairs.map(([question, answer]) => `Q: ${question}\nA: ${answer}`).join("\n\n")}`;
+}
+
+export function answerWithoutPreamble(answer: string): string {
+ return answer.startsWith(`${ANSWER_PREAMBLE}\n\n`) ? answer.slice(ANSWER_PREAMBLE.length + 2) : answer;
+}
+
+/** Sized so a reply typed in a card is never cut; only a longer chat message echoed back as free text is. */
+export const MAX_ANSWER_ECHO = ANSWER_PREAMBLE.length + MAX_QUESTIONS
+ * ("\n\nQ: \nA: ".length + MAX_QUESTION_TEXT + MAX_OPTIONS * (MAX_LABEL + ", ".length) + MAX_CUSTOM_ANSWER);
+
+/** Cut back to the last whole block, so no partial answer reads as one. */
+export function capAnswerEcho(answer: string, limit = MAX_ANSWER_ECHO): string {
+ if (answer.length <= limit) return answer;
+ const cut = answer.slice(0, limit);
+ const boundary = cut.lastIndexOf("\n\nQ: ");
+ const kept = boundary > 0 ? cut.slice(0, boundary) : cut;
+ return kept + "\n\n[answer truncated]";
+}
+
+/**
+ * The card sends one answer for the whole set; `formatQuestionAnswers` writes
+ * each question's text beside its answer, so the map is recovered rather than
+ * guessed. A message with no blocks is filed only when there is exactly one
+ * question.
+ */
+export function questionAnswersByQuestion(
+ message: string,
+ questions: readonly AskQuestion[],
+): Record<string, string> {
+ return questionAnswersById(message, questions.map(question => ({ id: question.question, question })));
+}
+
+/**
+ * One answer read back as picked option labels plus the person's own words, for a protocol that answers by option.
+ * The card joins multi-select labels with ", " and a label may contain ", ": every reading is tried, a reading that
+ * is labels end to end wins, and when the best readings disagree the whole answer is own words, never a guessed option.
+ */
+export function pickedOptionLabels(answer: string, question: AskQuestion): { labels: string[]; other?: string } {
+ const text = answer.trim();
+ const labels = question.options.map((option) => option.label);
+ if (!question.multiSelect) {
+ if (labels.includes(text)) return { labels: [text] };
+ return text ? { labels: [], other: text } : { labels: [] };
+ }
+ const whole: string[][] = [];
+ const partial: Array<{ labels: string[]; other: string }> = [];
+ const read = (rest: string, picked: string[]): void => {
+ const next = labels.filter((label) => !picked.includes(label) && (rest === label || rest.startsWith(`${label}, `)));
+ if (!next.length) {
+ if (rest) partial.push({ labels: picked, other: rest });
+ else whole.push(picked);
+ return;
+ }
+ for (const label of next) read(rest.slice(label.length + 2), [...picked, label]);
+ };
+ read(text, []);
+ const key = (reading: { labels: string[]; other?: string }) => JSON.stringify([[...reading.labels].sort(), reading.other ?? null]);
+ const readings = whole.length ? whole.map((picked) => ({ labels: picked })) : partial;
+ const first = readings[0]!;
+ const agree = readings.every((reading) => key(reading) === key(first));
+ return agree ? first : { labels: [], other: text };
+}
+
+/** Ids ride the reply, so they are capped like the rest. */
+const MAX_QUESTION_ID = 200;
+
+/** Ids live only in the protocol; the card never sees them. */
+export interface ProtocolAskQuestion {
+ id: string;
+ question: AskQuestion;
+}
+
+/** Entries carry their own string ids (codex's item/tool/requestUserInput). An
+ * entry without a usable id and question is skipped; nothing answerable parses
+ * to null. */
+export function parseProtocolAskQuestions(entries: unknown): ProtocolAskQuestion[] | null {
+ if (!Array.isArray(entries)) return null;
+ const parsed: ProtocolAskQuestion[] = [];
+ const seenIds = new Set<string>();
+ for (const raw of entries) {
+ if (!isRecord(raw)) continue;
+ const question = parseQuestion(raw);
+ // Echoed back verbatim, so preserved exactly and an overlong id rejected
+ // whole. A duplicate id fails the request: two questions cannot share one
+ // answer slot.
+ const id = raw.id;
+ if (!question || typeof id !== "string" || !id.trim() || id.length > MAX_QUESTION_ID) continue;
+ if (seenIds.has(id)) return null;
+ seenIds.add(id);
+ parsed.push({ id, question });
+ if (parsed.length === MAX_QUESTIONS) break;
+ }
+ return parsed.length ? parsed : null;
+}
+
+/** A card reply answers by question text, so it cannot tell two questions with the same text apart. */
+export function repeatsQuestionText(questions: readonly ProtocolAskQuestion[]): boolean {
+ return new Set(questions.map(({ question }) => question.question)).size !== questions.length;
+}
+
+/**
+ * Answers by id (codex's requestUserInput). Only ids with a real block are
+ * answered; without blocks, the whole message answers a lone question.
+ */
+export function questionAnswersById(
+ message: string,
+ questions: readonly ProtocolAskQuestion[],
+): Record<string, string> {
+ const answers: Record<string, string> = Object.create(null);
+ const idByText = new Map<string, string>();
+ const ambiguous = new Set<string>();
+ for (const { id, question } of questions) {
+ if (idByText.has(question.question)) {
+ // Identical question text cannot be told apart in a block: neither is answered.
+ ambiguous.add(question.question);
+ continue;
+ }
+ idByText.set(question.question, id);
+ }
+ if (message.startsWith(JSON_ANSWERS_PREFIX)) {
+ let pairs: unknown;
+ try { pairs = JSON.parse(message.slice(JSON_ANSWERS_PREFIX.length)); }
+ catch { return {}; }
+ if (!Array.isArray(pairs) || !pairs.every(pair => Array.isArray(pair) && pair.length === 2 && pair.every(value => typeof value === "string"))) return {};
+ for (const [asked, answer] of pairs as [string, string][]) {
+ const id = idByText.get(asked);
+ if (id && !ambiguous.has(asked) && answer.trim()) answers[id] = answer;
+ }
+ return answers;
+ }
+ // A block runs from one Q: header to the next; blank lines inside an answer
+ // are the answer's.
+ const blocks = message.matchAll(/(?:^|\n\n)Q: ([\s\S]+?)\nA: ([\s\S]*?)(?=\n\nQ: |$)/g);
+ let sawBlock = false;
+ for (const match of blocks) {
+ sawBlock = true;
+ const asked = match[1]!.trim();
+ if (ambiguous.has(asked)) continue;
+ const id = idByText.get(asked);
+ const answer = match[2]!.trim();
+ // A blank A: is no answer.
+ if (id && answer) answers[id] = answer;
+ }
+ if (Object.keys(answers).length) return answers;
+ // A reply that matched a block is authoritative even when it answered
+ // nothing, or the literal Q:/A: text would be filed as the answer.
+ if (sawBlock) return {};
+ const only = questions.length === 1 ? questions[0] : undefined;
+ const flat = message.trim();
+ return only && flat ? { [only.id]: flat } : {};
+}
diff --git a/packages/phone-protocol/src/bot-access.ts b/packages/phone-protocol/src/bot-access.ts
new file mode 100644
index 0000000000..cb90837ab7
--- /dev/null
+++ b/packages/phone-protocol/src/bot-access.ts
@@ -0,0 +1,72 @@
+// Who may see, chat with and change a Team Cloud bot. Four levels, lowest first; a person's level is the highest of what
+// everyone in the team gets and what they were given. Admins and the bot's owner can always edit, so neither is listed.
+import type { BotVisibility } from "./wire.ts";
+
+export const BOT_ACCESS_LEVELS = ["none", "view", "chat", "edit"] as const;
+export type BotAccessLevel = (typeof BOT_ACCESS_LEVELS)[number];
+export type GrantedLevel = Exclude<BotAccessLevel, "none">;
+export const GRANTED_LEVELS: readonly GrantedLevel[] = ["view", "chat", "edit"];
+
+/** A Team Cloud bot's sharing. `everyone` is what every member of the team may do ("none": only the people added);
+ * `people` gives each added person a level by lowercased address. An `@domain` entry, which only an older list carries,
+ * covers that domain's addresses. */
+export interface BotAccess {
+ everyone: BotAccessLevel;
+ people: Record<string, GrantedLevel>;
+}
+
+export interface BotAccessFields {
+ /** Team Cloud only, and only on the copy sent to someone who can edit the bot: who may see, chat with and change it. */
+ access?: BotAccess;
+ /** Team Cloud only: what the person this copy was sent to may do with the bot. */
+ yourAccess?: BotAccessLevel;
+ /** Team Cloud only, on everyone's copy: only the people added, whoever looks after the bot and the admins see it, so
+ * its shared chats reach no further. */
+ onlyPeopleAdded?: true;
+}
+
+export const levelRank = (level: BotAccessLevel | undefined): number => BOT_ACCESS_LEVELS.indexOf(level ?? "none");
+export const atLeast = (level: BotAccessLevel | undefined, wanted: BotAccessLevel): boolean => levelRank(level) >= levelRank(wanted);
+export const higherLevel = (a: BotAccessLevel, b: BotAccessLevel): BotAccessLevel => (atLeast(a, b) ? a : b);
+export const isAccessLevel = (value: unknown): value is BotAccessLevel => (BOT_ACCESS_LEVELS as readonly unknown[]).includes(value);
+
+/** A bot nobody set sharing for: what its older visibility setting meant. Everyone could chat with an everyone bot, the
+ * listed people with a listed one, and only admins (who edit every bot) with an admins-only one. */
+export function accessFromVisibility(visibility: BotVisibility | undefined): BotAccess {
+ if (visibility === undefined || visibility === "everyone") return { everyone: "chat", people: {} };
+ if (visibility === "admins") return { everyone: "none", people: {} };
+ return { everyone: "none", people: Object.fromEntries(visibility.people.map((entry) => [entry.trim().toLowerCase(), "chat" as const])) };
+}
+
+/** Who sees the bot at all: everyone when every member may at least view it, else its owner and the people added, else
+ * admins only. */
+export function visibilityFromAccess(access: BotAccess, owner: string | null): BotVisibility {
+ if (access.everyone !== "none") return "everyone";
+ const people = [...new Set([...(owner ? [owner] : []), ...Object.keys(access.people)])];
+ return people.length ? { people } : "admins";
+}
+
+export function entryMatches(entry: string, email: string): boolean {
+ return entry.startsWith("@") ? email.endsWith(entry) && email.length > entry.length : entry === email;
+}
+
+/** What this address may do by the bot's sharing alone, before admins and the owner. */
+export function sharedLevel(access: BotAccess, email: string): BotAccessLevel {
+ const address = email.trim().toLowerCase();
+ let level = access.everyone;
+ if (!address) return level;
+ for (const [entry, granted] of Object.entries(access.people)) if (entryMatches(entry, address)) level = higherLevel(level, granted);
+ return level;
+}
+
+export function sameAccess(a: BotAccess, b: BotAccess): boolean {
+ const left = Object.entries(a.people), right = b.people;
+ return a.everyone === b.everyone && left.length === Object.keys(right).length && left.every(([entry, level]) => right[entry] === level);
+}
+
+export interface AccessRequestCardField {
+ /** Someone who can view a team bot asks the person this card is in front of to let them chat with it. */
+ accessRequest?: { botId: string; botName: string; email: string; name: string };
+}
+
+export const ACCESS_REQUEST_OPTIONS = ["Allow", "Not now"] as const;
diff --git a/packages/phone-protocol/src/bot-avatar.ts b/packages/phone-protocol/src/bot-avatar.ts
new file mode 100644
index 0000000000..e359281c73
--- /dev/null
+++ b/packages/phone-protocol/src/bot-avatar.ts
@@ -0,0 +1,86 @@
+import { z } from "zod";
+
+export const MASCOT_FACE_COLORS = ["white", "black"] as const;
+export const mascotFaceColorSchema = z.enum(MASCOT_FACE_COLORS);
+export type MascotFaceColor = z.infer<typeof mascotFaceColorSchema>;
+
+export function mascotFaceInk(value: unknown): string | undefined {
+ const color = mascotFaceColorSchema.safeParse(value).data;
+ return color === "white" ? "#ffffff" : color === "black" ? "#000000" : undefined;
+}
+
+/**
+ * `mascot` draws the animated mascot body, filled with the bot's colour
+ * gradient. `circle`, `rounded`, and `square` crop the bot's own image
+ * instead, shown as it is, with no mascot at all.
+ */
+export const BOT_AVATAR_CROPS = ["mascot", "circle", "rounded", "square"] as const;
+export const botAvatarCropSchema = z.enum(BOT_AVATAR_CROPS);
+export type BotAvatarCrop = z.infer<typeof botAvatarCropSchema>;
+
+/** CSS radius for a profile crop. Mascot is drawn, not photo-cropped, so it is not clipped. */
+export function avatarCropRadius(crop: BotAvatarCrop): string {
+ if (crop === "circle") return "50%";
+ if (crop === "rounded") return "22%";
+ return "0";
+}
+
+/** 1 shows the picture with object-fit cover. Larger values zoom in. */
+export const AVATAR_ZOOM_MIN = 1;
+export const AVATAR_ZOOM_MAX = 3;
+/** The point of the picture kept in the middle of the crop, from 0 to 1. */
+export const AVATAR_FOCUS_CENTER = 0.5;
+
+export function clampAvatarZoom(value: unknown): number {
+ const parsed = typeof value === "number" ? value : Number.NaN;
+ if (!Number.isFinite(parsed)) return AVATAR_ZOOM_MIN;
+ const clamped = Math.min(AVATAR_ZOOM_MAX, Math.max(AVATAR_ZOOM_MIN, parsed));
+ return Math.round(clamped * 100) / 100;
+}
+
+export function clampAvatarFocus(value: unknown): number {
+ const parsed = typeof value === "number" ? value : Number.NaN;
+ if (!Number.isFinite(parsed)) return AVATAR_FOCUS_CENTER;
+ const clamped = Math.min(1, Math.max(0, parsed));
+ return Math.round(clamped * 1000) / 1000;
+}
+
+/**
+ * Custom avatars are deliberately limited to this app's attachment server.
+ * Besides making persisted profiles portable across desktop/browser clients,
+ * this prevents a bot profile from becoming an external tracking pixel or a
+ * script-capable SVG.
+ */
+export const botAvatarUrlSchema = z
+ .string()
+ .regex(
+ /^\/api\/attachments\/[A-Za-z0-9-]+\.(?:png|jpg|gif|webp)$/,
+ "must be a stored PNG, JPEG, GIF, or WebP attachment",
+ );
+
+export function botAvatarUrlFromStoredPath(path: string): string | null {
+ const name = path.replaceAll("\\", "/").split("/").pop();
+ if (!name) return null;
+ const url = `/api/attachments/${name}`;
+ return botAvatarUrlSchema.safeParse(url).success ? url : null;
+}
+
+/** Runtime-safe defaults for untrusted persisted/SSE profile data. */
+export interface BotAvatarProfileInput {
+ avatarUrl?: unknown;
+ avatarCrop?: unknown;
+}
+
+export interface BotAvatarProfile {
+ avatarUrl?: string;
+ avatarCrop: BotAvatarCrop;
+}
+
+export function botAvatarProfile(value: BotAvatarProfileInput): BotAvatarProfile {
+ const profile: BotAvatarProfile = {
+ avatarCrop: botAvatarCropSchema.safeParse(value.avatarCrop).data ?? "mascot",
+ };
+ const url = botAvatarUrlSchema.safeParse(value.avatarUrl);
+ if (url.success) profile.avatarUrl = url.data;
+ return profile;
+}
diff --git a/packages/phone-protocol/src/bot-body.ts b/packages/phone-protocol/src/bot-body.ts
new file mode 100644
index 0000000000..5d3e076a79
--- /dev/null
+++ b/packages/phone-protocol/src/bot-body.ts
@@ -0,0 +1,63 @@
+/** Every body a bot can wear: the gradient catalog plus the festival bodies. */
+
+import { z } from "zod";
+
+import { DEFAULT_MASCOT_BODY, MASCOT_BODY_IDS } from "./mascot-bodies.ts";
+import { CARVED_BODY_IDS, DIWALI_BODY_IDS, HALLOWEEN_BODY_IDS, type CarvedBodyId } from "./carved-bodies.ts";
+import type { MausColor } from "./wire.ts";
+
+export const BOT_BODY_IDS = [...MASCOT_BODY_IDS, ...CARVED_BODY_IDS] as const;
+
+export type BotBodyId = (typeof BOT_BODY_IDS)[number];
+
+export const botBodySchema = z.enum(BOT_BODY_IDS);
+
+/** Runtime-safe read of an untrusted persisted or streamed body id. */
+export function botBodyId(value: unknown): BotBodyId {
+ return botBodySchema.safeParse(value).data ?? DEFAULT_MASCOT_BODY;
+}
+
+export function isCarvedBody(value: unknown): value is CarvedBodyId {
+ return (CARVED_BODY_IDS as readonly unknown[]).includes(value);
+}
+
+export type CostumeColor = Exclude<MausColor, "silver" | "chrome">;
+
+/** A festival skin's own bodies, and the costume each bot colour wears while "Dress my bots up" is on with it. */
+const festival = <Id extends CarvedBodyId>(bodies: readonly Id[], costumes: Record<CostumeColor, NoInfer<Id>>) => ({ bodies, costumes });
+
+/** Keyed by the skin id that turns each festival on. */
+export const FESTIVALS = {
+ halloween: festival(HALLOWEEN_BODY_IDS, {
+ orange: "pumpkin",
+ purple: "ghost",
+ teal: "witch",
+ red: "bat",
+ blue: "cat",
+ cyan: "skull",
+ green: "monster",
+ yellow: "mummy",
+ coral: "vampire",
+ pink: "spider",
+ }),
+ diwali: festival(DIWALI_BODY_IDS, {
+ orange: "laddu",
+ purple: "chakri",
+ teal: "karanji",
+ red: "rocket",
+ blue: "bomb",
+ cyan: "chakli",
+ green: "anaar",
+ yellow: "katli",
+ coral: "jalebi",
+ pink: "sparkler",
+ }),
+};
+
+export type FestivalId = keyof typeof FESTIVALS;
+
+export const FESTIVAL_IDS = Object.keys(FESTIVALS) as FestivalId[];
+
+export function isFestival(value: unknown): value is FestivalId {
+ return typeof value === "string" && Object.hasOwn(FESTIVALS, value);
+}
diff --git a/packages/phone-protocol/src/burst.ts b/packages/phone-protocol/src/burst.ts
new file mode 100644
index 0000000000..2f8d8a474e
--- /dev/null
+++ b/packages/phone-protocol/src/burst.ts
@@ -0,0 +1,55 @@
+/** One burst: one person's task split into many threads of the same bot, run in parallel, merged into one result. */
+export type BurstPhase = "preview" | "running" | "merging" | "done" | "cancelled";
+export type BurstChildStatus = "queued" | "running" | "done" | "failed" | "cancelled";
+export type BurstCounts = Record<BurstChildStatus, number>;
+
+/** The card in the parent chat: a preview until the person presses Run, then the one progress card, patched in place. It
+ * carries counts only, and the rows come from GET /api/bursts/<id>, so a card stays one small row however large the burst. */
+export interface BurstCardData {
+ version: 1;
+ burstId: string;
+ botId: string;
+ task: string;
+ phase: BurstPhase;
+ /** Tasks that run. */
+ total: number;
+ /** Tasks the bot proposed: more than `total` when the plan's task limit cut the list. */
+ requested: number;
+ /** How many run at once here. */
+ parallel: number;
+ /** The plan's most tasks per burst, set when it cut this list. */
+ taskLimit?: number;
+ /** Set on a plan where a higher one runs more at once. */
+ smallPlan?: true;
+ modelName: string;
+ /** A rough figure for the preview, in minutes. */
+ estimateMinutes: number;
+ counts: BurstCounts;
+ /** The first few tasks, for the preview. */
+ sample: string[];
+ /** Parts that did not finish, named once the burst settles, with `failedMore` counting past the ones listed. */
+ failed?: BurstFailure[];
+ failedMore?: number;
+}
+
+export interface BurstFailure {
+ title: string;
+ reason: string;
+}
+
+/** One part of a burst, as GET /api/bursts/<id> lists it. `threadId` is absent until it starts. */
+export interface BurstChildRow {
+ seq: number;
+ title: string;
+ status: BurstChildStatus;
+ threadId?: string;
+ error?: string;
+}
+
+export interface BurstView {
+ burstId: string;
+ phase: BurstPhase;
+ instructions: string;
+ items: string[];
+ children: BurstChildRow[];
+}
diff --git a/packages/phone-protocol/src/carved-bodies.ts b/packages/phone-protocol/src/carved-bodies.ts
new file mode 100644
index 0000000000..4bbd5ab892
--- /dev/null
+++ b/packages/phone-protocol/src/carved-bodies.ts
@@ -0,0 +1,321 @@
+/**
+ * The festival bodies a bot can wear, drawn flat with a carved face.
+ *
+ * GENERATED FILE — do not hand-edit. Run `pnpm gen:carved` to rebuild it from
+ * `scripts/gen-carved-bodies.ts`.
+ *
+ * Drawn flat: the bot's own colour (or a pale or fixed stand-in), a few fixed-colour accents
+ * and a carved face. Paths are in a 240-unit square centred on x = 120.
+ */
+
+/** Every Halloween body id, in the order the picker shows them. */
+export const HALLOWEEN_BODY_IDS = ["pumpkin", "ghost", "witch", "bat", "cat", "skull", "monster", "mummy", "vampire", "spider"] as const;
+
+export type HalloweenBodyId = (typeof HALLOWEEN_BODY_IDS)[number];
+
+/** Every Diwali body id, in the order the picker shows them. */
+export const DIWALI_BODY_IDS = ["rocket", "anaar", "chakri", "sparkler", "bomb", "laddu", "chakli", "jalebi", "katli", "karanji"] as const;
+
+export type DiwaliBodyId = (typeof DIWALI_BODY_IDS)[number];
+
+export const CARVED_BODY_IDS = [...HALLOWEEN_BODY_IDS, ...DIWALI_BODY_IDS] as const;
+
+export type CarvedBodyId = (typeof CARVED_BODY_IDS)[number];
+
+export interface CarvedEyes {
+ /** Rest position of the pair's centre. */
+ cx: number;
+ cy: number;
+ /** Half the distance between the two eyes. */
+ dx: number;
+ /** Resting pill size. */
+ w: number;
+ h: number;
+ /** Diameter when startled. */
+ round: number;
+ ink: string;
+ /** False when the drawing carries its own mouth. */
+ mouth: boolean;
+ mouthInk: string;
+ /** Where the smile sits when it can't hang under the eyes. */
+ mouthY: number | null;
+}
+
+export interface CarvedBody {
+ id: CarvedBodyId;
+ /** Human-readable name, used for the picker and the accessible label. */
+ name: string;
+ /** "bot" fills with the bot's colour, "pale" with a near-white tint of it, "bone" with `bone`. */
+ paint: "bot" | "pale" | "bone";
+ bone: string | null;
+ eyes: CarvedEyes;
+ /** Where the eyes may show. */
+ clip: string;
+ /** Draw order, bottom first. "body" is the paint; "accent" is the bot's colour. */
+ parts: ReadonlyArray<{ fill: string; d: string }>;
+}
+
+export const CARVED_BODIES: Record<CarvedBodyId, CarvedBody> = {
+ pumpkin: {
+ id: "pumpkin",
+ name: "Pumpkin",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 152, dx: 35, w: 28, h: 56, round: 50, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M90.5 54.48 C77.98 56.31 67.02 63.37 58.51 72.5 C55.95 75.24 53.91 78.51 51.11 81 C47.33 84.36 42.38 85.53 38 87.83 C32.54 90.69 27.86 94.89 24 99.66 C0.95 128.17 1.01 181.52 24.97 209.5 C31.03 216.58 39.12 222.26 48.5 223.66 C53.49 224.41 58.74 223.08 63.5 225.16 C66.21 226.35 68.43 228.42 70.9 230 C78.54 234.9 87.38 237.89 96.5 238 C102.12 238.06 107.73 237.03 113 235.08 C114.66 234.46 118.98 231.87 120.5 232.13 C121.68 232.33 127.39 235.28 129.5 235.93 C135.79 237.88 142.47 238.48 149 237.59 C156.48 236.58 163.59 233.66 169.87 229.5 C172.18 227.96 174.28 226.04 176.89 225 C181.28 223.25 185.94 224.33 190.5 223.8 C198.11 222.91 205.1 219.14 210.69 214 C238.8 188.15 239.54 131.34 217.5 101.6 C212.81 95.28 206.78 89.78 199.5 86.63 C196.43 85.31 193.26 84.22 190.5 82.26 C185.59 78.78 182.01 72.7 177.5 68.51 C167.37 59.12 153.97 53.16 140 54.1 C134.84 54.45 129.76 55.71 125 57.71 C123.69 58.27 121.86 59.64 120.5 59.87 C119.38 60.06 111.9 56.48 110 55.92 C103.69 54.04 97.01 53.52 90.5 54.48 Z",
+ parts: [
+ { fill: "#3d3d3d", d: "M94.5 3.93 C90.73 5.44 88.5 9.55 89.93 13.5 C91.2 17 95.18 19.44 97.5 22.28 C101.77 27.51 104.88 33.56 106.89 40 C109.27 47.63 110.3 56.02 109.8 64 C109.52 68.57 107.41 72.89 108.74 77.5 C110.77 84.55 118.63 88.55 125.5 85.93 C135.23 82.22 133.7 73.67 132.84 65.5 C130.89 47.14 126.81 30.93 114.5 16.5 C110.8 12.16 100.82 1.39 94.5 3.93 Z" },
+ { fill: "body", d: "M90.5 54.48 C77.98 56.31 67.02 63.37 58.51 72.5 C55.95 75.24 53.91 78.51 51.11 81 C47.33 84.36 42.38 85.53 38 87.83 C32.54 90.69 27.86 94.89 24 99.66 C0.95 128.17 1.01 181.52 24.97 209.5 C31.03 216.58 39.12 222.26 48.5 223.66 C53.49 224.41 58.74 223.08 63.5 225.16 C66.21 226.35 68.43 228.42 70.9 230 C78.54 234.9 87.38 237.89 96.5 238 C102.12 238.06 107.73 237.03 113 235.08 C114.66 234.46 118.98 231.87 120.5 232.13 C121.68 232.33 127.39 235.28 129.5 235.93 C135.79 237.88 142.47 238.48 149 237.59 C156.48 236.58 163.59 233.66 169.87 229.5 C172.18 227.96 174.28 226.04 176.89 225 C181.28 223.25 185.94 224.33 190.5 223.8 C198.11 222.91 205.1 219.14 210.69 214 C238.8 188.15 239.54 131.34 217.5 101.6 C212.81 95.28 206.78 89.78 199.5 86.63 C196.43 85.31 193.26 84.22 190.5 82.26 C185.59 78.78 182.01 72.7 177.5 68.51 C167.37 59.12 153.97 53.16 140 54.1 C134.84 54.45 129.76 55.71 125 57.71 C123.69 58.27 121.86 59.64 120.5 59.87 C119.38 60.06 111.9 56.48 110 55.92 C103.69 54.04 97.01 53.52 90.5 54.48 Z" },
+ ],
+ },
+ ghost: {
+ id: "ghost",
+ name: "Ghost",
+ paint: "pale",
+ bone: null,
+ eyes: {cx: 120, cy: 112, dx: 32, w: 26, h: 52, round: 44, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M111.5 18.45 C102.67 19.45 94.05 21.8 86 25.58 C79.38 28.69 73.19 32.71 67.66 37.5 C55.69 47.85 46.96 61.73 42.81 77 C41.15 83.07 41.21 88.17 40.02 93.5 C39.67 95.08 38.72 96.36 38.5 97.97 C37.5 105.16 38.47 113.18 38.11 120.5 C37.62 130.51 36.53 140.51 35.71 150.5 C34.9 160.48 34.46 170.57 33.23 180.5 C32.61 185.5 30.7 190.45 30.58 195.5 C30.54 197.24 31.38 198.4 31.89 200 C33.45 204.88 34.26 209.22 38 213.1 C45.27 220.62 57.05 222.23 65.9 216.5 C68.85 214.59 75.17 206.54 75.27 206.5 C75.82 206.31 76.48 206.39 77 206.65 C77.78 207.05 82.14 213.41 84 214.97 C91.11 220.92 101.63 221.6 109.5 216.75 C112.96 214.63 119.13 206.55 119.27 206.5 C121.64 205.67 124.14 210.98 125.45 212.5 C129.1 216.73 134.46 219.4 140 219.91 C146.43 220.5 153.1 218.15 157.61 213.5 C158.94 212.13 161.82 207.01 163.27 206.5 C165.61 205.68 168.9 212.06 170.5 213.61 C175.27 218.25 181.86 220.62 188.5 219.86 C196.53 218.94 203.54 213.52 206.49 206 C207.26 204.04 207.48 201.99 208.11 200 C208.44 198.97 209.07 198.05 209.32 197 C210.25 193.16 207.29 184.77 206.77 180.5 C205.35 169.08 204.85 157.47 203.92 146 C203.19 137.02 202.16 128.01 201.83 119 C201.57 112.11 202.45 104.83 201.5 98 C201.28 96.4 200.36 95.14 200 93.58 C199.55 91.62 199.57 89.5 199.31 87.5 C198.7 82.92 197.7 78.4 196.32 74 C190.52 55.58 178.01 39.62 161.5 29.61 C154.53 25.38 146.92 22.23 139 20.29 C130.06 18.1 120.66 17.42 111.5 18.45 Z",
+ parts: [
+ { fill: "body", d: "M111.5 18.45 C102.67 19.45 94.05 21.8 86 25.58 C79.38 28.69 73.19 32.71 67.66 37.5 C55.69 47.85 46.96 61.73 42.81 77 C41.15 83.07 41.21 88.17 40.02 93.5 C39.67 95.08 38.72 96.36 38.5 97.97 C37.5 105.16 38.47 113.18 38.11 120.5 C37.62 130.51 36.53 140.51 35.71 150.5 C34.9 160.48 34.46 170.57 33.23 180.5 C32.61 185.5 30.7 190.45 30.58 195.5 C30.54 197.24 31.38 198.4 31.89 200 C33.45 204.88 34.26 209.22 38 213.1 C45.27 220.62 57.05 222.23 65.9 216.5 C68.85 214.59 75.17 206.54 75.27 206.5 C75.82 206.31 76.48 206.39 77 206.65 C77.78 207.05 82.14 213.41 84 214.97 C91.11 220.92 101.63 221.6 109.5 216.75 C112.96 214.63 119.13 206.55 119.27 206.5 C121.64 205.67 124.14 210.98 125.45 212.5 C129.1 216.73 134.46 219.4 140 219.91 C146.43 220.5 153.1 218.15 157.61 213.5 C158.94 212.13 161.82 207.01 163.27 206.5 C165.61 205.68 168.9 212.06 170.5 213.61 C175.27 218.25 181.86 220.62 188.5 219.86 C196.53 218.94 203.54 213.52 206.49 206 C207.26 204.04 207.48 201.99 208.11 200 C208.44 198.97 209.07 198.05 209.32 197 C210.25 193.16 207.29 184.77 206.77 180.5 C205.35 169.08 204.85 157.47 203.92 146 C203.19 137.02 202.16 128.01 201.83 119 C201.57 112.11 202.45 104.83 201.5 98 C201.28 96.4 200.36 95.14 200 93.58 C199.55 91.62 199.57 89.5 199.31 87.5 C198.7 82.92 197.7 78.4 196.32 74 C190.52 55.58 178.01 39.62 161.5 29.61 C154.53 25.38 146.92 22.23 139 20.29 C130.06 18.1 120.66 17.42 111.5 18.45 Z" },
+ ],
+ },
+ witch: {
+ id: "witch",
+ name: "Witch",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 174, dx: 30, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M70 115.37 C64.92 118.19 58.38 126.61 55.15 131.5 C39.04 155.88 40.93 187.85 59.5 210.37 C83.52 239.49 127.61 245.99 160 227.52 C193.86 208.21 206.9 166.06 185.5 132.5 C182.23 127.37 176.01 119.21 170.88 116 C168.88 114.75 156.18 116.17 153 116.31 C138.51 116.93 124 117.12 109.5 116.93 C100 116.81 90.49 116.52 81 116.03 C79.79 115.97 70.33 115.19 70 115.37 Z",
+ parts: [
+ { fill: "#3d3d3d", d: "M56 93.43 C43.48 96.13 40.36 109.2 37.78 120 C31.5 146.29 30.56 174.43 35.74 201 C37.12 208.09 38.78 215.1 40.92 222 C41.86 225.03 42.59 228.55 45.34 230.5 C50.73 234.32 58.38 230.12 57.98 223.5 C57.72 219 56.75 214.51 56.42 210 C55.7 200 56.02 189.96 57.07 180 C57.37 177.15 58.02 166.48 61 165.64 C63.18 165.03 66.49 167.44 68.5 168.11 C72.91 169.6 77.38 170 82 170 C105.5 170 129 170 152.5 170 C158.59 170 164.6 170.23 170.5 168.43 C172.53 167.82 177.65 164.86 179.5 165.82 C181.99 167.11 182.45 176.27 182.79 179 C184.42 191.91 184.37 205.09 182.77 218 C182.17 222.84 180.96 227.92 186 230.93 C187.77 231.99 190.01 232.27 192 231.75 C196.36 230.6 197.5 226.81 198.73 223 C201.11 215.63 202.91 208.12 204.32 200.5 C208.97 175.34 208.61 149 203.13 124 C201.42 116.16 199.23 104.47 193.5 98.63 C188.23 93.26 179.97 91.56 173 94.34 C168.24 96.23 164.9 99.79 159.5 100 C144.55 100.56 129.46 100 114.5 100 C103.07 100 91.41 100.67 80 99.98 C70.75 99.42 67.69 90.9 56 93.43 Z" },
+ { fill: "body", d: "M111 98.49 C99.92 99.78 89.16 103.16 79.5 108.77 C71.23 113.57 63.85 119.91 58.01 127.5 C52.95 134.08 49.07 141.54 46.7 149.5 C31.29 201.28 80.43 243.45 130 237.39 C141.09 236.03 151.91 232.4 161.5 226.64 C169.36 221.92 176.39 215.78 181.99 208.5 C186.73 202.34 190.44 195.4 192.83 188 C209.5 136.52 160.9 92.7 111 98.49 Z" },
+ { fill: "#3d3d3d", d: "M177 10.96 C138.98 13.21 103.23 27.45 85.12 63 C81.33 70.43 77.84 78.65 76.85 87 C76.55 89.52 76.75 91.99 76.61 94.5 C76.56 95.51 76.17 96.49 76.14 97.5 C76 101.4 77.46 105.9 78.82 109.5 C85.72 127.81 104.52 139.6 124 137.82 C143.59 136.03 160 120.88 163.36 101.5 C163.9 98.37 164.65 94.14 163.9 91 C162.95 87.07 162.41 82.91 161.16 79 C158.31 70.02 153.98 63.41 156.17 53.5 C158.71 41.94 167.43 31.98 176.22 24.5 C178.98 22.16 184.33 18.67 186.45 16.5 C187.23 15.7 187.64 14.61 187.46 13.5 C186.74 9 180.07 10.78 177 10.96 Z" },
+ { fill: "accent", d: "M81 72.19 C79.92 73.17 77.55 82.62 77.22 84.5 C77.21 84.56 76.73 87.42 76.79 87.5 C77.5 88.43 80.51 88 81.5 88 C86.5 88 91.5 88 96.5 88 C113 88 129.5 88 146 88 C150 88 154 88 158 88 C158.41 88 162.39 88.09 162.5 88 C163.43 87.24 162.51 84.38 162.33 83.5 C161.84 81.07 159.9 72.86 157.5 72 C155.93 71.44 142.27 72 139.5 72 C126 72 112.5 72 99 72 C94.5 72 90 72 85.5 72 C84.65 72 81.67 71.58 81 72.19 Z" },
+ { fill: "#3d3d3d", d: "M92.5 82.49 C70.51 83.29 48.05 84.51 26.5 89.19 C21.5 90.28 16.04 91.43 11.56 94 C9.93 94.93 7.19 96.67 8.22 99 C9.82 102.64 17.9 104.67 21.5 105.62 C34.2 108.96 47.45 110.39 60.5 111.56 C99.75 115.07 139.74 115.08 179 111.6 C192.04 110.44 217.43 108.32 228.44 102 C234.96 98.26 231.04 94.96 226 92.83 C217.57 89.26 208 87.94 199 86.66 C163.9 81.67 127.88 81.21 92.5 82.49 Z" },
+ ],
+ },
+ bat: {
+ id: "bat",
+ name: "Bat",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 142, dx: 28, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M78.5 28.29 C74.93 30.19 75.47 37.8 75.15 41.5 C74.53 48.5 73.91 55.5 73.29 62.5 C72.9 66.96 72.85 71.64 71.75 76 C70.83 79.6 68.82 85.6 64.5 86.26 C59.64 87 48.75 76.45 44 74 C41.3 72.61 37.88 71.96 35 71 C27.5 68.5 20 66 12.5 63.5 C8.5 62.17 4.5 60.83 0.5 59.5 C-0.78 59.07 -2.92 57.58 -3.85 59.5 C-4.29 60.4 -3.66 61.5 -3.56 62.5 C-3.1 67.12 -0.34 68.8 2.57 72 C7.4 77.32 10.12 84.29 10 91.5 C9.9 96.81 8.27 102.08 5.32 106.5 C4.31 108.01 3.03 109.34 2.25 111 C1.43 112.74 1.01 118.51 2.5 119.97 C3.97 121.42 10.69 121.29 13 121.89 C18.65 123.35 23.67 126.57 27.45 131 C31.02 135.19 33.25 140.53 33.84 146 C34.08 148.27 33.22 153.18 34.21 155 C35.72 157.76 38.05 155.63 40 154.7 C43.58 153 47.39 152.47 50.08 156 C52.67 159.38 53.61 164.19 55.5 168 C58.57 174.19 62.54 179.93 67.25 185 C89.14 208.58 125.04 214.65 153.5 199.73 C165.15 193.62 175.01 184.28 181.77 173 C184.06 169.17 188.57 157.24 190.5 155.3 C193.16 152.64 196.34 153.04 199.5 154.47 C200.95 155.13 203.95 157.59 205.5 155.79 C206.74 154.34 205.93 148.54 206.11 146.5 C206.6 141.11 208.67 135.94 212 131.68 C215.97 126.61 221.72 123.03 228 121.65 C230.52 121.1 236.88 121.57 238.04 119 C238.13 118.81 238.37 116.21 238.39 116 C238.8 111.43 236.27 109.16 234.05 105.5 C231.32 101.01 229.91 95.75 230 90.5 C230.12 83.91 232.62 77.44 236.98 72.5 C239.99 69.1 243.08 67.35 243.56 62.5 C243.66 61.5 244.29 60.4 243.85 59.5 C242.92 57.58 240.78 59.07 239.5 59.5 C235.5 60.83 231.5 62.17 227.5 63.5 C220 66 212.5 68.5 205 71 C202.11 71.96 198.7 72.62 196 74 C191.23 76.44 180.37 87 175.5 86.26 C171.18 85.6 169.16 79.6 168.25 76 C167.15 71.64 167.1 66.96 166.71 62.5 C166.09 55.5 165.47 48.5 164.85 41.5 C164.54 37.89 165.2 28.63 160.5 28.03 C156.82 27.56 152.58 35.31 150.59 38 C146.75 43.2 137.29 57.47 133 60.83 C130.83 62.53 128.21 63.45 125.5 63.81 C123.5 64.08 121.51 63.99 119.5 64 C109.03 64.05 106.48 61.1 100.5 53.01 C97.5 48.95 94.5 44.89 91.5 40.83 C89.48 38.09 84.84 30.64 82.5 28.88 C81.44 28.09 79.75 27.63 78.5 28.29 Z",
+ parts: [
+ { fill: "body", d: "M78.5 28.29 C74.93 30.19 75.47 37.8 75.15 41.5 C74.53 48.5 73.91 55.5 73.29 62.5 C72.9 66.96 72.85 71.64 71.75 76 C70.83 79.6 68.82 85.6 64.5 86.26 C59.64 87 48.75 76.45 44 74 C41.3 72.61 37.88 71.96 35 71 C27.5 68.5 20 66 12.5 63.5 C8.5 62.17 4.5 60.83 0.5 59.5 C-0.78 59.07 -2.92 57.58 -3.85 59.5 C-4.29 60.4 -3.66 61.5 -3.56 62.5 C-3.1 67.12 -0.34 68.8 2.57 72 C7.4 77.32 10.12 84.29 10 91.5 C9.9 96.81 8.27 102.08 5.32 106.5 C4.31 108.01 3.03 109.34 2.25 111 C1.43 112.74 1.01 118.51 2.5 119.97 C3.97 121.42 10.69 121.29 13 121.89 C18.65 123.35 23.67 126.57 27.45 131 C31.02 135.19 33.25 140.53 33.84 146 C34.08 148.27 33.22 153.18 34.21 155 C35.72 157.76 38.05 155.63 40 154.7 C43.58 153 47.39 152.47 50.08 156 C52.67 159.38 53.61 164.19 55.5 168 C58.57 174.19 62.54 179.93 67.25 185 C89.14 208.58 125.04 214.65 153.5 199.73 C165.15 193.62 175.01 184.28 181.77 173 C184.06 169.17 188.57 157.24 190.5 155.3 C193.16 152.64 196.34 153.04 199.5 154.47 C200.95 155.13 203.95 157.59 205.5 155.79 C206.74 154.34 205.93 148.54 206.11 146.5 C206.6 141.11 208.67 135.94 212 131.68 C215.97 126.61 221.72 123.03 228 121.65 C230.52 121.1 236.88 121.57 238.04 119 C238.13 118.81 238.37 116.21 238.39 116 C238.8 111.43 236.27 109.16 234.05 105.5 C231.32 101.01 229.91 95.75 230 90.5 C230.12 83.91 232.62 77.44 236.98 72.5 C239.99 69.1 243.08 67.35 243.56 62.5 C243.66 61.5 244.29 60.4 243.85 59.5 C242.92 57.58 240.78 59.07 239.5 59.5 C235.5 60.83 231.5 62.17 227.5 63.5 C220 66 212.5 68.5 205 71 C202.11 71.96 198.7 72.62 196 74 C191.23 76.44 180.37 87 175.5 86.26 C171.18 85.6 169.16 79.6 168.25 76 C167.15 71.64 167.1 66.96 166.71 62.5 C166.09 55.5 165.47 48.5 164.85 41.5 C164.54 37.89 165.2 28.63 160.5 28.03 C156.82 27.56 152.58 35.31 150.59 38 C146.75 43.2 137.29 57.47 133 60.83 C130.83 62.53 128.21 63.45 125.5 63.81 C123.5 64.08 121.51 63.99 119.5 64 C109.03 64.05 106.48 61.1 100.5 53.01 C97.5 48.95 94.5 44.89 91.5 40.83 C89.48 38.09 84.84 30.64 82.5 28.88 C81.44 28.09 79.75 27.63 78.5 28.29 Z" },
+ ],
+ },
+ cat: {
+ id: "cat",
+ name: "Cat",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 156, dx: 36, w: 27, h: 52, round: 46, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M48 25.42 C46.77 26.16 46.14 26.51 45.5 27.83 C44.09 30.74 43.01 40.74 42.34 44.5 C39.14 62.5 35.94 80.5 32.74 98.5 C31.46 105.73 28.94 112.44 27.09 119.5 C26.44 121.96 26.44 124.52 25.93 127 C25.3 130.04 24.17 132.96 23.51 136 C21.02 147.42 21.66 159.39 25.27 170.5 C29.81 184.46 38.78 196.64 50 205.99 C85.42 235.47 140.72 237.75 179.5 213.57 C186.45 209.23 192.84 204.02 198.4 198 C210.43 184.96 218 167.87 218 150 C218 141.88 215.96 135.26 214.18 127.5 C213.61 125.03 213.61 122.47 213.04 120 C211.96 115.44 210.13 111.04 208.95 106.5 C206.39 96.7 205.12 86.47 203.35 76.5 C201.03 63.5 198.72 50.5 196.41 37.5 C195.71 33.57 195.94 26.16 191 25.1 C187.51 24.35 184.88 27.92 182.63 30 C176.13 36 169.63 42 163.13 48 C157.65 53.05 146.41 64.8 140.5 67.87 C138.17 69.08 135.61 69.79 133 70.1 C130.41 70.4 108.36 70.34 106 69.96 C98.34 68.74 93.44 63.3 88 58.27 C79.78 50.68 71.55 43.09 63.33 35.5 C60.5 32.89 52.07 22.98 48 25.42 Z",
+ parts: [
+ { fill: "body", d: "M48 25.42 C46.77 26.16 46.14 26.51 45.5 27.83 C44.09 30.74 43.01 40.74 42.34 44.5 C39.14 62.5 35.94 80.5 32.74 98.5 C31.46 105.73 28.94 112.44 27.09 119.5 C26.44 121.96 26.44 124.52 25.93 127 C25.3 130.04 24.17 132.96 23.51 136 C21.02 147.42 21.66 159.39 25.27 170.5 C29.81 184.46 38.78 196.64 50 205.99 C85.42 235.47 140.72 237.75 179.5 213.57 C186.45 209.23 192.84 204.02 198.4 198 C210.43 184.96 218 167.87 218 150 C218 141.88 215.96 135.26 214.18 127.5 C213.61 125.03 213.61 122.47 213.04 120 C211.96 115.44 210.13 111.04 208.95 106.5 C206.39 96.7 205.12 86.47 203.35 76.5 C201.03 63.5 198.72 50.5 196.41 37.5 C195.71 33.57 195.94 26.16 191 25.1 C187.51 24.35 184.88 27.92 182.63 30 C176.13 36 169.63 42 163.13 48 C157.65 53.05 146.41 64.8 140.5 67.87 C138.17 69.08 135.61 69.79 133 70.1 C130.41 70.4 108.36 70.34 106 69.96 C98.34 68.74 93.44 63.3 88 58.27 C79.78 50.68 71.55 43.09 63.33 35.5 C60.5 32.89 52.07 22.98 48 25.42 Z" },
+ ],
+ },
+ skull: {
+ id: "skull",
+ name: "Skull",
+ paint: "bone",
+ bone: "#f1ede6",
+ eyes: {cx: 120, cy: 112, dx: 34, w: 42, h: 44, round: 50, ink: "#0d0a10", mouth: false, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M111 16.48 C60.53 22.23 26.1 71.09 38.54 120.5 C40.96 130.13 45.1 139.31 50.72 147.5 C55.37 154.28 61.54 159.58 64.33 167.5 C66.25 172.92 65.77 178.38 66.35 184 C66.91 189.5 67.86 194.95 67.98 200.5 C68.17 209.19 66.13 215.91 73.45 222.5 C80.55 228.89 89.65 228 98.5 228 C111 228 123.5 228 136 228 C141.94 228 148.08 228.45 154 227.91 C161.84 227.19 170.56 221.74 171.93 213.5 C172.59 209.54 171.97 205.49 172 201.5 C172.05 195.44 173.12 189.51 173.7 183.5 C174.04 180.01 173.78 176.47 174.27 173 C174.64 170.41 175.44 167.92 176.42 165.5 C179.29 158.45 185.28 153.4 189.5 147.18 C196.53 136.81 201.2 124.89 203.06 112.5 C211.17 58.67 165.37 10.29 111 16.48 Z",
+ parts: [
+ { fill: "body", d: "M111 16.48 C60.53 22.23 26.1 71.09 38.54 120.5 C40.96 130.13 45.1 139.31 50.72 147.5 C55.37 154.28 61.54 159.58 64.33 167.5 C66.25 172.92 65.77 178.38 66.35 184 C66.91 189.5 67.86 194.95 67.98 200.5 C68.17 209.19 66.13 215.91 73.45 222.5 C80.55 228.89 89.65 228 98.5 228 C111 228 123.5 228 136 228 C141.94 228 148.08 228.45 154 227.91 C161.84 227.19 170.56 221.74 171.93 213.5 C172.59 209.54 171.97 205.49 172 201.5 C172.05 195.44 173.12 189.51 173.7 183.5 C174.04 180.01 173.78 176.47 174.27 173 C174.64 170.41 175.44 167.92 176.42 165.5 C179.29 158.45 185.28 153.4 189.5 147.18 C196.53 136.81 201.2 124.89 203.06 112.5 C211.17 58.67 165.37 10.29 111 16.48 Z" },
+ { fill: "#0d0a10", d: "M108.5 149.4 C107.57 150.05 107 150.82 107 152 C107 154.18 114.28 164.52 115.84 167 C116.89 168.68 118.36 171.98 121 170.83 C123.26 169.84 129.3 158.78 131 156.06 C132.04 154.39 134.17 151.94 132.23 150 C130.51 148.28 117.13 149 114 149 C112.48 149 109.83 148.48 108.5 149.4 Z" },
+ { fill: "#0d0a10", d: "M94.5 187.86 C90.92 189.52 93.89 198.41 92.8 199.5 C91.51 200.79 82.21 198.69 80.5 200.4 C80.09 200.81 79.82 201.42 79.8 202 C79.71 204.75 83.35 204.2 85 204.2 C85.71 204.2 92.43 204.13 92.5 204.2 C94.27 205.97 90.74 214.92 94.5 216.14 C99.5 217.76 95.66 205.52 98 204.2 C98.87 203.71 100 204.2 101 204.2 C102.15 204.2 104.56 203.68 105.3 205 C106.51 207.15 103.11 216.05 107.5 216.2 C112.34 216.36 107.39 205.23 111 204.2 C111.96 203.93 113 204.2 114 204.2 C115 204.2 116.13 203.71 117 204.2 C118.31 204.94 117.8 210.08 117.8 211.5 C117.8 213.04 117.59 217.08 120.5 216.14 C124.04 215 121.14 205.56 122.2 204.5 C122.63 204.07 123.39 204.26 124 204.2 C124.45 204.16 129.99 204.19 130 204.2 C131.77 205.97 128.24 214.92 132 216.14 C134.91 217.08 134.7 213.04 134.7 211.5 C134.7 210.08 134.19 204.94 135.5 204.2 C136.37 203.71 137.5 204.2 138.5 204.2 C139.5 204.2 140.54 203.93 141.5 204.2 C141.99 204.34 142.55 204.56 142.8 205 C143.36 206 142.47 212.32 142.8 214 C143.12 215.64 144.94 217.16 146.5 215.6 C148.29 213.81 146.31 206.57 147.2 205 C148.42 202.83 156.88 205.32 159 203.96 C159.52 203.62 159.95 203.09 160.14 202.5 C161.24 199.11 155.62 199.8 154 199.8 C153.08 199.8 148.56 200.12 148 199.8 C145.66 198.48 149.5 186.24 144.5 187.86 C140.96 189 143.86 198.44 142.8 199.5 C142.42 199.88 140.04 199.8 139.5 199.8 C139.14 199.8 135.05 199.85 135 199.8 C133.92 198.72 136.59 184.88 131.5 188.04 C128.44 189.94 132 198.39 129.5 199.8 C128.63 200.29 127.5 199.8 126.5 199.8 C125.35 199.8 122.94 200.32 122.2 199 C120.99 196.85 124.39 187.95 120 187.8 C115.16 187.64 120.11 198.77 116.5 199.8 C115.54 200.07 114.5 199.8 113.5 199.8 C112.5 199.8 111.37 200.29 110.5 199.8 C108.57 198.71 110.45 191.48 109.64 189.5 C108.87 187.61 106.74 187.14 105.54 189 C104.68 190.34 105.78 199.02 105.3 199.5 C104.92 199.88 102.54 199.8 102 199.8 C101.64 199.8 97.55 199.85 97.5 199.8 C96.32 198.62 99.05 185.75 94.5 187.86 Z" },
+ ],
+ },
+ monster: {
+ id: "monster",
+ name: "Monster",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 156, dx: 36, w: 27, h: 52, round: 46, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M62.5 85.83 C62.35 85.86 59.77 89.26 59.5 89.6 C57.48 92.13 51.44 101.28 48.5 101.5 C45.58 101.72 39.42 92.42 37.5 90.01 C36.59 88.88 34.53 86.24 34.5 86.25 C33.82 86.47 34 93.06 34 94 C34 102 34 110 34 118 C34 142 34 166 34 190 C34 201.71 32.25 214.47 41 223.75 C50.98 234.33 65.82 232 79 232 C103 232 127 232 151 232 C159.5 232 179.87 233.04 187 231.04 C196.89 228.27 204.38 219.67 205.76 209.5 C206.8 201.92 206 189.13 206 181 C206 162 206 143 206 124 C206 114.5 206 105 206 95.5 C206 92.69 206.04 86.51 206 86.5 C205.02 86.17 202.97 89.42 202.51 90 C200.52 92.51 195.5 100.01 193 101.23 C192.11 101.67 190.85 101.54 190 101.08 C188.02 99.98 182.32 91.88 180.5 89.6 C180.27 89.3 177.53 85.83 177.5 85.83 C176.98 85.81 174.43 89.26 174 89.8 C171.93 92.41 166.13 101.35 163 101.5 C160.25 101.63 153.88 92.16 152 89.8 C151.76 89.5 149.08 86.05 149 86.04 C147.81 85.89 146.09 88.85 145.5 89.6 C143.48 92.13 137.44 101.28 134.5 101.5 C130.72 101.78 122.19 86.67 120.5 86.25 C119.09 85.89 117.64 88.58 117 89.39 C115.13 91.74 108.86 100.75 106.5 101.4 C101.99 102.65 94.55 87.55 92.04 86.5 C90.19 85.73 88.38 89.32 87.5 90.43 C85.52 92.92 79.68 101.98 76.5 101.46 C73.7 101.01 67.54 91.73 65.5 89.18 C65.15 88.73 62.92 85.74 62.5 85.83 Z",
+ parts: [
+ { fill: "#8d8d8d", d: "M14.5 180.29 C13.19 180.99 12.59 181.55 12.13 183 C11.71 184.32 11.73 193.65 12.13 195 C12.45 196.1 13.06 196.94 14.07 197.5 C16.14 198.66 31.56 198 35 198 C37.29 198 40.56 198.62 42.5 197.12 C44.75 195.37 44.74 182.84 42.64 181 C40.99 179.55 38.5 180 36.5 180 C33.26 180 16.22 179.38 14.5 180.29 Z M198.5 180.29 C197.19 180.99 196.59 181.55 196.13 183 C195.71 184.32 195.73 193.65 196.13 195 C196.45 196.1 197.06 196.94 198.07 197.5 C200.14 198.66 215.56 198 219 198 C221.29 198 224.56 198.62 226.5 197.12 C228.75 195.37 228.74 182.84 226.64 181 C224.99 179.55 222.5 180 220.5 180 C217.26 180 200.22 179.38 198.5 180.29 Z" },
+ { fill: "#6f6f6f", d: "M6 174.34 C2.94 176.55 4 181.14 4 184.5 C4 188.39 3.35 197.74 4.04 201 C4.3 202.25 4.84 203.05 6 203.66 C7.59 204.49 10.27 204 12 204 C13.45 204 15.23 204.3 16.5 203.37 C18.94 201.57 18 197.12 18 194.5 C18 191.27 18.73 176.79 17 175.05 C15.47 173.52 12.94 174 11 174 C9.71 174 7.11 173.53 6 174.34 Z M224 174.34 C220.94 176.55 222 181.14 222 184.5 C222 188.39 221.35 197.74 222.04 201 C222.3 202.25 222.84 203.05 224 203.66 C225.59 204.49 228.27 204 230 204 C231.45 204 233.23 204.3 234.5 203.37 C236.94 201.57 236 197.12 236 194.5 C236 191.27 236.73 176.79 235 175.05 C233.47 173.52 230.94 174 229 174 C227.71 174 225.11 173.53 224 174.34 Z" },
+ { fill: "body", d: "M55 22.49 C44.2 24.71 35.73 33.52 34.24 44.5 C33.64 48.92 34 53.55 34 58 C34 96 34 134 34 172 C34 180 34 188 34 196 C34 200.93 33.53 206.14 34.49 211 C35.1 214.13 36.29 217.16 38 219.86 C46.73 233.59 60.38 232 74.5 232 C99 232 123.5 232 148 232 C156.48 232 178.53 232.92 185.5 231.41 C196.07 229.12 204.3 220.22 205.76 209.5 C206.43 204.6 206 199.44 206 194.5 C206 157 206 119.5 206 82 C206 74 206 66 206 58 C206 53.07 206.47 47.86 205.51 43 C204.9 39.87 203.71 36.84 202 34.14 C193.01 20 178.47 22 164 22 C140 22 116 22 92 22 C83.69 22 61.8 21.08 55 22.49 Z" },
+ { fill: "#3d3d3d", d: "M55 18.42 C42.19 20.59 32 31.13 30.27 44 C29.41 50.36 30 57.09 30 63.5 C30 68 30 72.5 30 77 C30 77.97 29.55 80.79 30.5 81.5 C31.3 82.1 32.64 81.26 33.5 81.78 C34.97 82.67 36.42 85.45 37.5 86.8 C38.91 88.58 46.34 98.67 47.5 99.24 C49.39 100.17 50.54 97.63 51.45 96.5 C54.13 93.13 56.82 89.76 59.5 86.38 C59.73 86.1 62.49 82.62 62.5 82.62 C62.95 82.64 64.72 84.99 65 85.34 C67.67 88.69 70.33 92.04 73 95.38 C73.82 96.42 75.75 100.08 77.5 99.41 C78.97 98.85 86.46 88.53 88 86.59 C88.24 86.3 90.94 82.83 91 82.83 C92.18 82.73 93.9 85.63 94.5 86.38 C97.17 89.73 99.83 93.08 102.5 96.43 C103.26 97.39 104.41 99.72 106 99.46 C106.95 99.31 115.23 88.4 116.5 86.8 C116.79 86.44 119.31 83.08 119.5 83.04 C120.91 82.68 122.36 85.37 123 86.18 C125.67 89.52 128.33 92.87 131 96.22 C131.72 97.12 133.05 99.61 134.5 99.49 C135.82 99.38 137.28 96.71 138 95.8 C139.12 94.4 147.45 83.47 148 83.25 C149.78 82.5 151.66 86.16 152.5 87.22 C153.82 88.88 161.68 99.49 163 99.5 C164.27 99.51 172.2 88.86 173.5 87.22 C174.35 86.16 176.2 82.54 178 83.25 C178.45 83.42 186.93 94.46 188 95.8 C188.74 96.74 190.2 99.31 191.5 99.49 C192.89 99.69 194.33 97.06 195 96.22 C197.98 92.48 200.96 88.74 203.94 85 C204.62 84.14 205.16 83.13 206 82.41 C207.66 80.98 209.21 82.38 210 80 C210.52 78.45 210 67.49 210 65 C210 50.51 211.96 36.41 200 25.64 C188.98 15.71 173.68 18 160 18 C137 18 114 18 91 18 C82.08 18 62.75 17.11 55 18.42 Z" },
+ ],
+ },
+ mummy: {
+ id: "mummy",
+ name: "Mummy",
+ paint: "bone",
+ bone: "#efe5cf",
+ eyes: {cx: 120, cy: 119, dx: 30, w: 24, h: 24, round: 30, ink: "#f4efe4", mouthInk: "#0d0a10", mouthY: 170, mouth: true},
+ clip: "M201.5 97.49 C164.5 98.63 127.5 99.77 90.5 100.91 C78 101.29 65.5 101.68 53 102.06 C48.3 102.21 42.56 101.73 38 102.52 C37.48 102.61 36.82 102.58 36.5 103 C36.25 103.33 36.5 109.62 36.5 110.5 C36.5 118 36.5 125.5 36.5 133 C36.5 133.71 36.42 140.42 36.5 140.5 C36.65 140.65 44.6 140.32 45.5 140.29 C55 140 64.5 139.71 74 139.42 C105.5 138.45 137 137.48 168.5 136.51 C177 136.25 185.5 135.98 194 135.72 C195.18 135.69 202.47 135.84 203 135.45 C203.86 134.81 203.5 127.83 203.5 126.5 C203.5 119 203.5 111.5 203.5 104 C203.5 103.31 203.7 98.26 203.5 98 C203.04 97.39 202.15 97.47 201.5 97.49 Z",
+ parts: [
+ { fill: "body", d: "M111 14.48 C76.78 18.38 47.65 43.09 38.8 76.5 C34.8 91.61 36 107.52 36 123 C36 140.11 34.75 157.49 40.13 174 C52.39 211.67 90.69 236.12 130 231.4 C163.8 227.35 192.49 202.41 201.2 169.5 C205.2 154.39 204 138.48 204 123 C204 105.89 205.25 88.51 199.87 72 C187.78 34.85 149.95 10.05 111 14.48 Z" },
+ { fill: "#d8ccb2", d: "M174.5 35.45 C146.5 38.81 118.5 42.17 90.5 45.53 C79.5 46.85 68.5 48.17 57.5 49.49 C53.73 49.94 51.23 49.33 49.07 53 C48.78 53.49 47.97 54.03 48.28 54.5 C48.38 54.65 55.19 53.79 56 53.69 C63.5 52.79 71 51.89 78.5 50.99 C101.5 48.23 124.5 45.47 147.5 42.71 C155.5 41.75 163.5 40.79 171.5 39.83 C173.36 39.61 178.97 38.95 179 38.88 C179.56 37.71 175.8 35.29 174.5 35.45 Z M43 64.46 C42.99 64.47 41.71 67.42 41.73 67.5 C42.08 68.71 45.14 68.52 46 68.61 C49.5 68.96 53 69.31 56.5 69.66 C72 71.21 87.5 72.76 103 74.31 C128.5 76.86 154 79.41 179.5 81.96 C185.5 82.56 191.5 83.16 197.5 83.76 C199.48 83.96 202.33 85.3 202.56 82.5 C202.66 81.24 202.17 80.54 201 80.09 C198.79 79.24 189.02 78.89 186 78.59 C168.5 76.84 151 75.09 133.5 73.34 C110.5 71.04 87.5 68.74 64.5 66.44 C59 65.89 53.5 65.34 48 64.79 C47.4 64.73 43.12 64.28 43 64.46 Z M36.5 145.97 C33.26 150.75 40.97 150.53 43.5 150.83 C52.5 151.91 61.5 152.99 70.5 154.07 C100 157.61 129.5 161.15 159 164.69 C170 166.01 181 167.33 192 168.65 C192.91 168.76 200.81 169.85 201 169.71 C201.48 169.35 201.42 168.58 201.58 168 C201.73 167.51 202.15 166.97 201.94 166.5 C201.4 165.34 195.79 165.08 194.5 164.93 C186.5 163.97 178.5 163.01 170.5 162.05 C137.5 158.09 104.5 154.13 71.5 150.17 C62.5 149.09 53.5 148.01 44.5 146.93 C42 146.63 39.5 146.33 37 146.03 C36.83 146.01 36.59 145.83 36.5 145.97 Z M195 178.49 C158 182.19 121 185.89 84 189.59 C75 190.49 66 191.39 57 192.29 C56.12 192.38 49.54 193 49.5 193.15 C49.31 193.81 50.04 194.41 50.38 195 C51.95 197.75 54.8 196.53 57.5 196.26 C66.5 195.36 75.5 194.46 84.5 193.56 C110.5 190.96 136.5 188.36 162.5 185.76 C167.23 185.29 193.16 183.27 195.5 182.46 C197.22 181.86 197.03 181.54 197.67 180 C198.87 177.08 197.1 178.28 195 178.49 Z M63 209.43 C63 209.92 66.26 212.65 66.79 213 C69.51 214.78 78.4 214.68 82 214.97 C102.5 216.61 123 218.25 143.5 219.89 C146.75 220.15 159.21 221.83 161.5 221.03 C161.84 220.92 166 218.31 166 218.29 C166 217.49 163.3 217.46 163 217.43 C159.5 217.15 156 216.87 152.5 216.59 C138 215.43 123.5 214.27 109 213.11 C99 212.31 89 211.51 79 210.71 C75.5 210.43 72 210.15 68.5 209.87 C67 209.75 65.5 209.63 64 209.51 C63.67 209.49 63 209.1 63 209.43 Z" },
+ { fill: "#0d0a10", d: "M201.5 97.49 C164.5 98.63 127.5 99.77 90.5 100.91 C78 101.29 65.5 101.68 53 102.06 C48.3 102.21 42.56 101.73 38 102.52 C37.48 102.61 36.82 102.58 36.5 103 C36.25 103.33 36.5 109.62 36.5 110.5 C36.5 118 36.5 125.5 36.5 133 C36.5 133.71 36.42 140.42 36.5 140.5 C36.65 140.65 44.6 140.32 45.5 140.29 C55 140 64.5 139.71 74 139.42 C105.5 138.45 137 137.48 168.5 136.51 C177 136.25 185.5 135.98 194 135.72 C195.18 135.69 202.47 135.84 203 135.45 C203.86 134.81 203.5 127.83 203.5 126.5 C203.5 119 203.5 111.5 203.5 104 C203.5 103.31 203.7 98.26 203.5 98 C203.04 97.39 202.15 97.47 201.5 97.49 Z" },
+ ],
+ },
+ vampire: {
+ id: "vampire",
+ name: "Vampire",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 150, dx: 28, w: 22, h: 42, round: 38, ink: "#7a0f24", mouth: true, mouthInk: "#7a0f24", mouthY: null},
+ clip: "M90.5 74.47 C84.48 75.44 78.4 77.7 72.5 79.27 C70.54 79.79 64.93 80.75 63.5 81.67 C61.68 82.85 59.36 87.13 58.03 89 C49.89 100.39 47.02 115.7 46.19 129.5 C44.07 165.18 60.28 205.2 94.5 220.49 C105.75 225.51 118.34 227.21 130.5 225.09 C176.27 217.11 198.13 165.57 193.28 123.5 C192.29 114.91 189.54 100.92 185.19 93.5 C183.7 90.97 181.7 88.63 180 86.24 C179.11 85 178.17 83 177 82.04 C175.59 80.88 159.05 77.02 156 76.2 C154.71 75.86 149.54 74.05 148.5 74.47 C147.76 74.76 145.18 78.26 144.5 79.04 C140.5 83.61 136.5 88.18 132.5 92.75 C129.5 96.18 126.5 99.61 123.5 103.04 C122.66 103.99 121.5 106 120 106 C118.37 106 114.64 100.91 113.5 99.61 C108.17 93.51 102.83 87.42 97.5 81.32 C96.28 79.93 92.06 74.22 90.5 74.47 Z",
+ parts: [
+ { fill: "#3d3d3d", d: "M23 108.27 C21.28 109.28 22.11 112.42 22.18 114 C22.41 119 22.63 124 22.86 129 C23.63 146 24.41 163 25.18 180 C25.33 183.4 25.18 197.44 26.68 199.5 C28.01 201.33 30.32 202.94 31.97 204.5 C37.79 210 43.62 215.5 49.44 221 C52.16 223.57 60.5 232.29 63 233.73 C64.91 234.82 77.88 237.02 81 237.69 C90.5 239.72 100 241.76 109.5 243.8 C112.77 244.5 116.66 246 120 246 C123.19 246 143.69 240.97 148.5 239.94 C152.57 239.07 175.06 234.84 177 233.73 C179.54 232.27 183.95 227.24 186.32 225 C192.55 219.12 198.77 213.24 205 207.36 C207.09 205.39 213.34 200.67 214 198.02 C214.74 195.06 214.65 183.83 214.82 180 C215.39 167.5 215.96 155 216.52 142.5 C216.91 134 217.3 125.5 217.68 117 C217.77 115.16 218.7 109.27 217 108.27 C214.68 106.91 211.26 112.91 210.04 114.5 C203.36 123.24 196.68 131.97 190 140.71 C183.68 148.97 177.36 157.24 171.04 165.5 C169.44 167.59 164.63 174.77 163.01 176 C161.21 177.37 157.66 177.66 155.5 178.25 C149 180.02 142.5 181.79 136 183.56 C132.6 184.49 122.37 188.05 119.5 187.79 C117.06 187.57 114.37 186.39 112 185.75 C105 183.84 98 181.93 91 180.02 C88.54 179.35 79.05 177.31 77.5 176.34 C75.46 175.05 71.68 169.06 70 166.86 C64 159.02 58 151.17 52 143.32 C45 134.17 38 125.02 31 115.86 C29.7 114.17 25.29 106.92 23 108.27 Z" },
+ { fill: "accent", d: "M31 129.08 C30.83 129.18 31.08 133.51 31.1 134 C31.3 138.5 31.51 143 31.71 147.5 C32.23 159 32.76 170.5 33.28 182 C33.38 184.26 33.26 194.09 34.09 195.5 C35.17 197.32 41.21 202.22 43.09 204 C48.73 209.32 54.36 214.65 60 219.97 C62.03 221.89 64.08 224.44 66.39 226 C68.95 227.74 86.26 230.63 90.5 231.54 C96.75 232.88 105.4 235.43 111.5 236 C115.59 236.38 125.58 236.47 129.5 235.83 C137.54 234.51 145.53 232.39 153.5 230.69 C156.99 229.94 170.79 227.62 173 226.51 C175.03 225.49 180.56 219.44 182.5 217.61 C187.67 212.73 192.83 207.85 198 202.97 C199.86 201.22 204.77 197.42 205.91 195.5 C206.62 194.3 206.5 186.83 206.58 185 C207.02 175.5 207.45 166 207.88 156.5 C208.2 149.5 208.52 142.5 208.83 135.5 C208.92 133.72 209.19 129.54 209.11 129.5 C208.57 129.27 203.65 136.03 202.52 137.5 C195.52 146.66 188.51 155.83 181.5 164.99 C178.96 168.31 169.94 181.38 167.31 183 C164.18 184.92 155.89 186.43 152 187.49 C144.5 189.54 137 191.58 129.5 193.63 C126.63 194.41 123.47 195.74 120.5 195.98 C117.18 196.25 111.81 193.99 108.5 193.08 C100.5 190.9 92.5 188.72 84.5 186.54 C81.26 185.65 75.08 184.81 72.5 182.87 C69.62 180.71 59.01 165.66 56 161.72 C49.67 153.44 43.33 145.16 37 136.88 C34.7 133.87 31.03 129.05 31 129.08 Z" },
+ { fill: "#f2eef4", d: "M112.5 46.46 C98.93 48.14 86.29 54.43 76.15 63.5 C44.86 91.51 38.25 141.01 54.77 178.5 C67.45 207.29 95.18 229.81 128 225.47 C141.63 223.67 154.29 217.22 164.4 208 C195.36 179.76 201.71 130.34 185.01 93 C172.31 64.61 144.93 42.44 112.5 46.46 Z" },
+ { fill: "#3d3d3d", d: "M112 42.49 C89.7 45.35 70.68 59.42 58.6 78 C55.5 82.75 52.85 87.79 50.63 93 C50.47 93.36 48.79 97.47 48.83 97.5 C49.49 97.91 52.03 93.96 52.36 93.5 C54.54 90.45 59.14 82.93 61.5 80.7 C63.5 78.81 80.21 75.14 84 74.13 C85.49 73.74 90.24 71.93 91.5 72.13 C93.06 72.39 96.82 77.5 98 78.86 C103.33 84.95 108.67 91.05 114 97.14 C115.67 99.05 117.33 100.95 119 102.86 C119.33 103.24 119.49 104 120 104 C120.51 104 120.67 103.24 121 102.86 C123 100.57 125 98.29 127 96 C132 90.29 137 84.57 142 78.86 C142.67 78.09 147.64 72.11 148 72 C148.73 71.78 154.39 73.71 155.5 74 C158.39 74.77 176.92 79.22 178 80 C179.49 81.07 186.35 91.69 188 94 C188.99 95.38 190.99 98.2 191 98.2 C191.69 97.94 188.7 91.44 188.27 90.5 C184.89 83.14 180.63 76.18 175.5 69.92 C160.15 51.18 136.5 39.36 112 42.49 Z" },
+ ],
+ },
+ spider: {
+ id: "spider",
+ name: "Spider",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 142, dx: 28, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M111.5 64.49 C100.9 65.75 90.63 69.24 81.5 74.8 C73.1 79.92 65.76 86.72 60 94.69 C29.57 136.79 51.51 197.11 102 209.78 C110.8 211.98 120 212.55 129 211.45 C139.53 210.16 149.8 206.59 158.82 201 C202.82 173.75 205.99 110.29 164.67 79 C157.16 73.32 148.58 69.1 139.5 66.62 C130.43 64.14 120.84 63.38 111.5 64.49 Z",
+ parts: [
+ { fill: "#8d8d8d", d: "M119.5 -1.2 C118.33 -0.73 118.7 8.01 118.7 9.5 C118.7 20 118.7 30.5 118.7 41 C118.7 48 118.7 55 118.7 62 C118.7 62.99 117.97 68.21 120.5 67.2 C121.67 66.73 121.3 57.99 121.3 56.5 C121.3 46 121.3 35.5 121.3 25 C121.3 18 121.3 11 121.3 4 C121.3 3.01 122.03 -2.21 119.5 -1.2 Z" },
+ { fill: "#3d3d3d", d: "M26 56.34 C22.33 58.06 6.97 75.56 3 79.77 C0.83 82.08 -2.54 85.01 -0.33 88.5 C0.9 90.45 3.25 91.52 5.5 90.77 C8.52 89.76 18.53 79.17 21.5 76.37 C22.78 75.17 26.71 70.42 28.5 71.33 C29.8 71.99 35.57 78.91 37.05 80.5 C43.27 87.17 49.49 93.83 55.71 100.5 C59.14 104.17 63.66 111.14 69.46 107.5 C76.32 103.2 70.53 97.33 67 93.69 C57.67 84.04 48.33 74.39 39 64.74 C36.15 61.79 30.77 54.11 26 56.34 Z M210 56.34 C206.02 58.21 200.28 65.48 197 68.88 C190.51 75.58 184.02 82.29 177.53 89 C174.72 91.91 171.28 94.74 168.88 98 C165.76 102.22 168.57 108.5 174 108.5 C178.19 108.5 180.94 104.08 183.5 101.35 C190.5 93.84 197.5 86.34 204.5 78.83 C205.33 77.95 211.72 70.85 212 70.8 C212.81 70.63 216.85 74.82 217.5 75.43 C221.83 79.51 226.17 83.6 230.5 87.68 C232.57 89.63 234.89 92.04 238 90.58 C240.63 89.35 241.87 86.06 240.33 83.5 C238.37 80.24 222.75 64.66 219 60.68 C216.77 58.32 213.77 54.57 210 56.34 Z M10 100.34 C6.57 101.78 5.82 105.35 4.59 108.5 C2.09 114.91 -3.16 126.5 -4.77 132.5 C-5.53 135.33 -3.96 138.26 -1 138.9 C0.61 139.25 2.32 138.71 3.5 137.57 C5.71 135.43 10 124.43 11.6 121 C12.42 119.26 13.6 114.34 16 114.47 C17.05 114.52 22.23 117.36 23.5 117.95 C30 120.96 36.5 123.98 43 126.99 C46.52 128.62 51.06 131.92 55 129.77 C59.03 127.57 59.76 121.75 56 118.88 C52.96 116.56 27.09 106.04 21.5 103.6 C18.36 102.23 13.53 98.87 10 100.34 Z M226 100.34 C219.38 102.72 212.95 106.02 206.5 108.84 C199.54 111.87 192.26 114.55 185.5 118 C180.19 120.71 180.18 128.78 186.5 130.32 C190.04 131.19 193.9 128.43 196.98 127 C203.45 124 209.92 121 216.39 118 C218.23 117.14 222.07 114.72 223.93 114.5 C226.17 114.23 227.56 119.21 228.4 121 C229.98 124.38 234.35 135.35 236.43 137.5 C237.58 138.69 239.38 139.25 241 138.9 C243.96 138.26 245.53 135.33 244.77 132.5 C243.68 128.44 241.63 124.42 240.1 120.5 C237.96 115.03 236.1 109.34 233.66 104 C232.3 101.03 229.26 99.18 226 100.34 Z M44 145.99 C35 146.55 26 147.11 17 147.68 C13.65 147.89 9.05 147.35 7 150.69 C5.17 153.67 4.75 159.49 4.03 163 C2.4 170.92 0.13 178.98 -0.9 187 C-1.28 189.93 0.44 192.59 3.5 192.97 C6.77 193.39 8.45 190.72 9.17 188 C11.04 181 12.89 174 14.75 167 C15.25 165.14 15.54 160.73 17.5 159.8 C18.46 159.34 24.99 159.52 26.5 159.46 C31.8 159.26 49.63 159.28 53.5 158.32 C58.63 157.06 60.29 150.15 56 146.88 C52.8 144.44 47.71 145.76 44 145.99 Z M186 145.82 C179.25 148.05 180.72 157.67 187.5 158.48 C195.76 159.46 206 159.18 214.5 159.5 C216.14 159.56 222.53 159.3 223.5 160.42 C224.25 161.29 225.14 166.61 225.51 168 C227.36 174.96 228.87 182.15 231.09 189 C232.47 193.22 237.75 194.57 240.33 190.5 C242.19 187.56 238.67 176.18 237.92 172.5 C237.05 168.24 234.71 152.61 232.5 150.03 C230.09 147.23 225.33 147.82 222 147.61 C214 147.11 206 146.61 198 146.11 C194.69 145.91 189.07 144.8 186 145.82 Z M62 171.82 C59.08 172.78 56.4 175.64 54 177.5 C47.94 182.16 41.87 186.83 35.81 191.5 C33.36 193.38 28.56 196.15 27 198.69 C25.09 201.8 24.02 214.22 23.36 218.5 C22.82 221.95 20.49 232.18 21.1 235 C21.37 236.25 21.99 237.19 23 238 C27 241.21 30.4 237.25 31.23 233.5 C32.65 227.01 34.08 220.52 35.5 214.03 C36.06 211.47 36.18 207.04 38 205.05 C39.42 203.49 41.79 202.27 43.5 201.03 C49.44 196.69 55.39 192.34 61.33 188 C63.95 186.09 67.63 184.22 69.48 181.5 C72.84 176.54 67.56 169.97 62 171.82 Z M174 171.82 C168.53 173.63 168.37 180.28 172.5 183.49 C179.62 189.04 187.12 194.17 194.41 199.5 C196.09 200.73 201.55 204.03 202.5 205.41 C203.45 206.81 203.88 211.21 204.27 213 C205.7 219.5 207.13 226 208.55 232.5 C209.34 236.06 211.26 240.8 216 238.58 C217.67 237.8 218.74 236.33 218.97 234.5 C219.36 231.5 217.12 221.59 216.56 218 C215.98 214.28 214.65 200.87 212.87 198.5 C210.6 195.47 194.7 184.19 190.55 181 C186.69 178.02 179.05 170.14 174 171.82 Z" },
+ { fill: "body", d: "M111.5 64.49 C100.9 65.75 90.63 69.24 81.5 74.8 C73.1 79.92 65.76 86.72 60 94.69 C29.57 136.79 51.51 197.11 102 209.78 C110.8 211.98 120 212.55 129 211.45 C139.53 210.16 149.8 206.59 158.82 201 C202.82 173.75 205.99 110.29 164.67 79 C157.16 73.32 148.58 69.1 139.5 66.62 C130.43 64.14 120.84 63.38 111.5 64.49 Z" },
+ ],
+ },
+ rocket: {
+ id: "rocket",
+ name: "Rocket",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 136, dx: 24, w: 20, h: 38, round: 34, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M84.5 92.44 C73.32 95.79 74 105.01 74 114.5 C74 134 74 153.5 74 173 C74 179.43 72.79 193.18 75.6 198.5 C79.55 205.97 86.14 206 93.5 206 C107.5 206 121.5 206 135.5 206 C141.06 206 151.57 206.94 156.5 205.26 C166.84 201.72 166 192.32 166 183.5 C166 163.5 166 143.5 166 123.5 C166 116.39 167.52 103.86 163.5 98.02 C159.05 91.55 151.95 92 145 92 C131.5 92 118 92 104.5 92 C99.62 92 88.68 91.19 84.5 92.44 Z",
+ parts: [
+ { fill: "#8d8d8d", d: "M118 195.42 C113.86 197.91 115.06 202.85 115.15 207 C115.38 218 115.6 229 115.83 240 C115.91 243.49 114.51 251.33 119.5 251.97 C125.29 252.7 124.07 244.44 124.15 241 C124.41 228.5 124.67 216 124.93 203.5 C124.96 202.08 125.21 200.4 124.9 199 C124.29 196.26 120.75 193.77 118 195.42 Z" },
+ { fill: "#ffc93c", d: "M84 213.4 C82.94 213.74 81.82 222.52 80.78 224 C79.27 226.14 70.96 226.4 70.5 227.28 C69.33 229.53 78.59 230.23 80 231.22 C82.14 232.73 82.4 241.04 83.28 241.5 C85.53 242.67 86.23 233.41 87.22 232 C88.73 229.86 97.04 229.6 97.5 228.72 C98.81 226.21 88.45 226.3 87 223.63 C85.53 220.92 85.89 217.33 84.72 214.5 C84.55 214.1 84.42 213.27 84 213.4 Z M158 223.4 C156.36 224.56 156.92 229.31 155.55 231 C154.23 232.63 148.14 232.93 148 233.4 C147.47 235.25 153.92 235.58 155 236.45 C156.63 237.77 156.93 243.86 157.4 244 C159.25 244.53 159.58 238.08 160.45 237 C161.77 235.37 167.86 235.07 168 234.6 C168.53 232.75 162.08 232.42 161 231.55 C158.88 229.83 159.6 226.27 158.6 224 C158.49 223.74 158.23 223.24 158 223.4 Z" },
+ { fill: "body", d: "M84.5 92.44 C73.32 95.79 74 105.01 74 114.5 C74 134 74 153.5 74 173 C74 179.43 72.79 193.18 75.6 198.5 C79.55 205.97 86.14 206 93.5 206 C107.5 206 121.5 206 135.5 206 C141.06 206 151.57 206.94 156.5 205.26 C166.84 201.72 166 192.32 166 183.5 C166 163.5 166 143.5 166 123.5 C166 116.39 167.52 103.86 163.5 98.02 C159.05 91.55 151.95 92 145 92 C131.5 92 118 92 104.5 92 C99.62 92 88.68 91.19 84.5 92.44 Z" },
+ { fill: "#fff3dc", d: "M74.5 178 C74.01 178.37 73.72 191.13 74 191.5 C74.32 191.92 74.98 191.91 75.5 192 C79.35 192.64 93.12 192 98 192 C113.5 192 129 192 144.5 192 C150 192 155.5 192 161 192 C162.97 192 165.59 192.94 166 190.5 C166.16 189.56 166.17 178.73 166 178.5 C165.39 177.69 161.04 178 160 178 C155 178 150 178 145 178 C127.5 178 110 178 92.5 178 C88 178 83.5 178 79 178 C78.56 178 74.65 177.88 74.5 178 Z" },
+ { fill: "#3d3d3d", d: "M118 14.34 C114.29 15.71 108.91 27.66 106.79 31.5 C97.95 47.5 89.11 63.5 80.26 79.5 C78.24 83.17 73.15 90.9 72.19 94.5 C71.8 95.98 72.01 97.69 72.81 99 C73.75 100.55 75.21 101.59 77 101.92 C81.22 102.68 90.27 102 95 102 C111 102 127 102 143 102 C147.08 102 161.03 102.75 164 101.66 C172.74 98.43 164.27 87.7 161.67 83 C152 65.5 142.33 48 132.66 30.5 C130.72 27 126.58 17.88 124 15.53 C122.41 14.08 120.02 13.6 118 14.34 Z" },
+ ],
+ },
+ anaar: {
+ id: "anaar",
+ name: "Anaar",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 170, dx: 26, w: 22, h: 40, round: 36, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M85.5 97.46 C83.8 98.28 82.55 99.28 81.68 101 C79.47 105.36 75.47 119.45 73.62 125 C64.95 151 56.29 177 47.62 203 C45.29 210 42.95 217 40.62 224 C39.47 227.46 37.89 231.06 40.5 234.33 C43.03 237.5 46.89 237 50.5 237 C59 237 67.5 237 76 237 C105 237 134 237 163 237 C171 237 179 237 187 237 C190.24 237 194.59 237.78 197.5 236.06 C203.71 232.4 199.73 225.07 198.05 220 C193.05 205 188.05 190 183.05 175 C176.71 156 170.38 137 164.05 118 C162.7 113.98 159.82 102.92 157.74 100 C157 98.96 156.14 98.24 155 97.68 C151.84 96.12 145.11 97 141.5 97 C132 97 122.5 97 113 97 C106.5 97 100 97 93.5 97 C91.12 97 87.71 96.39 85.5 97.46 Z",
+ parts: [
+ { fill: "#ffc93c", d: "M119 5.71 C116.56 7.31 117.27 11.92 117.13 14.5 C116.63 23 116.14 31.5 115.65 40 C115.58 41.37 115.32 49.98 114.55 50.5 C112.6 51.82 110.67 45.61 110.21 44.5 C107.69 38.5 105.18 32.5 102.67 26.5 C101.93 24.72 100.92 19.95 98 20.92 C94.8 21.99 96.74 25.86 97.31 28 C99.04 34.49 100.77 40.98 102.5 47.47 C102.75 48.42 104.49 54.52 103.71 55 C102.24 55.9 98.4 50.91 97.5 49.89 C92.84 44.59 88.17 39.3 83.51 34 C81.99 32.28 79.13 28.39 77.05 32 C76.18 33.51 77.75 35.16 78.5 36.29 C81.17 40.29 83.83 44.29 86.5 48.3 C91.5 55.81 96.5 63.31 101.5 70.82 C104.14 74.79 107.27 78.72 109.39 83 C110.59 85.4 110.6 88.16 111.97 90.5 C114.3 94.45 119.21 96.31 123.5 94.51 C129.49 91.99 129.75 84.46 132.76 79.5 C139.59 68.24 147.4 57.46 154.7 46.5 C156.1 44.39 163.2 34.78 163.17 33 C163.16 32.47 163 31.9 162.65 31.5 C159.85 28.35 156.6 33.88 155 35.7 C150.67 40.61 146.33 45.53 142 50.45 C141.38 51.16 138.17 55 137.51 55 C134.61 55 137.38 47.94 137.76 46.5 C139.36 40.5 140.96 34.5 142.56 28.5 C143.13 26.36 145.07 22.67 142.5 21.12 C139.53 19.32 138.26 24.27 137.54 26 C135.03 32 132.51 38 130 44 C129.58 45.01 127.2 51.27 126.08 51 C124.62 50.65 124.54 43.36 124.46 42 C123.94 33 123.42 24 122.9 15 C122.81 13.36 123.24 2.93 119 5.71 Z" },
+ { fill: "#fff3c4", d: "M118.5 36.36 C114.78 38.21 113.38 43.83 112.53 47.5 C110.82 54.8 110.6 62.56 111.44 70 C111.72 72.5 112.49 75 112.62 77.5 C112.77 80.03 111.72 82.46 112.06 85 C112.75 90.08 118.2 93.41 123 91.42 C130.09 88.47 127.07 82.94 127.38 77.5 C127.51 75 128.28 72.5 128.56 70 C129.4 62.56 129.18 54.8 127.47 47.5 C126.7 44.21 123.66 33.8 118.5 36.36 Z" },
+ { fill: "#ffc93c", d: "M120 -3.6 C118.09 -2.25 119.38 2.17 117 3.91 C115.7 4.86 111.13 4.95 111 5.4 C110.48 7.21 116.67 7.3 117.91 9 C118.86 10.3 118.95 14.87 119.4 15 C121.23 15.53 121.36 10.39 121.84 9.5 C123.09 7.14 128.92 6.87 129 6.6 C129.52 4.79 123.33 4.7 122.09 3 C120.9 1.37 121.38 -1.21 120.6 -3 C120.49 -3.26 120.23 -3.76 120 -3.6 Z M56 22.4 C53.85 23.91 55.2 29.53 52.54 31.5 C50.93 32.7 45.18 32.78 45 33.4 C44.45 35.34 52.08 35.53 53.5 37.46 C54.7 39.07 54.78 44.82 55.4 45 C57.3 45.54 57.67 39.05 58.23 38 C59.66 35.35 66.89 35 67 34.6 C67.55 32.66 59.92 32.47 58.5 30.54 C57.02 28.54 57.59 25.22 56.6 23 C56.48 22.74 56.23 22.24 56 22.4 Z M184 22.4 C181.85 23.91 183.2 29.53 180.54 31.5 C178.93 32.7 173.18 32.78 173 33.4 C172.45 35.34 180.08 35.53 181.5 37.46 C182.7 39.07 182.78 44.82 183.4 45 C185.3 45.54 185.67 39.05 186.23 38 C187.66 35.35 194.89 35 195 34.6 C195.55 32.66 187.92 32.47 186.5 30.54 C185.02 28.54 185.59 25.22 184.6 23 C184.48 22.74 184.23 22.24 184 22.4 Z" },
+ { fill: "body", d: "M85.5 97.46 C83.8 98.28 82.55 99.28 81.68 101 C79.47 105.36 75.47 119.45 73.62 125 C64.95 151 56.29 177 47.62 203 C45.29 210 42.95 217 40.62 224 C39.47 227.46 37.89 231.06 40.5 234.33 C43.03 237.5 46.89 237 50.5 237 C59 237 67.5 237 76 237 C105 237 134 237 163 237 C171 237 179 237 187 237 C190.24 237 194.59 237.78 197.5 236.06 C203.71 232.4 199.73 225.07 198.05 220 C193.05 205 188.05 190 183.05 175 C176.71 156 170.38 137 164.05 118 C162.7 113.98 159.82 102.92 157.74 100 C157 98.96 156.14 98.24 155 97.68 C151.84 96.12 145.11 97 141.5 97 C132 97 122.5 97 113 97 C106.5 97 100 97 93.5 97 C91.12 97 87.71 96.39 85.5 97.46 Z" },
+ { fill: "#fff3dc", d: "M76 118 C75.28 118.7 72.97 126.95 72.45 128.5 C72.12 129.5 70.97 130.57 71.45 131.5 C71.94 132.43 75.2 132 76 132 C80.5 132 85 132 89.5 132 C108.5 132 127.5 132 146.5 132 C152 132 157.5 132 163 132 C164.65 132 168.04 132.94 168.21 130.5 C168.25 130.02 164.42 118.69 164.21 118.5 C163.17 117.56 149.79 118 147.5 118 C131.5 118 115.5 118 99.5 118 C93.5 118 87.5 118 81.5 118 C80.99 118 76.06 117.94 76 118 Z" },
+ { fill: "#3d3d3d", d: "M102.5 86.46 C98.27 88.32 98 91.95 98 96 C98 99.72 98.12 103.49 102 105.32 C104.64 106.57 108.16 106 111 106 C115.81 106 134.81 106.83 138 105.32 C143.72 102.62 143.72 89.38 138 86.68 C134.81 85.17 115.81 86 111 86 C108.41 86 104.93 85.4 102.5 86.46 Z" },
+ ],
+ },
+ chakri: {
+ id: "chakri",
+ name: "Chakri",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 126, dx: 24, w: 20, h: 38, round: 34, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M111 46.47 C98.86 47.75 87.03 51.64 76.5 57.81 C66.82 63.49 58.28 71.06 51.5 80 C14.9 128.24 38.89 199.11 97.48 215 C107.72 217.78 118.45 218.64 129 217.53 C141.14 216.25 152.97 212.36 163.5 206.19 C173.18 200.51 181.72 192.94 188.5 184 C225.1 135.76 201.11 64.89 142.52 49 C132.28 46.22 121.55 45.36 111 46.47 Z",
+ parts: [
+ { fill: "#ffc93c", d: "M74 30.45 C70.49 31.64 64.72 37 62 39.72 C51.88 49.87 45.59 62.85 43.61 77 C42.81 82.68 41.74 95.72 48 98.45 C52.15 100.26 56.99 97.42 57.65 93 C58.04 90.36 55.7 83.04 55.4 79.5 C54.75 71.87 56.06 64.16 58.69 57 C61.05 50.58 64.6 44.67 69 39.44 C70.84 37.26 73.16 35.52 75 33.38 C76.08 32.13 76.14 29.72 74 30.45 Z M150.5 33.46 C138.12 34.29 126.42 38.39 116.5 45.91 C111.03 50.06 112.32 59 120 59 C124.16 59 126.63 55.04 129.5 52.61 C134.19 48.64 139.68 45.6 145.5 43.64 C153.7 40.86 162.4 40.01 171 40.99 C172.62 41.18 184.35 43.93 184.5 43.85 C188.58 41.74 178.17 38.02 177 37.57 C168.7 34.37 159.39 32.87 150.5 33.46 Z M187 85.38 C181.77 87.68 180.52 94.47 185.5 97.89 C188.08 99.66 192.92 100.18 195.99 101.5 C202.87 104.47 208.94 108.98 213.99 114.5 C218.86 119.84 222.71 126.24 225.24 133 C225.71 134.24 228.08 143.29 228.31 143.5 C228.74 143.9 229.44 144.2 229.99 144 C231.59 143.4 230.9 140.64 230.84 139.5 C230.55 134.43 229.53 129.32 227.91 124.5 C223.32 110.78 214.55 99.06 202.5 91.03 C199.18 88.81 191.04 83.6 187 85.38 Z M10.5 119.91 C8.34 120.32 9.07 122.57 9.14 124 C9.38 129.07 10.36 134.17 11.91 139 C16.47 153.16 25.72 165.52 38.3 173.5 C42.52 176.18 50.17 181.49 55 177.54 C58.29 174.85 58.61 170.04 55.61 167 C53.12 164.47 48.22 164.22 45 162.93 C38.4 160.29 32.46 156.11 27.5 151.05 C21.93 145.35 17.55 138.46 14.76 131 C14.14 129.35 12.19 121.12 11.69 120.5 C11.42 120.15 10.94 119.83 10.5 119.91 Z M187 165.38 C184.27 166.58 182.27 168.88 182.28 172 C182.3 175.45 184 179.03 184.4 182.5 C185.35 190.59 184.28 198.82 181.5 206.47 C179.01 213.3 175.31 219.7 170.5 225.16 C169.45 226.36 164.6 230.52 164.21 231.5 C163.69 232.82 164.75 233.69 166 233.55 C168.2 233.31 176.11 226.18 178 224.28 C188.58 213.68 195.87 199.08 196.67 184 C196.96 178.59 197.96 168.15 192 165.55 C190.54 164.91 188.5 164.72 187 165.38 Z M117.5 205.46 C114.7 206.69 109.27 212.67 105.65 215 C98.01 219.9 89.04 222.68 80 223.3 C74.5 223.67 68.88 223.28 63.5 222.08 C62.07 221.76 57.07 219.8 56 220.03 C54.77 220.29 54.13 221.41 54.95 222.5 C56.54 224.63 67.12 227.84 70 228.61 C85.91 232.86 103.96 230.48 118 221.84 C120.3 220.42 122.96 218.92 124.9 217 C130 211.92 124.39 202.44 117.5 205.46 Z" },
+ { fill: "body", d: "M111 46.47 C98.86 47.75 87.03 51.64 76.5 57.81 C66.82 63.49 58.28 71.06 51.5 80 C14.9 128.24 38.89 199.11 97.48 215 C107.72 217.78 118.45 218.64 129 217.53 C141.14 216.25 152.97 212.36 163.5 206.19 C173.18 200.51 181.72 192.94 188.5 184 C225.1 135.76 201.11 64.89 142.52 49 C132.28 46.22 121.55 45.36 111 46.47 Z" },
+ { fill: "#3d3d3d", d: "M151.5 53.91 C149.68 54.3 148.66 56.44 149.83 58 C150.98 59.53 155.66 61.23 157.5 62.31 C161.79 64.82 165.84 67.73 169.58 71 C182.08 81.92 190.92 96.78 194.43 113 C203.28 153.79 177.05 195.2 135.5 202.65 C84.6 211.77 39.51 164.21 55.93 114 C58.35 106.59 62.08 99.6 66.93 93.5 C72.41 86.61 79.25 80.84 87 76.67 C116.65 60.68 154.62 70.66 171.14 100.5 C177.43 111.85 179.88 125.17 177.92 138 C177.3 142.1 176.23 146.13 174.75 150 C174.19 151.45 173.19 153.01 172.81 154.5 C172.19 156.98 174.88 159.06 177 157.29 C180.8 154.11 183.66 135.74 183.77 130.5 C184.39 100.13 162.81 73.06 133.5 65.81 C124.69 63.62 115.46 63.25 106.5 64.67 C97.48 66.1 88.78 69.34 81 74.13 C74.14 78.36 68.02 83.8 63 90.1 C31.87 129.13 49.92 186.89 96 204.13 C156.15 226.64 214.37 169.92 198.83 109 C194.01 90.12 182.41 73.32 166.57 62 C164.36 60.42 153.86 53.41 151.5 53.91 Z" },
+ ],
+ },
+ sparkler: {
+ id: "sparkler",
+ name: "Sparkler",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 104, dx: 24, w: 21, h: 40, round: 36, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M112.5 46.46 C104.13 47.48 95.94 50.21 88.67 54.5 C41.85 82.12 50.89 153.23 103.5 167.76 C111.29 169.91 119.48 170.52 127.5 169.54 C135.87 168.52 144.06 165.79 151.33 161.5 C198.15 133.88 189.11 62.77 136.5 48.24 C128.71 46.09 120.52 45.48 112.5 46.46 Z",
+ parts: [
+ { fill: "#8d8d8d", d: "M118 155.97 C116.82 156.76 116.29 157.12 115.76 158.5 C114.81 160.99 115.57 171.69 115.59 175 C115.69 193 115.8 211 115.9 229 C115.92 232.52 115.37 244.42 116.13 247 C116.59 248.57 117.85 249.76 119.5 249.97 C121.12 250.17 122.71 249.35 123.5 247.93 C124.83 245.56 124.07 233.41 124.09 230 C124.21 210.5 124.32 191 124.43 171.5 C124.46 167.4 126.07 157.51 121.5 155.76 C120.5 155.38 118.93 155.35 118 155.97 Z" },
+ { fill: "#ffc93c", d: "M147.5 0 C146.05 0.87 144.26 7.21 143.57 9 C140.94 15.9 136.25 26.33 134.42 33 C133.53 36.24 135.58 39.61 139 40.05 C142.95 40.55 144.77 37.34 145.31 34 C146.75 25 148.2 16 149.64 7 C149.95 5.1 151.62 0.75 149 -0.18 C148.53 -0.35 147.93 -0.26 147.5 0 Z M94.5 13.38 C92.16 14.23 93.48 18.71 93.64 20.5 C93.94 23.84 94.18 34.58 95.39 37 C96.66 39.55 99.86 40.85 102.5 39.64 C104.51 38.73 105.89 36.74 105.83 34.5 C105.76 31.79 100.69 22.52 99.29 19.5 C98.53 17.87 97.1 12.44 94.5 13.38 Z M41.5 28.35 C40.38 28.74 39.99 29.99 40.38 31 C41.12 32.94 46.85 39.07 48.5 41.09 C51.67 44.99 59.38 55.53 62.5 58.27 C64.68 60.19 67.81 60.25 70 58.29 C72.05 56.45 72.31 53.19 70.69 51 C68.79 48.44 54.22 37.41 50.64 34.5 C49.04 33.21 43.34 27.71 41.5 28.35 Z M187 38.33 C184.94 39.36 171.17 48.97 169.73 50.5 C167.74 52.61 167.81 55.87 169.71 58 C171.53 60.03 174.83 60.34 177 58.69 C179.44 56.83 183.98 49.1 186 46.23 C187.07 44.7 189.49 42.34 189.84 40.5 C190.15 38.9 188.41 37.61 187 38.33 Z M223.5 77.96 C214 79.48 204.5 81.01 195 82.53 C191.31 83.13 186.95 84.74 188.04 89.5 C188.69 92.38 191.59 94.32 194.5 93.72 C198.75 92.85 213.38 86.57 218.5 84.62 C220.15 83.99 226.55 82.04 227.5 81.09 C227.91 80.67 228.24 80.09 228.25 79.5 C228.28 76.78 224.99 77.72 223.5 77.96 Z M26.5 81.31 C24.17 82.43 25.59 84.32 27 85.2 C29.32 86.65 44.47 93.77 46.5 93.83 C48.74 93.89 50.73 92.5 51.64 90.5 C52.78 88.01 51.68 84.74 49.21 83.5 C46.33 82.05 37.59 82.09 34 81.77 C32.52 81.64 27.68 80.74 26.5 81.31 Z M45 122.42 C42.46 123.12 39.96 124.34 37.5 125.28 C31.5 127.57 25.5 129.86 19.5 132.15 C17.81 132.79 10.94 134.51 11.82 137 C12.81 139.78 18.45 137.73 20.5 137.4 C24.9 136.69 46.6 133.83 49 132.61 C54.91 129.6 51.29 120.7 45 122.42 Z M192 122.35 C187.44 123.62 186.34 130.26 190.79 132.5 C193.45 133.84 203.95 134.05 207.5 134.36 C209 134.49 212.11 135.36 213.5 134.69 C215.83 133.57 214.41 131.68 213 130.8 C210.51 129.24 197.79 123.33 195 122.43 C194.01 122.12 193.01 122.08 192 122.35 Z M65 156.39 C61.08 157.74 54.77 168.67 52.09 172.5 C51.16 173.81 48.32 177.47 52 177.88 C53.42 178.04 55.47 175.94 56.5 175.21 C59.62 173.02 70.36 166.61 71.47 163.5 C72.79 159.79 69.07 154.98 65 156.39 Z M172.5 156.38 C168.57 157.72 166.8 162.16 169.73 165.5 C172.49 168.64 185.23 178.14 189.36 181.5 C190.96 182.79 196.66 188.29 198.5 187.65 C202.13 186.38 196.6 181.18 195.5 179.82 C190.5 173.68 185.5 167.53 180.5 161.38 C178.6 159.04 176.17 155.13 172.5 156.38 Z M99.5 175.97 C95.51 176.61 94.98 180.2 94.45 183.5 C93.25 191 92.04 198.5 90.84 206 C90.49 208.17 88.38 215.25 91 216.18 C93.52 217.07 95.2 210.22 95.85 208.5 C98.14 202.5 100.43 196.5 102.72 190.5 C103.66 188.04 104.88 185.54 105.58 183 C106.62 179.22 103.52 175.33 99.5 175.97 Z M139 175.95 C136.26 176.26 134.1 178.75 134.17 181.5 C134.25 184.35 139.9 194.76 141.41 198 C142.1 199.48 143.1 203.49 145.5 202.62 C147.84 201.77 146.52 197.29 146.36 195.5 C146.06 192.16 145.82 181.42 144.61 179 C143.57 176.9 141.32 175.69 139 175.95 Z" },
+ { fill: "#ffc93c", d: "M28 21.4 C26.98 21.73 26.13 29.17 25.16 30.5 C23.82 32.35 16.86 32.6 16.5 33.28 C15.35 35.45 23.22 35.91 24.5 36.84 C26.35 38.18 26.6 45.14 27.28 45.5 C29.45 46.65 29.91 38.78 30.84 37.5 C32.18 35.65 39.14 35.4 39.5 34.72 C40.75 32.35 31.89 32.57 30.54 30 C29.05 27.18 29.25 21 28 21.4 Z M214 47.4 C212.36 48.56 212.92 53.31 211.55 55 C210.23 56.63 204.14 56.93 204 57.4 C203.47 59.25 209.92 59.58 211 60.45 C212.63 61.77 212.93 67.86 213.4 68 C215.25 68.53 215.58 62.08 216.45 61 C217.77 59.37 223.86 59.07 224 58.6 C224.53 56.75 218.08 56.42 217 55.55 C214.88 53.83 215.6 50.27 214.6 48 C214.49 47.74 214.23 47.24 214 47.4 Z M36 160.4 C34.09 161.75 35.38 166.17 33 167.91 C31.7 168.86 27.13 168.95 27 169.4 C26.48 171.21 32.67 171.3 33.91 173 C34.86 174.3 34.95 178.87 35.4 179 C37.23 179.53 37.36 174.39 37.84 173.5 C39.09 171.14 44.92 170.87 45 170.6 C45.52 168.79 39.33 168.7 38.09 167 C36.9 165.37 37.38 162.79 36.6 161 C36.49 160.74 36.23 160.24 36 160.4 Z" },
+ { fill: "body", d: "M112.5 46.46 C104.13 47.48 95.94 50.21 88.67 54.5 C41.85 82.12 50.89 153.23 103.5 167.76 C111.29 169.91 119.48 170.52 127.5 169.54 C135.87 168.52 144.06 165.79 151.33 161.5 C198.15 133.88 189.11 62.77 136.5 48.24 C128.71 46.09 120.52 45.48 112.5 46.46 Z" },
+ ],
+ },
+ bomb: {
+ id: "bomb",
+ name: "Bomb",
+ paint: "bot",
+ bone: null,
+ eyes: {cx: 120, cy: 150, dx: 34, w: 26, h: 50, round: 44, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M111 62.47 C98.86 63.75 87.03 67.64 76.5 73.81 C66.82 79.49 58.28 87.06 51.5 96 C14.9 144.24 38.89 215.11 97.48 231 C107.72 233.78 118.45 234.64 129 233.53 C141.14 232.25 152.97 228.36 163.5 222.19 C173.18 216.51 181.72 208.94 188.5 200 C225.1 151.76 201.11 80.89 142.52 65 C132.28 62.22 121.55 61.36 111 62.47 Z",
+ parts: [
+ { fill: "#b08a5a", d: "M190.5 14.84 C188.2 16.26 186.69 22.31 182.29 25.5 C171.79 33.11 159.94 29.76 151.1 43.5 C149.19 46.48 145.5 52.25 149 55.35 C154.69 60.39 156.89 50.92 158.67 48 C159.93 45.93 161.56 44.17 163.5 42.73 C171.81 36.57 182.48 36.65 189.94 28.5 C192.23 26 195.04 21.96 195.46 18.5 C195.77 16.02 192.92 13.34 190.5 14.84 Z" },
+ { fill: "#3d3d3d", d: "M132.5 40.29 C129.8 41.52 123.5 56.05 121.78 59.5 C120.88 61.29 119.34 63.4 120.29 65.5 C121.29 67.69 124.01 68.48 126 69.47 C131 71.97 136 74.47 141 76.97 C144.05 78.5 154.65 85 157.5 83.71 C160.2 82.48 166.5 67.95 168.22 64.5 C169.12 62.71 170.66 60.6 169.71 58.5 C168.71 56.31 165.99 55.52 164 54.53 C159 52.03 154 49.53 149 47.03 C145.95 45.5 135.35 39 132.5 40.29 Z" },
+ { fill: "body", d: "M111 62.47 C98.86 63.75 87.03 67.64 76.5 73.81 C66.82 79.49 58.28 87.06 51.5 96 C14.9 144.24 38.89 215.11 97.48 231 C107.72 233.78 118.45 234.64 129 233.53 C141.14 232.25 152.97 228.36 163.5 222.19 C173.18 216.51 181.72 208.94 188.5 200 C225.1 151.76 201.11 80.89 142.52 65 C132.28 62.22 121.55 61.36 111 62.47 Z" },
+ { fill: "#ffc93c", d: "M196 -6.6 C194.72 -6.19 193.32 5.23 192 7 C190.4 9.13 184.13 9.89 181.5 10.54 C180.5 10.78 178.97 10.36 178.5 11.28 C177.22 13.76 189.33 14.75 191 16 C193.13 17.6 193.89 23.87 194.54 26.5 C194.78 27.5 194.36 29.03 195.28 29.5 C197.76 30.78 198.75 18.67 200 17 C201.6 14.87 207.87 14.11 210.5 13.46 C211.5 13.22 213.03 13.64 213.5 12.72 C214.49 10.8 210.78 10.61 210 10.41 C207 9.67 201.4 9.44 199.75 6.5 C198.53 4.35 197.74 -1.36 197.09 -4 C196.82 -5.13 196.52 -6.76 196 -6.6 Z" },
+ { fill: "#fff3c4", d: "M194 6.34 C185.67 9.82 192 21.46 199 17.19 C204.97 13.56 200.6 3.59 194 6.34 Z" },
+ ],
+ },
+ laddu: {
+ id: "laddu",
+ name: "Laddu",
+ paint: "bone",
+ bone: "#f6a420",
+ eyes: {cx: 120, cy: 138, dx: 34, w: 26, h: 50, round: 44, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M118 44.82 C114.73 46.19 114.06 49.72 112 50.32 C109.4 51.07 107.36 44.78 102 46.23 C97.16 47.54 98.12 52.8 95 53.5 C92.77 54 90.49 49.4 86 50.78 C80.4 52.5 82.43 58.49 79.68 59.5 C77.1 60.45 74.63 56.47 70.5 58.39 C64.71 61.09 68.32 65.69 66 67.95 C63.86 70.04 59.56 65.76 55.58 69.5 C51.81 73.05 55.55 78.07 53 79.77 C50.36 81.53 46.21 77.52 43.14 83.5 C41.36 86.98 44.7 90.79 43.54 92.5 C41.61 95.36 34.86 92.17 33.88 99.5 C33.47 102.66 36.59 104.71 36.2 107 C35.76 109.56 30.29 109.18 28.5 112.92 C25.79 118.57 31.55 119.99 31.56 123 C31.57 125.72 25.92 126.11 25.01 130.5 C23.79 136.37 29.98 136.93 29.99 140 C30.01 142.91 24.23 143.49 24.93 149 C25.6 154.32 29.84 153.19 31.35 156 C32.58 158.3 26.85 161.35 28.11 166 C29.6 171.53 34.04 169.54 35.78 172 C37.53 174.47 32.16 177.91 34.48 182.5 C36.96 187.41 42.48 184.84 43.75 188 C44.38 189.58 41.85 192.6 42.75 195.5 C45.02 202.81 51.48 198.16 53.5 200.68 C54.97 202.51 52.93 205.91 54.14 208.5 C57.26 215.16 62.61 210.56 65 211.44 C68.44 212.71 64.59 219.43 71 221.8 C74.53 223.11 78.1 219.43 80 220.65 C82.91 222.51 80.14 227.96 86.5 229.35 C90.35 230.19 93.62 225.72 95.5 226.62 C98.57 228.09 97.03 232.87 102.5 233.88 C107.85 234.87 107.96 230.39 111 229.66 C114.12 228.92 115.05 236.9 121.5 235.32 C125 234.47 126.5 229.11 129 229.66 C131.94 230.32 132.17 234.87 137.5 233.88 C142.95 232.88 142.19 226.21 145.5 226.49 C148.56 226.74 149.49 231.07 154.5 229.05 C159.76 226.93 157.34 223.11 159.5 221.01 C161.48 219.1 165.4 222.8 168.5 221.96 C175.59 220.04 171.5 213.57 174.5 211.67 C177.08 210.03 180.79 214.73 184.89 210 C187.99 206.42 184.79 203.31 186.25 201 C187.8 198.53 192.98 201.74 196.25 197.5 C199.37 193.45 194.8 188.99 196.84 187 C199.21 184.68 202.93 187.6 205.5 182.54 C207.85 177.91 202.48 174.47 204.22 172 C206.03 169.44 211.41 171.42 212.07 165 C212.47 161.15 207.52 158.17 208.65 156 C210.12 153.18 215.81 153.89 215.08 147.5 C214.63 143.5 210.02 142.44 210.01 140 C210 137.61 214.63 136.47 215.08 132.5 C215.81 126.12 210.18 126.85 208.65 124 C207.42 121.7 213.15 118.65 211.89 114 C210.4 108.47 205.96 110.46 204.22 108 C202.47 105.53 207.84 102.09 205.52 97.5 C203.04 92.59 197.52 95.16 196.25 92 C195.26 89.53 200.17 86.01 195.5 81.66 C192.49 78.85 187.92 81.1 186.5 79.32 C184.77 77.17 187.83 73.6 185 70.13 C181 65.24 175.66 70.47 173.63 67.5 C171.98 65.09 175.31 60.53 169 58.2 C165.47 56.89 161.9 60.57 160 59.35 C157.95 58.04 158.79 54.22 156.5 52.18 C150.9 47.2 147.12 54.63 144.5 53.38 C142.27 52.31 142.37 49.11 140.5 47.51 C134.76 42.58 131.49 49.75 129 50.34 C125.88 51.08 124.32 42.16 118 44.82 Z",
+ parts: [
+ { fill: "body", d: "M118 44.82 C114.73 46.19 114.06 49.72 112 50.32 C109.4 51.07 107.36 44.78 102 46.23 C97.16 47.54 98.12 52.8 95 53.5 C92.77 54 90.49 49.4 86 50.78 C80.4 52.5 82.43 58.49 79.68 59.5 C77.1 60.45 74.63 56.47 70.5 58.39 C64.71 61.09 68.32 65.69 66 67.95 C63.86 70.04 59.56 65.76 55.58 69.5 C51.81 73.05 55.55 78.07 53 79.77 C50.36 81.53 46.21 77.52 43.14 83.5 C41.36 86.98 44.7 90.79 43.54 92.5 C41.61 95.36 34.86 92.17 33.88 99.5 C33.47 102.66 36.59 104.71 36.2 107 C35.76 109.56 30.29 109.18 28.5 112.92 C25.79 118.57 31.55 119.99 31.56 123 C31.57 125.72 25.92 126.11 25.01 130.5 C23.79 136.37 29.98 136.93 29.99 140 C30.01 142.91 24.23 143.49 24.93 149 C25.6 154.32 29.84 153.19 31.35 156 C32.58 158.3 26.85 161.35 28.11 166 C29.6 171.53 34.04 169.54 35.78 172 C37.53 174.47 32.16 177.91 34.48 182.5 C36.96 187.41 42.48 184.84 43.75 188 C44.38 189.58 41.85 192.6 42.75 195.5 C45.02 202.81 51.48 198.16 53.5 200.68 C54.97 202.51 52.93 205.91 54.14 208.5 C57.26 215.16 62.61 210.56 65 211.44 C68.44 212.71 64.59 219.43 71 221.8 C74.53 223.11 78.1 219.43 80 220.65 C82.91 222.51 80.14 227.96 86.5 229.35 C90.35 230.19 93.62 225.72 95.5 226.62 C98.57 228.09 97.03 232.87 102.5 233.88 C107.85 234.87 107.96 230.39 111 229.66 C114.12 228.92 115.05 236.9 121.5 235.32 C125 234.47 126.5 229.11 129 229.66 C131.94 230.32 132.17 234.87 137.5 233.88 C142.95 232.88 142.19 226.21 145.5 226.49 C148.56 226.74 149.49 231.07 154.5 229.05 C159.76 226.93 157.34 223.11 159.5 221.01 C161.48 219.1 165.4 222.8 168.5 221.96 C175.59 220.04 171.5 213.57 174.5 211.67 C177.08 210.03 180.79 214.73 184.89 210 C187.99 206.42 184.79 203.31 186.25 201 C187.8 198.53 192.98 201.74 196.25 197.5 C199.37 193.45 194.8 188.99 196.84 187 C199.21 184.68 202.93 187.6 205.5 182.54 C207.85 177.91 202.48 174.47 204.22 172 C206.03 169.44 211.41 171.42 212.07 165 C212.47 161.15 207.52 158.17 208.65 156 C210.12 153.18 215.81 153.89 215.08 147.5 C214.63 143.5 210.02 142.44 210.01 140 C210 137.61 214.63 136.47 215.08 132.5 C215.81 126.12 210.18 126.85 208.65 124 C207.42 121.7 213.15 118.65 211.89 114 C210.4 108.47 205.96 110.46 204.22 108 C202.47 105.53 207.84 102.09 205.52 97.5 C203.04 92.59 197.52 95.16 196.25 92 C195.26 89.53 200.17 86.01 195.5 81.66 C192.49 78.85 187.92 81.1 186.5 79.32 C184.77 77.17 187.83 73.6 185 70.13 C181 65.24 175.66 70.47 173.63 67.5 C171.98 65.09 175.31 60.53 169 58.2 C165.47 56.89 161.9 60.57 160 59.35 C157.95 58.04 158.79 54.22 156.5 52.18 C150.9 47.2 147.12 54.63 144.5 53.38 C142.27 52.31 142.37 49.11 140.5 47.51 C134.76 42.58 131.49 49.75 129 50.34 C125.88 51.08 124.32 42.16 118 44.82 Z" },
+ { fill: "#ffc560", d: "M105.5 58.92 C100.23 60.32 102.29 68.46 107.5 67.08 C112.77 65.68 110.71 57.54 105.5 58.92 Z M125.5 58.92 C120.23 60.32 122.29 68.46 127.5 67.08 C132.77 65.68 130.71 57.54 125.5 58.92 Z M79 71.92 C73.73 73.32 75.79 81.46 81 80.08 C86.27 78.68 84.21 70.54 79 71.92 Z M99 71.92 C93.73 73.32 95.79 81.46 101 80.08 C106.27 78.68 104.21 70.54 99 71.92 Z M114 71.92 C108.73 73.32 110.79 81.46 116 80.08 C121.27 78.68 119.21 70.54 114 71.92 Z M134 71.92 C128.73 73.32 130.79 81.46 136 80.08 C141.27 78.68 139.21 70.54 134 71.92 Z M149 71.92 C143.73 73.32 145.79 81.46 151 80.08 C156.27 78.68 154.21 70.54 149 71.92 Z M54.5 84.92 C49.23 86.32 51.29 94.46 56.5 93.08 C61.77 91.68 59.71 83.54 54.5 84.92 Z M74.5 84.92 C69.23 86.32 71.29 94.46 76.5 93.08 C81.77 91.68 79.71 83.54 74.5 84.92 Z M89.5 84.92 C84.23 86.32 86.29 94.46 91.5 93.08 C96.77 91.68 94.71 83.54 89.5 84.92 Z M104.5 84.92 C99.23 86.32 101.29 94.46 106.5 93.08 C111.77 91.68 109.71 83.54 104.5 84.92 Z M124.5 84.92 C119.23 86.32 121.29 94.46 126.5 93.08 C131.77 91.68 129.71 83.54 124.5 84.92 Z M139.5 84.92 C134.23 86.32 136.29 94.46 141.5 93.08 C146.77 91.68 144.71 83.54 139.5 84.92 Z M159.5 89.92 C154.23 91.32 156.29 99.46 161.5 98.08 C166.77 96.68 164.71 88.54 159.5 89.92 Z M174.5 89.92 C169.23 91.32 171.29 99.46 176.5 98.08 C181.77 96.68 179.71 88.54 174.5 89.92 Z M48 102.92 C42.73 104.32 44.79 112.46 50 111.08 C55.27 109.68 53.21 101.54 48 102.92 Z M63 102.92 C57.73 104.32 59.79 112.46 65 111.08 C70.27 109.68 68.21 101.54 63 102.92 Z M83 102.92 C77.73 104.32 79.79 112.46 85 111.08 C90.27 109.68 88.21 101.54 83 102.92 Z M98 102.92 C92.73 104.32 94.79 112.46 100 111.08 C105.27 109.68 103.21 101.54 98 102.92 Z M113 102.92 C107.73 104.32 109.79 112.46 115 111.08 C120.27 109.68 118.21 101.54 113 102.92 Z M133 102.92 C127.73 104.32 129.79 112.46 135 111.08 C140.27 109.68 138.21 101.54 133 102.92 Z M148 107.92 C142.73 109.32 144.79 117.46 150 116.08 C155.27 114.68 153.21 106.54 148 107.92 Z M168 107.92 C162.73 109.32 164.79 117.46 170 116.08 C175.27 114.68 173.21 106.54 168 107.92 Z M183 107.92 C177.73 109.32 179.79 117.46 185 116.08 C190.27 114.68 188.21 106.54 183 107.92 Z M38.5 115.92 C33.23 117.32 35.29 125.46 40.5 124.08 C45.77 122.68 43.71 114.54 38.5 115.92 Z M53.5 115.92 C48.23 117.32 50.29 125.46 55.5 124.08 C60.77 122.68 58.71 114.54 53.5 115.92 Z M73.5 115.92 C68.23 117.32 70.29 125.46 75.5 124.08 C80.77 122.68 78.71 114.54 73.5 115.92 Z M88.5 115.92 C83.23 117.32 85.29 125.46 90.5 124.08 C95.77 122.68 93.71 114.54 88.5 115.92 Z M108.5 115.92 C103.23 117.32 105.29 125.46 110.5 124.08 C115.77 122.68 113.71 114.54 108.5 115.92 Z M123.5 115.92 C118.23 117.32 120.29 125.46 125.5 124.08 C130.77 122.68 128.71 114.54 123.5 115.92 Z M138.5 120.92 C133.23 122.32 135.29 130.46 140.5 129.08 C145.77 127.68 143.71 119.54 138.5 120.92 Z M158.5 120.92 C153.23 122.32 155.29 130.46 160.5 129.08 C165.77 127.68 163.71 119.54 158.5 120.92 Z M178.5 120.92 C173.23 122.32 175.29 130.46 180.5 129.08 C185.77 127.68 183.71 119.54 178.5 120.92 Z M193.5 120.92 C188.23 122.32 190.29 130.46 195.5 129.08 C200.77 127.68 198.71 119.54 193.5 120.92 Z M47 133.92 C41.73 135.32 43.79 143.46 49 142.08 C54.27 140.68 52.21 132.54 47 133.92 Z M62 133.92 C56.73 135.32 58.79 143.46 64 142.08 C69.27 140.68 67.21 132.54 62 133.92 Z M82 133.92 C76.73 135.32 78.79 143.46 84 142.08 C89.27 140.68 87.21 132.54 82 133.92 Z M97 133.92 C91.73 135.32 93.79 143.46 99 142.08 C104.27 140.68 102.21 132.54 97 133.92 Z M117 133.92 C111.73 135.32 113.79 143.46 119 142.08 C124.27 140.68 122.21 132.54 117 133.92 Z M137 133.92 C131.73 135.32 133.79 143.46 139 142.08 C144.27 140.68 142.21 132.54 137 133.92 Z M152 133.92 C146.73 135.32 148.79 143.46 154 142.08 C159.27 140.68 157.21 132.54 152 133.92 Z M172 133.92 C166.73 135.32 168.79 143.46 174 142.08 C179.27 140.68 177.21 132.54 172 133.92 Z M187 133.92 C181.73 135.32 183.79 143.46 189 142.08 C194.27 140.68 192.21 132.54 187 133.92 Z M37.5 146.92 C32.23 148.32 34.29 156.46 39.5 155.08 C44.77 153.68 42.71 145.54 37.5 146.92 Z M57.5 146.92 C52.23 148.32 54.29 156.46 59.5 155.08 C64.77 153.68 62.71 145.54 57.5 146.92 Z M72.5 146.92 C67.23 148.32 69.29 156.46 74.5 155.08 C79.77 153.68 77.71 145.54 72.5 146.92 Z M92.5 146.92 C87.23 148.32 89.29 156.46 94.5 155.08 C99.77 153.68 97.71 145.54 92.5 146.92 Z M112.5 146.92 C107.23 148.32 109.29 156.46 114.5 155.08 C119.77 153.68 117.71 145.54 112.5 146.92 Z M127.5 151.92 C122.23 153.32 124.29 161.46 129.5 160.08 C134.77 158.68 132.71 150.54 127.5 151.92 Z M142.5 151.92 C137.23 153.32 139.29 161.46 144.5 160.08 C149.77 158.68 147.71 150.54 142.5 151.92 Z M162.5 151.92 C157.23 153.32 159.29 161.46 164.5 160.08 C169.77 158.68 167.71 150.54 162.5 151.92 Z M177.5 151.92 C172.23 153.32 174.29 161.46 179.5 160.08 C184.77 158.68 182.71 150.54 177.5 151.92 Z M197.5 151.92 C192.23 153.32 194.29 161.46 199.5 160.08 C204.77 158.68 202.71 150.54 197.5 151.92 Z M51 159.92 C45.73 161.32 47.79 169.46 53 168.08 C58.27 166.68 56.21 158.54 51 159.92 Z M66 159.92 C60.73 161.32 62.79 169.46 68 168.08 C73.27 166.68 71.21 158.54 66 159.92 Z M86 159.92 C80.73 161.32 82.79 169.46 88 168.08 C93.27 166.68 91.21 158.54 86 159.92 Z M101 164.92 C95.73 166.32 97.79 174.46 103 173.08 C108.27 171.68 106.21 163.54 101 164.92 Z M121 164.92 C115.73 166.32 117.79 174.46 123 173.08 C128.27 171.68 126.21 163.54 121 164.92 Z M136 164.92 C130.73 166.32 132.79 174.46 138 173.08 C143.27 171.68 141.21 163.54 136 164.92 Z M151 164.92 C145.73 166.32 147.79 174.46 153 173.08 C158.27 171.68 156.21 163.54 151 164.92 Z M171 164.92 C165.73 166.32 167.79 174.46 173 173.08 C178.27 171.68 176.21 163.54 171 164.92 Z M186 164.92 C180.73 166.32 182.79 174.46 188 173.08 C193.27 171.68 191.21 163.54 186 164.92 Z M61.5 177.92 C56.23 179.32 58.29 187.46 63.5 186.08 C68.77 184.68 66.71 176.54 61.5 177.92 Z M76.5 177.92 C71.23 179.32 73.29 187.46 78.5 186.08 C83.77 184.68 81.71 176.54 76.5 177.92 Z M91.5 177.92 C86.23 179.32 88.29 187.46 93.5 186.08 C98.77 184.68 96.71 176.54 91.5 177.92 Z M111.5 182.92 C106.23 184.32 108.29 192.46 113.5 191.08 C118.77 189.68 116.71 181.54 111.5 182.92 Z M126.5 182.92 C121.23 184.32 123.29 192.46 128.5 191.08 C133.77 189.68 131.71 181.54 126.5 182.92 Z M146.5 182.92 C141.23 184.32 143.29 192.46 148.5 191.08 C153.77 189.68 151.71 181.54 146.5 182.92 Z M161.5 182.92 C156.23 184.32 158.29 192.46 163.5 191.08 C168.77 189.68 166.71 181.54 161.5 182.92 Z M176.5 182.92 C171.23 184.32 173.29 192.46 178.5 191.08 C183.77 189.68 181.71 181.54 176.5 182.92 Z M85 195.92 C79.73 197.32 81.79 205.46 87 204.08 C92.27 202.68 90.21 194.54 85 195.92 Z M100 195.92 C94.73 197.32 96.79 205.46 102 204.08 C107.27 202.68 105.21 194.54 100 195.92 Z M120 195.92 C114.73 197.32 116.79 205.46 122 204.08 C127.27 202.68 125.21 194.54 120 195.92 Z M135 195.92 C129.73 197.32 131.79 205.46 137 204.08 C142.27 202.68 140.21 194.54 135 195.92 Z M155 195.92 C149.73 197.32 151.79 205.46 157 204.08 C162.27 202.68 160.21 194.54 155 195.92 Z M110.5 208.92 C105.23 210.32 107.29 218.46 112.5 217.08 C117.77 215.68 115.71 207.54 110.5 208.92 Z M125.5 208.92 C120.23 210.32 122.29 218.46 127.5 217.08 C132.77 215.68 130.71 207.54 125.5 208.92 Z" },
+ ],
+ },
+ chakli: {
+ id: "chakli",
+ name: "Chakli",
+ paint: "bone",
+ bone: "#cf8f45",
+ eyes: {cx: 120, cy: 128, dx: 30, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M110.5 42.49 C108.7 42.68 106.15 42.62 104.53 43.5 C101.84 44.96 101.77 47.78 98 48.22 C92.47 48.87 93.76 44.31 84.5 49.13 C81.79 50.53 81.81 53.93 79.12 55.5 C76.05 57.29 72.97 55.04 70 56.77 C60.87 62.1 65.76 62.65 62.04 67 C59.43 70.05 55.7 68.43 53 70.95 C51.59 72.27 49.26 74.49 48.5 76.31 C47.41 78.9 49 81.48 47 83.95 C43.57 88.21 42.2 84.22 38.41 91.5 C38.26 91.77 37.02 94.19 36.93 94.5 C35.97 97.64 38.9 100.01 36.84 103.5 C35.29 106.11 32.27 106.46 31.32 109.5 C30.68 111.55 29.38 114.86 30.04 117 C30.73 119.2 32.36 120.49 32.18 123 C31.95 126.21 29 127.23 28.15 130 C28.03 130.42 28.01 132.57 28.01 133 C27.9 142.82 31.77 139.38 32.18 145 C32.39 147.92 29.75 149.72 29.89 152.5 C30 154.55 30.77 158.25 31.86 160 C33.44 162.54 36.54 162.71 37.45 166 C38.08 168.27 36.85 169.84 36.73 172 C36.6 174.3 38.75 177.58 40 179.43 C42.04 182.46 46.2 181.67 47.83 185.5 C50.04 190.69 45.57 190.06 52.96 197 C55.65 199.53 59.41 197.93 62 200.95 C65.3 204.81 61.28 205.3 68 209.89 C68.36 210.14 70.57 211.64 71 211.81 C73.45 212.78 75.93 211.03 78.5 212.18 C81.46 213.51 81.28 216.49 83.5 218.31 C85.11 219.64 88.94 220.99 91 221.27 C93.66 221.63 95.68 219.29 98.5 219.86 C102.43 220.64 102.82 224.47 107 225.08 C108.79 225.34 111.2 225.98 113 225.65 C115.87 225.11 117.22 222.26 120.5 222.52 C124.44 222.83 124.8 226 129.5 225.51 C131.3 225.32 133.85 225.38 135.47 224.5 C138.16 223.04 138.23 220.22 142 219.78 C147.53 219.13 146.24 223.69 155.5 218.87 C158.21 217.47 158.19 214.07 160.88 212.5 C163.95 210.71 167.03 212.96 170 211.23 C179.13 205.9 174.24 205.35 177.96 201 C180.57 197.95 184.3 199.57 187 197.05 C188.41 195.73 190.74 193.51 191.5 191.69 C192.59 189.1 191 186.52 193 184.05 C196.43 179.79 197.8 183.78 201.59 176.5 C201.74 176.23 202.98 173.81 203.07 173.5 C204.03 170.36 201.1 167.99 203.16 164.5 C204.71 161.89 207.73 161.54 208.68 158.5 C209.32 156.45 210.62 153.14 209.96 151 C209.27 148.8 207.64 147.51 207.82 145 C208.05 141.79 211 140.77 211.85 138 C211.97 137.58 211.99 135.43 211.99 135 C212.1 125.18 208.23 128.62 207.82 123 C207.61 120.08 210.25 118.28 210.11 115.5 C210 113.45 209.23 109.75 208.14 108 C206.56 105.46 203.46 105.29 202.55 102 C201.92 99.73 203.15 98.16 203.27 96 C203.4 93.7 201.25 90.42 200 88.57 C197.96 85.54 193.8 86.33 192.17 82.5 C189.96 77.31 194.43 77.94 187.04 71 C184.35 68.47 180.59 70.07 178 67.05 C174.7 63.19 178.72 62.7 172 58.11 C171.64 57.86 169.43 56.36 169 56.19 C166.55 55.22 164.07 56.97 161.5 55.82 C158.54 54.49 158.72 51.51 156.5 49.69 C154.89 48.36 151.06 47.01 149 46.73 C146.34 46.37 144.32 48.71 141.5 48.14 C137.57 47.36 137.18 43.53 133 42.92 C131.21 42.66 128.8 42.02 127 42.35 C124.13 42.89 122.78 45.74 119.5 45.48 C115.56 45.17 115.2 42 110.5 42.49 Z",
+ parts: [
+ { fill: "body", d: "M110.5 42.49 C108.7 42.68 106.15 42.62 104.53 43.5 C101.84 44.96 101.77 47.78 98 48.22 C92.47 48.87 93.76 44.31 84.5 49.13 C81.79 50.53 81.81 53.93 79.12 55.5 C76.05 57.29 72.97 55.04 70 56.77 C60.87 62.1 65.76 62.65 62.04 67 C59.43 70.05 55.7 68.43 53 70.95 C51.59 72.27 49.26 74.49 48.5 76.31 C47.41 78.9 49 81.48 47 83.95 C43.57 88.21 42.2 84.22 38.41 91.5 C38.26 91.77 37.02 94.19 36.93 94.5 C35.97 97.64 38.9 100.01 36.84 103.5 C35.29 106.11 32.27 106.46 31.32 109.5 C30.68 111.55 29.38 114.86 30.04 117 C30.73 119.2 32.36 120.49 32.18 123 C31.95 126.21 29 127.23 28.15 130 C28.03 130.42 28.01 132.57 28.01 133 C27.9 142.82 31.77 139.38 32.18 145 C32.39 147.92 29.75 149.72 29.89 152.5 C30 154.55 30.77 158.25 31.86 160 C33.44 162.54 36.54 162.71 37.45 166 C38.08 168.27 36.85 169.84 36.73 172 C36.6 174.3 38.75 177.58 40 179.43 C42.04 182.46 46.2 181.67 47.83 185.5 C50.04 190.69 45.57 190.06 52.96 197 C55.65 199.53 59.41 197.93 62 200.95 C65.3 204.81 61.28 205.3 68 209.89 C68.36 210.14 70.57 211.64 71 211.81 C73.45 212.78 75.93 211.03 78.5 212.18 C81.46 213.51 81.28 216.49 83.5 218.31 C85.11 219.64 88.94 220.99 91 221.27 C93.66 221.63 95.68 219.29 98.5 219.86 C102.43 220.64 102.82 224.47 107 225.08 C108.79 225.34 111.2 225.98 113 225.65 C115.87 225.11 117.22 222.26 120.5 222.52 C124.44 222.83 124.8 226 129.5 225.51 C131.3 225.32 133.85 225.38 135.47 224.5 C138.16 223.04 138.23 220.22 142 219.78 C147.53 219.13 146.24 223.69 155.5 218.87 C158.21 217.47 158.19 214.07 160.88 212.5 C163.95 210.71 167.03 212.96 170 211.23 C179.13 205.9 174.24 205.35 177.96 201 C180.57 197.95 184.3 199.57 187 197.05 C188.41 195.73 190.74 193.51 191.5 191.69 C192.59 189.1 191 186.52 193 184.05 C196.43 179.79 197.8 183.78 201.59 176.5 C201.74 176.23 202.98 173.81 203.07 173.5 C204.03 170.36 201.1 167.99 203.16 164.5 C204.71 161.89 207.73 161.54 208.68 158.5 C209.32 156.45 210.62 153.14 209.96 151 C209.27 148.8 207.64 147.51 207.82 145 C208.05 141.79 211 140.77 211.85 138 C211.97 137.58 211.99 135.43 211.99 135 C212.1 125.18 208.23 128.62 207.82 123 C207.61 120.08 210.25 118.28 210.11 115.5 C210 113.45 209.23 109.75 208.14 108 C206.56 105.46 203.46 105.29 202.55 102 C201.92 99.73 203.15 98.16 203.27 96 C203.4 93.7 201.25 90.42 200 88.57 C197.96 85.54 193.8 86.33 192.17 82.5 C189.96 77.31 194.43 77.94 187.04 71 C184.35 68.47 180.59 70.07 178 67.05 C174.7 63.19 178.72 62.7 172 58.11 C171.64 57.86 169.43 56.36 169 56.19 C166.55 55.22 164.07 56.97 161.5 55.82 C158.54 54.49 158.72 51.51 156.5 49.69 C154.89 48.36 151.06 47.01 149 46.73 C146.34 46.37 144.32 48.71 141.5 48.14 C137.57 47.36 137.18 43.53 133 42.92 C131.21 42.66 128.8 42.02 127 42.35 C124.13 42.89 122.78 45.74 119.5 45.48 C115.56 45.17 115.2 42 110.5 42.49 Z" },
+ { fill: "#a8692b", d: "M93.5 50.95 C84.2 53.05 69.54 63.76 62.74 70.5 C23.83 109.08 31.36 176.49 81.5 201.68 C89.47 205.68 98.14 208.3 107 209.35 C116.52 210.48 126.24 209.8 135.5 207.31 C164.66 199.48 186.95 173.78 189.33 143.5 C192.65 101.31 156.21 64.42 113.5 71.68 C89.04 75.83 68.66 94.93 64.09 119.5 C57.81 153.24 83.71 186.58 119 184.46 C137.57 183.34 154.61 171.52 161.28 154 C170.67 129.3 156.23 100 129 96.42 C115.86 94.69 102.28 100.11 94.53 111 C83.78 126.11 87.67 149.25 105.5 157.09 C114.39 161.01 125.16 159.7 132.37 153 C134.18 151.32 138.65 146.12 137.56 143.5 C136.65 141.3 133.76 140.62 132.14 142.5 C131.4 143.36 131.16 144.55 130.55 145.5 C128.35 148.89 124.87 151.28 121 152.36 C111.69 154.96 102.03 149.75 97.57 141.5 C84.73 117.74 114.27 92.24 140 106.69 C161.3 118.65 163.21 148.04 146.98 165 C134.8 177.72 115.78 181.45 99.5 175.02 C69.42 163.16 61.11 125.79 79 100.23 C92.04 81.59 116.14 73.41 138 78.91 C177.03 88.72 194.13 133.84 175.5 168.34 C162.44 192.53 135.17 206.16 108 203.03 C64.27 198 36.31 154.58 46.2 112.5 C50.42 94.56 61.17 78.46 76 67.54 C80.23 64.43 84.75 61.74 89.5 59.51 C91.39 58.62 93.64 58.05 95.43 57 C98.47 55.23 97.28 50.09 93.5 50.95 Z" },
+ ],
+ },
+ jalebi: {
+ id: "jalebi",
+ name: "Jalebi",
+ paint: "bone",
+ bone: "#f7941d",
+ eyes: {cx: 120, cy: 128, dx: 30, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M111 46.46 C98.31 47.8 85.98 51.84 75 58.38 C65.1 64.27 56.39 72.11 49.5 81.33 C12.72 130.58 37.1 202.34 96.5 218.8 C107.2 221.77 118.46 222.69 129.5 221.49 C141.62 220.17 153.44 216.31 164 210.21 C174.31 204.26 183.38 196.21 190.5 186.67 C227.67 136.89 202.32 64.37 142 48.79 C131.92 46.19 121.35 45.37 111 46.46 Z",
+ parts: [
+ { fill: "#c9650c", d: "M111 46.46 C66.5 51.29 30.86 89.67 32.01 135 C32.21 143.1 34.35 151.44 37.15 159 C50.23 194.25 86.34 217.76 124 213.29 C148.37 210.41 170.75 195.84 182.5 174.16 C185.85 167.99 188.33 161.37 189.81 154.5 C190.24 152.52 190.58 150.51 190.84 148.5 C190.9 148 190.6 147.28 191.02 147 C192.04 146.31 194.35 149.04 195 149.49 C196.48 150.54 203.77 154.07 205.5 152.99 C205.97 152.7 206.06 152.03 206.24 151.5 C208.89 143.83 208.18 128.07 206.88 120 C199.53 74.41 157.06 41.46 111 46.46 Z" },
+ { fill: "body", d: "M119.5 41.47 C77.13 44.17 41.16 76.39 36.27 119 C30.32 170.89 74.59 217.91 127.5 208.75 C152.93 204.35 174.95 186.47 183.56 162 C196.52 125.13 175.17 82.72 135.5 75.85 C94.49 68.75 56.62 107.47 73.08 147.5 C75.45 153.28 78.95 158.56 83.35 163 C103.34 183.2 140.39 180.27 151.45 152 C156.14 140.01 153.75 126.23 145 116.71 C141.79 113.22 137.87 110.41 133.5 108.54 C132.27 108.01 125.29 106.81 128.5 105.3 C129.48 104.84 133.43 105.92 134.5 106.24 C140.62 108.09 145.99 112.04 149.96 117 C161.5 131.44 159.3 152.82 147 166.04 C126.62 187.95 91.64 182.67 75.11 159 C63.75 142.73 62.76 121.09 71.68 103.5 C92.18 63.1 146.85 61.52 174.92 94.5 C181.77 102.55 186.64 112.25 189.16 122.5 C190.47 127.79 190.36 136.13 192.48 140.5 C197.19 150.21 210.56 151.8 217.5 143.63 C219.32 141.48 220.49 138.78 220.87 136 C222.08 127.05 217.16 109.9 213.73 101.5 C198.41 64 160.17 38.89 119.5 41.47 Z" },
+ { fill: "#ffc566", d: "M119.5 50.48 C92.13 52.57 66.86 68.13 53.81 92.5 C50.53 98.63 48.07 105.21 46.55 112 C46.33 112.98 45.16 117.31 46 118 C46.77 118.64 48 118 49 118 C50.72 118 55.05 118.53 56.5 118 C57 117.82 57.46 117.45 57.74 117 C58.27 116.12 59.91 108.43 60.62 106.5 C62.97 100.1 66.32 94.09 70.5 88.71 C83.88 71.48 105.28 61.77 127 62.26 C149.28 62.77 170.44 73.85 184 91.46 C188.13 96.83 191.55 102.74 194.15 109 C194.7 110.31 196.78 117.5 197.5 118 C198.06 118.39 205.3 118 206.5 118 C207.5 118 208.86 118.77 209.5 118 C209.74 117.71 207.76 111.33 207.5 110.54 C205.03 103.12 201.6 96.03 197.3 89.5 C180.44 63.92 150.26 48.13 119.5 50.48 Z M123 83.99 C108.29 84.83 94.43 91.98 86 104.22 C85.03 105.63 79.16 116.42 79.83 117.5 C80.07 117.9 91.51 118.33 92 118 C92.08 117.94 93.38 115.09 93.42 115 C94.65 112.52 96.18 110.17 98 108.09 C104.68 100.45 114.38 96.07 124.5 95.86 C135.27 95.62 145.87 100.05 153.5 107.63 C155.56 109.67 160.86 117.41 160.97 117.5 C161.46 117.92 172.53 118.31 173 118 C174.73 116.85 172.93 114.66 172.34 113.5 C170.23 109.33 167.6 105.41 164.5 101.91 C154.16 90.26 138.7 83.09 123 83.99 Z M122 117.47 C122 118.17 124.83 118 125 118 C126 118 128 119 128 118 C128 116.6 122 117.41 122 117.47 Z" },
+ ],
+ },
+ katli: {
+ id: "katli",
+ name: "Kaju katli",
+ paint: "bone",
+ bone: "#f2e4c6",
+ eyes: {cx: 120, cy: 122, dx: 30, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M117.5 18.4 C113.87 19.89 111.22 23.46 108.5 26.19 C103.06 31.62 97.62 37.06 92.19 42.5 C73.46 61.23 54.73 79.96 36 98.69 C30.17 104.52 24.33 110.35 18.5 116.19 C15.74 118.94 13.14 121.77 14.25 126 C15.13 129.33 18.35 131.67 20.69 134 C26.12 139.44 31.56 144.88 37 150.31 C56.56 169.88 76.12 189.44 95.69 209 C101.12 214.44 106.56 219.88 112 225.31 C115.17 228.48 118.8 231.55 123.5 229.19 C126.94 227.47 143.48 209.83 147.5 205.81 C165.83 187.48 184.17 169.15 202.5 150.81 C208.33 144.98 214.17 139.15 220 133.31 C222.79 130.52 226.26 127.87 225.98 123.5 C225.75 119.83 222.91 117.6 220.5 115.19 C215.5 110.19 210.5 105.19 205.5 100.19 C185.1 79.79 164.71 59.4 144.31 39 C138.48 33.17 132.65 27.33 126.81 21.5 C124.39 19.08 121.08 16.94 117.5 18.4 Z",
+ parts: [
+ { fill: "#d9c39a", d: "M117.5 32.4 C113.87 33.89 111.22 37.46 108.5 40.19 C103.06 45.62 97.62 51.06 92.19 56.5 C73.46 75.23 54.73 93.96 36 112.69 C30.17 118.52 24.33 124.35 18.5 130.19 C15.74 132.94 13.14 135.77 14.25 140 C15.13 143.33 18.35 145.67 20.69 148 C26.12 153.44 31.56 158.88 37 164.31 C56.56 183.88 76.12 203.44 95.69 223 C101.12 228.44 106.56 233.88 112 239.31 C115.17 242.48 118.8 245.55 123.5 243.19 C126.94 241.47 143.48 223.83 147.5 219.81 C165.83 201.48 184.17 183.15 202.5 164.81 C208.33 158.98 214.17 153.15 220 147.31 C222.79 144.52 226.26 141.87 225.98 137.5 C225.75 133.83 222.91 131.6 220.5 129.19 C215.5 124.19 210.5 119.19 205.5 114.19 C185.1 93.79 164.71 73.4 144.31 53 C138.48 47.17 132.65 41.33 126.81 35.5 C124.39 33.08 121.08 30.94 117.5 32.4 Z" },
+ { fill: "body", d: "M117.5 18.4 C113.87 19.89 111.22 23.46 108.5 26.19 C103.06 31.62 97.62 37.06 92.19 42.5 C73.46 61.23 54.73 79.96 36 98.69 C30.17 104.52 24.33 110.35 18.5 116.19 C15.74 118.94 13.14 121.77 14.25 126 C15.13 129.33 18.35 131.67 20.69 134 C26.12 139.44 31.56 144.88 37 150.31 C56.56 169.88 76.12 189.44 95.69 209 C101.12 214.44 106.56 219.88 112 225.31 C115.17 228.48 118.8 231.55 123.5 229.19 C126.94 227.47 143.48 209.83 147.5 205.81 C165.83 187.48 184.17 169.15 202.5 150.81 C208.33 144.98 214.17 139.15 220 133.31 C222.79 130.52 226.26 127.87 225.98 123.5 C225.75 119.83 222.91 117.6 220.5 115.19 C215.5 110.19 210.5 105.19 205.5 100.19 C185.1 79.79 164.71 59.4 144.31 39 C138.48 33.17 132.65 27.33 126.81 21.5 C124.39 19.08 121.08 16.94 117.5 18.4 Z" },
+ { fill: "#cdd3db", d: "M116.5 50.48 C109.63 51.83 98.39 57.9 106.97 65.5 C112.3 70.23 121.35 70.74 128 69.43 C135.21 68.01 145.85 61 136.4 54 C131.01 50.01 122.93 49.21 116.5 50.48 Z M64 104.45 C56.72 105.58 41.53 112.42 50.5 121.56 C56.71 127.88 67.69 128.83 76 127.55 C83.28 126.42 98.47 119.58 89.5 110.44 C83.29 104.12 72.31 103.17 64 104.45 Z M164.5 121.42 C156.96 122.61 143.48 129.58 153.24 138 C159 142.97 168.3 143.71 175.5 142.58 C183.04 141.39 196.52 134.42 186.76 126 C181 121.03 171.7 120.29 164.5 121.42 Z M119 187.45 C112.47 188.8 102.49 195.04 111.34 201.5 C116.33 205.15 123.62 205.67 129.5 204.45 C135.47 203.22 144.64 197.57 137.5 191.17 C132.84 187 124.9 186.23 119 187.45 Z" },
+ ],
+ },
+ karanji: {
+ id: "karanji",
+ name: "Karanji",
+ paint: "bone",
+ bone: "#ecb460",
+ eyes: {cx: 120, cy: 150, dx: 30, w: 24, h: 44, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
+ clip: "M110.5 72.46 C61.45 77.23 24.93 117.01 12.78 163 C10.06 173.28 8.5 183.87 8.1 194.5 C8.05 195.91 7.65 204.26 8.09 205 C9.05 206.66 17.9 206 20 206 C32.5 206 45 206 57.5 206 C100.5 206 143.5 206 186.5 206 C197.5 206 208.5 206 219.5 206 C220.94 206 230.97 206.41 231.5 206 C232.39 205.31 231.94 195.58 231.88 194 C231.31 180.23 228.8 166.54 224.35 153.5 C207.85 105.16 163.52 67.3 110.5 72.46 Z",
+ parts: [
+ { fill: "body", d: "M117.5 65.91 C114.31 66.95 111.01 71.93 109.5 71.82 C106.46 71.59 104.87 65.82 98 67.92 C92.99 69.45 91.87 75.89 89.5 76.07 C86.62 76.28 83.82 70.96 77.5 74.5 C72.94 77.06 73.27 83.27 71 84.25 C69.72 84.8 67.69 83.51 66.5 83.21 C63.2 82.38 59.78 83.49 57.5 86 C54.74 89.05 56.04 95.08 53.5 96.25 C50.74 97.52 46.49 93.39 41.63 99 C38.01 103.19 40.95 109.28 39.13 111 C36.36 113.61 30.21 109.49 26.73 117 C24.62 121.54 28.47 126.92 26.51 129 C23.87 131.81 18.58 128.74 15.58 136 C13.31 141.49 18.38 145.09 17.5 148 C16.61 150.95 10.42 151 8.07 155.5 C4.29 162.75 12.23 166.45 11.03 170 C10.05 172.93 5.04 173.58 3.26 177.5 C0 184.68 5.89 186.57 7.8 190.5 C8.64 192.21 8.09 194.67 8.04 196.5 C8.02 197.45 7.85 205.24 8.1 205.5 C9.11 206.54 19.98 206 22 206 C35 206 48 206 61 206 C100.5 206 140 206 179.5 206 C191.5 206 203.5 206 215.5 206 C217.91 206 229.05 206.5 230.5 206 C231.05 205.81 231.62 205.5 231.91 205 C232.75 203.56 231.37 193.92 231.89 191.5 C232.84 187.02 239.51 186.13 237.11 178.5 C235.56 173.55 229.32 172.61 228.87 169.5 C228.54 167.17 231.05 165.36 231.99 163.5 C233.98 159.55 232.57 154.34 228.79 152 C226.86 150.81 223.84 150.71 222.67 148.5 C221.61 146.5 223.73 144.2 224.4 142.5 C225.57 139.55 225.05 135.99 223 133.55 C220.13 130.13 213.96 130.6 212.88 128 C211.69 125.12 216.15 121.28 212.73 116 C208.96 110.18 201.78 113.22 200.26 110 C198.78 106.87 202.98 102.98 197.5 98.12 C193.3 94.4 187.1 97.34 185.5 95.63 C183.08 93.03 186.94 86.9 179 83.55 C175.34 82 169.93 84.96 168.5 84.02 C165.62 82.12 168 75.76 160.5 73.69 C155.81 72.4 151.93 76.49 150 75.98 C147.68 75.37 147.13 69.17 141.5 67.78 C135.68 66.35 131.71 72.41 129.5 71.68 C127 70.85 125.09 63.45 117.5 65.91 Z" },
+ { fill: "#cf923d", d: "M111 87.49 C72.98 91.74 43.35 121.08 30.67 156 C27.67 164.25 25.55 172.81 24.31 181.5 C24.17 182.46 23.1 190.18 23.34 190.5 C24 191.36 32.51 191 34 191 C45.5 191 57 191 68.5 191 C103 191 137.5 191 172 191 C182 191 192 191 202 191 C204.21 191 214.14 191.52 215.5 191 C215.97 190.82 216.43 190.46 216.62 190 C217.01 189.03 215.63 181.02 215.39 179.5 C213.32 166.47 209.26 153.75 203.23 142 C185.79 108.01 150.26 83.1 111 87.49 Z M120 91.5 C158.05 91.62 189.39 118.96 203.36 153 C206.72 161.2 209.16 169.77 210.66 178.5 C210.79 179.25 211.87 185.81 211.73 186 C211.06 186.85 202.49 186.5 201 186.5 C191 186.5 181 186.5 171 186.5 C135.5 186.5 100 186.5 64.5 186.5 C55.5 186.5 46.5 186.5 37.5 186.5 C36.6 186.5 28.65 186.64 28.5 186.5 C27.99 186.02 29.32 178.58 29.51 177.5 C31.09 168.76 33.61 160.19 37.06 152 C51.13 118.58 82.4 91.38 120 91.5 Z" },
+ ],
+ },
+};
diff --git a/packages/phone-protocol/src/command-allowlist.ts b/packages/phone-protocol/src/command-allowlist.ts
new file mode 100644
index 0000000000..8430ab5990
--- /dev/null
+++ b/packages/phone-protocol/src/command-allowlist.ts
@@ -0,0 +1,18 @@
+/** An exact command in one engine instance and working directory. */
+export interface CommandAllowlistCandidate {
+ command: string;
+ cwd: string;
+ providerInstanceId: string;
+}
+
+export interface CommandAllowlistRule extends CommandAllowlistCandidate {
+ id: string;
+}
+
+export type CommandAllowRule = CommandAllowlistRule;
+
+export interface CommandAllowlistResponse {
+ rules: CommandAllowlistRule[];
+ context: { providerInstanceId: string; cwd: string | null };
+ supported: boolean;
+}
diff --git a/packages/phone-protocol/src/computer-ask.ts b/packages/phone-protocol/src/computer-ask.ts
new file mode 100644
index 0000000000..6cdf51dc8e
--- /dev/null
+++ b/packages/phone-protocol/src/computer-ask.ts
@@ -0,0 +1,129 @@
+// A bot on the person's own Cloud that needs their computer (its apps and screen, its files, or its terminal) when it
+// isn't available asks once with a card: what it wants and why, why it isn't available, and the one-tap fix. The English
+// mirrors src/locales/en.json `computerAsk.*` exactly (a test holds them together): the server has no i18n.
+
+/** The card's tool name: no engine has a tool by this name, and "Always allow" is never offered for it. */
+export const COMPUTER_ASK_TOOL = "turn_on_your_computer";
+/** The bots' tool that raises the card. */
+export const ASK_FOR_COMPUTER_TOOL = "ask_for_computer";
+export const DESKTOP_DOWNLOAD_URL = "https://www.openmausbot.com/download";
+
+export const COMPUTER_NEEDS = ["screen", "folders", "terminal"] as const;
+export type ComputerNeed = (typeof COMPUTER_NEEDS)[number];
+
+/**
+ * Why the computer can't give what's needed now. From the app on that computer: "paused" (the person paused it from its
+ * icon), and for apps and screen "starting", "permissions" (macOS hasn't allowed it), "blocked" (its helper is missing
+ * or stopped, as Windows Security does), "off" (Linux control is off), "not-running" and "unsupported"; "terminal-off"
+ * (running commands isn't turned on). Without the app there: "closed" (it was used before), "never", and "update" (an
+ * app too old to answer the card).
+ */
+export const COMPUTER_ASK_REASONS = [
+ "paused", "starting", "permissions", "blocked", "off", "not-running", "unsupported", "terminal-off", "closed", "never", "update",
+] as const;
+export type ComputerAskReason = (typeof COMPUTER_ASK_REASONS)[number];
+
+/** "asking" until an answer; "turning-on" once Turn on was tapped; "on" once it lends what was needed; "failed" when the
+ * app there couldn't turn it on (Turn on again tries again); "declined" for Not now; "ended" when the conversation
+ * was stopped or deleted. */
+export type ComputerAskState = "asking" | "turning-on" | "on" | "failed" | "declined" | "ended";
+
+export type ComputerDevice = "PC" | "Mac" | "computer";
+
+export interface ComputerAskCard {
+ need: ComputerNeed;
+ reason: ComputerAskReason;
+ device: ComputerDevice;
+ state: ComputerAskState;
+ /** What the bot wants to do and why, in its own words, cleaned. */
+ why?: string;
+}
+
+export interface ComputerAskField {
+ /** A bot on the person's own Cloud asks to turn on what it needs from their computer. */
+ computerAsk?: ComputerAskCard;
+}
+
+/** A tap on Turn on can fix this from wherever the card is: the app on that computer does it. */
+export function turnsOnFromHere(reason: ComputerAskReason): boolean {
+ return reason === "paused" || reason === "permissions" || reason === "blocked" || reason === "off" || reason === "not-running" || reason === "terminal-off";
+}
+
+/** The fix is getting the app there: install it, open it, or update it. */
+export function needsTheApp(reason: ComputerAskReason): boolean {
+ return reason === "closed" || reason === "never" || reason === "update";
+}
+
+export const COMPUTER_ASK_WORDS = {
+ "computerAsk.want.screen": "{name} wants to use your {device}'s apps and screen",
+ "computerAsk.want.folders": "{name} wants to use the files on your {device}",
+ "computerAsk.want.terminal": "{name} wants to run commands on your {device}",
+ "computerAsk.reason.paused": "Using your {device} is paused.",
+ "computerAsk.reason.starting": "Screen control is still starting on your {device}.",
+ "computerAsk.reason.permissions": "macOS hasn't allowed {app} to see and use the screen yet.",
+ "computerAsk.reason.blocked": "Screen control is blocked on your {device}.",
+ "computerAsk.reason.blockedPc": "Screen control is blocked on your PC: Windows Security may have stopped it.",
+ "computerAsk.reason.off": "Screen control is off on your {device}.",
+ "computerAsk.reason.notRunning": "Screen control isn't running on your {device}.",
+ "computerAsk.reason.unsupported": "Screen control can't work on your {device} right now.",
+ "computerAsk.reason.terminalOff": "Running commands isn't turned on for your {device}.",
+ "computerAsk.reason.closed": "{app} isn't open on your {device}. Open it there and {name} carries on.",
+ "computerAsk.reason.never": "{app} isn't on your computer yet. Install it, sign in to MausBot Cloud there, and {name} carries on.",
+ "computerAsk.reason.update": "{app} on your {device} needs an update first. Update it, and {name} carries on.",
+ "computerAsk.action.turnOn": "Turn on",
+ "computerAsk.action.tryAgain": "Try again",
+ "computerAsk.action.notNow": "Not now",
+ "computerAsk.action.getApp": "Get {app}",
+ "computerAsk.state.turningOn": "Turning on…",
+ "computerAsk.state.on": "Turned on. {name} is carrying on.",
+ "computerAsk.state.failed": "It didn't turn on.",
+ "computerAsk.state.declined": "Not now",
+ "computerAsk.state.ended": "No longer needed",
+} as const;
+
+export type ComputerAskKey = keyof typeof COMPUTER_ASK_WORDS;
+
+/** The product's name as the person reads it, as the app fills `{app}`. */
+export const COMPUTER_ASK_APP = "MausBot";
+
+export function computerAskText(key: ComputerAskKey, params: Record<string, string>): string {
+ return COMPUTER_ASK_WORDS[key].replace(/\{(\w+)\}/g, (whole, name: string) => (name === "app" ? params.app ?? COMPUTER_ASK_APP : params[name] ?? whole));
+}
+
+const WANT_KEY: Record<ComputerNeed, ComputerAskKey> = {
+ screen: "computerAsk.want.screen",
+ folders: "computerAsk.want.folders",
+ terminal: "computerAsk.want.terminal",
+};
+
+/** The card's headline: who wants what, from which computer. */
+export function computerAskHeadline(card: Pick<ComputerAskCard, "need" | "device">): { key: ComputerAskKey; params: Record<string, string> } {
+ return { key: WANT_KEY[card.need], params: { device: card.device } };
+}
+
+/** Why it isn't available, as a catalog key and its values. */
+export function computerAskReasonLine(card: Pick<ComputerAskCard, "reason" | "device">, name: string): { key: ComputerAskKey; params: Record<string, string> } {
+ const params = { device: card.device, name };
+ switch (card.reason) {
+ case "paused": return { key: "computerAsk.reason.paused", params };
+ case "starting": return { key: "computerAsk.reason.starting", params };
+ case "permissions": return { key: "computerAsk.reason.permissions", params };
+ case "blocked": return { key: card.device === "PC" ? "computerAsk.reason.blockedPc" : "computerAsk.reason.blocked", params };
+ case "off": return { key: "computerAsk.reason.off", params };
+ case "unsupported": return { key: "computerAsk.reason.unsupported", params };
+ case "terminal-off": return { key: "computerAsk.reason.terminalOff", params };
+ case "closed": return { key: "computerAsk.reason.closed", params };
+ case "never": return { key: "computerAsk.reason.never", params };
+ case "update": return { key: "computerAsk.reason.update", params };
+ default: return { key: "computerAsk.reason.notRunning", params };
+ }
+}
+
+/** What a bot wrote as its reason, made safe for one line on the card: no control or direction characters, at most 200. */
+export function cleanAskWhy(value: unknown): string | undefined {
+ if (typeof value !== "string") return undefined;
+ // eslint-disable-next-line no-control-regex
+ const line = value.replace(/[\u0000-\u001f\u007f‪-‮⁦-⁩]+/g, " ").replace(/\s+/g, " ").trim();
+ if (!line) return undefined;
+ return line.length > 200 ? `${line.slice(0, 199).trimEnd()}…` : line;
+}
diff --git a/packages/phone-protocol/src/connector-card.ts b/packages/phone-protocol/src/connector-card.ts
new file mode 100644
index 0000000000..f3a52f57c3
--- /dev/null
+++ b/packages/phone-protocol/src/connector-card.ts
@@ -0,0 +1,21 @@
+export interface ConnectorCardData {
+ /** What the card connects: a Composio app (absent or "composio"), or a sign-in to an MCP server ("mcp"). */
+ source?: "composio" | "mcp";
+ /** Composio toolkit slug, or the MCP server's name. It is validated server-side before every action. */
+ slug: string;
+ label: string;
+ description: string;
+ status: "required" | "authorizing" | "connected" | "failed";
+ /** Cards created by one agent request resume together after all connect. */
+ resumeKey: string;
+ /** Account alias supplied by the agent when adding a second account. */
+ alias?: string;
+ error?: string;
+ dismissed?: boolean;
+ /** A newer card for the same request replaced this one: it is hidden as `dismissed` is, and nothing waits on it. */
+ superseded?: boolean;
+ resumed?: boolean;
+ /** Stop ended the turn this card paused: it offers no action, and a
+ * connection made afterwards is kept but continues nothing. */
+ stopped?: boolean;
+}
diff --git a/packages/phone-protocol/src/connector-scopes.ts b/packages/phone-protocol/src/connector-scopes.ts
new file mode 100644
index 0000000000..e7a64f3f19
--- /dev/null
+++ b/packages/phone-protocol/src/connector-scopes.ts
@@ -0,0 +1,101 @@
+// Per-bot connection scopes: which connected apps a bot may use, and whether
+// only to read. Absent means every connected app, read and write; present, an
+// app not listed is off and "read" refuses anything that is not a read. The
+// harness enforces it at the connector relay; the app shows the control.
+import { KNOWN_READ_SLUGS } from "./outbound.ts";
+
+const READ_VERBS = new Set(["GET", "LIST", "FETCH", "SEARCH", "READ", "FIND", "RETRIEVE", "LOOKUP", "DOWNLOAD", "VIEW", "CHECK", "COUNT"]);
+
+interface ScopedCall {
+ slug: string;
+}
+
+export type ConnectorScope = "read" | "write";
+
+export interface ConnectorScopes {
+ /** toolkit slug (lower case, Composio's) → what this bot may do with it */
+ apps: Record<string, ConnectorScope>;
+}
+
+const TOOLKIT_SLUG = /^[a-z0-9][a-z0-9_-]{0,63}$/;
+
+/** The toolkit a Composio slug belongs to: the part before the first
+ * underscore, lower-cased. A workbench API proxy belongs to no app. */
+export function toolkitOf(slug: string): string {
+ const cut = slug.indexOf("_");
+ return (cut > 0 ? slug.slice(0, cut) : slug).toLowerCase();
+}
+
+/** Toolkits whose actions name a one-word resource before the verb
+ * (HIGHLEVEL_MCP_CONTACTS_GET_CONTACTS lists contacts). Anything else there,
+ * such as a longer resource name, stays a write. */
+const RESOURCE_FIRST_TOOLKITS = ["highlevel_mcp"];
+
+/** A read verb first means the tool reads. Creating a draft writes to the
+ * account even though it sends nothing, so it is a write here. */
+export function isReadOnlyAction(slug: string, toolkit?: string): boolean {
+ if (slug === "COMPOSIO_PROXY_EXECUTE") return false;
+ if (KNOWN_READ_SLUGS.has(slug)) return true;
+ const resourceFirst = RESOURCE_FIRST_TOOLKITS.find((candidate) => (toolkit ?? candidate) === candidate && slug.startsWith(candidate.toUpperCase() + "_"));
+ const cut = resourceFirst ? resourceFirst.length : toolkit ? toolkit.length : slug.indexOf("_");
+ const action = cut > 0 ? slug.slice(cut + 1) : "";
+ const verb = action.toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean)[resourceFirst ? 1 : 0];
+ return verb !== undefined && READ_VERBS.has(verb);
+}
+
+/** The stored shape, or null when the value is not one. */
+export function normalizeConnectorScopes(value: unknown): ConnectorScopes | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const raw = (value as { apps?: unknown }).apps;
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
+ const apps: Record<string, ConnectorScope> = Object.create(null);
+ for (const [key, scope] of Object.entries(raw as Record<string, unknown>)) {
+ const slug = key.trim().toLowerCase();
+ if (!TOOLKIT_SLUG.test(slug)) return null;
+ if (scope !== "read" && scope !== "write") return null;
+ apps[slug] = scope;
+ }
+ return { apps };
+}
+
+export type ConnectorAccess =
+ | { ok: true }
+ | { ok: false; slug: string; toolkit: string; reason: "app" | "write" };
+
+/** May this bot run these calls? The first refusal wins, so a batch that
+ * mixes an allowed read with a forbidden write is refused whole rather
+ * than half-run. */
+export function connectorAccessDecision(scopes: ConnectorScopes | undefined, calls: ScopedCall[], toolkits: readonly string[] = []): ConnectorAccess {
+ if (!scopes) return { ok: true };
+ for (const call of calls) {
+ const toolkit = toolkits.filter(candidate => call.slug.startsWith(candidate.toUpperCase() + "_"))
+ .sort((a, b) => b.length - a.length)[0] ?? toolkitOf(call.slug);
+ const scope = call.slug === "COMPOSIO_PROXY_EXECUTE" || !Object.hasOwn(scopes.apps, toolkit) ? undefined : scopes.apps[toolkit];
+ if (!scope) return { ok: false, slug: call.slug, toolkit, reason: "app" };
+ if (scope === "read" && !isReadOnlyAction(call.slug, toolkit)) return { ok: false, slug: call.slug, toolkit, reason: "write" };
+ }
+ return { ok: true };
+}
+
+/** A bot whose scopes switch an app on gets that app's tools: every one, unless its tool list already names some. A tool
+ * list that leaves out an app its scopes turn on would give that app no tool on any engine. True when `bot` changed. */
+export function grantScopedApps(bot: { connectorScopes?: ConnectorScopes; connectorTools?: Record<string, { tools: "*" | string[] }> }): boolean {
+ const tools = bot.connectorTools, scopes = bot.connectorScopes;
+ if (!scopes || !tools || typeof tools !== "object" || Array.isArray(tools)) return false;
+ const missing = Object.keys(scopes.apps).filter((slug) => !Object.hasOwn(tools, slug));
+ if (!missing.length) return false;
+ bot.connectorTools = { ...tools, ...Object.fromEntries(missing.map((slug) => [slug, { tools: "*" as const }])) };
+ return true;
+}
+
+/** One sentence for the bot's prompt, so it does not spend a turn finding
+ * out. Empty when the bot is unscoped. */
+export function describeConnectorScopes(scopes: ConnectorScopes | undefined): string {
+ if (!scopes) return "";
+ const entries = Object.entries(scopes.apps);
+ if (entries.length === 0) return " This bot has been given no connected apps; do not try to use any.";
+ const listed = entries
+ .map(([slug, scope]) => `${slug} (${scope === "read" ? "read only" : "read and write"})`)
+ .join(", ");
+ return ` This bot may use only these connected apps: ${listed}. Do not try others, and do not write to a read-only one.`;
+}
diff --git a/packages/phone-protocol/src/credential-request.ts b/packages/phone-protocol/src/credential-request.ts
new file mode 100644
index 0000000000..f55e45d75b
--- /dev/null
+++ b/packages/phone-protocol/src/credential-request.ts
@@ -0,0 +1,324 @@
+import { MODELGO_URL } from "./modelgo.ts";
+/**
+ * Credentials an agent may ask the person to provide through an inline
+ * card. The id is the entire authority surface: agents never choose a
+ * config path, label, URL, or arbitrary field name.
+ */
+export const CREDENTIAL_TARGETS = {
+ xaiApiKey: {
+ label: "xAI API key",
+ description: "Used by the built-in Grok provider.",
+ placeholder: "xai-…",
+ helpUrl: "https://console.x.ai/",
+ },
+ boxToken: {
+ label: "Boat API key",
+ description: "Gives bots an isolated cloud computer when Boat is selected.",
+ placeholder: "Paste your Boat API key",
+ helpUrl: "https://docs.boat.dev/api-keys",
+ },
+ opencodeGoApiKey: {
+ label: "OpenCode API key",
+ description: "Used for OpenCode Zen and Go.",
+ placeholder: "Paste your OpenCode API key",
+ helpUrl: "https://opencode.ai/docs/providers/",
+ },
+ ttsKey: {
+ label: "ElevenLabs API key",
+ description: "Enables text-to-speech voices in calls.",
+ placeholder: "Paste your ElevenLabs API key",
+ helpUrl: "https://elevenlabs.io/app/settings/api-keys",
+ },
+ geminiTtsKey: {
+ label: "Gemini speech API key",
+ description: "Generates spoken replies, voice notes and call speech with Gemini.",
+ placeholder: "Paste your Google AI Studio API key",
+ helpUrl: "https://aistudio.google.com/api-keys",
+ },
+ fishAudioKey: {
+ label: "Fish Audio API key",
+ description: "Enables Fish Audio voices in calls.",
+ placeholder: "Paste your Fish Audio API key",
+ helpUrl: "https://fish.audio/app/api-keys/",
+ },
+ openaiImageApiKey: {
+ label: "OpenAI API key",
+ description: "Used to generate images in chats and bot avatars when OpenAI is the image provider.",
+ placeholder: "sk-…",
+ helpUrl: "https://platform.openai.com/api-keys",
+ },
+ onePasswordToken: {
+ label: "1Password service account token",
+ description: "Lets bots sign in with the website logins in the 1Password vault this token can read, the way Settings → Logins does.",
+ placeholder: "ops_…",
+ helpUrl: "https://developer.1password.com/docs/service-accounts/get-started/",
+ },
+ composioApiKey: {
+ label: "Composio API key",
+ description: "Connects apps such as Gmail, Slack and GitHub through your own Composio project.",
+ placeholder: "ak_…",
+ helpUrl: "https://dashboard.composio.dev/~/project/settings/api-keys",
+ },
+ openaiApiKey: {
+ label: "OpenAI API key",
+ description: "Runs OpenAI models with your own key.",
+ placeholder: "sk-…",
+ helpUrl: "https://platform.openai.com/api-keys",
+ },
+ anthropicApiKey: {
+ label: "Anthropic API key",
+ description: "Runs Claude models with your own key. Bots signed in to Claude keep using their sign-in.",
+ placeholder: "sk-ant-…",
+ helpUrl: "https://console.anthropic.com/settings/keys",
+ },
+ openrouterApiKey: {
+ label: "OpenRouter API key",
+ description: "Runs models from many providers through OpenRouter.",
+ placeholder: "sk-or-v1-…",
+ helpUrl: "https://openrouter.ai/keys",
+ },
+ mistralApiKey: {
+ label: "Mistral API key",
+ description: "Runs Mistral models with your own key.",
+ placeholder: "Paste your Mistral API key",
+ helpUrl: "https://console.mistral.ai/api-keys",
+ },
+ cerebrasApiKey: {
+ label: "Cerebras API key",
+ description: "Runs Cerebras models with your own key.",
+ placeholder: "csk-…",
+ helpUrl: "https://cloud.cerebras.ai/",
+ },
+ groqApiKey: {
+ label: "Groq API key",
+ description: "Runs Groq models with your own key.",
+ placeholder: "gsk_…",
+ helpUrl: "https://console.groq.com/keys",
+ },
+ greenferenceApiKey: {
+ label: "Greenference API key",
+ description: "Runs Greenference models with your own key.",
+ placeholder: "Paste your Greenference API key",
+ helpUrl: "https://greenference.com/dashboard/tokens",
+ },
+ modelgoApiKey: {
+ label: "ModelGo API key",
+ description: "Runs ModelGo models with your own key.",
+ placeholder: "Paste your ModelGo API key",
+ helpUrl: MODELGO_URL,
+ },
+ metaApiKey: {
+ label: "Meta API key",
+ description: "Runs Meta's models with your own key.",
+ placeholder: "LLM|…",
+ helpUrl: "https://dev.meta.ai/docs/authentication",
+ },
+ deepseekApiKey: {
+ label: "DeepSeek API key",
+ description: "Runs DeepSeek models with your own key.",
+ placeholder: "sk-…",
+ helpUrl: "https://platform.deepseek.com/api_keys",
+ },
+} as const;
+
+export type CredentialTargetId = keyof typeof CREDENTIAL_TARGETS;
+/** Saved in the sealed login store, not the settings file. */
+export type LoginCredentialTargetId = "onePasswordToken";
+export type ConfigCredentialTargetId = Exclude<CredentialTargetId, LoginCredentialTargetId>;
+/** AI provider keys: refused where Admin manages the models, and typed only in the computer's own app or a desktop paired to it, never on a phone. */
+export const PROVIDER_CREDENTIAL_TARGETS = [
+ "openaiApiKey", "anthropicApiKey", "openrouterApiKey", "mistralApiKey", "cerebrasApiKey", "groqApiKey", "greenferenceApiKey", "modelgoApiKey", "metaApiKey", "deepseekApiKey",
+] as const satisfies readonly ConfigCredentialTargetId[];
+export type DesktopCredentialSlot = ConfigCredentialTargetId;
+export type CredentialConfig = {
+ xai?: { key?: string };
+ box?: { token?: string };
+ opencodeGo?: { apiKey?: string };
+ tts?: { key?: string; fishKey?: string; geminiKey?: string };
+ imageGen?: { key?: string };
+ composio?: { apiKey?: string };
+ openai?: { key?: string };
+ anthropic?: { key?: string; everyClaudeBot?: boolean };
+ openrouter?: { key?: string };
+ mistral?: { key?: string };
+ cerebras?: { key?: string };
+ groq?: { key?: string };
+ greenference?: { key?: string };
+ modelgo?: { key?: string };
+ meta?: { key?: string };
+ deepseek?: { key?: string };
+ /** Not in the settings file: the server fills it from its login store. */
+ onePassword?: { connected?: boolean };
+};
+
+/** A secret OpenMausBot does not keep itself: the bot names it, and gets a one-use reference or a private file. */
+export const CUSTOM_SECRET_TARGET = "customSecret";
+export type SecretDelivery = "ref" | "file";
+export const SECRET_DELIVERIES: readonly SecretDelivery[] = ["ref", "file"];
+export const CUSTOM_SECRET_LABEL_MAX = 80;
+export const CUSTOM_SECRET_REASON_MAX = 240;
+
+export function isCredentialTargetId(value: unknown): value is CredentialTargetId {
+ return typeof value === "string" && Object.prototype.hasOwnProperty.call(CREDENTIAL_TARGETS, value);
+}
+
+export function isConfigCredentialTarget(id: CredentialTargetId): id is ConfigCredentialTargetId {
+ return id !== "onePasswordToken";
+}
+
+export function isProviderCredentialTarget(id: CredentialTargetId): boolean {
+ return (PROVIDER_CREDENTIAL_TARGETS as readonly string[]).includes(id);
+}
+
+/** The desktop's encrypted-store slot that holds this key, where Settings saves it; null for the 1Password token, which Logins keeps. */
+export function desktopCredentialSlot(id: CredentialTargetId): DesktopCredentialSlot | null {
+ return isConfigCredentialTarget(id) ? id : null;
+}
+
+/** Where a card saves what the person typed: the 1Password token goes to Logins, which checks it reaches 1Password. */
+export function credentialSaveRequest(id: CredentialTargetId, value: string): { path: string; method: "PUT" | "POST"; body: object } {
+ return isConfigCredentialTarget(id)
+ ? { path: "/api/config", method: "PUT", body: credentialConfigPatch(id, value) }
+ : { path: "/api/logins/1password", method: "POST", body: { token: value } };
+}
+
+export function credentialConfigPatch(id: ConfigCredentialTargetId, value: string): CredentialConfig {
+ switch (id) {
+ case "xaiApiKey":
+ return { xai: { key: value } };
+ case "boxToken":
+ return { box: { token: value } };
+ case "opencodeGoApiKey":
+ return { opencodeGo: { apiKey: value } };
+ case "ttsKey":
+ return { tts: { key: value } };
+ case "geminiTtsKey":
+ return { tts: { geminiKey: value } };
+ case "fishAudioKey":
+ return { tts: { fishKey: value } };
+ case "openaiImageApiKey":
+ return { imageGen: { key: value } };
+ case "composioApiKey":
+ return { composio: { apiKey: value } };
+ case "openaiApiKey":
+ return { openai: { key: value } };
+ // Settings' first Anthropic key leaves every bot signed in to Claude on its sign-in; a card appears only while none is set.
+ case "anthropicApiKey":
+ return { anthropic: { key: value, everyClaudeBot: false } };
+ case "openrouterApiKey":
+ return { openrouter: { key: value } };
+ case "mistralApiKey":
+ return { mistral: { key: value } };
+ case "cerebrasApiKey":
+ return { cerebras: { key: value } };
+ case "groqApiKey":
+ return { groq: { key: value } };
+ case "greenferenceApiKey":
+ return { greenference: { key: value } };
+ case "modelgoApiKey":
+ return { modelgo: { key: value } };
+ case "metaApiKey":
+ return { meta: { key: value } };
+ case "deepseekApiKey":
+ return { deepseek: { key: value } };
+ }
+}
+
+export function credentialIsConfigured(config: CredentialConfig, id: CredentialTargetId): boolean {
+ switch (id) {
+ case "xaiApiKey":
+ return Boolean(config.xai?.key);
+ case "boxToken":
+ return Boolean(config.box?.token);
+ case "opencodeGoApiKey":
+ return Boolean(config.opencodeGo?.apiKey);
+ case "ttsKey":
+ return Boolean(config.tts?.key);
+ case "geminiTtsKey":
+ return Boolean(config.tts?.geminiKey);
+ case "fishAudioKey":
+ return Boolean(config.tts?.fishKey);
+ case "openaiImageApiKey":
+ return Boolean(config.imageGen?.key);
+ case "onePasswordToken":
+ return Boolean(config.onePassword?.connected);
+ case "composioApiKey":
+ return Boolean(config.composio?.apiKey);
+ case "openaiApiKey":
+ return Boolean(config.openai?.key);
+ case "anthropicApiKey":
+ return Boolean(config.anthropic?.key);
+ case "openrouterApiKey":
+ return Boolean(config.openrouter?.key);
+ case "mistralApiKey":
+ return Boolean(config.mistral?.key);
+ case "cerebrasApiKey":
+ return Boolean(config.cerebras?.key);
+ case "groqApiKey":
+ return Boolean(config.groq?.key);
+ case "greenferenceApiKey":
+ return Boolean(config.greenference?.key);
+ case "modelgoApiKey":
+ return Boolean(config.modelgo?.key);
+ case "metaApiKey":
+ return Boolean(config.meta?.key);
+ case "deepseekApiKey":
+ return Boolean(config.deepseek?.key);
+ }
+}
+
+/** A still-pending credential card for this target — the set a newer
+ * request supersedes. Provided, dismissed, and already-superseded cards
+ * keep their settled state untouched. */
+export function isPendingCredentialRequest(
+ message: {
+ kind?: unknown;
+ secret?: { target?: unknown; provided?: unknown; dismissed?: unknown; superseded?: unknown };
+ from?: { botId?: unknown };
+ },
+ target: CredentialTargetId,
+ requestingBotId: string,
+ roomThread: boolean,
+): boolean {
+ return (
+ message.kind === "secret" &&
+ message.secret?.target === target &&
+ message.secret.provided !== true &&
+ message.secret.dismissed !== true &&
+ message.secret.superseded !== true &&
+ (!roomThread || message.from?.botId === requestingBotId)
+ );
+}
+
+/** A still-pending card from this bot for a custom secret with the same name, which a newer request supersedes. */
+export function isPendingCustomSecretRequest(
+ message: {
+ kind?: unknown;
+ secret?: { target?: unknown; label?: unknown; provided?: unknown; dismissed?: unknown; superseded?: unknown };
+ from?: { botId?: unknown };
+ },
+ label: string,
+ requestingBotId: string,
+ roomThread: boolean,
+): boolean {
+ return (
+ message.kind === "secret" &&
+ message.secret?.target === CUSTOM_SECRET_TARGET &&
+ typeof message.secret.label === "string" &&
+ message.secret.label.toLowerCase() === label.toLowerCase() &&
+ message.secret.provided !== true &&
+ message.secret.dismissed !== true &&
+ message.secret.superseded !== true &&
+ (!roomThread || message.from?.botId === requestingBotId)
+ );
+}
+
+export function credentialResumeOutcome(state: {
+ provided?: unknown;
+ dismissed?: unknown;
+}): "provided" | "dismissed" | null {
+ const provided = state.provided === true;
+ const dismissed = state.dismissed === true;
+ if (provided === dismissed) return null;
+ return provided ? "provided" : "dismissed";
+}
diff --git a/packages/phone-protocol/src/data-surface.ts b/packages/phone-protocol/src/data-surface.ts
new file mode 100644
index 0000000000..c776ebf974
--- /dev/null
+++ b/packages/phone-protocol/src/data-surface.ts
@@ -0,0 +1,254 @@
+// The Data surface: what the server, the bots' tools and the panel agree on.
+// DuckDB runs in the OMB server, one database per bot.
+
+/** The five tools a bot gets, in the order the catalog lists them. */
+export const DATA_TOOL_NAMES = ["data_load", "data_describe", "data_sql", "data_show", "data_export"] as const;
+export type DataToolName = (typeof DATA_TOOL_NAMES)[number];
+
+/** Bounds. Every result is capped by rows AND bytes; the gate's own trimming
+ * is the backstop, never the plan. */
+export const DATA_LIMITS = {
+ /** `data_sql` rows returned to the model by default, and at most. */
+ sqlRowsDefault: 50,
+ sqlRowsMax: 500,
+ /** Bytes of rows `data_sql` returns to the model. */
+ sqlBytesMax: 32 * 1024,
+ /** `data_describe` result bytes; beyond `describeColumnsMax` columns, types only. */
+ describeBytesMax: 16 * 1024,
+ describeColumnsMax: 50,
+ /** Sample values per column, each at most `sampleChars` characters. */
+ sampleValues: 3,
+ sampleChars: 40,
+ /** Rows per page the panel's grid asks for (Tad's proven size). */
+ pageSize: 1024,
+ /** Marks a chart may render after its SQL reduction. */
+ chartMaxMarks: 10_000,
+ /** Rows `data_show kind:"table"` keeps for the panel; the grid pages them. */
+ showTableRowsMax: 1_000_000,
+ /** One statement's wall clock before `interrupt()`. */
+ sqlTimeoutMs: 60_000,
+ /** Cards a sheet holds; the oldest unpinned card goes first. */
+ sheetCardsMax: 200,
+} as const;
+
+/** Where materialised results live inside a bot's database. DuckDB temp tables
+ * are per connection; a real schema is visible to both and survives a restart. */
+export const DATA_RESULTS_SCHEMA = "omb_results";
+
+export type DataErrorCode =
+ | "invalid_input"
+ | "source_not_found"
+ | "source_unsupported"
+ | "sql_error"
+ | "write_refused"
+ | "table_not_found"
+ | "spec_invalid"
+ | "card_not_found"
+ | "output_too_large"
+ | "timeout"
+ | "cancelled"
+ | "engine_unavailable";
+
+/** The structured failure every tool and route returns. `line` is DuckDB's
+ * own 1-based line in `sql`; `message` is DuckDB's text, never reworded. */
+export interface DataError {
+ code: DataErrorCode;
+ message: string;
+ sql?: string;
+ line?: number;
+ hint?: string;
+ retryable?: boolean;
+ /** For `table_not_found`: close names the bot can use instead. */
+ candidates?: string[];
+}
+
+export interface DataColumn {
+ name: string;
+ /** DuckDB's type name as `DESCRIBE` prints it (BIGINT, VARCHAR, DECIMAL(10,2), …). */
+ type: string;
+ nullPct?: number;
+ approxUnique?: number;
+ min?: string | null;
+ max?: string | null;
+ /** Up to DATA_LIMITS.sampleValues distinct values, as text. */
+ sample?: string[];
+}
+
+/** One entry of the bot's table catalog, as GET /data reports it from DuckDB. */
+export interface DataTable {
+ name: string;
+ /** A quoted identifier ready to paste into SQL; `name` remains the identity. */
+ sqlName?: string;
+ rowCount: number;
+ columns: DataColumn[];
+}
+
+/** A table the bot loaded, as the Sources strip and `data_load` report it. */
+export interface DataSource {
+ name: string;
+ /** A quoted identifier ready to paste into SQL; name remains the source identity. */
+ sqlName?: string;
+ kind: "csv" | "parquet" | "json" | "xlsx" | "folder" | "url" | "postgres" | "mysql" | "sqlite" | "gsheet" | "connector" | "sql";
+ /** The path, URL or connection the table came from, with credentials removed. */
+ source: string;
+ options?: Record<string, string | number | boolean>;
+ rowCount: number;
+ columns: DataColumn[];
+ loadedAt: string;
+}
+
+/** What a bot says when it wants a chart. Small on purpose: the server
+ * compiles it to SQL (with the reduction) and to Vega-Lite, so the model
+ * never writes a chart grammar. */
+export interface OmbChartSpec {
+ type: "bar" | "line" | "area" | "scatter" | "histogram" | "pie" | "heatmap";
+ /** Column for the x axis (the category, the time, or the value to bin). */
+ x: string;
+ /** Column for the y axis. Absent means count. */
+ y?: string;
+ /** Column to colour by (series, stack segments, heatmap cells). */
+ color?: string;
+ /** How y is aggregated per x (and colour). Default: sum when y is set, else count. */
+ agg?: "count" | "sum" | "avg" | "min" | "max" | "median";
+ /** Order of categories. Default: by x. */
+ sort?: "x" | "-x" | "y" | "-y";
+ /** Categories to keep (the rest fold into "other"). Default 20 for categorical x. */
+ limit?: number;
+ stack?: boolean;
+ /** Bucket a date or timestamp x. Default: chosen from the x range. */
+ timeUnit?: "hour" | "day" | "week" | "month" | "quarter" | "year";
+ /** Histogram bins. Default 30. */
+ bins?: number;
+ /** Column for mark size (scatter). */
+ size?: string;
+}
+
+/** How the compiler shrank the data before charting, shown on the card. */
+export interface DataReduction {
+ method: "group" | "bins" | "topN" | "timeBucket" | "m4" | "sample" | "none";
+ inputRows: number;
+ outputRows: number;
+ note?: string;
+}
+
+export type DataCardKind = "table" | "chart" | "text";
+
+/** One card on the sheet. The SQL is always kept so Refresh re-runs it; the
+ * result table is `${DATA_RESULTS_SCHEMA}.${result}` while it exists. */
+export interface DataCard {
+ id: string;
+ kind: DataCardKind;
+ title: string;
+ /** The SQL whose result this card shows (table and chart cards). */
+ sql?: string;
+ /** The materialised result table in DATA_RESULTS_SCHEMA, or null while running or failed. */
+ result?: string | null;
+ columns?: DataColumn[];
+ rowCount?: number;
+ truncated?: boolean;
+ /** Chart cards: the bot's spec, the compiled Vega-Lite (data-free; the
+ * panel binds the reduced rows as the dataset named "table"), the reduction. */
+ chart?: OmbChartSpec;
+ vegaLite?: Record<string, unknown>;
+ reduction?: DataReduction;
+ /** Text cards: Markdown. */
+ text?: string;
+ status: "running" | "ready" | "failed";
+ error?: DataError;
+ /** Who made or last changed it: the bot (tool) or the person (panel). */
+ by: "bot" | "person";
+ pinned?: boolean;
+ createdAt: string;
+ updatedAt: string;
+ elapsedMs?: number;
+}
+
+/** The sheet: what the Data tab shows and what `sheet.json` stores. */
+export interface DataSheet {
+ version: 1;
+ botId: string;
+ cards: DataCard[];
+ sources: DataSource[];
+ updatedAt: string;
+}
+
+/** Server → client. One message carries the whole sheet (sheets hold no rows).
+ * The database's catalog is not on it: GET /api/bots/:id/data reads it fresh. */
+export interface DataBroadcast {
+ kind: "data";
+ botId: string;
+ sheet: DataSheet;
+}
+
+/** Panel routes, all under `/api/bots/:botId/data`. The person's own
+ * actions take the same paths as the bot's tools inside the server. */
+export interface DataPageRequest {
+ /** A source table name, or a card id (its result table). Exactly one. */
+ table?: string;
+ cardId?: string;
+ offset: number;
+ limit: number;
+ sort?: { column: string; direction: "asc" | "desc" };
+ /** Case-insensitive literal text matching, across all columns unless filterColumn is set. */
+ filter?: string;
+ /** Exact column name to search; values are cast to text. */
+ filterColumn?: string;
+}
+
+export interface DataPage {
+ columns: DataColumn[];
+ /** Cells as JSON: DuckDB bigints and decimals arrive as strings. */
+ rows: Array<Array<string | number | boolean | null>>;
+ rowCount: number;
+ offset: number;
+}
+
+export interface DataRunRequest {
+ sql: string;
+ /** Update this card instead of adding one. */
+ cardId?: string;
+ title?: string;
+ /** Chart the result instead of tabling it. */
+ chart?: OmbChartSpec;
+ vegaLite?: Record<string, unknown>;
+ /** Replace an existing result only after a successful, current live edit. */
+ live?: boolean;
+}
+
+export interface DataColumnStats {
+ table: string;
+ rowCount: number;
+ columns: DataColumn[];
+}
+
+export interface DataHistogram {
+ table: string;
+ column: string;
+ /** Numeric and date columns: equal-width bins; text: top values. */
+ bins: Array<{ label: string; count: number }>;
+}
+
+export type DataExportFormat = "csv" | "parquet" | "xlsx" | "png" | "svg";
+
+export interface DataExportRequest {
+ cardId?: string;
+ table?: string;
+ format: DataExportFormat;
+}
+
+export const DATA_ROUTES = {
+ sheet: (botId: string) => `/api/bots/${encodeURIComponent(botId)}/data`,
+ page: (botId: string) => `/api/bots/${encodeURIComponent(botId)}/data/page`,
+ run: (botId: string) => `/api/bots/${encodeURIComponent(botId)}/data/run`,
+ cancel: (botId: string) => `/api/bots/${encodeURIComponent(botId)}/data/cancel`,
+ card: (botId: string, cardId: string) => `/api/bots/${encodeURIComponent(botId)}/data/cards/${encodeURIComponent(cardId)}`,
+ stats: (botId: string, table: string) => `/api/bots/${encodeURIComponent(botId)}/data/tables/${encodeURIComponent(table)}/stats`,
+ histogram: (botId: string, table: string, column: string) =>
+ `/api/bots/${encodeURIComponent(botId)}/data/tables/${encodeURIComponent(table)}/histogram?column=${encodeURIComponent(column)}`,
+ export: (botId: string) => `/api/bots/${encodeURIComponent(botId)}/data/export`,
+ /** Server-rendered chart image for phones, Slack and email. */
+ image: (botId: string, cardId: string) => `/api/bots/${encodeURIComponent(botId)}/data/cards/${encodeURIComponent(cardId)}/image`,
+} as const;
+
+/** The tab's id in the Computer panel and the storage key suffix. */
+export const DATA_PANEL_VIEW = "data" as const;
diff --git a/packages/phone-protocol/src/default-bot.ts b/packages/phone-protocol/src/default-bot.ts
new file mode 100644
index 0000000000..52bc8930a4
--- /dev/null
+++ b/packages/phone-protocol/src/default-bot.ts
@@ -0,0 +1,48 @@
+import type { HelperFollowupField } from "./helper-followup.ts";
+import type { MausColor } from "./wire.ts";
+
+/** MausBot: every person's built-in helper. A new install's first bot (its Chief of Staff too); an existing place or
+ * person without one is given one once. It can be renamed and recoloured, hidden from the sidebar, never deleted. */
+export const DEFAULT_BOT_NAME = "MausBot";
+export const DEFAULT_BOT_COLOR: MausColor = "chrome";
+
+export interface DefaultBotMark {
+ /** Team Cloud only: the lowercased email of the member this MausBot belongs to. Absent: the place's own. */
+ person?: string;
+}
+
+export interface DefaultBotFields {
+ /** This bot is its place's (or, on a Team Cloud, its member's) MausBot. Never deleted or archived. */
+ defaultBot?: DefaultBotMark;
+ /** Settings → General "Show MausBot in the sidebar" is off: the bot keeps working, only its sidebar row is gone. */
+ sidebarHidden?: boolean;
+ /** Its person has seen MausBot's first-launch welcome here and chose Add or Not now. */
+ welcomed?: boolean;
+}
+
+export interface HelperIntroField extends HelperFollowupField {
+ /** MausBot's introduction. Clients that know it say it in the viewer's language with example asks; `text` is the
+ * English fallback the model and older clients read. */
+ helperIntro?: true;
+}
+
+export const defaultBotPerson = (bot: DefaultBotFields): string => bot.defaultBot?.person?.trim().toLowerCase() ?? "";
+
+/** The MausBot a viewer sees as theirs: their own on a Team Cloud (by email), else the place's. */
+export function viewersDefaultBot<T extends DefaultBotFields>(bots: readonly T[], email?: string | null): T | undefined {
+ const person = email?.trim().toLowerCase() ?? "";
+ return (person ? bots.find((bot) => bot.defaultBot && defaultBotPerson(bot) === person) : undefined)
+ ?? bots.find((bot) => bot.defaultBot && !defaultBotPerson(bot));
+}
+
+/** A MausBot hidden from the sidebar comes back when it is renamed or moved to another department, unless the same
+ * change says whether to show it. Returns the patch to save. */
+export function reshowWhenMoved<P extends { name?: string; section?: string; sidebarHidden?: boolean }>(
+ bot: DefaultBotFields & { name: string; section?: string },
+ patch: P,
+): P {
+ if (!bot.defaultBot || !bot.sidebarHidden || Object.hasOwn(patch, "sidebarHidden")) return patch;
+ const renamed = patch.name !== undefined && patch.name.trim() !== bot.name.trim();
+ const moved = Object.hasOwn(patch, "section") && (patch.section?.trim() ?? "") !== (bot.section?.trim() ?? "");
+ return renamed || moved ? { ...patch, sidebarHidden: false } : patch;
+}
diff --git a/packages/phone-protocol/src/devs-report-status.ts b/packages/phone-protocol/src/devs-report-status.ts
new file mode 100644
index 0000000000..147444b1f8
--- /dev/null
+++ b/packages/phone-protocol/src/devs-report-status.ts
@@ -0,0 +1,33 @@
+// A @devs bug report's status, as the MausBot team last said it (server/host/devs-reports.ts asks about it hourly and at each
+// start). The server writes it on the person's message that sent the report, and on the one line that tells them its fix
+// runs here; clients say it in their own words (src/components/BugReportNote.tsx), so it follows the app's language.
+
+export interface BugReportStatus {
+ /** The MausBot team's id for the report (the "Sent to the MausBot team (report …)" line names it). */
+ id: string;
+ /** `received`: we have it and are looking; `fixed`: the team fixed it. */
+ status: "received" | "fixed";
+ /** The release the fix ships in, once the team knows it. */
+ fixedIn?: string;
+ /** This app runs that release (or a later one): the fix is here. */
+ running?: true;
+}
+
+export interface BugReportField {
+ /** On a person's message that tagged @devs: its report's status. On the one notice that tells them the fix runs here: the same, `running` set. */
+ bugReport?: BugReportStatus;
+}
+
+const VERSION = /^v?(\d{1,6})\.(\d{1,6})\.(\d{1,6})(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
+
+/** Whether this app's version (`running`) is the release `fixedIn` or a later one. Anything that doesn't read as a version is
+ * never at least it, and neither is a pre-release of that very release: the fix is said to be here only when it surely is. */
+export function versionAtLeast(running: string, fixedIn: string): boolean {
+ const have = VERSION.exec(running.trim()), want = VERSION.exec(fixedIn.trim());
+ if (!have || !want || want[4] !== undefined) return false;
+ for (const part of [1, 2, 3]) {
+ const a = Number(have[part]), b = Number(want[part]);
+ if (a !== b) return a > b;
+ }
+ return have[4] === undefined;
+}
diff --git a/packages/phone-protocol/src/digest.ts b/packages/phone-protocol/src/digest.ts
new file mode 100644
index 0000000000..940ef13b45
--- /dev/null
+++ b/packages/phone-protocol/src/digest.ts
@@ -0,0 +1,38 @@
+// Observed per-turn evidence, shared by server and companion renderers.
+export type HookCoverage = "full" | "preview" | "none";
+
+export interface DigestFiles {
+ changed: string[];
+ added: string[];
+ deleted: string[];
+ /** How many paths were cut from the lists above to stay within bounds. */
+ truncated?: number;
+}
+
+export interface DigestTool {
+ name: string;
+ count: number;
+ failed: number;
+ /** One redacted one-line sample of the tool's input (the existing chip summary). */
+ sample?: string;
+}
+
+export interface TurnDigest {
+ turnId: string;
+ botId: string;
+ threadId: string;
+ at: number;
+ durationMs: number;
+ tools: DigestTool[];
+ /** Total observed calls, including tool names omitted from the list. */
+ toolCalls?: number;
+ /** Tools beyond the busiest MAX_TOOLS, dropped from `tools`. */
+ toolsDropped?: number;
+ files?: DigestFiles;
+ memory: Array<{ path: string; kind: "created" | "updated" | "deleted" }>;
+ memoryDropped?: number;
+ /** First sentence of the terminal assistant text, at most REPLY_CHARS. */
+ reply: string;
+ usage?: { input: number; output: number; cachedInput?: number; costUsd?: number | null };
+ hookCoverage: HookCoverage;
+}
diff --git a/packages/phone-protocol/src/email.ts b/packages/phone-protocol/src/email.ts
new file mode 100644
index 0000000000..fe140fe73c
--- /dev/null
+++ b/packages/phone-protocol/src/email.ts
@@ -0,0 +1,92 @@
+// The Email connector's fixed names, shared by the server (tools, per-bot checks) and the app (bot settings, the card).
+// Tool names are upper-snake with the EMAIL_ prefix so the connector grant and scope rules apply unchanged.
+
+/** The connector slug in a bot's connectorScopes.apps and connectorTools. */
+export const EMAIL_SLUG = "email";
+/** The MCP server name bots see (tools arrive as mcp__email__EMAIL_<ACTION>). */
+export const EMAIL_MCP_SERVER = "email";
+/** What a bot passes as request_credential's credential_id for the mailbox card. */
+export const EMAIL_CREDENTIAL = "email";
+
+export const EMAIL_READ_TOOL_NAMES = ["EMAIL_LIST_MAILBOXES", "EMAIL_LIST_MESSAGES", "EMAIL_SEARCH_MESSAGES", "EMAIL_READ_MESSAGE"] as const;
+export const EMAIL_TOOL_NAMES = [...EMAIL_READ_TOOL_NAMES, "EMAIL_SEND_MESSAGE"] as const;
+export type EmailToolName = (typeof EMAIL_TOOL_NAMES)[number];
+
+/** How a mail server speaks TLS: from the first byte, or upgraded with STARTTLS. Never in the clear. */
+export type EmailSecurity = "tls" | "starttls";
+
+/** Where a mailbox's outgoing server is, when the person types it, and its own sign-in when that isn't the incoming
+ * server's. A password left out is the mailbox's own. */
+export interface EmailOutgoingFields {
+ smtpHost?: string;
+ smtpPort?: number;
+ smtpSecurity?: EmailSecurity;
+ smtpUsername?: string;
+ smtpPassword?: string;
+}
+
+/** Where a mailbox's mail servers are, when the person types them. */
+export interface EmailServerFields extends EmailOutgoingFields {
+ imapHost?: string;
+ imapPort?: number;
+ username?: string;
+}
+
+export interface EmailConnectRequest extends EmailServerFields {
+ address: string;
+ password: string;
+}
+
+export interface EmailAccountView {
+ address: string;
+ imapHost: string;
+ /** The server that sends, once one took the password. */
+ smtpHost?: string;
+ smtpPort?: number;
+ smtpSecurity?: EmailSecurity;
+ /** The outgoing server's own user name, when it has one. */
+ smtpUsername?: string;
+ /** While sending doesn't work: the outgoing server the reason is about, to start the form with. */
+ smtpTried?: Pick<EmailOutgoingFields, "smtpHost" | "smtpPort" | "smtpSecurity">;
+ connectedAt: string;
+ /** Why it needs the person, in one plain sentence. */
+ problem?: string;
+ /** Why sending doesn't work, in one plain sentence naming the server; none while it works. */
+ sendingProblem?: string;
+}
+
+/** What an outgoing form starts with: the server a mailbox sends through, or the one its sending problem is about; never a
+ * password. */
+export function outgoingFieldsOf(account: EmailAccountView): EmailOutgoingFields {
+ const server = account.smtpHost ? { smtpHost: account.smtpHost, smtpPort: account.smtpPort, smtpSecurity: account.smtpSecurity } : account.smtpTried ?? {};
+ return Object.fromEntries(Object.entries({ ...server, smtpUsername: account.smtpUsername }).filter(([, value]) => value !== undefined)) as EmailOutgoingFields;
+}
+
+/** What POST /api/email/accounts/:address/outgoing answers: it checked sending again, at the server typed there (an
+ * EmailOutgoingFields body) or the ones found for the address, without signing in to read again. */
+export type EmailOutgoingAnswer = { ok: true; account: EmailAccountView } | { ok: false; error: string; account?: EmailAccountView };
+
+/** A provider whose own sign-in fits better than a mailbox password: its app in Connected apps (`app`, its slug there),
+ * or an app password made at `appPasswordUrl`. */
+export interface EmailSignInHint {
+ provider: string;
+ app?: "gmail" | "outlook";
+ appPasswordUrl?: string;
+}
+
+/** POST /api/email/accounts/:address/test: a message from the mailbox to itself. */
+export type EmailTestAnswer = { ok: true } | { ok: false; error: string };
+
+/** GET /api/email. */
+export interface EmailStatus {
+ state: "unavailable" | "signed-out" | "connected";
+ accounts: EmailAccountView[];
+ /** Why it is unavailable here. */
+ reason?: string;
+}
+
+/** What POST /api/email/accounts answers: read a real header, or why not. `needsServer`: nothing was found, so the person
+ * types where their mail server is. */
+export type EmailConnectAnswer =
+ | { ok: true; account: EmailAccountView; inbox: { messages: number; newest?: { from: string; subject: string } }; sending: { ok: boolean; problem?: string; signIn?: EmailSignInHint } }
+ | { ok: false; error: string; needsServer?: true; signIn?: EmailSignInHint };
diff --git a/packages/phone-protocol/src/environment.ts b/packages/phone-protocol/src/environment.ts
new file mode 100644
index 0000000000..ba6fc8115a
--- /dev/null
+++ b/packages/phone-protocol/src/environment.ts
@@ -0,0 +1,52 @@
+/** Node's `process.platform` values: the server's operating system. */
+export type ServerPlatform = "aix" | "android" | "cygwin" | "darwin" | "freebsd" | "haiku" | "linux" | "netbsd" | "openbsd" | "sunos" | "win32";
+
+/** How an operator's server was installed. */
+export type ServerInstall = "npx" | "global" | "docker" | "source";
+
+/** GET /.well-known/openmausbot/environment, served without auth, and the `environment` of a POST /api/auth/pair answer:
+ * a saved connection checks it still reaches the same server. */
+export interface EnvironmentDescriptor {
+ environmentId: string;
+ label: string;
+ platform: ServerPlatform;
+ version: string;
+ capabilities: {
+ /** Pairing and sessions are available (this build). */
+ remoteSessions: true;
+ /** Only while the maintainer flag `features.sharedComputers` is on; otherwise absent, like a build without the feature. */
+ sharedComputers?: true;
+ lendingDetails?: true;
+ /** A Cloud home with lending on: a lent computer may open the device link and lend its internet connection. */
+ deviceLink?: true;
+ /** A personal Cloud home with lending on: a lent computer may lend its Chrome to the bots here. Never a team Cloud. */
+ myChromeLink?: true;
+ /** The same: the app on the person's computer says how it is and hears what the bots here ask of it
+ * (POST /api/shared-computers/asks). */
+ computerAsks?: true;
+ /** A lent computer may say it takes run_command's timeout_seconds; only then does this server send it. */
+ commandTimeouts?: true;
+ /** A lent computer may say it runs a command for up to 900 seconds; only then does this server ask it for more than 240. */
+ longCommands?: true;
+ /** A lent computer may say it takes edit_file, append_file and delete_file; only then does this server send them. */
+ fileEdits?: true;
+ /** A lent computer may say it runs the MCP servers saved here that run on it (mcp_tools, mcp_call). Never a team Cloud. */
+ lentMcp?: true;
+ /** A person's own OMB Cloud home. */
+ cloudHome?: true;
+ /** A team's Cloud home: `label` is the team's name. */
+ cloudTeam?: true;
+ /** A Cloud home, or a server one person owns, that takes the one-time move from that person's computer: by-row chats,
+ * the manifest, the chats and credentials checks, and lines its owner wrote there stamped as the owner's. Whether a
+ * session is that person, /api/auth/session says (`own`). */
+ move?: 1;
+ /** Who can update the server: the desktop app that runs it, or the operator. */
+ selfUpdate: "desktop-managed" | "operator";
+ /** For an operator's server: how it was installed, so a client offers the update command that fits it. */
+ install?: ServerInstall;
+ /** Whether /pair offers "sign in with your email" (an allow-list is set). */
+ emailSignIn?: boolean;
+ /** GET /api/threads/:id/job answers, long-polled (the headless CLI needs it). */
+ jobs: true;
+ };
+}
diff --git a/packages/phone-protocol/src/first-reply-rescue.ts b/packages/phone-protocol/src/first-reply-rescue.ts
new file mode 100644
index 0000000000..c65b94e0ab
--- /dev/null
+++ b/packages/phone-protocol/src/first-reply-rescue.ts
@@ -0,0 +1,38 @@
+// A chat whose AI has said nothing yet, some seconds into the turn, gets one
+// notice row with what the person can do about it. The row's tool name is a
+// whole plain sentence, so a client that only prints tool names (the phones)
+// still reads it; this payload is what lets the desktop draw its buttons.
+
+export interface FirstReplyRescue {
+ /** The bot whose turn is waiting: its AI is what "Switch AI" changes. */
+ botId: string;
+ threadId: string;
+ /** The turn this row is about: its buttons never reach another one. */
+ turnId: string;
+ /** The person's message that turn answers, to send again on another AI. */
+ requestMessageId?: string;
+ /** The AI the turn waits on, as its instance id and the name a person knows it by. */
+ instanceId: string;
+ ai: string;
+ /** A room turn: the room it is running in. */
+ groupId?: string;
+ /** The AI has started answering: the row no longer asks anything of the person. */
+ settled?: true;
+ /** Its turn ended (or gave way to the next) without an answer: the row is history, with no live buttons. */
+ over?: true;
+}
+
+/** The waiting row's words, for clients that print the tool name. */
+export function firstReplyWaitingName(botName: string, ai: string): string {
+ return `notice: ${botName} hasn't heard back from ${ai} yet.`;
+}
+
+/** The same row once its turn ended without an answer: history, true as it stands. */
+export function firstReplyOverName(botName: string, ai: string): string {
+ return `notice: ${botName} didn't hear back from ${ai}.`;
+}
+
+/** The same row once the AI's first output arrived. */
+export function firstReplySettledName(ai: string): string {
+ return `notice: ${ai} answered after a slow start.`;
+}
diff --git a/packages/phone-protocol/src/group-goal-run.ts b/packages/phone-protocol/src/group-goal-run.ts
new file mode 100644
index 0000000000..37ad398ac2
--- /dev/null
+++ b/packages/phone-protocol/src/group-goal-run.ts
@@ -0,0 +1,28 @@
+import type { ServerTextParams } from "./server-text.ts";
+/** Durable progress receipt for one goal-driven channel run. */
+export type GroupGoalRunStatus =
+ | "working"
+ | "completed"
+ | "needs-input"
+ | "blocked"
+ | "limit-reached"
+ /** The operator (or a guard) parked the run. */
+ | "paused"
+ | "stopped"
+ | "failed";
+
+export interface GroupGoalRunCardData {
+ runId: string;
+ goal: string;
+ status: GroupGoalRunStatus;
+ coordinatorBotId: string;
+ coordinatorName: string;
+ turnCount: number;
+ maxTurns: number;
+ detail?: string;
+ /** Fixed detail words, used only while they reconstruct the stored English. */
+ detailCode?: string;
+ detailParams?: ServerTextParams;
+ startedAt: number;
+ finishedAt?: number;
+}
diff --git a/packages/phone-protocol/src/helper-followup.ts b/packages/phone-protocol/src/helper-followup.ts
new file mode 100644
index 0000000000..af9ebf75e2
--- /dev/null
+++ b/packages/phone-protocol/src/helper-followup.ts
@@ -0,0 +1,79 @@
+// MausBot's follow-up after its first look around, under its intro (HelperIntro). The server writes it once, in English,
+// as a real message the model and the sidebar's preview read; clients say it in the viewer's language from its facts.
+// ENGLISH mirrors src/locales/en.json helperIntro.followup.*. It never names the AI it thinks with.
+
+export interface HelperFollowupFacts {
+ /** "own": an AI of the person's own answers; "backup": only the free backup model works; "none": no AI yet. */
+ ai: "own" | "backup" | "none";
+ /** The apps every bot here can use, by name. */
+ apps: string[];
+ /** The person's other bots, and the routines running here, when it looked. */
+ bots: number;
+ routines: number;
+ /** On a team, for someone who can't connect an AI: the name of the person who does; empty until the team's owner has
+ * opened the team. */
+ connects?: string;
+}
+
+export interface HelperFollowupField {
+ helperFollowup?: HelperFollowupFacts;
+}
+
+/** At most this many app names; the rest are counted. */
+export const FOLLOWUP_APP_NAMES = 3;
+
+export const FOLLOWUP_ENGLISH = {
+ "helperIntro.followup.found": "I looked around and nothing's waiting on you yet.",
+ "helperIntro.followup.empty": "There's no unfinished work, no other bots or routines, and no apps are connected so far.",
+ "helperIntro.followup.counts": "You have {bots} and {routines}, and no apps are connected so far.",
+ "helperIntro.followup.botsNone": "no other bots",
+ "helperIntro.followup.botOne": "1 other bot",
+ "helperIntro.followup.bots": "{count} other bots",
+ "helperIntro.followup.routinesNone": "no routines",
+ "helperIntro.followup.routineOne": "1 routine",
+ "helperIntro.followup.routines": "{count} routines",
+ "helperIntro.followup.offer": "If you'd like me to keep an eye on your day, I can connect your email and calendar so I can flag what matters each morning. Just say the word, or hand me whatever's on your plate today.",
+ "helperIntro.followup.apps": "I can already use {apps}. Hand me whatever's on your plate today, or ask me to set up a bot for something you do every week.",
+ "helperIntro.followup.more": "{count} more",
+ "helperIntro.followup.noAi": "I looked around. Before I can do real work, I need an AI to think with. Sign in with an account you already have, like Claude or ChatGPT, and I'll take it from there.",
+ "helperIntro.followup.backup": "I looked around. For now I'm thinking with a free backup model. Sign in with an account you already have, like Claude or ChatGPT, and I'll take it from there.",
+ "helperIntro.followup.noAiOwner": "I looked around. Before I can do real work, I need an AI to think with. {name} connects that for the team, and I'll take it from there.",
+ "helperIntro.followup.noAiTeamOwner": "I looked around. Before I can do real work, I need an AI to think with. The team's owner connects that, and I'll take it from there.",
+ "helperIntro.followup.backupOwner": "I looked around. For now I'm thinking with a free backup model. {name} can connect a better one for the team.",
+ "helperIntro.followup.backupTeamOwner": "I looked around. For now I'm thinking with a free backup model. The team's owner can connect a better one.",
+} as const;
+
+export type FollowupKey = keyof typeof FOLLOWUP_ENGLISH;
+type Say = (key: FollowupKey, params?: Record<string, string | number>) => string;
+
+function counted(say: Say, count: number, none: FollowupKey, one: FollowupKey, many: FollowupKey): string {
+ return count <= 0 ? say(none) : count === 1 ? say(one) : say(many, { count });
+}
+
+/** The follow-up in `say`'s language; `list` joins app names as that language does. */
+export function followupText(facts: HelperFollowupFacts, say: Say, list: (items: string[]) => string): string {
+ if (facts.ai !== "own") {
+ const none = facts.ai === "none", connects = facts.connects;
+ if (connects === undefined) return say(none ? "helperIntro.followup.noAi" : "helperIntro.followup.backup");
+ if (connects) return say(none ? "helperIntro.followup.noAiOwner" : "helperIntro.followup.backupOwner", { name: connects });
+ return say(none ? "helperIntro.followup.noAiTeamOwner" : "helperIntro.followup.backupTeamOwner");
+ }
+ const found = say("helperIntro.followup.found");
+ if (facts.apps.length) {
+ const shown = facts.apps.slice(0, FOLLOWUP_APP_NAMES);
+ const rest = facts.apps.length - shown.length;
+ return `${found} ${say("helperIntro.followup.apps", { apps: list(rest > 0 ? [...shown, say("helperIntro.followup.more", { count: rest })] : shown) })}`;
+ }
+ const middle = facts.bots <= 0 && facts.routines <= 0 ? say("helperIntro.followup.empty") : say("helperIntro.followup.counts", {
+ bots: counted(say, facts.bots, "helperIntro.followup.botsNone", "helperIntro.followup.botOne", "helperIntro.followup.bots"),
+ routines: counted(say, facts.routines, "helperIntro.followup.routinesNone", "helperIntro.followup.routineOne", "helperIntro.followup.routines"),
+ });
+ return `${found} ${middle} ${say("helperIntro.followup.offer")}`;
+}
+
+/** The English the server stores, which the model reads. */
+export function englishFollowup(facts: HelperFollowupFacts): string {
+ const fill = (key: FollowupKey, params?: Record<string, string | number>) =>
+ FOLLOWUP_ENGLISH[key].replace(/\{(\w+)\}/g, (match, name: string) => (params && name in params ? String(params[name]) : match));
+ return followupText(facts, fill, (items) => new Intl.ListFormat("en", { style: "long", type: "conjunction" }).format(items));
+}
diff --git a/packages/phone-protocol/src/inbox.ts b/packages/phone-protocol/src/inbox.ts
new file mode 100644
index 0000000000..58f5e46c75
--- /dev/null
+++ b/packages/phone-protocol/src/inbox.ts
@@ -0,0 +1,78 @@
+import type { ConnectorCardData } from "./connector-card.ts";
+import type { OptionCardData, SecretRequestCardData, SignInRequestCardData } from "./wire.ts";
+
+/** On a Team Cloud, a line in a person's inbox: their own conversation with their own Chief of Staff (their own MausBot
+ * when they crowned none), where everything addressed to them arrives. It says who it is from and where it came from,
+ * so clients can label it and open that conversation. Replying to the line answers it: the answer goes back where it
+ * came from. */
+export interface InboxItem {
+ /** "message": a teammate's or a bot's message, or an @mention; "ask": a question or approval card, copied here
+ * and answered here as there; "result": a routine's report; "notice": a failure or a sign-in it needs. */
+ kind: "message" | "ask" | "result" | "notice";
+ /** Who it is from: a teammate (their address) or a bot (its id). */
+ from: { name: string; email?: string; botId?: string };
+ /** The bot that passed a teammate's message on. */
+ via?: { botId: string; name: string };
+ /** The conversation it came from, when the person may open it. */
+ origin?: { botId: string; threadId: string; title: string; groupId?: string; messageId?: string };
+ /** It waits on the person's answer. */
+ replies?: true;
+ /** The sender's assistant wrote it for them, from what they share with the team. */
+ assistant?: true;
+ /** How it was answered: the person's own words, or their assistant's, which answers facts only. */
+ answers?: Array<{ by: "person" | "assistant"; text: string; at: number }>;
+}
+
+/** A task's fields on a team's server when it is a person's inbox, sent to that person alone. */
+export interface InboxTask {
+ /** This person's inbox, the conversation with their Chief where everything for them arrives. */
+ inbox?: true;
+ /** The asks waiting on them there (questions, approvals, work handed on), each open where it was asked; absent when
+ * none. */
+ openAsks?: number;
+ /** When what the inbox lists last changed; a client that shows the list reads it again when this moves. */
+ inboxChangedAt?: number;
+}
+
+/** Where a line of the inbox is listed: "needs-you" while it waits on the person (an ask whose card is open where it was
+ * asked), "info" for news until they answer it or mark it done, "done" once it is settled or marked done. */
+export type InboxTab = "needs-you" | "info" | "done";
+
+/** One line of a person's inbox as their inbox lists it, newest first. `kind` names its source; a new source adds a kind
+ * of its own with what its row needs. */
+export interface InboxRow {
+ /** The line's id in the inbox conversation. */
+ id: string;
+ kind: InboxItem["kind"];
+ tab: InboxTab;
+ from: InboxItem["from"];
+ via?: InboxItem["via"];
+ /** The bot that handed this work to the bot it is from. */
+ workingFor?: { botId: string; name: string };
+ /** On someone's Cloud: a guest's conversation asks this, not its owner's; `name` is empty when it isn't known. */
+ askedBy?: { name: string };
+ origin?: InboxItem["origin"];
+ text: string;
+ at: number;
+ unread: boolean;
+ replies?: true;
+ answers?: InboxItem["answers"];
+ /** An ask's card as the inbox holds it: answering it answers the card where it was asked. */
+ card?: OptionCardData;
+ /** A password the bot asked for, answered with the chat's own card for it. */
+ secret?: SecretRequestCardData;
+ /** A sign-in the bot asked the person to do, answered with the chat's own card for it. */
+ signIn?: SignInRequestCardData;
+ /** An app the bot asked the person to connect, answered with the chat's own card for it. */
+ connector?: ConnectorCardData;
+}
+
+/** A person's inbox: where its lines live (none yet before the first arrives), and the line the inbox's card in that
+ * conversation sits under (the newest that needed them, else the newest). Off a team `botId` and `threadId` are null: its
+ * lines stay in the conversations they came from, each answered through its `origin`. */
+export interface InboxView {
+ botId: string | null;
+ threadId: string | null;
+ rows: InboxRow[];
+ anchor: string | null;
+}
diff --git a/packages/phone-protocol/src/json.ts b/packages/phone-protocol/src/json.ts
new file mode 100644
index 0000000000..95c075ce39
--- /dev/null
+++ b/packages/phone-protocol/src/json.ts
@@ -0,0 +1,8 @@
+/** Plain JSON values: the vocabulary every cross-layer payload that is "just
+ * JSON" shares. */
+export type JsonPrimitive = string | number | boolean | null;
+export interface JsonObject {
+ [key: string]: JsonValue;
+}
+export type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
+
diff --git a/packages/phone-protocol/src/limit-reset.ts b/packages/phone-protocol/src/limit-reset.ts
new file mode 100644
index 0000000000..715de71dba
--- /dev/null
+++ b/packages/phone-protocol/src/limit-reset.ts
@@ -0,0 +1,73 @@
+/** Wire shapes for automations that run when an engine's usage limit resets, and for the engines' limit state
+ * the Automations page, the chat and the calendar show. */
+
+export type LimitResetRepeat = "once" | "every_reset";
+
+/** A routine schedule that runs when an engine's usage limit resets. */
+export interface LimitResetSchedule {
+ type: "limit_reset";
+ /** The engine instance id whose limit it waits for, e.g. "claude" or "codex". */
+ engine: string;
+ repeat: LimitResetRepeat;
+ /** Derived by the server, never taken from input: the reset plus a short buffer, or null while the time is not known. */
+ at: number | null;
+}
+
+/** As a request or an edit sends it: the server derives `at`. */
+export type LimitResetScheduleInput = Omit<LimitResetSchedule, "at" | "repeat"> & { repeat?: LimitResetRepeat; at?: number | null };
+
+/** How long after a reset the run starts, so the provider has rolled its window over. */
+export const AFTER_RESET_MS = 60_000;
+
+/** From this share of a window used, an engine is shown as near its limit. */
+export const NEAR_LIMIT_PERCENT = 90;
+
+export type LimitWindowName = "5-hour" | "weekly" | "other";
+
+/** One usage window as the engine reported it. */
+export interface LimitWindowUsage {
+ window: LimitWindowName;
+ /** 0–100. */
+ usedPercent: number;
+ /** Epoch ms when it resets; null when not known. */
+ resetsAt: number | null;
+}
+
+/** One engine's usage limit as OpenMausBot knows it now. */
+export interface EngineLimit {
+ /** Engine instance id. */
+ engine: string;
+ /** The engine's display name ("Claude", "Codex", or the instance's own name). */
+ name: string;
+ driver: "claude" | "codex" | "grok" | "opencode";
+ /** The window that decides the reset: the fullest, or the one refusing work. */
+ window: LimitWindowName | null;
+ /** 0–100, or null when the engine reported no window. */
+ usedPercent: number | null;
+ /** Epoch ms when that window resets; null when not known. */
+ resetsAt: number | null;
+ /** The engine refuses work until resetsAt. */
+ blocked: boolean;
+ /** Blocked only by a refusal's hold, which "Try again now" can end; absent when a window at its limit blocks it. */
+ held?: boolean;
+ /** Every window the engine reported, in the engine's order. A server that predates it sends only the deciding window above. */
+ windows?: LimitWindowUsage[];
+}
+
+export interface EngineLimitsReport {
+ checkedAt: number;
+ engines: EngineLimit[];
+}
+
+export function isLimitResetSchedule(schedule: { type: string } | null | undefined): schedule is LimitResetSchedule {
+ return schedule?.type === "limit_reset";
+}
+
+/** A one-time automation: a fixed time, or the next reset only. */
+export function runsOnce(schedule: { type: string; repeat?: unknown }): boolean {
+ return schedule.type === "once" || (schedule.type === "limit_reset" && schedule.repeat !== "every_reset");
+}
+
+export function nearLimit(limit: Pick<EngineLimit, "usedPercent" | "blocked">): boolean {
+ return limit.blocked || (limit.usedPercent ?? 0) >= NEAR_LIMIT_PERCENT;
+}
diff --git a/packages/phone-protocol/src/live-approval.ts b/packages/phone-protocol/src/live-approval.ts
new file mode 100644
index 0000000000..0187312b03
--- /dev/null
+++ b/packages/phone-protocol/src/live-approval.ts
@@ -0,0 +1,145 @@
+// What the harness tells GPT-Live about the bot's cards during a Live call.
+// English only (the voice speaks the user's language on its own), mirroring
+// src/locales/en.json approval.voice.* and approval.tool.*.
+import type { OptionCardData } from "./wire.ts";
+
+export type LiveCardKind = "approval" | "review" | "question";
+
+/** "approval": a provider or peer ask the voice may decide with a strict yes/no.
+ * "review": a harness-native proposal (skill, routine, profile, default
+ * model, team setup, an MCP server change, a quota-switch offer) that must be
+ * reviewed on screen.
+ * "question": a provider question. An expired proposal is settled: nothing
+ * can answer it any more. */
+export function liveCardKind(card: OptionCardData | undefined): LiveCardKind | null {
+ if (!card?.requestId || card.answered || card.dismissed || card.expired) return null;
+ if (card.skillRequest || card.routineRequest || card.profileRequest || card.modelRequest || card.teamSetupRequest || card.mcpRequest || card.quotaSwitch || card.lendingLift) {
+ return "review";
+ }
+ return card.tool ? "approval" : "question";
+}
+
+/** Why a decision made on a Live call must not reach this card, or null to
+ * deliver it. A card settled a moment earlier (answered or dismissed on
+ * screen) is refused before anything runs: delivering to it would add a
+ * false "the action was not run" line after the tap did run it. A card that
+ * is not on the thread is left to the normal answer path. */
+export function liveDecisionRefusal(card: OptionCardData | undefined): string | null {
+ if (!card) return null;
+ const kind = liveCardKind(card);
+ if (kind === "review") return "This request is reviewed on screen.";
+ return kind ? null : "The request is no longer open.";
+}
+
+const TOOL_PHRASES: Record<string, string> = {
+ Bash: "run a command",
+ Read: "read a file",
+ Write: "write a file",
+ Edit: "edit a file",
+ WebFetch: "fetch a web page",
+ WebSearch: "search the web",
+ schedule_routine: "schedule a routine",
+ manage_routine: "change a routine",
+ stage_skill: "enable a learned skill",
+ update_skill: "update a learned skill",
+ update_profile: "update its profile",
+ shell: "run a command",
+ edit: "edit a file",
+ read: "read a file",
+ fetch: "fetch a web page",
+ delete: "delete a file",
+ think: "think",
+ other: "take an action",
+ tool: "use a tool",
+};
+
+export function toolPhrase(tool?: string): string {
+ if (!tool) return "take an action";
+ return TOOL_PHRASES[tool] ?? tool.replace(/^mcp__[^_]+__/, "").replace(/_/g, " ");
+}
+
+const DETAIL_LIMIT = 400;
+
+function duration(ms: number): string {
+ const seconds = Math.max(0, Math.round(ms / 1_000));
+ if (seconds < 60) return `${seconds} second${seconds === 1 ? "" : "s"}`;
+ const minutes = Math.round(seconds / 60);
+ return `${minutes} minute${minutes === 1 ? "" : "s"}`;
+}
+
+/** A bot's step as the voice may name it: the tool's own spoken label, or
+ * the tool's name ("team notes: query database") — never its arguments,
+ * which can hold paths, queries or private text. */
+export function liveStepLabel(tool: { name: string; spoken?: string }): string {
+ if (tool.spoken?.trim()) return brief(tool.spoken, 80);
+ const parts = tool.name.split("__");
+ if (parts[0] === "mcp" && parts.length >= 3) {
+ const server = parts[1].replace(/[-_]+/g, " ").trim();
+ const action = parts.slice(2).join(" ").replace(/_+/g, " ").trim();
+ return brief(`${server}: ${action}`, 80);
+ }
+ return toolPhrase(tool.name);
+}
+
+function brief(text: string, limit = DETAIL_LIMIT): string {
+ const flat = text.replace(/\s+/g, " ").trim().replace(/[.!?]+$/, "");
+ return flat.length <= limit ? flat : `${flat.slice(0, limit).replace(/\s+\S*$/, "")}…`;
+}
+
+// The voice IS the bot to the person on the call: say everything as the bot
+// ("I …") or to the voice as "you", never naming the bot in the third person.
+
+export function spokenApprovalPrompt(card: OptionCardData): string {
+ const detail = brief(card.subtitle);
+ return `I want to ${toolPhrase(card.tool)}.${detail ? ` ${detail}.` : ""} May I?`;
+}
+
+export function spokenReviewPrompt(card: OptionCardData): string {
+ const title = brief(card.title || "a proposal", 200);
+ return `Tell the user, in your own words, that you need their decision in the chat: ${title}. They review it on screen and choose there; it cannot be decided by voice.`;
+}
+
+/** The bot waits for an app to be connected in the chat (a connector card). */
+export function spokenConnectorPrompt(label: string): string {
+ return `Tell the user, in your own words, that you need them to connect ${brief(label || "an app", 80)} in the chat before you can go on. It cannot be done by voice.`;
+}
+
+/** The bot waits for a credential entered on screen (a secret card). It must
+ * never travel through the call, so the voice never asks for it aloud. */
+export function spokenSecretPrompt(label: string): string {
+ return `Tell the user, in your own words, that you need ${brief(label || "a credential", 80)} entered in the chat on screen before you can go on. Never ask them to say it aloud.`;
+}
+
+/** The bot waits for the person to sign in to a site themselves (a sign-in
+ * card). The password goes into the page only, never through the call. */
+export function spokenSignInPrompt(site: string): string {
+ return `Tell the user, in your own words, that you need them to sign in to ${brief(site || "a website", 80)} themselves on screen, then press Done in the chat, before you can go on. Never ask them to say a password or code aloud.`;
+}
+
+export function spokenQuestionPrompt(card: OptionCardData): string {
+ const detail = brief(card.subtitle || card.title);
+ const choices = card.options.length ? ` The options are ${card.options.join(", ")}.` : "";
+ return `Ask the user, in your own words: ${detail}${detail.endsWith("?") ? "" : "?"}${choices} Then delegate their answer.`;
+}
+
+export const LIVE_COPY = {
+ notHeard: "The request was not heard clearly. Ask the user to say it again.",
+ notClear: "That was not a clear yes or no. Ask the user again for a clear yes or no.",
+ deniedMessage: "Denied by the user, on a live call.",
+ answeredInChat: "The user answered that request in the chat. Do not ask about it again.",
+ working: "You are working on the request now. Nothing is done until the result comes back; do not guess it.",
+ answerPassed: "You are using the user's answer now. Wait for the result.",
+ granted: "Thanks, I'll go ahead.",
+ denied: "Okay, I won't do it.",
+ saveFailed: (detail: string) => `The decision could not be saved${detail ? `: ${detail}` : "."} Ask the user to try again.`,
+ noAnswer: "I'm done. The result, or what went wrong, is in the chat.",
+ typedAnswerLead: (typed: string) => `About what you typed in the chat ("${brief(typed, 200)}"):`,
+ progress: (spoken: string) => `Progress: ${brief(spoken, 200)}`,
+ status: (workedMs: number, steps: number, lastStep: string | null, lastStepAgoMs: number) =>
+ `Status note, do not announce it: you are still working on it (${duration(workedMs)} so far, ${steps} step${steps === 1 ? "" : "s"}${
+ lastStep ? `; last step: ${lastStep}, ${duration(lastStepAgoMs)} ago` : ""}).`,
+ signedOut: "The call has ended because the sign-in that started it has ended. Sign in again to start a new call.",
+ unpaired: "The call has ended because the phone that started it was unpaired from this computer.",
+ goodbye: "The user asked to end the call. Say a short goodbye in one sentence and nothing else; the call ends right after.",
+ permissionRequest: (prompt: string) => `You need the user's permission. Say it in your own words: ${prompt} Ask for a clear yes or no, then delegate their answer.`,
+};
diff --git a/packages/phone-protocol/src/live-call-wire.ts b/packages/phone-protocol/src/live-call-wire.ts
new file mode 100644
index 0000000000..512843acb7
--- /dev/null
+++ b/packages/phone-protocol/src/live-call-wire.ts
@@ -0,0 +1,104 @@
+/** A Live call as the wire carries it: its state, the record a finished call
+ * leaves, and the non-secret Live settings. Types only; `wire.ts` re-exports them. */
+
+/** Which app holds the microphone of a Live call: the desktop app (its own
+ * page or a server's page in it), a web browser, or a phone. Self-declared;
+ * for display and logs only. The phone apps show a value they do not know as
+ * "another device". */
+export type LiveClient = "desktop" | "web" | "ios" | "android";
+export type LiveCallStatus = "connecting" | "live" | "ending" | "ended";
+/** Why a call ended. "signed-out": the sign-in or paired phone that started
+ * it was signed out, revoked or unpaired. A client that does not know a
+ * reason shows the call's `error` text, or plain "Call ended.". */
+export type LiveEndReason =
+ | "hung-up" | "idle" | "expired" | "content" | "remote-hangup" | "connection-lost"
+ | "sideband-lost" | "deleted" | "shutdown" | "signed-out" | "error";
+
+/** The one Live call a harness runs. Never carries the key or any speech. */
+export interface LiveCallState {
+ callId: string;
+ botId: string;
+ threadId: string;
+ client: LiveClient;
+ voice: string;
+ /** epoch ms when the session was created */
+ startedAt: number;
+ status: LiveCallStatus;
+ endReason?: LiveEndReason;
+ /** short, user-facing; present when the call ended on a problem */
+ error?: string;
+}
+
+/** One finished Live call, written once when a call that went live ends. Never carries speech. */
+export interface LiveCallRecord {
+ callId: string;
+ botId: string;
+ client: LiveClient;
+ /** epoch ms, = LiveCallState.startedAt */
+ startedAt: number;
+ /** epoch ms when the call ended */
+ endedAt: number;
+ /** whole seconds: OpenAI usage seconds when given, else wall clock */
+ seconds: number;
+ endReason: LiveEndReason;
+ /** only when LLM thread titles are on and the engine can generateText */
+ title?: string;
+}
+
+/** Who runs a Live call's voice session: OpenAI itself, a GPT-Live deployment on the user's own Azure OpenAI / Foundry
+ * resource, or a Fish Audio Live 3 agent the harness sets up on the person's Fish Audio account, whose session the client joins with Fish's SDK. */
+export type LiveProvider = "openai" | "azure" | "fish";
+
+/** `live`: the key saved for Live calls only; `openai`: the OpenAI API key from Settings → API keys, used when there is no `live` key;
+ * `fishAudio`: the Fish Audio key from Settings → API keys, the only key a Fish Audio call uses. */
+export type LiveKeySource = "live" | "openai" | "fishAudio";
+
+/** Non-secret Live settings, as GET /api/config and PATCH /api/live/settings report them. */
+export interface LiveSettings {
+ /** A Live call has everything it needs: a key (`keySource` says which; never the key itself), and for Azure a valid endpoint and deployment. */
+ configured: boolean;
+ keySource?: LiveKeySource;
+ /** Absent means "openai". With "azure" only the `live` key is used and with "fish" only the Fish Audio key, never the OpenAI API key. */
+ provider?: LiveProvider;
+ /** The Azure resource endpoint as saved, e.g. `https://my-resource.openai.azure.com`. Not a secret. */
+ azureEndpoint?: string;
+ /** The Azure deployment of gpt-live-1; empty means "gpt-live-1". */
+ azureDeployment?: string;
+ voice: string;
+ readTypedReplies: boolean;
+ idleMinutes: number;
+}
+
+/** The single-use token Fish Audio returns for one agent session (Fish API v1 `LiveKitSessionToken`), passed verbatim to
+ * `AgentSession.start({ sessionToken })` of `@fishaudio/agent-client` 1.x. Holds no API key. */
+export interface LiveFishSessionToken {
+ transport: "livekit";
+ session_id: string;
+ /** ISO time by which the client must join */
+ expires_at: string;
+ max_duration_seconds: number;
+ livekit_url: string;
+ token: string;
+}
+
+/** A "fish" call's transport, answered only to the client that started the call: Fish's session token, and the token
+ * that client presents on POST /api/live/relay, the call's only route for what it heard and for the bot's replies. */
+export interface LiveFishTransport {
+ type: "fish";
+ session: LiveFishSessionToken;
+ relayToken: string;
+}
+
+/** What the client of a "fish" call reports on POST /api/live/relay. Times are ms since the client joined the session. */
+export type LiveFishRelayEvent =
+ | { type: "connected" }
+ | { type: "heard"; text: string; startMs: number; endMs: number }
+ | { type: "spoke"; startMs: number; endMs: number }
+ | { type: "delegate"; id: string; atMs: number }
+ | { type: "ended"; reason: string }
+ | { type: "error"; code: string };
+
+/** What the harness hands the client of a "fish" call: words for the agent to speak or know (`kind` as on GPT-Live), or the end of the call. */
+export type LiveFishRelayCommand =
+ | { type: "append"; kind: "instructions" | "thinking" | "commentary"; content: string; delegationId: string | null }
+ | { type: "close" };
diff --git a/packages/phone-protocol/src/mascot-bodies.ts b/packages/phone-protocol/src/mascot-bodies.ts
new file mode 100644
index 0000000000..8c11bf2c4b
--- /dev/null
+++ b/packages/phone-protocol/src/mascot-bodies.ts
@@ -0,0 +1,129 @@
+/**
+ * The mascot bodies a bot can wear.
+ *
+ * GENERATED FILE — do not hand-edit. Run `pnpm gen:bodies` to rebuild it from
+ * `scripts/gen-mascot-bodies.ts`, which solves each face placement against the real
+ * expression geometry and verifies that nothing clips.
+ *
+ * Every body carries the same face at the same size: the generator clamps the whole
+ * catalog to the smallest face any one body can hold, so the mascot reads as one
+ * character in different bodies rather than ten different mascots. Roomier bodies simply
+ * end up with more margin around the face.
+ *
+ * The fields match `CursorSilhouette` exactly, so a body can be handed to the renderer
+ * with no adapter in between.
+ */
+
+import { z } from "zod";
+
+/** Every selectable body id, in the order the picker shows them. */
+export const MASCOT_BODY_IDS = ["cursor", "blob", "circle", "squircle", "capsule", "drop", "shield", "hexagon", "diamond", "star"] as const;
+
+export type MascotBodyId = (typeof MASCOT_BODY_IDS)[number];
+
+export const mascotBodySchema = z.enum(MASCOT_BODY_IDS);
+
+export interface MascotBody {
+ id: MascotBodyId;
+ /** Human-readable name, used for the picker and the accessible label. */
+ name: string;
+ /** Transform mapping the outline into the face box. */
+ fit: string;
+ /** Body markup. `{{GRADIENT}}` is replaced with the bot's own gradient. */
+ body: string;
+ /** The same outline without a fill, used as the clip region. */
+ clip: string;
+ /** Where the face sits inside the body, in face-space units. */
+ anchor: { x: number; y: number; scale: number };
+}
+
+/** The shipped mascot, and the fallback for any unrecognised value. */
+export const DEFAULT_MASCOT_BODY: MascotBodyId = "cursor";
+
+export const MASCOT_BODIES: Record<MascotBodyId, MascotBody> = {
+ cursor: {
+ id: "cursor",
+ name: "Cursor",
+ fit: "translate(68.1612 9.8302) scale(0.593918)",
+ body: "<path fill=\"{{GRADIENT}}\" d=\"M0 0 C1.12815992 0.94880479 2.25705591 1.89673511 3.38671875 2.84375 C5.57657936 4.68528228 7.75793952 6.53624249 9.93359375 8.39453125 C13.5602214 11.48647103 17.25022962 14.49819427 20.9453125 17.5078125 C25.41301487 21.15281776 29.86103386 24.8215994 34.31054688 28.48876953 C38.00933931 31.5370903 41.70951059 34.58367973 45.4140625 37.625 C52.50037463 43.44570076 59.55669812 49.29508834 66.54003906 55.23901367 C70.43289872 58.54377434 74.40406577 61.73568847 78.40625 64.90625 C82.05401433 67.85083084 85.6145398 70.89451533 89.18359375 73.93359375 C92.41424312 76.67774533 95.67698054 79.36747809 99 82 C103.47931906 85.54855146 107.83340036 89.22936876 112.18359375 92.93359375 C115.41424312 95.67774533 118.67698054 98.36747809 122 101 C125.9014198 104.09073517 129.71091352 107.27378506 133.5 110.5 C137.99002543 114.32092614 142.53350963 118.0537239 147.15234375 121.71875 C156.74255328 129.40144186 166.1812645 137.27326897 175.53833008 145.23754883 C179.4317456 148.54281661 183.40347641 151.73522157 187.40625 154.90625 C191.05401433 157.85083084 194.6145398 160.89451533 198.18359375 163.93359375 C201.41424312 166.67774533 204.67698054 169.36747809 208 172 C236.43637507 194.63776677 236.43637507 194.63776677 238.27050781 209.13867188 C239.19944445 221.27193361 237.57124038 231.13444436 230 241 C223.66050278 247.82715086 215.75482398 254.47140646 206.04764748 255.13307858 C205.3615811 255.13693349 204.67551472 255.1407884 203.96865845 255.14476013 C203.17563324 255.15165863 202.38260803 255.15855713 201.56555176 255.16566467 C200.27360901 255.16958473 200.27360901 255.16958473 198.95556641 255.17358398 C198.04112762 255.180271 197.12668884 255.18695801 196.18453979 255.19384766 C194.19843498 255.20789156 192.21231409 255.21978771 190.22618484 255.22979546 C187.07149762 255.24625057 183.91692738 255.26949556 180.76229858 255.29469299 C171.79227585 255.36530712 162.82220292 255.42526708 153.85205078 255.47680664 C148.36195434 255.5088283 142.87198905 255.55017011 137.38199997 255.59700203 C135.30028042 255.61289593 133.21853066 255.62527474 131.13676834 255.63390923 C104.46972494 255.74602279 80.75351522 259.19455182 60.52978516 278.41845703 C55.75259196 283.35727885 51.81217213 289.04473423 47.77441406 294.5859375 C44.62107661 298.87600364 41.36381878 303.08685058 38.125 307.3125 C32.82026548 314.26649347 27.55386673 321.24815866 22.3125 328.25 C21.07690581 329.89589556 19.84122979 331.5417297 18.60546875 333.1875 C16.22002164 336.36552908 13.84996009 339.55428087 11.48828125 342.75 C3.0450311 354.10095576 -5.25712203 365.22607871 -20 368 C-33.42903027 368.85957067 -44.2929604 367.90032788 -55 358.9140625 C-63.51513963 350.76480778 -67.79688328 340.99527428 -68.37686157 329.29350281 C-68.43541887 328.1487851 -68.49397617 327.00406738 -68.55430794 325.82466125 C-68.61453573 324.57243271 -68.67476353 323.32020416 -68.73681641 322.0300293 C-68.80423726 320.68369989 -68.87198477 319.33738681 -68.94003105 317.99108887 C-69.12569162 314.29881586 -69.30666938 310.60632592 -69.48688698 306.91378379 C-69.68142908 302.94481208 -69.88036562 298.97606035 -70.07873535 295.00727844 C-70.55465828 285.46711948 -71.02377004 275.92663022 -71.49235249 266.3861084 C-71.71278092 261.90166682 -71.93398876 257.41726373 -72.1552124 252.93286133 C-72.22122149 251.59460763 -72.22122149 251.59460763 -72.28856409 250.2293185 C-72.37783973 248.41936974 -72.46711776 246.6094211 -72.55639815 244.79947257 C-72.7821203 240.22326204 -73.00777832 235.64704836 -73.23336792 231.0708313 C-73.2783997 230.15734865 -73.32343148 229.24386601 -73.36982787 228.30270207 C-73.64581049 222.70253299 -73.92113412 217.10233189 -74.19602597 211.50210917 C-75.35713101 187.85146938 -76.54638525 164.20245932 -77.76320994 140.55462319 C-78.3174362 129.77404232 -78.86176258 118.9929594 -79.40472984 108.2118063 C-79.83986282 99.58021501 -80.28322749 90.94912395 -80.73695588 82.31848997 C-81.04621068 76.42094211 -81.34513355 70.52292566 -81.63612723 64.62444884 C-81.8031421 61.24551841 -81.97612174 57.86718776 -82.15861511 54.48903847 C-84.29931862 14.73242483 -84.29931862 14.73242483 -72.03125 -1.625 C-50.89854752 -24.96559677 -21.34867451 -18.24899383 0 0 Z \"/>",
+ clip: "<path d=\"M0 0 C1.12815992 0.94880479 2.25705591 1.89673511 3.38671875 2.84375 C5.57657936 4.68528228 7.75793952 6.53624249 9.93359375 8.39453125 C13.5602214 11.48647103 17.25022962 14.49819427 20.9453125 17.5078125 C25.41301487 21.15281776 29.86103386 24.8215994 34.31054688 28.48876953 C38.00933931 31.5370903 41.70951059 34.58367973 45.4140625 37.625 C52.50037463 43.44570076 59.55669812 49.29508834 66.54003906 55.23901367 C70.43289872 58.54377434 74.40406577 61.73568847 78.40625 64.90625 C82.05401433 67.85083084 85.6145398 70.89451533 89.18359375 73.93359375 C92.41424312 76.67774533 95.67698054 79.36747809 99 82 C103.47931906 85.54855146 107.83340036 89.22936876 112.18359375 92.93359375 C115.41424312 95.67774533 118.67698054 98.36747809 122 101 C125.9014198 104.09073517 129.71091352 107.27378506 133.5 110.5 C137.99002543 114.32092614 142.53350963 118.0537239 147.15234375 121.71875 C156.74255328 129.40144186 166.1812645 137.27326897 175.53833008 145.23754883 C179.4317456 148.54281661 183.40347641 151.73522157 187.40625 154.90625 C191.05401433 157.85083084 194.6145398 160.89451533 198.18359375 163.93359375 C201.41424312 166.67774533 204.67698054 169.36747809 208 172 C236.43637507 194.63776677 236.43637507 194.63776677 238.27050781 209.13867188 C239.19944445 221.27193361 237.57124038 231.13444436 230 241 C223.66050278 247.82715086 215.75482398 254.47140646 206.04764748 255.13307858 C205.3615811 255.13693349 204.67551472 255.1407884 203.96865845 255.14476013 C203.17563324 255.15165863 202.38260803 255.15855713 201.56555176 255.16566467 C200.27360901 255.16958473 200.27360901 255.16958473 198.95556641 255.17358398 C198.04112762 255.180271 197.12668884 255.18695801 196.18453979 255.19384766 C194.19843498 255.20789156 192.21231409 255.21978771 190.22618484 255.22979546 C187.07149762 255.24625057 183.91692738 255.26949556 180.76229858 255.29469299 C171.79227585 255.36530712 162.82220292 255.42526708 153.85205078 255.47680664 C148.36195434 255.5088283 142.87198905 255.55017011 137.38199997 255.59700203 C135.30028042 255.61289593 133.21853066 255.62527474 131.13676834 255.63390923 C104.46972494 255.74602279 80.75351522 259.19455182 60.52978516 278.41845703 C55.75259196 283.35727885 51.81217213 289.04473423 47.77441406 294.5859375 C44.62107661 298.87600364 41.36381878 303.08685058 38.125 307.3125 C32.82026548 314.26649347 27.55386673 321.24815866 22.3125 328.25 C21.07690581 329.89589556 19.84122979 331.5417297 18.60546875 333.1875 C16.22002164 336.36552908 13.84996009 339.55428087 11.48828125 342.75 C3.0450311 354.10095576 -5.25712203 365.22607871 -20 368 C-33.42903027 368.85957067 -44.2929604 367.90032788 -55 358.9140625 C-63.51513963 350.76480778 -67.79688328 340.99527428 -68.37686157 329.29350281 C-68.43541887 328.1487851 -68.49397617 327.00406738 -68.55430794 325.82466125 C-68.61453573 324.57243271 -68.67476353 323.32020416 -68.73681641 322.0300293 C-68.80423726 320.68369989 -68.87198477 319.33738681 -68.94003105 317.99108887 C-69.12569162 314.29881586 -69.30666938 310.60632592 -69.48688698 306.91378379 C-69.68142908 302.94481208 -69.88036562 298.97606035 -70.07873535 295.00727844 C-70.55465828 285.46711948 -71.02377004 275.92663022 -71.49235249 266.3861084 C-71.71278092 261.90166682 -71.93398876 257.41726373 -72.1552124 252.93286133 C-72.22122149 251.59460763 -72.22122149 251.59460763 -72.28856409 250.2293185 C-72.37783973 248.41936974 -72.46711776 246.6094211 -72.55639815 244.79947257 C-72.7821203 240.22326204 -73.00777832 235.64704836 -73.23336792 231.0708313 C-73.2783997 230.15734865 -73.32343148 229.24386601 -73.36982787 228.30270207 C-73.64581049 222.70253299 -73.92113412 217.10233189 -74.19602597 211.50210917 C-75.35713101 187.85146938 -76.54638525 164.20245932 -77.76320994 140.55462319 C-78.3174362 129.77404232 -78.86176258 118.9929594 -79.40472984 108.2118063 C-79.83986282 99.58021501 -80.28322749 90.94912395 -80.73695588 82.31848997 C-81.04621068 76.42094211 -81.34513355 70.52292566 -81.63612723 64.62444884 C-81.8031421 61.24551841 -81.97612174 57.86718776 -82.15861511 54.48903847 C-84.29931862 14.73242483 -84.29931862 14.73242483 -72.03125 -1.625 C-50.89854752 -24.96559677 -21.34867451 -18.24899383 0 0 Z \"/>",
+ anchor: { x: 85.54, y: 106.35, scale: 0.791 },
+ },
+ blob: {
+ id: "blob",
+ name: "Blob",
+ fit: "translate(-0.7217 2.9555) scale(1.134706)",
+ body: "<path fill=\"{{GRADIENT}}\" d=\"M198.91052 113.12915C198.30169 121.88191 196.37668 130.37605 193.1355 138.61157C189.89431 146.84709 185.49332 154.4026 179.93252 161.27809C174.37172 168.15358 167.99976 174.1053 160.81663 179.13325C153.6335 184.1612 145.98678 188.22176 137.87645 191.31491C129.76613 194.40806 121.42581 196.55178 112.85548 197.74609C104.28516 198.94039 95.66469 199.12755 86.99407 198.30758C78.32344 197.4876 69.86713 195.54477 61.62513 192.47909C53.38313 189.41341 45.74309 185.20915 38.70501 179.86633C31.66693 174.52351 25.60941 168.25632 20.53243 161.06476C15.45546 153.87319 11.54067 146.15559 8.78808 137.91195C6.03549 129.66831 4.37316 121.28874 3.80109 112.77325C3.22902 104.25775 3.5616 95.83136 4.79882 87.49409C6.03604 79.15682 8.08364 70.99969 10.94163 63.0227C13.79962 55.04571 17.53174 47.38891 22.13799 40.0523C26.74425 32.71568 32.30193 26.0276 38.81103 19.98806C45.32014 13.94852 52.65266 9.00619 60.80862 5.16109C68.96458 1.31599 77.53546 -1.10241 86.52128 -2.09412C95.50709 -3.08583 104.37427 -2.64309 113.12282 -0.76589C121.87137 1.11131 130.09712 4.12751 137.80007 8.28271C145.50302 12.43791 152.53652 17.35515 158.90058 23.03443C165.26463 28.7137 170.969 34.91856 176.01368 41.649C181.05836 48.37944 185.3953 55.56843 189.02451 63.21597C192.65372 70.86352 195.3609 78.90607 197.14605 87.34364C198.93119 95.78121 199.51935 104.37638 198.91052 113.12915Z\"/>",
+ clip: "<path d=\"M198.91052 113.12915C198.30169 121.88191 196.37668 130.37605 193.1355 138.61157C189.89431 146.84709 185.49332 154.4026 179.93252 161.27809C174.37172 168.15358 167.99976 174.1053 160.81663 179.13325C153.6335 184.1612 145.98678 188.22176 137.87645 191.31491C129.76613 194.40806 121.42581 196.55178 112.85548 197.74609C104.28516 198.94039 95.66469 199.12755 86.99407 198.30758C78.32344 197.4876 69.86713 195.54477 61.62513 192.47909C53.38313 189.41341 45.74309 185.20915 38.70501 179.86633C31.66693 174.52351 25.60941 168.25632 20.53243 161.06476C15.45546 153.87319 11.54067 146.15559 8.78808 137.91195C6.03549 129.66831 4.37316 121.28874 3.80109 112.77325C3.22902 104.25775 3.5616 95.83136 4.79882 87.49409C6.03604 79.15682 8.08364 70.99969 10.94163 63.0227C13.79962 55.04571 17.53174 47.38891 22.13799 40.0523C26.74425 32.71568 32.30193 26.0276 38.81103 19.98806C45.32014 13.94852 52.65266 9.00619 60.80862 5.16109C68.96458 1.31599 77.53546 -1.10241 86.52128 -2.09412C95.50709 -3.08583 104.37427 -2.64309 113.12282 -0.76589C121.87137 1.11131 130.09712 4.12751 137.80007 8.28271C145.50302 12.43791 152.53652 17.35515 158.90058 23.03443C165.26463 28.7137 170.969 34.91856 176.01368 41.649C181.05836 48.37944 185.3953 55.56843 189.02451 63.21597C192.65372 70.86352 195.3609 78.90607 197.14605 87.34364C198.93119 95.78121 199.51935 104.37638 198.91052 113.12915Z\"/>",
+ anchor: { x: 111.22, y: 116.58, scale: 0.791 },
+ },
+ circle: {
+ id: "circle",
+ name: "Circle",
+ fit: "translate(0 0) scale(1.142705)",
+ body: "<path fill=\"{{GRADIENT}}\" d=\"M200 100C200 155.22847 155.22847 200 100 200C44.77153 200 0 155.22847 0 100C0 44.77153 44.77153 0 100 0C155.22847 0 200 44.77153 200 100Z\"/>",
+ clip: "<path d=\"M200 100C200 155.22847 155.22847 200 100 200C44.77153 200 0 155.22847 0 100C0 44.77153 44.77153 0 100 0C155.22847 0 200 44.77153 200 100Z\"/>",
+ anchor: { x: 113.82, y: 110.27, scale: 0.791 },
+ },
+ squircle: {
+ id: "squircle",
+ name: "Squircle",
+ fit: "translate(0 0) scale(1.142705)",
+ body: "<path fill=\"{{GRADIENT}}\" d=\"M50 0C83.33333 0 116.66667 0 150 0C177.61424 0 200 22.38576 200 50C200 83.33333 200 116.66667 200 150C200 177.61424 177.61424 200 150 200C116.66667 200 83.33333 200 50 200C22.38576 200 0 177.61424 0 150C0 116.66667 0 83.33333 0 50C0 22.38576 22.38576 0 50 0Z\"/>",
+ clip: "<path d=\"M50 0C83.33333 0 116.66667 0 150 0C177.61424 0 200 22.38576 200 50C200 83.33333 200 116.66667 200 150C200 177.61424 177.61424 200 150 200C116.66667 200 83.33333 200 50 200C22.38576 200 0 177.61424 0 150C0 116.66667 0 83.33333 0 50C0 22.38576 22.38576 0 50 0Z\"/>",
+ anchor: { x: 111.78, y: 111.79, scale: 0.791 },
+ },
+ capsule: {
+ id: "capsule",
+ name: "Capsule",
+ fit: "translate(0 0) scale(1.142705)",
+ body: "<path fill=\"{{GRADIENT}}\" d=\"M100 0C141.42136 0 175 33.57864 175 75C175 91.66667 175 108.33333 175 125C175 166.42136 141.42136 200 100 200C58.57864 200 25 166.42136 25 125C25 108.33333 25 91.66667 25 75C25 33.57864 58.57864 0 100 0Z\"/>",
+ clip: "<path d=\"M100 0C141.42136 0 175 33.57864 175 75C175 91.66667 175 108.33333 175 125C175 166.42136 141.42136 200 100 200C58.57864 200 25 166.42136 25 125C25 108.33333 25 91.66667 25 75C25 33.57864 58.57864 0 100 0Z\"/>",
+ anchor: { x: 113.82, y: 131.68, scale: 0.791 },
+ },
+ drop: {
+ id: "drop",
+ name: "Drop",
+ fit: "translate(-3.5341 -3.5341) scale(1.178046)",
+ body: "<path fill=\"{{GRADIENT}}\" d=\"M100 3C160.84 78.2235 178 103.298 178 119C178 162.07821 143.07821 197 100 197C56.92179 197 22 162.07821 22 119C22 103.298 39.16 78.2235 100 3Z\"/>",
+ clip: "<path d=\"M100 3C160.84 78.2235 178 103.298 178 119C178 162.07821 143.07821 197 100 197C56.92179 197 22 162.07821 22 119C22 103.298 39.16 78.2235 100 3Z\"/>",
+ anchor: { x: 112.47, y: 138.8, scale: 0.791 },
+ },
+ shield: {
+ id: "shield",
+ name: "Shield",
+ fit: "translate(-12.1611 -24.3222) scale(1.264316)",
+ body: "<path fill=\"{{GRADIENT}}\" d=\"M57.25 38.475C85.75 12.825 114.25 12.825 142.75 38.475C153.89667 76.64167 165.04333 114.80833 176.19 152.975C188.73 184.325 179.325 200 147.975 200C115.99167 200 84.00833 200 52.025 200C20.675 200 11.27 184.325 23.81 152.975C34.95667 114.80833 46.10333 76.64167 57.25 38.475Z\"/>",
+ clip: "<path d=\"M57.25 38.475C85.75 12.825 114.25 12.825 142.75 38.475C153.89667 76.64167 165.04333 114.80833 176.19 152.975C188.73 184.325 179.325 200 147.975 200C115.99167 200 84.00833 200 52.025 200C20.675 200 11.27 184.325 23.81 152.975C34.95667 114.80833 46.10333 76.64167 57.25 38.475Z\"/>",
+ anchor: { x: 112.38, y: 170.61, scale: 0.791 },
+ },
+ hexagon: {
+ id: "hexagon",
+ name: "Hexagon",
+ fit: "translate(-4.1077 -4.1077) scale(1.183782)",
+ body: "<path fill=\"{{GRADIENT}}\" d=\"M94.90777 4.94C98.30259 2.98 101.69741 2.98 105.09223 4.94C129.98757 19.31333 154.88292 33.68667 179.77826 48.06C183.17308 50.02 184.87049 52.96 184.87049 56.88C184.87049 85.62667 184.87049 114.37333 184.87049 143.12C184.87049 147.04 183.17308 149.98 179.77826 151.94C154.88292 166.31333 129.98757 180.68667 105.09223 195.06C101.69741 197.02 98.30259 197.02 94.90777 195.06C70.01243 180.68667 45.11708 166.31333 20.22174 151.94C16.82692 149.98 15.12951 147.04 15.12951 143.12C15.12951 114.37333 15.12951 85.62667 15.12951 56.88C15.12951 52.96 16.82692 50.02 20.22174 48.06C45.11708 33.68667 70.01243 19.31333 94.90777 4.94Z\"/>",
+ clip: "<path d=\"M94.90777 4.94C98.30259 2.98 101.69741 2.98 105.09223 4.94C129.98757 19.31333 154.88292 33.68667 179.77826 48.06C183.17308 50.02 184.87049 52.96 184.87049 56.88C184.87049 85.62667 184.87049 114.37333 184.87049 143.12C184.87049 147.04 183.17308 149.98 179.77826 151.94C154.88292 166.31333 129.98757 180.68667 105.09223 195.06C101.69741 197.02 98.30259 197.02 94.90777 195.06C70.01243 180.68667 45.11708 166.31333 20.22174 151.94C16.82692 149.98 15.12951 147.04 15.12951 143.12C15.12951 114.37333 15.12951 85.62667 15.12951 56.88C15.12951 52.96 16.82692 50.02 20.22174 48.06C45.11708 33.68667 70.01243 19.31333 94.90777 4.94Z\"/>",
+ anchor: { x: 112.26, y: 110.7, scale: 0.791 },
+ },
+ diamond: {
+ id: "diamond",
+ name: "Diamond",
+ fit: "translate(-5.9383 -5.9383) scale(1.202088)",
+ body: "<path fill=\"{{GRADIENT}}\" d=\"M94.12 7.88C98.04 3.96 101.96 3.96 105.88 7.88C134.62667 36.62667 163.37333 65.37333 192.12 94.12C196.04 98.04 196.04 101.96 192.12 105.88C163.37333 134.62667 134.62667 163.37333 105.88 192.12C101.96 196.04 98.04 196.04 94.12 192.12C65.37333 163.37333 36.62667 134.62667 7.88 105.88C3.96 101.96 3.96 98.04 7.88 94.12C36.62667 65.37333 65.37333 36.62667 94.12 7.88Z\"/>",
+ clip: "<path d=\"M94.12 7.88C98.04 3.96 101.96 3.96 105.88 7.88C134.62667 36.62667 163.37333 65.37333 192.12 94.12C196.04 98.04 196.04 101.96 192.12 105.88C163.37333 134.62667 134.62667 163.37333 105.88 192.12C101.96 196.04 98.04 196.04 94.12 192.12C65.37333 163.37333 36.62667 134.62667 7.88 105.88C3.96 101.96 3.96 98.04 7.88 94.12C36.62667 65.37333 65.37333 36.62667 94.12 7.88Z\"/>",
+ anchor: { x: 112.53, y: 109.95, scale: 0.791 },
+ },
+ star: {
+ id: "star",
+ name: "Star",
+ fit: "translate(-8.3327 3.1407) scale(1.226032)",
+ body: "<path fill=\"{{GRADIENT}}\" d=\"M100 2C110.56054 20.13133 121.12108 38.26266 131.68163 56.39398C152.18893 60.83477 172.69623 65.27555 193.20354 69.71633C179.22301 85.3629 165.24248 101.00946 151.26195 116.65602C153.37562 137.5319 155.48929 158.40778 157.60295 179.28367C138.40197 170.82244 119.20098 162.36122 100 153.9C80.79902 162.36122 61.59803 170.82244 42.39705 179.28367C44.51071 158.40778 46.62438 137.5319 48.73805 116.65602C34.75752 101.00946 20.77699 85.3629 6.79646 69.71633C27.30377 65.27555 47.81107 60.83477 68.31837 56.39398C78.87892 38.26266 89.43946 20.13133 100 2Z\"/>",
+ clip: "<path d=\"M100 2C110.56054 20.13133 121.12108 38.26266 131.68163 56.39398C152.18893 60.83477 172.69623 65.27555 193.20354 69.71633C179.22301 85.3629 165.24248 101.00946 151.26195 116.65602C153.37562 137.5319 155.48929 158.40778 157.60295 179.28367C138.40197 170.82244 119.20098 162.36122 100 153.9C80.79902 162.36122 61.59803 170.82244 42.39705 179.28367C44.51071 158.40778 46.62438 137.5319 48.73805 116.65602C34.75752 101.00946 20.77699 85.3629 6.79646 69.71633C27.30377 65.27555 47.81107 60.83477 68.31837 56.39398C78.87892 38.26266 89.43946 20.13133 100 2Z\"/>",
+ anchor: { x: 113.82, y: 125.43, scale: 0.791 },
+ },
+};
+
+/** Runtime-safe read of an untrusted persisted or streamed body id. */
+export function botMascotBody(value: unknown): MascotBodyId {
+ return mascotBodySchema.safeParse(value).data ?? DEFAULT_MASCOT_BODY;
+}
diff --git a/packages/phone-protocol/src/mcp-request.ts b/packages/phone-protocol/src/mcp-request.ts
new file mode 100644
index 0000000000..045591ebc7
--- /dev/null
+++ b/packages/phone-protocol/src/mcp-request.ts
@@ -0,0 +1,18 @@
+/** Security: display data only. An update's change (the bot's fields, its secretRefs) stays in the server's memory until
+ * the person answers and never reaches the wire or messages.json, so after a restart a Change card can only expire. A
+ * Turn on or Remove card holds no fields, so it still applies after a restart. */
+export interface McpChangeRequest {
+ requestId: string;
+ botId: string;
+ threadId: string;
+ action: "enable" | "update" | "remove";
+ name: string;
+ /** sha256 hex of the server's display target (the masked address, or the command line with secrets hidden), the string
+ * the card and the bot show. An answer applies only while the server still reaches there. Security: the card is stored,
+ * synced to phones and visible to teammates, so the hash must never cover a raw secret a reader could guess offline;
+ * a change confined to a masked part is not detected. */
+ targetHash: string;
+ result?: { state: "applied" | "denied" | "expired" | "failed"; text: string };
+ /** The bot's parked turn took the result. */
+ resumed?: boolean;
+}
diff --git a/packages/phone-protocol/src/model-request.ts b/packages/phone-protocol/src/model-request.ts
new file mode 100644
index 0000000000..b115a2e28c
--- /dev/null
+++ b/packages/phone-protocol/src/model-request.ts
@@ -0,0 +1,22 @@
+/**
+ * Durable payload carried by a default-model confirmation card (propose_model).
+ * "before" is the exact selection the user was shown; a confirmation fails
+ * closed if the target's default moved since.
+ */
+import type { ModelSelection } from "./wire.ts";
+
+export interface ModelRequestCardData {
+ version: 1;
+ requestId: string;
+ /** The proposing conversation; authority is fixed here. */
+ botId: string;
+ threadId: string;
+ /** Whose default model changes: the proposer, or a section peer named by a Chief. */
+ targetBotId: string;
+ targetName: string;
+ createdAt: number;
+ reason: string;
+ selection: ModelSelection;
+ before: ModelSelection;
+ appliedAt?: number;
+}
diff --git a/packages/phone-protocol/src/modelgo.ts b/packages/phone-protocol/src/modelgo.ts
new file mode 100644
index 0000000000..09c5cbf048
--- /dev/null
+++ b/packages/phone-protocol/src/modelgo.ts
@@ -0,0 +1,2 @@
+/** The sponsor asked for this exact address, every parameter included, on every in-app link to its site. */
+export const MODELGO_URL = "https://modelgo.ai/?utm_source=openmausbot&utm_medium=sponsorship&utm_content=app&campaign_id=openmausbot&ad_group_id=app";
diff --git a/packages/phone-protocol/src/notification.ts b/packages/phone-protocol/src/notification.ts
new file mode 100644
index 0000000000..026701fb51
--- /dev/null
+++ b/packages/phone-protocol/src/notification.ts
@@ -0,0 +1,63 @@
+/** The notification wire shape: what the harness decides is worth
+ * interrupting someone for, emitted as the `notify` live frame. */
+export type NotifyKind =
+ | "approval"
+ | "question"
+ | "done"
+ | "routine-failed"
+ | "routine-deferred"
+ | "turn-failed"
+ /** A run failed, stalled or could not start and no Chief of Staff was
+ * there to take it: the person is the one who has to look. */
+ | "incident"
+ /** A bot asked the person to sign in to a website themselves
+ * (request_sign_in): it waits on their hands, at the place it works. */
+ | "sign-in"
+ /** A bot asked the person for a password or key on a secure card (request_credential): its work rests on them until
+ * they save it or say no. */
+ | "secret"
+ /** A delegated request settled and the coordinator auto-resumed the person's
+ * own conversation with the results; both are internal, so without this it
+ * sits silent until the resume's first token. A teammate's own step in a
+ * longer chain sends none: nothing there waits on the person. */
+ | "delegation-settled"
+ /** A bot's settled room reply tagged the person (`@you` or their profile name). Rooms only. On a Team Cloud also
+ * a teammate tagged by name, or a message a bot passed on to them, with `forPerson`. */
+ | "mention"
+ /** The workspace crossed its monthly spend warning or reached its cap.
+ * Sent to admins only, at most once per month for each. */
+ | "spend"
+ /** The main agent's brief has something new that needs the person, or a
+ * meeting prep or reminder it posted with no AI turn. Personal installs only. */
+ | "brief"
+ /** A wait a bot set up (wait_until) fired: what it was waiting for happened. */
+ | "wait"
+ /** Something OpenMausBot changed on its own that the person hears about
+ * once: a tool turned off for the bots it doesn't start for. */
+ | "notice";
+
+export interface Notification {
+ kind: NotifyKind;
+ botId: string;
+ botName: string;
+ threadId: string;
+ title: string;
+ body: string;
+ /** The bot's stored profile image, when it has one; clients show it as
+ * the OS notification's icon so every banner carries its bot's face. */
+ avatarUrl?: string;
+ /** The room this came out of, when the bot was speaking in one. Routing
+ * already works off `threadId` alone; this is what lets a client say which
+ * room, and stack a room's banners together instead of under the bot. */
+ groupId?: string;
+ /** On a Team Cloud, the one person this is for (their person key): a teammate tagged by name, or the person a bot
+ * passed a message to. It reaches nobody else, an admin included. */
+ forPerson?: string;
+}
+
+/** A `Notification` as the feed stores it: the live `notify` frame and `GET /api/notifications` carry the same entry. */
+export interface NotificationLogEntry extends Notification {
+ id: string;
+ at: number;
+ read: boolean;
+}
diff --git a/packages/phone-protocol/src/options-card.ts b/packages/phone-protocol/src/options-card.ts
new file mode 100644
index 0000000000..5ed342ab32
--- /dev/null
+++ b/packages/phone-protocol/src/options-card.ts
@@ -0,0 +1,58 @@
+/** The one bot allowed to create passive choice cards for the Watcher flow. */
+export const WATCHER_OPTIONS_CARD_BOT_ID = "f08dd8e3-f942-4eb4-8783-df32b26b88a4";
+
+/** Keep agent-authored cards small enough to remain useful on desktop and mobile. */
+export const OPTIONS_CARD_LIMITS = {
+ title: 120,
+ subtitle: 1_000,
+ option: 120,
+ minOptions: 2,
+ maxOptions: 6,
+} as const;
+
+export interface OptionsCardInput {
+ title: string;
+ subtitle: string;
+ options: string[];
+}
+
+export type ParsedOptionsCardInput =
+ | { ok: true; value: OptionsCardInput }
+ | { ok: false; error: string };
+
+function record(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+function boundedText(value: unknown, field: string, maximum: number): string | { error: string } {
+ if (typeof value !== "string") return { error: `${field} must be a string.` };
+ const text = value.trim();
+ if (!text) return { error: `${field} must not be blank.` };
+ if (text.length > maximum) return { error: `${field} must be at most ${maximum} characters.` };
+ return text;
+}
+
+/** Normalize untrusted model input before it is persisted into a native card. */
+export function parseOptionsCardInput(value: unknown): ParsedOptionsCardInput {
+ if (!record(value)) return { ok: false, error: "create_options_card needs an object." };
+
+ const title = boundedText(value.title, "title", OPTIONS_CARD_LIMITS.title);
+ if (typeof title !== "string") return { ok: false, error: title.error };
+ const subtitle = boundedText(value.subtitle, "subtitle", OPTIONS_CARD_LIMITS.subtitle);
+ if (typeof subtitle !== "string") return { ok: false, error: subtitle.error };
+ if (!Array.isArray(value.options)) return { ok: false, error: "options must be an array of strings." };
+ if (value.options.length < OPTIONS_CARD_LIMITS.minOptions || value.options.length > OPTIONS_CARD_LIMITS.maxOptions) {
+ return { ok: false, error: `options must contain ${OPTIONS_CARD_LIMITS.minOptions}-${OPTIONS_CARD_LIMITS.maxOptions} items.` };
+ }
+
+ const options: string[] = [];
+ const seen = new Set<string>();
+ for (let index = 0; index < value.options.length; index += 1) {
+ const option = boundedText(value.options[index], `options[${index}]`, OPTIONS_CARD_LIMITS.option);
+ if (typeof option !== "string") return { ok: false, error: option.error };
+ if (seen.has(option)) return { ok: false, error: `options must be unique; "${option}" is repeated.` };
+ seen.add(option);
+ options.push(option);
+ }
+ return { ok: true, value: { title, subtitle, options } };
+}
diff --git a/packages/phone-protocol/src/outbound.ts b/packages/phone-protocol/src/outbound.ts
new file mode 100644
index 0000000000..3aace15a2d
--- /dev/null
+++ b/packages/phone-protocol/src/outbound.ts
@@ -0,0 +1,167 @@
+// Outbound actions: calls that reach a person outside the app or move money.
+// Below Full access they get their own confirmation unless the bot's rule sends
+// without asking; at Full access they run unless the bot has a rule of its own.
+// A read-and-draft routine run never reaches them: the relay refuses every send
+// there. Shared by the harness (which enforces it) and the app.
+import { isConnectedAppsServer } from "./own-apps.ts";
+
+export type OutboundPolicy = {
+ /** ask: every outbound call waits for a tap. allow: outbound calls go out without asking. */
+ policy: "ask" | "allow";
+};
+
+/** Tools whose action is one of these words send something somewhere. */
+const SEND_VERBS = new Set([
+ "SEND",
+ "SENDS",
+ "REPLY",
+ "RESPOND",
+ "FORWARD",
+ "POST",
+ "PUBLISH",
+ "TWEET",
+ "RETWEET",
+ "BROADCAST",
+ "INVITE",
+ "SHARE",
+ "REFUND",
+ "CHARGE",
+ "PAY",
+ "PAYOUT",
+ "TRANSFER",
+ "BUY",
+ "PURCHASE",
+ "DIAL",
+]);
+
+/** Creating one of these is sending it: a created comment is a comment
+ * someone reads, a created invoice is one someone receives, a created call rings someone. */
+const CREATE_VERBS = new Set(["CREATE", "CREATION", "ADD", "NEW", "MAKE"]);
+const SENT_NOUNS = new Set(["MESSAGE", "COMMENT", "POST", "EMAIL", "MAIL", "INVOICE", "PAYMENT", "REFUND", "REPLY", "TWEET", "DM", "CALL"]);
+
+/** Telnyx's hosted server reaches its whole API through one tool, so any call of it may ring, text or buy. */
+const RAW_API_ACTION = /^mcp__.+__invoke_api_endpoint$/;
+
+/** A read verb first means the rest of the name is what is being read:
+ * REDDIT_GET_POST fetches a post, it does not post. */
+const READ_VERBS = new Set(["GET", "LIST", "FETCH", "SEARCH", "READ", "FIND", "RETRIEVE", "LOOKUP", "DOWNLOAD", "VIEW", "CHECK", "COUNT"]);
+
+/** Composio reads known by slug, since some put the noun first (GOOGLECALENDAR_EVENTS_LIST lists events). */
+export const KNOWN_READ_SLUGS: ReadonlySet<string> = new Set([
+ "GMAIL_FETCH_EMAILS",
+ "GMAIL_GET_PROFILE",
+ "GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID",
+ "GMAIL_FETCH_MESSAGE_BY_THREAD_ID",
+ "GOOGLECALENDAR_EVENTS_LIST",
+ "GOOGLECALENDAR_EVENTS_GET",
+ "GOOGLECALENDAR_FIND_EVENT",
+ "GOOGLECALENDAR_LIST_CALENDARS",
+]);
+
+/** The action part of a tool name, as upper-case word tokens. Composio's
+ * TOOLKIT_ACTION drops its toolkit; an MCP server's mcp__server__action
+ * drops its server; a bare built-in like Bash stays as it is. */
+function actionTokens(name: string): string[] {
+ let action = name;
+ if (name.startsWith("mcp__")) {
+ const [, server = "", ...rest] = name.split("__");
+ action = rest.join("_");
+ if (isConnectedAppsServer(server)) return actionTokens(action);
+ } else if (/^[A-Z][A-Z0-9]*_[A-Z0-9_]+$/.test(name)) {
+ action = name.slice(name.indexOf("_") + 1);
+ }
+ return action
+ .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
+ .toUpperCase()
+ .split(/[^A-Z0-9]+/)
+ .filter(Boolean);
+}
+
+/** Does the tool name describe a read-only action? This is deliberately
+ * narrower than "not outbound": updates, deletes and other writes do not
+ * become reads merely because they send nothing to another person. */
+export function isReadOnlyTool(name: string): boolean {
+ if (KNOWN_READ_SLUGS.has(name.replace(/^mcp__(?:composio|own_apps)__/, ""))) return true;
+ const tokens = actionTokens(name);
+ return tokens.length > 0 && READ_VERBS.has(tokens[0]);
+}
+
+/** The built-in agents server's X research tools only read X: x_post reads a post, it does not post one. */
+const AGENTS_X_READS = /^(?:mcp__agents__|agents__|agents_)?x_(?:search|user_posts|post|profile)$/;
+
+/** Does this tool send something to someone, or move money? */
+export function isOutboundTool(name: string): boolean {
+ // A raw API call from the workbench can do anything an app tool can, and
+ // nothing here can read which; it is treated as a send.
+ if (name === "COMPOSIO_PROXY_EXECUTE" || RAW_API_ACTION.test(name)) return true;
+ if (AGENTS_X_READS.test(name)) return false;
+ const tokens = actionTokens(name);
+ if (tokens.length === 0) return false;
+ if (isReadOnlyTool(name)) return false;
+ if (tokens.some((token) => SEND_VERBS.has(token))) return true;
+ if (tokens.includes("DRAFT")) return false;
+ return tokens.some((token) => CREATE_VERBS.has(token)) && tokens.some((token) => SENT_NOUNS.has(token));
+}
+
+/** The stored shape, or null when the value is not one. Fields other than `policy` are dropped. */
+export function normalizeOutboundPolicy(value: unknown): OutboundPolicy | null {
+ if (!value || typeof value !== "object" || Array.isArray(value)) return null;
+ const { policy } = value as { policy?: unknown };
+ return policy === "ask" || policy === "allow" ? { policy } : null;
+}
+
+/** What a bot without a stored policy does: ask, every time. */
+export const DEFAULT_OUTBOUND_POLICY: OutboundPolicy = { policy: "ask" };
+
+/** Drops from a stored bot's rule what `normalizeOutboundPolicy` drops, so every copy of one rule reads the same; true
+ * when it changed. A rule that is not one is left as it is, and asks. */
+export function trimOutboundPolicy(bot: { outbound?: OutboundPolicy }): boolean {
+ const kept = bot.outbound && normalizeOutboundPolicy(bot.outbound);
+ if (!kept || Object.keys(bot.outbound!).length === Object.keys(kept).length) return false;
+ bot.outbound = kept;
+ return true;
+}
+
+/** One app tool a connector request would run, with its arguments when the
+ * request carries them. */
+export interface ConnectorCall {
+ slug: string;
+ arguments?: unknown;
+}
+
+const isRecord = (value: unknown): value is Record<string, unknown> =>
+ Boolean(value) && typeof value === "object" && !Array.isArray(value);
+
+/** Composio's session exposes a handful of meta tools and runs the app
+ * tools inside them: a multi-execute call carries a list of slugs with
+ * arguments. Arbitrary workbench/bash code is opaque: it requires an
+ * explicit unrestricted approval, never an inferred app or send count.
+ * Search, schema lookup, and connection management run no app tools. */
+export function connectorCallsIn(name: string, args: unknown): ConnectorCall[] {
+ if (name === "COMPOSIO_MULTI_EXECUTE_TOOL") {
+ const tools = isRecord(args) && Array.isArray(args.tools) ? args.tools
+ : isRecord(args) && typeof args.tool_slug === "string" ? [args] : [];
+ if (!tools.length) return [{ slug: "COMPOSIO_PROXY_EXECUTE", arguments: args }];
+ const calls: ConnectorCall[] = [];
+ for (const item of tools) {
+ if (!isRecord(item)) return [{ slug: "COMPOSIO_PROXY_EXECUTE", arguments: args }];
+ const slug = [item.tool_slug, item.slug, item.name, item.tool].find((value) => typeof value === "string" && value);
+ if (typeof slug !== "string") return [{ slug: "COMPOSIO_PROXY_EXECUTE", arguments: args }];
+ calls.push({ slug, ...(item.arguments !== undefined ? { arguments: item.arguments } : {}) });
+ }
+ return calls;
+ }
+ if (name === "COMPOSIO_REMOTE_WORKBENCH" || name === "COMPOSIO_REMOTE_BASH_TOOL") {
+ // Arbitrary code can compute tool names and repeat calls. Its app and
+ // outbound count cannot be inferred from literals in the source.
+ return [{ slug: "COMPOSIO_PROXY_EXECUTE", arguments: args }];
+ }
+ if (["COMPOSIO_SEARCH_TOOLS", "COMPOSIO_GET_TOOL_SCHEMAS", "COMPOSIO_MANAGE_CONNECTIONS", "COMPOSIO_WAIT_FOR_CONNECTIONS"].includes(name)) return [];
+ if (name.startsWith("COMPOSIO_")) return [{ slug: "COMPOSIO_PROXY_EXECUTE", arguments: args }];
+ return [{ slug: name, ...(args !== undefined ? { arguments: args } : {}) }];
+}
+
+/** The subset of a request's app tools that would send something. */
+export function outboundCallsIn(name: string, args: unknown): ConnectorCall[] {
+ return connectorCallsIn(name, args).filter((call) => isOutboundTool(call.slug));
+}
diff --git a/packages/phone-protocol/src/outside-write.ts b/packages/phone-protocol/src/outside-write.ts
new file mode 100644
index 0000000000..a74d55dbeb
--- /dev/null
+++ b/packages/phone-protocol/src/outside-write.ts
@@ -0,0 +1,4 @@
+export interface OutsideWriteCardField {
+ /** What work from outside asked to write where later turns read it; nothing is written until a person says yes. */
+ outsideWrite?: { kind: "room-bulletin"; roomId: string; bulletin: string } | { kind: "memory"; action: string; text?: string; oldText?: string; until?: string };
+}
diff --git a/packages/phone-protocol/src/own-apps.ts b/packages/phone-protocol/src/own-apps.ts
new file mode 100644
index 0000000000..538a10226f
--- /dev/null
+++ b/packages/phone-protocol/src/own-apps.ts
@@ -0,0 +1,6 @@
+// A Team Cloud member's own connected apps: mounted beside the team's `composio` server, only in that member's own turns in
+// their private chat. Everything that reads a `composio` tool as an app tool reads this one the same way.
+export const OWN_APPS_SERVER = "own_apps";
+
+/** The two servers whose tools are connected-app (Composio) tools. */
+export const isConnectedAppsServer = (server: string): boolean => server === "composio" || server === OWN_APPS_SERVER;
diff --git a/packages/phone-protocol/src/pairing-code.ts b/packages/phone-protocol/src/pairing-code.ts
new file mode 100644
index 0000000000..9b5078061f
--- /dev/null
+++ b/packages/phone-protocol/src/pairing-code.ts
@@ -0,0 +1,79 @@
+/** The one kind of secret a device joins with: 12 symbols from this alphabet, shown as `7KQ2-M9XD-H4TP`. Dashes,
+ * spaces and case never matter. A link or QR carries the same code with an address. */
+export const PAIRING_CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
+export const PAIRING_CODE_LENGTH = 12;
+/** The high-entropy credential a QR carries instead of the code; accepted wherever a code is, never shown. */
+export const PAIRING_CREDENTIAL_PREFIX = "omb_pair_";
+const PAIRING_CREDENTIAL = /^omb_pair_[A-Za-z0-9_-]{43}$/;
+
+export function normalizePairingCode(input: string): string {
+ return input
+ .toUpperCase()
+ .replace(/[^A-Z0-9]/g, "")
+ .replace(/0/g, "O")
+ .replace(/1/g, "I");
+}
+
+export function formatPairingCode(code: string): string {
+ return normalizePairingCode(code).match(/.{1,4}/g)?.join("-") ?? code;
+}
+
+/** What someone typed or pasted where a pairing code goes, and the sentence that explains anything else. */
+export type PairingInput =
+ | { kind: "code"; code: string }
+ | { kind: "credential"; credential: string }
+ | { kind: "wrong"; problem: PairingInputProblem }
+ | { kind: "empty" };
+
+export type PairingInputProblem = "emailCode" | "oldCode" | "scriptKey" | "notACode";
+
+/** English for each problem; src/locales/en.json carries the same sentences under the same keys. */
+export const PAIRING_INPUT_PROBLEM_TEXT = {
+ "serverError.pair.emailCode": "That's a sign-in code from an email. Pairing needs a 12-character code like 7KQ2-M9XD-H4TP.",
+ "serverError.pair.oldCode": "That's a code from an older MausBot. Make a new one on the other computer: Phone & devices → Pair a device.",
+ "serverError.pair.scriptKey": "That's a script key. Pairing needs a pairing code.",
+ "serverError.pair.notACode": "That isn't a pairing code. Pairing needs a 12-character code like 7KQ2-M9XD-H4TP.",
+} as const;
+
+/** `serverError.*` catalog keys, so the server, the CLI and every screen word a wrong kind of code the same way. */
+export const PAIRING_INPUT_PROBLEM_KEY: Record<PairingInputProblem, keyof typeof PAIRING_INPUT_PROBLEM_TEXT> = {
+ emailCode: "serverError.pair.emailCode",
+ oldCode: "serverError.pair.oldCode",
+ scriptKey: "serverError.pair.scriptKey",
+ notACode: "serverError.pair.notACode",
+};
+
+function fromLink(raw: string): string | null {
+ let url: URL;
+ try {
+ url = new URL(raw);
+ } catch {
+ return null;
+ }
+ const hash = new URLSearchParams(url.hash.replace(/^#/, ""));
+ return url.searchParams.get("token") ?? url.searchParams.get("code") ?? hash.get("code");
+}
+
+/** Reads a typed code, an `omb_pair_` credential, or a link that carries either (`openmausbot://pair?…`,
+ * `…/pair#code=…`, `?code=…`). */
+export function readPairingInput(raw: string): PairingInput {
+ let value = raw.trim();
+ if (!value) return { kind: "empty" };
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
+ const carried = fromLink(value);
+ if (!carried) return { kind: "wrong", problem: "notACode" };
+ value = carried.trim();
+ }
+ if (value.startsWith("omb_sess_")) return { kind: "wrong", problem: "scriptKey" };
+ if (value.startsWith(PAIRING_CREDENTIAL_PREFIX)) {
+ return PAIRING_CREDENTIAL.test(value) ? { kind: "credential", credential: value } : { kind: "wrong", problem: "notACode" };
+ }
+ const digits = value.replace(/[\s-]/g, "");
+ if (/^\d{8}$/.test(digits)) return { kind: "wrong", problem: "emailCode" };
+ if (/^\d{6}$/.test(digits)) return { kind: "wrong", problem: "oldCode" };
+ const code = normalizePairingCode(value);
+ if (code.length !== PAIRING_CODE_LENGTH || [...code].some((symbol) => !PAIRING_CODE_ALPHABET.includes(symbol))) {
+ return { kind: "wrong", problem: "notACode" };
+ }
+ return { kind: "code", code };
+}
diff --git a/packages/phone-protocol/src/pairing-link.ts b/packages/phone-protocol/src/pairing-link.ts
new file mode 100644
index 0000000000..4c9c822868
--- /dev/null
+++ b/packages/phone-protocol/src/pairing-link.ts
@@ -0,0 +1,198 @@
+// The one `openmausbot://pair` link builder, read by the Android and iOS
+// scanners (`PairingInvite.parse`). Every value is written with
+// encodeURIComponent, so a space is `%20`.
+
+export type CompanionEndpointKind = "hosted" | "tailnet" | "lan" | "bonjour";
+
+export interface CompanionEndpoint {
+ url: string;
+ kind: CompanionEndpointKind;
+ priority: number;
+}
+
+export interface PairingE2EDescriptor {
+ v: 1;
+ k: string;
+ h?: string;
+ r?: string[];
+}
+
+const B64U_FIELD = /^[A-Za-z0-9_-]+$/;
+const RELAY_HOST = /^relay[1-9][0-9]?\.openmausbot\.com$/;
+
+/** The QR's `e2e` value, or null for anything a phone would refuse: then the link goes out without it, as from a
+ * computer without the encrypted connection. A QR never says "local": a restriction is set per phone, later. */
+export function encodePairingE2E(descriptor: PairingE2EDescriptor | null | undefined): string | null {
+ if (!descriptor || descriptor.v !== 1 || typeof descriptor.k !== "string" || descriptor.k.length !== 87 || !B64U_FIELD.test(descriptor.k)) return null;
+ const relay = typeof descriptor.h === "string" && Array.isArray(descriptor.r) && descriptor.r.length >= 1 && descriptor.r.length <= 4
+ && descriptor.h.length === 22 && B64U_FIELD.test(descriptor.h) && descriptor.r.every((node) => RELAY_HOST.test(node))
+ ? { h: descriptor.h, r: descriptor.r }
+ : {};
+ const json = JSON.stringify({ v: 1, k: descriptor.k, ...relay });
+ const encoded = btoa(json).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
+ return encoded.length <= 1024 ? encoded : null;
+}
+
+export interface PhonePairingLinkOptions {
+ /** Where the phone dials first: a host or IP literal together with `port`
+ * (the desktop companion), or a complete http(s) origin (a server). */
+ address: string;
+ port?: number;
+ /** The high-entropy one-time credential the scanner redeems. */
+ token: string;
+ /** The six digits the desktop shows; servers have none. */
+ code?: string;
+ name?: string;
+ /** Every host the phone could dial later, best first. */
+ hosts?: string[];
+ /** Complete base URLs, encoded apart from `address`/`hosts` so HTTPS and
+ * port 443 stay unambiguous. */
+ endpoints?: CompanionEndpoint[];
+ /** The end-to-end descriptor `{v, k, h?, r?}`: the computer's transport key, pinned by the scan, and its relay
+ * identity. Sent as `e2e=<base64url JSON>`; a phone that can't parse it refuses the whole link. */
+ e2e?: PairingE2EDescriptor | null;
+ /** P-256 HPKE recipient key pinned by the camera scan. Its private half
+ * remains in the desktop's OS-encrypted credential store. */
+ secretPublicKey?: string;
+}
+
+/** How many fallback routes a link will carry. The list is tiny in practice;
+ * the cap only keeps a pathological interface table from bloating the QR. */
+export const MAX_PAIRING_HOSTS = 8;
+
+const ENDPOINT_KINDS = new Set<CompanionEndpointKind>(["hosted", "tailnet", "lan", "bonjour"]);
+
+/** Strict even for our own sidecar's input: a public URL with credentials or a
+ * path is not a companion base URL. Sorted by priority, deduplicated by origin,
+ * capped. */
+export function qrEndpoints(endpoints: CompanionEndpoint[] | undefined): CompanionEndpoint[] {
+ const seen = new Set<string>();
+ const valid: CompanionEndpoint[] = [];
+
+ for (const endpoint of endpoints ?? []) {
+ if (
+ !endpoint ||
+ !ENDPOINT_KINDS.has(endpoint.kind) ||
+ !Number.isInteger(endpoint.priority) ||
+ endpoint.priority < 0 ||
+ endpoint.priority > 1_000_000
+ ) {
+ continue;
+ }
+
+ try {
+ const parsed = new URL(endpoint.url);
+ const expectedProtocol = endpoint.kind === "hosted" ? "https:" : "http:";
+ const explicitPort = parsed.port ? Number(parsed.port) : null;
+ const hostname = parsed.hostname.toLowerCase().replace(/\.$/, "");
+ if (
+ parsed.protocol !== expectedProtocol ||
+ // No empty DNS label (".ts.net", "mac..local"): the phones refuse
+ // one, and one endpoint they refuse makes them refuse the whole QR.
+ hostname.split(".").includes("") ||
+ (endpoint.kind === "tailnet" && !hostname.endsWith(".ts.net")) ||
+ (explicitPort !== null && (!Number.isInteger(explicitPort) || explicitPort < 1 || explicitPort > 65_535)) ||
+ parsed.username ||
+ parsed.password ||
+ parsed.pathname !== "/" ||
+ parsed.search ||
+ parsed.hash ||
+ seen.has(parsed.origin)
+ ) {
+ continue;
+ }
+ seen.add(parsed.origin);
+ valid.push({ url: parsed.origin, kind: endpoint.kind, priority: endpoint.priority });
+ } catch {
+ }
+ }
+
+ return valid.sort((left, right) => left.priority - right.priority).slice(0, MAX_PAIRING_HOSTS);
+}
+
+/** URL-safe, unpadded base64 keeps the structured JSON smaller than query
+ * escaping every quote and slash while remaining straightforward to decode
+ * with Foundation on iOS. */
+function encodeEndpoints(endpoints: CompanionEndpoint[]): string {
+ const bytes = new TextEncoder().encode(JSON.stringify(endpoints));
+ let binary = "";
+ for (const byte of bytes) binary += String.fromCharCode(byte);
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
+}
+
+function validSecretPublicKey(value: string | undefined): string | null {
+ if (!value || !/^[A-Za-z0-9_-]{87}$/.test(value)) return null;
+ try {
+ const base64 = value.replaceAll("-", "+").replaceAll("_", "/") + "=";
+ const decoded = atob(base64);
+ if (decoded.length !== 65 || decoded.charCodeAt(0) !== 4) return null;
+ let binary = "";
+ for (let index = 0; index < decoded.length; index += 1) binary += decoded[index];
+ return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "") === value
+ ? value
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+/** The `address` value: `host:port` (IPv6 bracketed) or a bare http(s)
+ * origin, or null when it is neither. Both phones refuse an address with
+ * credentials, a path, a query or a fragment, as `qrEndpoints` does. */
+function linkAddress(address: string, port: number | undefined): string | null {
+ const value = address.trim();
+ if (!value) return null;
+ if (/^https?:\/\//i.test(value)) {
+ try {
+ const parsed = new URL(value);
+ if (parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash) return null;
+ return parsed.origin;
+ } catch {
+ return null;
+ }
+ }
+ if (port === undefined || !Number.isInteger(port) || port < 1 || port > 65_535) return null;
+ const authority = value.includes(":") && !value.startsWith("[") ? `[${value}]` : value;
+ return `${authority}:${port}`;
+}
+
+/**
+ * A short-lived handoff from a trusted pairing screen to the mobile app. The
+ * credential still has to be redeemed; putting it in the link does not
+ * create or expose the long-lived device token. Null when any required part
+ * is malformed, so a caller never prints a link a phone would refuse.
+ */
+export function phonePairingLink({
+ address,
+ port,
+ token,
+ code,
+ name,
+ hosts,
+ endpoints,
+ secretPublicKey,
+ e2e,
+}: PhonePairingLinkOptions): string | null {
+ const dial = linkAddress(address, port);
+ if (!dial || !/^omb_pair_[A-Za-z0-9_-]{43}$/.test(token)) return null;
+ if (code !== undefined && !/^\d{6}$/.test(code)) return null;
+
+ const fields: Array<[string, string]> = [["address", dial], ["token", token]];
+ if (code !== undefined) fields.push(["code", code]);
+ if (name?.trim()) fields.push(["name", name.trim()]);
+ // Comma-joined, which no hostname or IP literal can contain. A bad candidate
+ // is filtered, not fatal: it costs the phone one failed dial.
+ const candidates = (hosts ?? [])
+ .map((candidate) => candidate.trim())
+ .filter((candidate) => candidate && !/[\s/?#,[\]]/.test(candidate))
+ .slice(0, MAX_PAIRING_HOSTS);
+ if (candidates.length) fields.push(["hosts", candidates.join(",")]);
+ const routes = qrEndpoints(endpoints);
+ if (routes.length) fields.push(["endpoints", encodeEndpoints(routes)]);
+ const secretKey = validSecretPublicKey(secretPublicKey);
+ if (secretKey) fields.push(["secretKey", secretKey]);
+ const descriptor = encodePairingE2E(e2e);
+ if (descriptor) fields.push(["e2e", descriptor]);
+
+ return `openmausbot://pair?${fields.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&")}`;
+}
diff --git a/packages/phone-protocol/src/phone-apps.ts b/packages/phone-protocol/src/phone-apps.ts
new file mode 100644
index 0000000000..476afac134
--- /dev/null
+++ b/packages/phone-protocol/src/phone-apps.ts
@@ -0,0 +1,66 @@
+// Vocabulary for "phone apps as bot tools": the apps a paired phone may allow,
+// per-bot grants, and the PHONE_* tool names served by the `device` MCP server.
+import { isReadOnlyAction } from "./connector-scopes.ts";
+
+export const PHONE_CAPABILITIES = ["calendar", "reminders", "contacts", "location", "home", "messages"] as const;
+export type PhoneCapability = (typeof PHONE_CAPABILITIES)[number];
+export type PhoneGrant = "read" | "write";
+/** Per-bot grant; an absent key is off. */
+export type PhoneApps = Partial<Record<PhoneCapability, PhoneGrant>>;
+
+export const PHONE_SLUG = "phone";
+export const PHONE_MCP_SERVER = "device";
+export const PHONE_PLATFORMS = ["ios", "android"] as const;
+export type PhonePlatform = (typeof PHONE_PLATFORMS)[number];
+
+export const PHONE_TOOL_NAMES = [
+ "PHONE_LIST_EVENTS", "PHONE_GET_EVENT", "PHONE_FIND_FREE_TIME", "PHONE_CREATE_EVENT", "PHONE_UPDATE_EVENT", "PHONE_DELETE_EVENT", "PHONE_RESPOND_TO_INVITE",
+ "PHONE_LIST_REMINDERS", "PHONE_CREATE_REMINDER", "PHONE_UPDATE_REMINDER", "PHONE_COMPLETE_REMINDER", "PHONE_DELETE_REMINDER",
+ "PHONE_SEARCH_CONTACTS", "PHONE_GET_CONTACT", "PHONE_CREATE_CONTACT", "PHONE_UPDATE_CONTACT",
+ "PHONE_GET_LOCATION", "PHONE_FIND_PLACES_NEARBY",
+ "PHONE_LIST_HOME", "PHONE_SET_ACCESSORY", "PHONE_RUN_SCENE",
+ "PHONE_SEND_MESSAGE", "PHONE_SEND_WHATSAPP",
+] as const;
+export type PhoneToolName = (typeof PHONE_TOOL_NAMES)[number];
+
+const TOOL_CAPABILITY: Record<PhoneToolName, PhoneCapability> = {
+ PHONE_LIST_EVENTS: "calendar", PHONE_GET_EVENT: "calendar", PHONE_FIND_FREE_TIME: "calendar", PHONE_CREATE_EVENT: "calendar",
+ PHONE_UPDATE_EVENT: "calendar", PHONE_DELETE_EVENT: "calendar", PHONE_RESPOND_TO_INVITE: "calendar",
+ PHONE_LIST_REMINDERS: "reminders", PHONE_CREATE_REMINDER: "reminders", PHONE_UPDATE_REMINDER: "reminders",
+ PHONE_COMPLETE_REMINDER: "reminders", PHONE_DELETE_REMINDER: "reminders",
+ PHONE_SEARCH_CONTACTS: "contacts", PHONE_GET_CONTACT: "contacts", PHONE_CREATE_CONTACT: "contacts", PHONE_UPDATE_CONTACT: "contacts",
+ PHONE_GET_LOCATION: "location", PHONE_FIND_PLACES_NEARBY: "location",
+ PHONE_LIST_HOME: "home", PHONE_SET_ACCESSORY: "home", PHONE_RUN_SCENE: "home",
+ PHONE_SEND_MESSAGE: "messages", PHONE_SEND_WHATSAPP: "messages",
+};
+
+export function isPhoneToolName(name: unknown): name is PhoneToolName {
+ return typeof name === "string" && Object.hasOwn(TOOL_CAPABILITY, name);
+}
+
+export function phoneToolCapability(name: PhoneToolName): PhoneCapability {
+ return TOOL_CAPABILITY[name];
+}
+
+/** GET/LIST/SEARCH/FIND read; everything else writes (isReadOnlyAction(name, "phone")). */
+export function isPhoneWrite(name: string): boolean {
+ return !isReadOnlyAction(name, PHONE_SLUG);
+}
+
+export function phoneToolSends(name: string): boolean {
+ return name.startsWith("PHONE_SEND_");
+}
+
+/** Unknown key or value → null; `{}` is valid (everything off). */
+export function normalizePhoneApps(value: unknown): PhoneApps | null {
+ if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
+ const out: PhoneApps = {};
+ for (const [key, grant] of Object.entries(value)) {
+ if (!(PHONE_CAPABILITIES as readonly string[]).includes(key)) return null;
+ if (grant !== "read" && grant !== "write") return null;
+ out[key as PhoneCapability] = grant;
+ }
+ return out;
+}
+
+export const ALL_PHONE_APPS: PhoneApps = Object.fromEntries(PHONE_CAPABILITIES.map((c) => [c, "write"])) as PhoneApps;
diff --git a/packages/phone-protocol/src/phone-steps.ts b/packages/phone-protocol/src/phone-steps.ts
new file mode 100644
index 0000000000..eee319f557
--- /dev/null
+++ b/packages/phone-protocol/src/phone-steps.ts
@@ -0,0 +1,4 @@
+/** The phone tools a step of the phone server's batch tool can run; a batch may run only where all of them may. */
+export const PHONE_STEP_TOOLS = ["open_app", "tap_text", "tap", "swipe", "type_text", "press", "read_screen"] as const;
+
+export type PhoneStepTool = (typeof PHONE_STEP_TOOLS)[number];
diff --git a/packages/phone-protocol/src/place-view.ts b/packages/phone-protocol/src/place-view.ts
new file mode 100644
index 0000000000..0aa6a8a0d6
--- /dev/null
+++ b/packages/phone-protocol/src/place-view.ts
@@ -0,0 +1,592 @@
+// Where a bot works, said once: one plain line and at most one next action for
+// every state a place can be in. The server words a failed turn's row from it
+// in English; the app renders the same state in the person's language. The
+// English mirrors src/locales/en.json `place.*` exactly (a test holds them
+// together): the server has no i18n.
+
+export type Place = "cloud" | "vm" | "local" | "browser";
+
+/** Every state a place can be in. cc-* is the cloud computer. */
+export const PLACE_STATES = [
+ "auto", "auto-team",
+ "cc-cannot", "cc-tools-off", "cc-sign-in", "cc-new", "cc-starting", "cc-waking", "cc-on", "cc-asleep",
+ "cc-no-hours", "cc-at-once", "cc-unavailable", "cc-ended", "cc-no-start", "cc-clearing", "cc-provider",
+ "cc-on-my-cloud", "cc-needs-key", "vps",
+ "browser", "browser-off", "browser-cannot",
+ "local", "local-unavailable", "vm", "vm-cannot", "place-failed",
+ "off",
+] as const;
+export type PlaceState = (typeof PLACE_STATES)[number];
+
+/** Where a failed place came from: the one control a person changes when it
+ * can't be used. A routine and a room member are their own sources; Auto and
+ * a team's shared computer name no place, so they never fail as one. */
+export type PlaceSource = "works-on" | "pin" | "auto-pin" | "routine" | "room";
+
+/** The next actions a place offers. Each is one button in the app and, on a
+ * stored row, one sentence a phone can read. */
+export const PLACE_ACTIONS = [
+ "choose-model", "open-tools", "sign-in", "start", "wake", "watch", "see-plan", "manage-computers",
+ "try-again", "open-my-cloud", "add-boat-key", "turn-on-browser", "open-team-map", "open-vm-settings",
+ "clear-pin", "change-routine", "open-computer-panel",
+] as const;
+export type PlaceActionId = (typeof PLACE_ACTIONS)[number];
+
+/** What a failed-turn row stores about its place, beside its English words,
+ * so the app can word it again in the reader's language. */
+export interface PlaceRow {
+ state: PlaceState;
+ params: PlaceParams;
+ source: PlaceSource;
+}
+
+export interface PlaceParams {
+ bot?: string;
+ engine?: string;
+ model?: string;
+ computer?: string;
+ hours?: number;
+ month?: string;
+ plan?: string;
+ max?: number;
+ holders?: string[];
+ words?: string;
+ reason?: string;
+ cause?: string;
+ /** The cloud desktop's limit is a free trial's. */
+ trial?: boolean;
+}
+
+export interface PlaceAction {
+ id: PlaceActionId;
+ label: string;
+}
+
+export interface PlaceView {
+ state: PlaceState;
+ params: PlaceParams;
+ /** A few words for a card, a grid tile or a chip row. */
+ short: string;
+ /** The one plain message. */
+ line: string;
+ action: PlaceAction | null;
+}
+
+/** Where this server runs, as the Auto line describes it. */
+export type ServerKind = "my-cloud" | "mac" | "pc" | "linux" | "remote";
+
+/** The facts a place's state is read from. */
+export interface PlaceFacts {
+ /** The place to describe: Auto, Off, or one of the four places. */
+ place: Place | "auto" | "off";
+ server: ServerKind;
+ bot: string;
+ /** Desktop only: signed in to a paid OpenMausBot Cloud plan (the desktop bridge). */
+ plan?: boolean;
+ /** Where cloud computers come from here: the plan's, the person's own Boat key, or nowhere. */
+ boat: "included" | "own-key" | "none";
+ /** The cloud computer's provider: Boat, or the person's own server. */
+ backend?: "box" | "vps";
+ engine: {
+ name: string;
+ model?: string;
+ /** It can use computer tools. */
+ computer: boolean;
+ /** It can use the built-in browser. */
+ browser: boolean;
+ /** Not waiting on a sign-in. */
+ signedIn: boolean;
+ };
+ /** The bot's tool selection includes the computer. */
+ toolsAllowComputer: boolean;
+ /** The built-in browser is switched on for this installation and bot. */
+ browserOn: boolean;
+ role: "admin" | "user";
+ mode?: "simple" | "advanced";
+ /** The cloud computer as last seen; unknown reads as not made yet. */
+ computer?: "none" | "starting" | "waking" | "on" | "asleep";
+ /** Auto uses a team's shared cloud computer by this name. */
+ teamComputer?: string;
+ /** This computer can be picked; `reason` says why not. */
+ local?: { ready: boolean; reason?: string };
+ /** A refusal already read from a failed start (cloudRefusal). */
+ refusal?: { state: PlaceState; params: PlaceParams };
+}
+
+/** The English catalog, mirrored by en.json. */
+export const PLACE_EN = {
+ "place.view.auto.short": "Chooses for you",
+ "place.view.auto.lineMyCloud": "Uses the built-in browser. In a chat, it starts its cloud desktop by itself when a task needs desktop apps.",
+ "place.view.auto.lineDesktop": "Uses the built-in browser, a private desktop on this computer, or this computer's screen, whichever the task needs.",
+ "place.view.auto.lineLinux": "Uses the built-in browser, or a running private desktop when a task needs one.",
+ "place.view.autoTeam.short": "Shared",
+ "place.view.autoTeam.line": "Uses {computer}, the cloud desktop this department shares.",
+ "place.view.ccCannot.short": "Not with this model",
+ "place.view.ccCannot.line": "{model} can't use a desktop. Choose a model that can, such as Claude or ChatGPT.",
+ "place.view.ccToolsOff.short": "Not allowed",
+ "place.view.ccToolsOff.line": "What {bot} can use doesn't include a desktop.",
+ "place.view.ccSignIn.short": "Sign in first",
+ "place.view.ccSignIn.line": "Sign in to {engine} first. {bot} uses it on its cloud desktop too.",
+ "place.view.ccSignIn.lineMyCloud": "Sign in to {engine} in the Cloud first. {bot} uses it on its cloud desktop too.",
+ "place.view.ccNew.short": "Ready",
+ "place.view.ccNew.line": "{bot} gets its own cloud desktop from Boat the first time a task needs one. The first start takes about a minute.",
+ "place.view.ccStarting.short": "Starting…",
+ "place.view.ccStarting.line": "Starting {bot}'s cloud desktop. The first start takes about a minute.",
+ "place.view.ccWaking.short": "Waking…",
+ "place.view.ccWaking.line": "Waking {bot}'s cloud desktop. This takes a few seconds.",
+ "place.view.ccOn.short": "On",
+ "place.view.ccOn.line": "{bot}'s cloud desktop is on. It goes to sleep after 10 minutes without use.",
+ "place.view.ccAsleep.short": "Asleep",
+ "place.view.ccAsleep.line": "{bot}'s cloud desktop is asleep. It wakes in a few seconds when {bot} needs it.",
+ "place.view.ccNoHours.short": "No hours left",
+ "place.view.ccNoHours.line": "This month's {hours} cloud desktop hours are used up. They come back on 1 {month}.",
+ "place.view.ccNoHours.lineUnknown": "This month's cloud desktop hours are used up.",
+ "place.view.ccNoHours.lineTrial": "The free trial's cloud desktop hours are used up. The full allowance starts with the first payment.",
+ "place.view.ccAtOnce.short": "In use",
+ "place.view.ccAtOnce.lineOne": "Your {plan} plan includes 1 cloud desktop, and {holders} has it.",
+ "place.view.ccAtOnce.lineMany": "Your {plan} plan includes {max} cloud desktops, and {holders} have them.",
+ "place.view.ccAtOnce.lineUnknown": "All the cloud desktops your plan includes are in use.",
+ "place.view.ccUnavailable.short": "Not available now",
+ "place.view.ccUnavailable.line": "Cloud desktops can't start right now. It isn't anything you did.",
+ "place.view.ccEnded.short": "Plan ended",
+ "place.view.ccEnded.line": "Your MausBot Cloud plan has ended, so cloud desktops are off.",
+ "place.view.ccNoStart.short": "Didn't start",
+ "place.view.ccNoStart.line": "{bot}'s cloud desktop didn't start.",
+ "place.view.ccClearing.short": "Clearing up",
+ "place.view.ccClearing.line": "{bot}'s previous cloud desktop is still being removed.",
+ "place.view.ccProvider.short": "Couldn't start",
+ "place.view.ccProvider.line": "Your Boat account couldn't start {bot}'s cloud desktop: {words}",
+ "place.view.ccOnMyCloud.short": "For Cloud bots",
+ "place.view.ccOnMyCloud.line": "Cloud desktops from your plan work for Cloud bots for now.",
+ "place.view.ccNeedsKey.short": "Connect Boat first",
+ "place.view.ccNeedsKey.line": "Bots here can get their own cloud desktops from Boat, a paid service.",
+ "place.view.vps.short": "Your own machine",
+ "place.view.vps.line": "Uses your own Linux machine, connected over SSH.",
+ "place.view.browser.short": "Web pages only",
+ "place.view.browser.line": "Works in the built-in browser only: web pages, no desktop apps.",
+ "place.view.browserOff.short": "Switched off",
+ "place.view.browserOff.line": "The bot's own browser is switched off, so it can't open web pages.",
+ "place.view.browserCannot.short": "Not with this model",
+ "place.view.browserCannot.line": "{model} can't use the built-in browser.",
+ "place.view.local.short": "Your screen",
+ "place.view.local.line": "Uses your screen, mouse, and keyboard.",
+ "place.view.localUnavailable.short": "Can't use it yet",
+ "place.view.localUnavailable.line": "{reason}",
+ "place.view.vm.short": "Separate from your screen",
+ "place.view.vm.line": "A private Linux desktop on this device, separate from your own screen.",
+ "place.view.vmCannot.short": "Not with this model",
+ "place.view.vmCannot.line": "{model} can't use a private desktop. Choose a model that can, such as Claude or ChatGPT.",
+ "place.view.placeFailed.short": "Didn't start",
+ "place.view.placeFailed.line": "{cause}",
+ "place.view.off.short": "No screen",
+ "place.view.off.line": "{bot} has no screen. It can still chat and do anything that doesn't need one.",
+ "place.action.chooseModel": "Choose a model",
+ "place.action.openTools": "Change what {bot} can use",
+ "place.action.signIn": "Sign in",
+ "place.action.start": "Start it now",
+ "place.action.wake": "Wake it now",
+ "place.action.watch": "Watch",
+ "place.action.seePlan": "See your plan",
+ "place.action.manageComputers": "Manage cloud desktops",
+ "place.action.tryAgain": "Try again",
+ "place.action.openMyCloud": "Open the Cloud",
+ "place.action.addBoatKey": "Connect Boat",
+ "place.action.turnOnBrowser": "Turn on the browser",
+ "place.action.openTeamMap": "Open Team map",
+ "place.action.openVmSettings": "Private desktop settings",
+ "place.action.clearPin": "Clear this conversation's place",
+ "place.action.usePlace": "Use {place}",
+ "place.action.changeRoutine": "Change where it runs",
+ "place.action.openComputerPanel": "Open the Screen panel",
+ "place.askAdmin": "Ask an Admin to change it.",
+ "place.backOnAuto": "This conversation is back on Auto.",
+} as const;
+export type PlaceKey = keyof typeof PLACE_EN;
+
+/** A stored row's next action as one English sentence: what a phone, which
+ * shows only the row's words, reads instead of a button. English only, like
+ * the row it ends. */
+export const PLACE_WORDS: Record<PlaceActionId, string> = {
+ "choose-model": "Choose another model in {bot}'s settings.",
+ "open-tools": "Change what {bot} can use in its settings.",
+ "sign-in": "Sign in to {engine} in Settings.",
+ start: "Start it from the Screen panel.",
+ wake: "Wake it from the Screen panel.",
+ watch: "Watch it from the Screen panel.",
+ "see-plan": "See your plan on the Plan page.",
+ "manage-computers": "Manage your cloud desktops in Settings → Bot desktops.",
+ "try-again": "Try again.",
+ "open-my-cloud": "Open My Cloud from the menu at the top of the sidebar.",
+ "add-boat-key": "Connect your Boat account in AI › Other services.",
+ "turn-on-browser": "Turn on the built-in browser in the Screen panel.",
+ "open-team-map": "Open Team map to manage it.",
+ "open-vm-settings": "Check it in Settings → Bot desktops.",
+ "clear-pin": "Clear this conversation's place in the composer to continue.",
+ "change-routine": "Change where this routine runs.",
+ "open-computer-panel": "Check it in the Screen panel.",
+};
+
+/** The words a person reads, in some language: the app passes its t(), the
+ * server the English mirror. */
+export type PlaceTranslate = (key: PlaceKey, params?: Record<string, string | number>) => string;
+
+function fill(template: string, params: Record<string, string | number> = {}): string {
+ return template.replace(/\{(\w+)\}/g, (whole, name: string) => (Object.hasOwn(params, name) ? String(params[name]) : whole));
+}
+
+export const english: PlaceTranslate = (key, params) => fill(PLACE_EN[key], params);
+
+/** Each state's key segment, short and line keys, and own action. */
+const STATE: Record<PlaceState, { key: string; action: PlaceActionId | null }> = {
+ auto: { key: "auto", action: null },
+ "auto-team": { key: "autoTeam", action: "open-team-map" },
+ "cc-cannot": { key: "ccCannot", action: "choose-model" },
+ "cc-tools-off": { key: "ccToolsOff", action: "open-tools" },
+ "cc-sign-in": { key: "ccSignIn", action: "sign-in" },
+ "cc-new": { key: "ccNew", action: "start" },
+ "cc-starting": { key: "ccStarting", action: "watch" },
+ "cc-waking": { key: "ccWaking", action: "watch" },
+ "cc-on": { key: "ccOn", action: "watch" },
+ "cc-asleep": { key: "ccAsleep", action: "wake" },
+ "cc-no-hours": { key: "ccNoHours", action: "see-plan" },
+ "cc-at-once": { key: "ccAtOnce", action: "manage-computers" },
+ "cc-unavailable": { key: "ccUnavailable", action: "try-again" },
+ "cc-ended": { key: "ccEnded", action: "see-plan" },
+ "cc-no-start": { key: "ccNoStart", action: "try-again" },
+ "cc-clearing": { key: "ccClearing", action: "try-again" },
+ "cc-provider": { key: "ccProvider", action: "try-again" },
+ "cc-on-my-cloud": { key: "ccOnMyCloud", action: "open-my-cloud" },
+ "cc-needs-key": { key: "ccNeedsKey", action: "add-boat-key" },
+ vps: { key: "vps", action: null },
+ browser: { key: "browser", action: null },
+ "browser-off": { key: "browserOff", action: "turn-on-browser" },
+ "browser-cannot": { key: "browserCannot", action: "choose-model" },
+ local: { key: "local", action: null },
+ "local-unavailable": { key: "localUnavailable", action: null },
+ vm: { key: "vm", action: "open-vm-settings" },
+ "vm-cannot": { key: "vmCannot", action: "choose-model" },
+ "place-failed": { key: "placeFailed", action: "open-computer-panel" },
+ off: { key: "off", action: null },
+};
+
+/** A passing cause: nothing to fix, so where the place came from decides the
+ * way on (sourceAction). Every other state's action removes its cause. */
+const PASSING: ReadonlySet<PlaceState> = new Set(["cc-unavailable", "cc-no-start", "cc-clearing", "cc-provider", "place-failed"]);
+
+/** Actions that change a setting, a sign-in or the plan: a User can't take
+ * them, so the line ends "Ask an Admin to change it." instead. */
+const ADMIN_ONLY: ReadonlySet<PlaceActionId> = new Set([
+ "choose-model", "open-tools", "sign-in", "see-plan", "manage-computers", "open-my-cloud",
+ "add-boat-key", "turn-on-browser", "open-team-map", "open-vm-settings", "change-routine",
+]);
+/** Starting or waking a computer early: a User's own message does it, so
+ * there is nothing to ask anyone for. */
+const ADMIN_SHORTCUT: ReadonlySet<PlaceActionId> = new Set(["start", "wake"]);
+
+const ACTION_KEY: Record<PlaceActionId, PlaceKey> = {
+ "choose-model": "place.action.chooseModel",
+ "open-tools": "place.action.openTools",
+ "sign-in": "place.action.signIn",
+ start: "place.action.start",
+ wake: "place.action.wake",
+ watch: "place.action.watch",
+ "see-plan": "place.action.seePlan",
+ "manage-computers": "place.action.manageComputers",
+ "try-again": "place.action.tryAgain",
+ "open-my-cloud": "place.action.openMyCloud",
+ "add-boat-key": "place.action.addBoatKey",
+ "turn-on-browser": "place.action.turnOnBrowser",
+ "open-team-map": "place.action.openTeamMap",
+ "open-vm-settings": "place.action.openVmSettings",
+ "clear-pin": "place.action.clearPin",
+ "change-routine": "place.action.changeRoutine",
+ "open-computer-panel": "place.action.openComputerPanel",
+};
+
+export function placeState(facts: PlaceFacts): { state: PlaceState; params: PlaceParams } {
+ const bot = facts.bot;
+ const model = facts.engine.model || facts.engine.name;
+ if (facts.place === "off") return { state: "off", params: { bot } };
+ if (facts.place === "auto") {
+ return facts.teamComputer
+ ? { state: "auto-team", params: { bot, computer: facts.teamComputer } }
+ : { state: "auto", params: { bot } };
+ }
+ if (facts.place === "browser") {
+ if (!facts.engine.browser) return { state: "browser-cannot", params: { bot, model } };
+ return facts.browserOn ? { state: "browser", params: { bot } } : { state: "browser-off", params: { bot } };
+ }
+ if (facts.place === "local") {
+ return facts.local?.ready === false
+ ? { state: "local-unavailable", params: { bot, reason: facts.local.reason ?? "" } }
+ : { state: "local", params: { bot } };
+ }
+ if (facts.place === "vm") {
+ return facts.engine.computer ? { state: "vm", params: { bot } } : { state: "vm-cannot", params: { bot, model } };
+ }
+ // On the person's own server (VPS) or on Boat, one rule for both.
+ const vps = facts.backend === "vps";
+ if (!facts.engine.computer) return { state: "cc-cannot", params: { bot, model } };
+ if (!facts.toolsAllowComputer) return { state: "cc-tools-off", params: { bot } };
+ if (!facts.engine.signedIn) return { state: "cc-sign-in", params: { bot, engine: facts.engine.name } };
+ if (vps) return { state: "vps", params: { bot } };
+ if (facts.refusal) return { state: facts.refusal.state, params: { bot, ...facts.refusal.params } };
+ if (facts.boat === "none") {
+ // My Cloud always has the plan's computers while the plan is active.
+ if (facts.server === "my-cloud") return { state: "cc-unavailable", params: { bot } };
+ return { state: facts.plan ? "cc-on-my-cloud" : "cc-needs-key", params: { bot } };
+ }
+ switch (facts.computer) {
+ case "starting": return { state: "cc-starting", params: { bot } };
+ case "waking": return { state: "cc-waking", params: { bot } };
+ case "on": return { state: "cc-on", params: { bot } };
+ case "asleep": return { state: "cc-asleep", params: { bot } };
+ default: return { state: "cc-new", params: { bot } };
+ }
+}
+
+/** Where the person goes when a passing cause stops a place: try again in
+ * place, clear the pin that holds this conversation, change where the
+ * routine runs. A room member's turn has no retry of its own. */
+function sourceAction(source: PlaceSource, state: PlaceState): PlaceActionId | null {
+ switch (source) {
+ case "works-on": return state === "place-failed" ? "open-computer-panel" : "try-again";
+ case "auto-pin": return "try-again";
+ case "pin": return "clear-pin";
+ case "routine": return "change-routine";
+ case "room": return null;
+ }
+}
+
+function lineKey(state: PlaceState, params: PlaceParams, server?: ServerKind): PlaceKey {
+ const segment = STATE[state].key;
+ if (state === "auto") {
+ return server === "my-cloud" ? "place.view.auto.lineMyCloud" : server === "linux" || server === "remote" ? "place.view.auto.lineLinux" : "place.view.auto.lineDesktop";
+ }
+ if (state === "cc-sign-in" && server === "my-cloud") return "place.view.ccSignIn.lineMyCloud";
+ if (state === "cc-no-hours" && params.trial) return "place.view.ccNoHours.lineTrial";
+ // A refusal read from a code alone has no numbers or names to give.
+ if (state === "cc-no-hours" && (params.hours === undefined || !params.month)) return "place.view.ccNoHours.lineUnknown";
+ if (state === "cc-at-once") {
+ if (!params.holders?.length || !params.plan || params.max === undefined) return "place.view.ccAtOnce.lineUnknown";
+ return params.max === 1 ? "place.view.ccAtOnce.lineOne" : "place.view.ccAtOnce.lineMany";
+ }
+ return `place.view.${segment}.line` as PlaceKey;
+}
+
+/** Join names the way a sentence lists them, in the reader's language. */
+export function listNames(names: readonly string[], locale = "en"): string {
+ try {
+ return new Intl.ListFormat(locale, { style: "long", type: "conjunction" }).format(names);
+ } catch {
+ return names.join(", ");
+ }
+}
+
+function templateParams(params: PlaceParams, locale: string): Record<string, string | number> {
+ const out: Record<string, string | number> = {};
+ for (const [name, value] of Object.entries(params)) {
+ if (value === undefined) continue;
+ out[name] = Array.isArray(value) ? listNames(value, locale) : value;
+ }
+ return out;
+}
+
+export interface PlaceContext {
+ server?: ServerKind;
+ role: "admin" | "user";
+ mode?: "simple" | "advanced";
+ source?: PlaceSource;
+ /** Simple mode words a pin's way back as "Use {place}", the grid's own label. */
+ worksOnLabel?: string;
+ translate?: PlaceTranslate;
+ locale?: string;
+}
+
+/** One state, worded: its short label, its one line and its one action. */
+export function placeViewOf(state: PlaceState, params: PlaceParams, context: PlaceContext): PlaceView {
+ const translate = context.translate ?? english;
+ const values = templateParams(params, context.locale ?? "en");
+ const segment = STATE[state].key;
+ let line = translate(lineKey(state, params, context.server), values);
+ let action: PlaceActionId | null = context.source && PASSING.has(state) ? sourceAction(context.source, state) : STATE[state].action;
+ // A failed row never offers what only the panel can do on the spot.
+ if (context.source && (action === "start" || action === "wake" || action === "watch")) action = null;
+ if (context.source === "auto-pin") line = `${line} ${translate("place.backOnAuto")}`;
+ // Simple mode leaves Local VM setup to Advanced.
+ if (action === "open-vm-settings" && context.mode === "simple") action = null;
+ if (action && context.role === "user" && ADMIN_SHORTCUT.has(action)) action = null;
+ if (action && context.role === "user" && ADMIN_ONLY.has(action)) {
+ action = null;
+ line = `${line} ${translate("place.askAdmin")}`;
+ }
+ // Simple mode has no composer chip, so a pin's way back is the grid's
+ // choice, by the grid's own name for it.
+ const label = !action ? null
+ : action === "clear-pin" && context.mode === "simple" && context.worksOnLabel
+ ? translate("place.action.usePlace", { place: context.worksOnLabel })
+ : translate(ACTION_KEY[action], values);
+ return {
+ state,
+ params,
+ short: translate(`place.view.${segment}.short` as PlaceKey, values),
+ line,
+ action: action && label ? { id: action, label } : null,
+ };
+}
+
+/** The view of a place from its facts. */
+export function placeView(facts: PlaceFacts, options: { translate?: PlaceTranslate; locale?: string } = {}): PlaceView {
+ const { state, params } = placeState(facts);
+ return placeViewOf(state, params, { server: facts.server, role: facts.role, mode: facts.mode, ...options });
+}
+
+/** A stored failed-turn row, worded for this reader. */
+export function placeRowView(row: PlaceRow, context: Omit<PlaceContext, "source">): PlaceView {
+ return placeViewOf(row.state, row.params, { ...context, source: row.source });
+}
+
+/** What the server stores as the row's words: the line and its action as a
+ * sentence, in English, so a phone that reads only the words knows both. */
+export function placeRowText(row: PlaceRow, server?: ServerKind): string {
+ const view = placeViewOf(row.state, row.params, { server, role: "admin", source: row.source });
+ if (!view.action) return view.line;
+ const words = row.source === "auto-pin" && view.action.id === "try-again"
+ ? "Send your message again."
+ : fill(PLACE_WORDS[view.action.id], templateParams(row.params, "en"));
+ return `${view.line} ${words}`;
+}
+
+
+const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] as const;
+const MONTH = `(${MONTHS.join("|")})`;
+const HOURS_USED = new RegExp(`Your (.+?) plan's (\\d+) cloud computer hours for \\w+ are used up\\. They reset on 1 ${MONTH}`);
+const TRIAL_HOURS_USED = new RegExp(`Your (.+?) free trial's (\\d+) cloud computer hours are used up\\. Your full allowance starts with your first payment on (\\d{1,2}) (${MONTHS.map((name) => name.slice(0, 3)).join("|")})`);
+const AT_ONCE = /Your (.+?) (plan|free trial) includes (\d+) cloud computers? at once/;
+const TOO_OFTEN = /(?:started|woken) too often\. Try again (in a minute|in an hour|tomorrow)/;
+const WINDOWS = { "in a minute": "minute", "in an hour": "hour", tomorrow: "day" } as const;
+const PASSING_WORDS = [
+ /cloud computers are busy right now/i, /temporarily unavailable/i, /can't be checked right now/i, /could not be reached/i,
+ /returned an unexpected answer/i, /could not complete that request/i, /started too often/i, /woken too often/i,
+ /included with your Cloud plan aren't available/i, /are not available right now/i, /fetch failed/i, /ECONNREFUSED/,
+ /rate-limiting/i, /\b50[234]\b/,
+];
+const NO_START_WORDS = [
+ /did not become ready/i, /desktop link could not be created/i, /could not be created or reached/i, /did not wake/i,
+ /no computer yet/i, /didn't start in time/i,
+];
+const CLEARING_WORDS = [/is being deleted/i, /previous cloud computer deletion/i, /deletion was not confirmed/i, /deletion is still being reconciled/i];
+
+/** Why the Admin turned a start of a plan's cloud desktop away, by its own limits. */
+export const CLOUD_LIMIT_REASONS = ["hours_used", "at_once", "too_many_starts", "usage_unavailable"] as const;
+export type CloudLimitReason = (typeof CLOUD_LIMIT_REASONS)[number];
+
+/** The Admin's refusal of a start, beside its code and sentence: `reason`;
+ * `trial` while the Cloud is on a free trial; the plan's name; the limit and
+ * what is used of it; when it lifts (ISO: for a trial's hours, its first
+ * payment); and, for starts, the window whose limit was reached. */
+export interface CloudLimit {
+ reason: CloudLimitReason;
+ trial?: boolean;
+ plan?: string;
+ limit?: number;
+ used?: number;
+ resetsAt?: string;
+ window?: "minute" | "hour" | "day";
+}
+
+/** A refusal body's limit fields, at its top or in its `error`; undefined
+ * from an Admin that sends no `reason`, or one this app doesn't know. */
+export function cloudLimitFromBody(body: unknown): CloudLimit | undefined {
+ const top = body && typeof body === "object" ? body as Record<string, unknown> : undefined;
+ const nested = top?.error && typeof top.error === "object" ? top.error as Record<string, unknown> : undefined;
+ const fields = typeof top?.reason === "string" ? top : nested;
+ const reason = fields?.reason;
+ if (!fields || !(CLOUD_LIMIT_REASONS as readonly unknown[]).includes(reason)) return undefined;
+ const count = (value: unknown) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
+ const limit = count(fields.limit), used = count(fields.used);
+ const plan = typeof fields.plan === "string" && fields.plan.length <= 40 ? fields.plan : undefined;
+ const resetsAt = typeof fields.resetsAt === "string" && !Number.isNaN(Date.parse(fields.resetsAt)) ? fields.resetsAt : undefined;
+ const window = fields.window === "minute" || fields.window === "hour" || fields.window === "day" ? fields.window : undefined;
+ return {
+ reason: reason as CloudLimitReason, ...(fields.trial === true ? { trial: true } : {}), ...(plan ? { plan } : {}),
+ ...(limit !== undefined ? { limit } : {}), ...(used !== undefined ? { used } : {}), ...(resetsAt ? { resetsAt } : {}), ...(window ? { window } : {}),
+ };
+}
+
+type CloudFailure = { message: string; code?: string; status?: number; limit?: CloudLimit };
+type LimitRead = { reason: CloudLimitReason; trial: boolean; plan?: string; max?: number; month?: string; resets?: string; window?: CloudLimit["window"] };
+
+function readLimit(failure: CloudFailure): LimitRead | null {
+ const { limit, code } = failure;
+ const message = failure.message.trim();
+ if (limit) {
+ const at = limit.resetsAt ? new Date(limit.resetsAt) : null;
+ const month = at ? MONTHS[at.getUTCMonth()] : undefined;
+ return {
+ reason: limit.reason, trial: limit.trial === true, ...(limit.plan ? { plan: limit.plan } : {}), ...(limit.limit !== undefined ? { max: limit.limit } : {}),
+ ...(at && month && !limit.trial ? { month } : {}),
+ ...(at && month ? { resets: `${at.getUTCDate()} ${limit.trial ? month.slice(0, 3) : month}` } : {}),
+ ...(limit.window ? { window: limit.window } : {}),
+ };
+ }
+ if ((CLOUD_LIMIT_REASONS as readonly unknown[]).includes(code)) return { reason: code as CloudLimitReason, trial: false };
+ const hours = HOURS_USED.exec(message);
+ if (hours) return { reason: "hours_used", trial: false, plan: hours[1], max: Number(hours[2]), month: hours[3], resets: `1 ${hours[3]}` };
+ const trialHours = TRIAL_HOURS_USED.exec(message);
+ if (trialHours) return { reason: "hours_used", trial: true, plan: trialHours[1], max: Number(trialHours[2]), resets: `${trialHours[3]} ${trialHours[4]}` };
+ const atOnce = AT_ONCE.exec(message);
+ if (atOnce) return { reason: "at_once", trial: atOnce[2] === "free trial", plan: atOnce[1], max: Number(atOnce[3]) };
+ const often = TOO_OFTEN.exec(message);
+ if (often) return { reason: "too_many_starts", trial: false, window: WINDOWS[often[1] as keyof typeof WINDOWS] };
+ if (code === "usage_unavailable") return { reason: "usage_unavailable", trial: false };
+ return null;
+}
+
+/** The Admin's refusal of a start, worded for the bot, so it never says one
+ * limit is another; null for any other failure. */
+export function cloudLimitSentence(failure: CloudFailure): string | null {
+ const limit = readLimit(failure);
+ switch (limit?.reason) {
+ case "hours_used":
+ return limit.trial
+ ? `This Cloud's free trial cloud computer hours are used up${limit.resets ? `; they come back on ${limit.resets}` : ""}.`
+ : `This Cloud's cloud computer hours for this month are used up${limit.resets ? `; they reset on ${limit.resets}` : ""}.`;
+ case "at_once":
+ return "This Cloud already has as many cloud computers running as its plan allows.";
+ case "too_many_starts":
+ return `Cloud computers were started too often; try again ${limit.window === "minute" ? "in a minute" : limit.window === "day" ? "tomorrow" : limit.window === "hour" ? "in an hour" : "later"}.`;
+ case "usage_unavailable":
+ return "Cloud computer use can't be checked right now.";
+ default:
+ return null;
+ }
+}
+
+/** The Admin's `reason` comes first, then its codes; from an Admin that
+ * sends neither, its English is read. `included`: the plan's computers, not
+ * the person's own Boat key, whose provider's words are shown as they are. */
+export function cloudRefusal(failure: CloudFailure, included: boolean): { state: PlaceState; params: PlaceParams } {
+ const message = failure.message.trim();
+ const code = failure.code;
+ const limit = readLimit(failure);
+ if (limit?.reason === "hours_used") {
+ if (limit.trial) return { state: "cc-no-hours", params: { trial: true } };
+ return { state: "cc-no-hours", params: limit.plan && limit.max !== undefined && limit.month ? { plan: limit.plan, hours: limit.max, month: limit.month } : {} };
+ }
+ if (limit?.reason === "at_once") {
+ return { state: "cc-at-once", params: limit.plan && limit.max !== undefined ? { plan: limit.plan, max: limit.max } : {} };
+ }
+ if (code === "subscription_inactive") return { state: "cc-ended", params: {} };
+ if (limit || code === "rate_limited" || code === "usage_unavailable" || code === "service_unavailable"
+ || code === "upstream_unavailable" || code === "invalid_response" || code === "upstream_error") {
+ return { state: "cc-unavailable", params: {} };
+ }
+ // A start that failed and left its new computer still being removed
+ // didn't start; the next attempt meets the removal.
+ if (NO_START_WORDS.some((words) => words.test(message))) return { state: "cc-no-start", params: {} };
+ if (CLEARING_WORDS.some((words) => words.test(message))) return { state: "cc-clearing", params: {} };
+ if ((failure.status ?? 0) >= 500 || PASSING_WORDS.some((words) => words.test(message))) return { state: "cc-unavailable", params: {} };
+ if (!included && message) return { state: "cc-provider", params: { words: message.replace(/[\s.]+$/, "") + "." } };
+ return { state: "cc-no-start", params: {} };
+}
diff --git a/packages/phone-protocol/src/profile-request.ts b/packages/phone-protocol/src/profile-request.ts
new file mode 100644
index 0000000000..fa14c96ec4
--- /dev/null
+++ b/packages/phone-protocol/src/profile-request.ts
@@ -0,0 +1,35 @@
+/**
+ * Durable payload carried by a profile confirmation card (propose_profile).
+ *
+ * The fields a bot may propose for itself (`cwd` is the working folder its
+ * tools run in; "" means its private workspace; `notifications` and
+ * `speakReplies` are the alert and voice toggles). `before` is the snapshot
+ * the user was shown; `expectedRevision` is a hash of the target's whole
+ * profile at proposal time so a confirmation fails closed if anything moved.
+ */
+export const PROFILE_REQUEST_FIELDS = ["name", "title", "description", "soul", "cwd", "notifications", "speakReplies"] as const;
+export type ProfileRequestField = (typeof PROFILE_REQUEST_FIELDS)[number];
+export type ProfileRequestChanges = Partial<Record<Exclude<ProfileRequestField, "notifications" | "speakReplies">, string>> &
+ Partial<Record<"notifications" | "speakReplies", boolean>>;
+
+export interface ProfileRequestCardData {
+ version: 1;
+ requestId: string;
+ /** The proposing conversation; authority is fixed here. */
+ botId: string;
+ threadId: string;
+ /** Whose profile changes: the proposer, or a section peer named by a Chief. */
+ targetBotId: string;
+ targetName: string;
+ createdAt: number;
+ reason: string;
+ changes: ProfileRequestChanges;
+ before: ProfileRequestChanges;
+ expectedRevision: string;
+ appliedAt?: number;
+ /** Written when the change applied without a person: the profile's
+ * revision right after it, so Undo refuses once anything moved. Absent
+ * when the before values could not be kept exactly (credential-shaped
+ * text is scrubbed from cards), which means no Undo. */
+ undo?: { appliedRevision: string };
+}
diff --git a/packages/phone-protocol/src/published-page.ts b/packages/phone-protocol/src/published-page.ts
new file mode 100644
index 0000000000..560d4a86aa
--- /dev/null
+++ b/packages/phone-protocol/src/published-page.ts
@@ -0,0 +1,36 @@
+/** A page a bot published to a public link, as its chat card shows it (WireMessage.publishedPage). The message's `text`
+ * says the same in words, with the link, for every client that does not draw the card. */
+export interface PublishedPageCard {
+ /** live: the link works, or may work when `uncertain` is true. unpublished: its owner took it down. limit: the plan's
+ * pages are used up, so nothing was published; `message` says so and `upgrade` offers a bigger plan. */
+ state: "live" | "unpublished" | "limit";
+ /** The upload's answer was lost. The page may be live and can still be unpublished. */
+ uncertain?: boolean;
+ title: string;
+ pageId?: string;
+ url?: string;
+ /** This account's pages and its plan's limit after this publish, as "3 of 5 pages". */
+ usage?: { pages: number; limit: number };
+ message?: string;
+ upgrade?: boolean;
+ /** limit cards: "free" (signed in, no Cloud) or the Cloud plan's tier. */
+ plan?: string;
+}
+
+/** The MausBot pages Worker's page ids: one DNS label of lowercase letters and digits. */
+export const PAGE_ID = /^[a-z0-9]{20,63}$/;
+
+/** What a page's files may be, by extension, and the Content-Type each is served with: the same list as the pages
+ * Worker's (openmaus-cloud pages-worker/src/files.ts refuses the rest). */
+export const PAGE_FILE_TYPES: Readonly<Record<string, string>> = {
+ html: "text/html; charset=utf-8", htm: "text/html; charset=utf-8", css: "text/css; charset=utf-8", js: "text/javascript; charset=utf-8",
+ mjs: "text/javascript; charset=utf-8", json: "application/json; charset=utf-8", txt: "text/plain; charset=utf-8", csv: "text/csv; charset=utf-8",
+ tsv: "text/tab-separated-values; charset=utf-8", ndjson: "application/x-ndjson; charset=utf-8", md: "text/markdown; charset=utf-8",
+ geojson: "application/geo+json", topojson: "application/json; charset=utf-8",
+ parquet: "application/vnd.apache.parquet", arrow: "application/vnd.apache.arrow.file", svg: "image/svg+xml",
+ png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", avif: "image/avif", ico: "image/x-icon",
+ woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf",
+};
+export const PAGE_FILE_EXTENSIONS: ReadonlySet<string> = new Set(Object.keys(PAGE_FILE_TYPES));
+export const PAGE_MAX_BYTES = 5 * 1024 * 1024;
+export const PAGE_MAX_FILES = 200;
diff --git a/packages/phone-protocol/src/reactions.ts b/packages/phone-protocol/src/reactions.ts
new file mode 100644
index 0000000000..72a78ac14c
--- /dev/null
+++ b/packages/phone-protocol/src/reactions.ts
@@ -0,0 +1,34 @@
+// Reactions on chat messages. A 👍 or 👎 on a bot's message is the person's reply to it; the others say how they feel.
+
+/** Every reaction a client offers and the server accepts, in the order clients show them. */
+export const REACTIONS = ["👍", "👎", "❤️", "😂", "🎉", "👀"] as const;
+export type Reaction = (typeof REACTIONS)[number];
+
+/** What a reaction did, as POST /api/threads/:threadId/messages/:messageId/reactions reports it: a turn `started` with
+ * it as the person's reply to that message, or the reply waits `queued` behind the running turn; the open card on the
+ * message was `answered`; a feeling the bot reads with its next turn (`noted`); or nothing reached a bot. */
+export type ReactionDelivery = "started" | "queued" | "answered" | "noted" | "none";
+
+/** 👍 answers yes and 👎 answers no; any other reaction answers nothing. */
+export function reactionAnswer(emoji: string | null | undefined): "yes" | "no" | null {
+ return emoji === "👍" ? "yes" : emoji === "👎" ? "no" : null;
+}
+
+/** Slack sends a reaction's short name. Telegram, Discord and WhatsApp send the emoji itself. */
+const SLACK_NAMES: Readonly<Record<string, Reaction>> = {
+ "+1": "👍", thumbsup: "👍", "-1": "👎", thumbsdown: "👎", heart: "❤️", joy: "😂", tada: "🎉", eyes: "👀",
+};
+const SLACK_NAME = /^:?([a-z0-9_+-]+)(?:::skin-tone-[2-6])?:?$/;
+/** Skin tones and the emoji presentation selector, which each platform adds or drops on its own. */
+const VARIANTS = /[\u{1F3FB}-\u{1F3FF}]|\uFE0F/gu;
+
+/** The reaction a person meant, from any client or chat channel: the emoji in any skin tone or presentation, or
+ * Slack's name for it. Null for anything outside REACTIONS. */
+export function normalizeReaction(raw: unknown): Reaction | null {
+ if (typeof raw !== "string" || raw.length > 64) return null;
+ const value = raw.trim();
+ const name = SLACK_NAME.exec(value.toLowerCase())?.[1];
+ if (name) return Object.hasOwn(SLACK_NAMES, name) ? SLACK_NAMES[name]! : null;
+ const bare = value.replace(VARIANTS, "");
+ return REACTIONS.find((reaction) => reaction.replace(VARIANTS, "") === bare) ?? null;
+}
diff --git a/packages/phone-protocol/src/reply-style.ts b/packages/phone-protocol/src/reply-style.ts
new file mode 100644
index 0000000000..5d8f24671c
--- /dev/null
+++ b/packages/phone-protocol/src/reply-style.ts
@@ -0,0 +1,44 @@
+/** An absent style means "default". */
+export const REPLY_STYLES = ["default", "conversational"] as const;
+export type ReplyStyle = (typeof REPLY_STYLES)[number];
+
+export function isConversational(style: ReplyStyle | undefined): boolean {
+ return style === "conversational";
+}
+
+const FENCE = /^ {0,3}(`{3,}|~{3,})/;
+const LIST_OR_TABLE = /^ {0,3}([-*+]\s|\d{1,3}[.)]\s|\|)/;
+
+/** Splits on blank lines but never inside a code fence, and keeps one loose list or table together. An unclosed fence keeps the rest in the last part, so finished parts never change. */
+export function splitConversationalReply(text: string): string[] {
+ const parts: string[] = [];
+ let current: string[] = [];
+ let fence: string | null = null;
+ const flush = () => {
+ // Leading indentation can make a code block, so only trailing space goes.
+ const block = current.join("\n").trimEnd();
+ current = [];
+ if (!block.trim()) return;
+ const prev = parts.at(-1);
+ if (prev !== undefined && LIST_OR_TABLE.test(block) && LIST_OR_TABLE.test(prev.split("\n").at(-1) ?? "")) {
+ parts[parts.length - 1] = `${prev}\n\n${block}`;
+ } else parts.push(block);
+ };
+ for (const line of text.split("\n")) {
+ const open = FENCE.exec(line);
+ if (fence) {
+ current.push(line);
+ if (open && open[1][0] === fence[0] && open[1].length >= fence.length && line.trim() === open[1]) fence = null;
+ continue;
+ }
+ if (open) {
+ fence = open[1];
+ current.push(line);
+ continue;
+ }
+ if (!line.trim()) flush();
+ else current.push(line);
+ }
+ flush();
+ return parts;
+}
diff --git a/packages/phone-protocol/src/responses.ts b/packages/phone-protocol/src/responses.ts
new file mode 100644
index 0000000000..51f8973e55
--- /dev/null
+++ b/packages/phone-protocol/src/responses.ts
@@ -0,0 +1,85 @@
+import type { EnvironmentDescriptor } from "./environment.ts";
+import type { CompanionEndpoint, PairingE2EDescriptor } from "./pairing-link.ts";
+import type { BotQueuedMessages, ComputerHelpRef, WireBot, WireGroup, WireMessage } from "./wire.ts";
+
+/** The encrypted-link descriptor a paired phone is sent. `routes: "local"` restricts it to Wi-Fi and Tailscale; absent
+ * means any route. */
+export interface CompanionE2EDescriptor extends PairingE2EDescriptor {
+ routes?: "any" | "local";
+}
+
+/** GET /api/companion/endpoints, and the body of a `companion.endpoints` frame: where a paired phone may connect. */
+export interface CompanionEndpointsSnapshot {
+ serverName: string;
+ endpoints: CompanionEndpoint[];
+ /** The desktop app's or server's release version (x.y.z, maybe with a suffix); absent from older versions. */
+ version?: string;
+ e2e?: CompanionE2EDescriptor;
+}
+
+/** A paired phone. A computer's companion sends its whole record; a server or Cloud sends only the first four fields. */
+export interface PairedDevice {
+ id: string;
+ name: string;
+ createdAt: number;
+ lastSeenAt: number;
+ cloudDesktopAccess?: boolean;
+ browserControlAccess?: boolean;
+ routes?: "any" | "local";
+ e2eAt?: number;
+}
+
+/** POST /api/pair: 201 from a computer's companion, 200 from a server or Cloud. */
+export interface PairResponse {
+ token: string;
+ device: PairedDevice;
+ serverName: string;
+ hosts?: string[];
+ endpoints?: CompanionEndpoint[];
+ e2e?: CompanionE2EDescriptor;
+}
+
+/** A signed-in session as the server describes it, never with its token. */
+export interface PairedSession {
+ id: string;
+ label: string;
+ scopes: Array<"admin" | "client">;
+ createdAt: number;
+ lastSeenAt: number;
+ expiresAt: number;
+ email?: string;
+ owner?: string;
+ teamRole?: string;
+ token?: true;
+}
+
+/** POST /api/auth/pair with a 12-character code, from a phone (no `cookie`). */
+export interface AuthPairResponse {
+ token: string;
+ session: PairedSession;
+ environment: EnvironmentDescriptor;
+}
+
+/** One page of a conversation, newest last. */
+export interface WireMessagePage<Message = WireMessage> {
+ messages: Message[];
+ hasMore?: boolean;
+ activeLeafId: string | null;
+}
+
+/** Whether someone holds a bot's computer, and the sign-in plea it stands for. */
+export interface WireComputerControl {
+ held: boolean;
+ helpReason: string | null;
+ help?: ComputerHelpRef;
+}
+
+/** GET /api/bots?messages=N: the fleet, each bot and room with the newest page of its selected conversation. */
+export interface BotsResponse<Message = WireMessage> {
+ bots: Array<WireBot & WireMessagePage<Message>>;
+ botQueuedMessages: BotQueuedMessages;
+ sections: string[];
+ groups: Array<WireGroup & WireMessagePage<Message>>;
+ /** By bot id. */
+ computerControl: Record<string, WireComputerControl>;
+}
diff --git a/packages/phone-protocol/src/routine-request.ts b/packages/phone-protocol/src/routine-request.ts
new file mode 100644
index 0000000000..2edcfd2899
--- /dev/null
+++ b/packages/phone-protocol/src/routine-request.ts
@@ -0,0 +1,130 @@
+/**
+ * Durable payload carried by a chat routine confirmation card. Tool input
+ * arrives normalized (milliseconds, numeric weekdays, credential-scrubbed
+ * text), so a confirmation survives a restart without asking the model again.
+ */
+
+import type { LimitResetRepeat } from "./limit-reset.ts";
+import type { RoutineCronSchedule } from "./routine-schedule.ts";
+
+export type RoutineRequestRunOn = "maus" | "cloud";
+
+export interface RoutineRequestIntervalWindow {
+ start: string;
+ end: string;
+}
+
+export type RoutineRequestSchedule =
+ | { type: "once"; at: number }
+ /** The time is the engine's, derived when the routine is saved. */
+ | { type: "limit_reset"; engine: string; repeat: LimitResetRepeat }
+ | { type: "daily"; time: string; weekdays: number[] }
+ | RoutineCronSchedule
+ | {
+ type: "interval";
+ everyMinutes: number;
+ anchorAt?: number;
+ /** Local weekdays (Sunday = 0). Missing means every day. */
+ weekdays?: number[];
+ /** Local wall-clock window. Missing means all day. */
+ window?: RoutineRequestIntervalWindow;
+ /** Inclusive epoch-millisecond cutoff. Missing means never. */
+ endsAt?: number;
+ };
+
+export type RoutineRequestScheduleChanges =
+ | Exclude<RoutineRequestSchedule, { type: "interval" }>
+ | {
+ type: "interval";
+ everyMinutes: number;
+ anchorAt?: number;
+ /** `null` explicitly restores the every-day default. */
+ weekdays?: number[] | null;
+ /** `null` explicitly restores the all-day default. */
+ window?: RoutineRequestIntervalWindow | null;
+ /** `null` explicitly removes an existing end date. */
+ endsAt?: number | null;
+ };
+
+export interface RoutineRequestDefinition {
+ name: string;
+ instructions: string;
+ schedule: RoutineRequestSchedule;
+ runOn: RoutineRequestRunOn;
+ /** Calendar/display length only: it does not stop an active run. */
+ durationMinutes: number;
+ /** Optional safety cap for active work. Missing means no timeout. */
+ timeoutMinutes?: number;
+ /** Carry the previous run's report into the next run. */
+ continuity?: boolean;
+ /** Skip by default, or keep at most one scheduled run waiting. */
+ overlap?: "skip" | "queue";
+ /** Also run once each time OpenMausBot starts. Repeating routines only. */
+ runOnStartup?: boolean;
+}
+
+export type RoutineRequestChanges =
+ & Omit<Partial<RoutineRequestDefinition>, "schedule" | "timeoutMinutes">
+ & {
+ schedule?: RoutineRequestScheduleChanges;
+ /** `null` removes an existing safety cap. */
+ timeoutMinutes?: number | null;
+ };
+
+/** Another bot in the proposer's section that this proposal targets: a
+ * routine scheduled for it, or one of its routines being changed. Captured
+ * (id + display name) when the card is created so the card stays meaningful
+ * if the bot is later renamed; authority over the card remains with the
+ * proposing conversation. */
+export interface RoutineRequestTargetBot {
+ botId: string;
+ name: string;
+}
+
+export type RoutineRequestOperation =
+ | { action: "create"; routine: RoutineRequestDefinition; forBot?: RoutineRequestTargetBot }
+ | { action: "update"; routineId: string; expectedUpdatedAt: number; changes: RoutineRequestChanges; forBot?: RoutineRequestTargetBot }
+ | { action: "pause"; routineId: string; expectedUpdatedAt: number; forBot?: RoutineRequestTargetBot }
+ | { action: "resume"; routineId: string; expectedUpdatedAt: number; forBot?: RoutineRequestTargetBot }
+ | { action: "run_now"; routineId: string; expectedUpdatedAt: number; forBot?: RoutineRequestTargetBot }
+ | { action: "delete"; routineId: string; expectedUpdatedAt: number; forBot?: RoutineRequestTargetBot };
+
+/** A routine as it stood before a change applied without a person, so Undo
+ * can put it back. Room goals keep their room; attachments are not kept, so
+ * a routine that has any is not offered an Undo for its update or delete. */
+export interface RoutineRequestSnapshot extends RoutineRequestDefinition {
+ enabled: boolean;
+ target?: "room-goal";
+ groupId?: string;
+ resultsThreadId?: string;
+}
+
+/** Written on a card whose change applied without a person (the bot's own
+ * routine, or Full access): what the one-line receipt shows, and what its
+ * Undo needs. */
+export interface RoutineRequestUndo {
+ /** The routine's name and schedule as the change left them. */
+ name: string;
+ schedule?: RoutineRequestSchedule;
+ /** The routine's revision right after the change; Undo refuses once it moved. */
+ appliedUpdatedAt?: number;
+ /** The routine before an update or a delete. */
+ before?: RoutineRequestSnapshot;
+ /** On a Cloud home: the routine was the owner's before the change. */
+ ownersBefore?: boolean;
+}
+
+export interface RoutineRequestCardData {
+ version: 1;
+ /** Also used as the scheduler's idempotency key after confirmation. */
+ requestId: string;
+ /** Authority is fixed when the card is created; an agent cannot redirect it later. */
+ botId: string;
+ threadId: string;
+ createdAt: number;
+ operation: RoutineRequestOperation;
+ /** Written after a successful confirmation. */
+ appliedAt?: number;
+ resultId?: string;
+ undo?: RoutineRequestUndo;
+}
diff --git a/packages/phone-protocol/src/routine-run.ts b/packages/phone-protocol/src/routine-run.ts
new file mode 100644
index 0000000000..e6bfc6cbbb
--- /dev/null
+++ b/packages/phone-protocol/src/routine-run.ts
@@ -0,0 +1,49 @@
+/** Durable, non-actionable projection of one background routine run.
+ *
+ * The provider still runs in its isolated execution task. This small card is
+ * upserted into the trusted conversation that created the routine so the user
+ * can see progress, results, and where to review an approval without hunting
+ * through the routines calendar.
+ */
+import type { RoutineRunTrigger } from "./routines.ts";
+
+export interface RoutineRunCardData {
+ runId: string;
+ routineId: string;
+ routineName: string;
+ scheduledFor?: number;
+ status: "queued" | "running" | "waiting" | "completed" | "failed" | "cancelled" | "missed";
+ /** Present while a queued run is being held because its target bot or room
+ * is busy. The status stays queued; this is the surfaced deferral fact. */
+ deferredAt?: number;
+ /** Exact terminal team-goal outcome when this run targeted a room. */
+ goalStatus?: "completed" | "needs-input" | "blocked" | "limit-reached" | "paused" | "stopped" | "failed";
+ executionThreadId?: string;
+ summary?: string;
+ error?: string;
+}
+
+/** A bot line one automation run wrote into the chat it reports to: the run's
+ * result, a copy of a card the run waits on (answering it there answers the
+ * run), or why the run failed. The run works in its own hidden conversation,
+ * `executionThreadId`, which keeps its full transcript. */
+export interface AutomationLine {
+ routineId: string;
+ runId: string;
+ name: string;
+ /** What started the run; "app" is a connected-app event, "wait" a wait's follow-up. A Bot API call starts a turn,
+ * never a run, so "api" is never seen here. */
+ trigger: RoutineRunTrigger | "app" | "wait";
+ executionThreadId: string;
+ scheduledFor: number;
+ /** The run needs the person: it asked them something or cannot go on without them. */
+ needsYou?: true;
+ failed?: true;
+ /** With `failed`: the run's reply came back; only a step it ran failed or wasn't allowed. */
+ partial?: true;
+ /** A run that had nothing new, posted only because this automation's line before it in the chat said a run failed. */
+ recovered?: true;
+ /** The card in the run's conversation this line stands for: an option card
+ * is copied whole, a sign-in, connection or credential card is named. */
+ copyOf?: string;
+}
diff --git a/packages/phone-protocol/src/routine-schedule.ts b/packages/phone-protocol/src/routine-schedule.ts
new file mode 100644
index 0000000000..110068c0f4
--- /dev/null
+++ b/packages/phone-protocol/src/routine-schedule.ts
@@ -0,0 +1,88 @@
+import { Cron } from "croner";
+
+export interface RoutineCronSchedule {
+ type: "cron";
+ expression: string;
+ /** Explicit IANA timezone; independent of the server or viewer's timezone. */
+ timeZone: string;
+}
+
+const MAX_EXPRESSION_LENGTH = 256;
+const MAX_PREVIEW_RUNS = 1000;
+
+function cronCalculator(value: unknown): { schedule: RoutineCronSchedule; cron: Cron } {
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Choose a valid cron schedule");
+ const input = value as Partial<RoutineCronSchedule>;
+ if (input.type !== "cron" || typeof input.expression !== "string") throw new Error("Choose a valid cron schedule");
+ if (Object.keys(input).some(key => !["type", "expression", "timeZone"].includes(key))) {
+ throw new Error("Cron schedules accept only type, expression and timeZone; start/end dates and other restrictions are not supported");
+ }
+ const expression = input.expression.trim().replace(/\s+/g, " ");
+ if (expression.length > MAX_EXPRESSION_LENGTH || expression.split(" ").length !== 5 || expression.includes("@")) {
+ throw new Error("Cron must have five fields: minute hour day-of-month month weekday (no seconds, year, or macros)");
+ }
+ const timeZone = typeof input.timeZone === "string" ? input.timeZone.trim() : "";
+ // Intl also accepts numeric offsets in newer runtimes. Require a named zone
+ // so wall-clock schedules follow its daylight-saving rules instead.
+ if (timeZone.length > 128 || !(timeZone === "UTC" || /^[A-Za-z][A-Za-z0-9_+-]*(?:\/[A-Za-z0-9_+-]+)+$/.test(timeZone))) {
+ throw new Error("Choose an IANA timezone such as America/New_York, Asia/Kolkata, or UTC");
+ }
+ try { new Intl.DateTimeFormat("en-US", { timeZone }).format(0); }
+ catch { throw new Error("Choose a valid IANA timezone such as America/New_York, Asia/Kolkata, or UTC"); }
+ try {
+ // Date calculator only: no callback, name, or timer. RoutineManager owns
+ // dispatch, persistence, catch-up and cancellation. Croner bounds its
+ // five-field search at year 3000, including impossible calendar dates.
+ const cron = new Cron(expression, { timezone: timeZone, mode: "5-part", paused: true });
+ return { schedule: { type: "cron", expression, timeZone }, cron };
+ } catch (error) {
+ throw new Error(`Invalid cron expression: ${(error as Error).message}`);
+ }
+}
+
+function calculationDate(after: number): Date {
+ const date = new Date(after);
+ if (!Number.isFinite(after) || !Number.isFinite(date.getTime())) throw new Error("Choose a valid cron preview date");
+ return date;
+}
+
+function futureRuns(cron: Cron, after: number, count: number): number[] {
+ const from = calculationDate(after);
+ // Croner resolves an ambiguous wall-clock time to its first occurrence.
+ // If the cursor is already in the second occurrence, its first candidate
+ // can therefore be in the past. Ask the same calculator for more candidates
+ // and discard those, rather than moving the scheduler cursor backwards.
+ // Minute precision bounds even a full-day historical timezone fold at 1440.
+ const maximum = count + 1440;
+ let requested = count;
+ while (true) {
+ const candidates = cron.nextRuns(requested, from);
+ const runs: number[] = [];
+ for (const date of candidates) {
+ const at = date.getTime();
+ if (!Number.isFinite(at)) throw new Error("The cron schedule produced an invalid date");
+ if (at > (runs.at(-1) ?? after)) runs.push(at);
+ if (runs.length === count) return runs;
+ }
+ if (candidates.length < requested || requested === maximum) return runs;
+ // Sparse schedules normally need just one more candidate. Grow only when
+ // needed, so a daily preview never scans years to skip one repeated hour.
+ requested = Math.min(maximum, requested * 2);
+ }
+}
+
+/** Normalize once at the trust boundary, rejecting impossible schedules. */
+export function normalizeCronSchedule(value: unknown, after = Date.now()): RoutineCronSchedule {
+ const { schedule, cron } = cronCalculator(value);
+ if (!futureRuns(cron, after, 1).length) throw new Error("This cron expression has no future runs. Choose dates that exist.");
+ return schedule;
+}
+
+/** Strictly-future instants, shared by the scheduler, cards and calendar.
+ * Croner's DST policy is intentional: missing clock times advance through
+ * the gap, and repeated clock times use their first occurrence only. */
+export function nextCronRuns(schedule: RoutineCronSchedule, after: number, count: number): number[] {
+ if (!Number.isInteger(count) || count < 1 || count > MAX_PREVIEW_RUNS) throw new Error("Choose between 1 and 1000 cron preview runs");
+ const { cron } = cronCalculator(schedule);
+ return futureRuns(cron, after, count);
+}
diff --git a/packages/phone-protocol/src/routines.ts b/packages/phone-protocol/src/routines.ts
new file mode 100644
index 0000000000..cf01c5cea4
--- /dev/null
+++ b/packages/phone-protocol/src/routines.ts
@@ -0,0 +1,258 @@
+/** Routine wire shapes: the routine and run records as they ride the REST
+ * snapshot and the `routine` / `routine.run` live frames. */
+import type { LimitResetSchedule, LimitResetScheduleInput } from "./limit-reset.ts";
+import type { RoutineCronSchedule } from "./routine-schedule.ts";
+import type { ModelSelection } from "./wire.ts";
+import type { ServerTextParams } from "./server-text.ts";
+
+export interface RoutineIntervalWindow {
+ start: string;
+ end: string;
+}
+
+export type RoutineSchedule =
+ | RoutineCronSchedule
+ | LimitResetSchedule
+ | { type: "once"; at: number }
+ | { type: "daily"; time: string; weekdays: number[] }
+ | {
+ type: "interval";
+ everyMinutes: number;
+ anchorAt: number;
+ /** Local weekdays (Sunday = 0). Missing means every day. */
+ weekdays?: number[];
+ /** Local wall-clock window. Missing means all day. */
+ window?: RoutineIntervalWindow;
+ /** Inclusive epoch-millisecond cutoff. Missing means never. */
+ endsAt?: number;
+ };
+
+export type RoutineScheduleInput =
+ | Extract<RoutineSchedule, { type: "once" | "daily" | "cron" }>
+ | LimitResetScheduleInput
+ | {
+ type: "interval";
+ everyMinutes: number;
+ anchorAt: number;
+ /** `null` explicitly restores the every-day default on updates. */
+ weekdays?: number[] | null;
+ /** `null` explicitly restores the all-day default on updates. */
+ window?: RoutineIntervalWindow | null;
+ /** `null` explicitly removes an existing end date on updates. */
+ endsAt?: number | null;
+ };
+
+export type RoutineRunOn = "maus" | "cloud";
+
+export type RoutineTarget = "bot" | "room-goal";
+export type RoutineGoalStatus =
+ | "completed"
+ | "needs-input"
+ | "blocked"
+ | "limit-reached"
+ | "paused"
+ | "stopped"
+ | "failed";
+
+export interface RoutineContextAttachment {
+ id: string;
+ kind: "file" | "image";
+ name: string;
+ path: string;
+ size: number;
+}
+
+/** "api": an outside caller through the bot's API; "webhook": an outside event. Both run as nobody's work. */
+export type RoutineRunTrigger = "schedule" | "manual" | "webhook" | "startup" | "api";
+
+/** A check a routine runs on each tick before any AI turn, in plain code: `calendar` reads the next 36 hours, `mail`
+ * new inbox mail since the last check, `runs` other routines' finished runs. Nothing new means no AI turn. */
+export type RoutineCheck = "calendar" | "mail" | "runs";
+export const ROUTINE_CHECKS: readonly RoutineCheck[] = ["calendar", "mail", "runs"];
+
+/** What a routine's runs may do. `read-and-draft`: read Gmail and Google Calendar and write reply drafts; every other
+ * tool is refused outright, never turned into a card. Missing means the bot's own level. */
+export type RoutineAccess = "read-and-draft";
+
+/** Where a routine's results go. `brief`: they become rows of the main agent's brief, not chat lines of their own. */
+export type RoutineDelivery = "brief";
+
+/** Why OpenMausBot paused a routine by itself, after its owner left: no AI of theirs is signed in here any more, they
+ * removed every connected app and server, or the plan was cancelled. It turns back on once that changes. */
+export type RoutineHoldCause = "plan_cancelled" | "no_engine" | "no_connections";
+export const ROUTINE_HOLD_CAUSES: readonly RoutineHoldCause[] = ["plan_cancelled", "no_engine", "no_connections"];
+
+/** What a finished run left in the chat it reports to: nothing, because it
+ * found nothing to tell; a report waiting for a turn there to end; or the bot
+ * message it wrote. */
+export type RoutineRunReport =
+ | { state: "quiet" }
+ | { state: "pending" }
+ | { state: "posted"; threadId: string; messageId: string };
+
+export type RoutineRunStatus =
+ | "queued"
+ | "running"
+ | "waiting"
+ | "completed"
+ | "failed"
+ | "cancelled"
+ | "missed";
+
+/** Why a run started a second time by itself: its engine stalled, OpenMausBot
+ * restarted while it ran, the provider rate-limited it or failed for a moment,
+ * it waited for its engine's usage limit to reset, or it failed some other way.
+ * A run gets one. */
+export type RoutineRetryCause = "stalled" | "restarted" | "rate_limited" | "provider" | "usage_limit" | "failed";
+
+/** The statuses both failure indicators count: a run that went wrong and has
+ * not been acknowledged. */
+export const ROUTINE_PROBLEM_STATUSES: readonly RoutineRunStatus[] = ["failed", "missed"];
+
+/** A run's `attention` while it waits only on work it handed to teammates: nothing is asked of the person. */
+export const ROUTINE_HANDOFF_WAIT = "Waiting for work it handed on to finish";
+
+export function isRoutineProblemRun(run: { status: RoutineRunStatus }): boolean {
+ return ROUTINE_PROBLEM_STATUSES.includes(run.status);
+}
+
+/** The logs view's status filter: every run, the composite problem set the
+ * indicators count, or one exact status. */
+export type RoutineRunStatusFilter = "all" | "problems" | RoutineRunStatus;
+
+export interface Routine {
+ id: string;
+ name: string;
+ prompt: string;
+ target: RoutineTarget;
+ botId: string;
+ /** The room a "room-goal" runs in; none runs the goal in the bot's own one-on-one chat, a room of one. */
+ groupId?: string;
+ runOn: RoutineRunOn;
+ enabled: boolean;
+ schedule: RoutineSchedule;
+ durationMinutes: number;
+ /** Optional wall-clock safety limit. Missing means the run is unlimited. */
+ timeoutMinutes?: number;
+ overlap?: "skip" | "queue";
+ /** Each run starts with the previous run's report. */
+ continuity?: boolean;
+ /** The model each run's thread uses instead of its bot's. Missing means the bot's model. */
+ modelSelection?: ModelSelection;
+ /** Also run once each time OpenMausBot starts. */
+ runOnStartup?: boolean;
+ checks?: RoutineCheck[];
+ access?: RoutineAccess;
+ deliver?: RoutineDelivery;
+ /** When its checks last read everything and found nothing for the AI. */
+ checkedAt?: number;
+ /** A plain sentence while its checks cannot read an app, so a failed read never looks like nothing new. */
+ checkTrouble?: string;
+ /** Catalog key for `checkTrouble` when it is one of the server's fixed lines; `checkTrouble` keeps the English. */
+ checkTroubleCode?: string;
+ /** The next time its checks have something to do on time (a reminder, meeting prep): only this may keep the
+ * computer awake or wake a sleeping Cloud. */
+ wakeAt?: number;
+ skippedRuns?: number;
+ lastSkippedAt?: number;
+ failureStreak?: number;
+ /** Runs that finished in the last seven days, and how many of them completed. */
+ weekRuns?: { ok: number; total: number };
+ /** A plain sentence when the routine names a path that cannot exist on the computer that runs it. */
+ warning?: string;
+ /** Set while OpenMausBot keeps it paused because its owner left; turning it on or off clears it. */
+ heldFor?: RoutineHoldCause;
+ attachments?: RoutineContextAttachment[];
+ sourceThreadId?: string;
+ resultsThreadId?: string;
+ nextRunAt: number | null;
+ createdAt: number;
+ updatedAt: number;
+}
+
+export interface RoutineRun {
+ id: string;
+ routineId: string;
+ routineName: string;
+ prompt?: string;
+ durationMinutes?: number;
+ timeoutMinutes?: number;
+ attachments?: RoutineContextAttachment[];
+ target: RoutineTarget;
+ goalStatus?: RoutineGoalStatus;
+ botId: string;
+ groupId?: string;
+ runOn: RoutineRunOn;
+ scheduledFor: number;
+ status: RoutineRunStatus;
+ manual: boolean;
+ triggerSource?: RoutineRunTrigger;
+ /** "app": a connected-app event started it; "wait": a wait's follow-up did. triggerSource is then "webhook" (an outside event). */
+ eventSource?: "app" | "wait";
+ webhookId?: string;
+ deliveryId?: string;
+ /** Room task created for a team-goal run. */
+ executionThreadId?: string;
+ sourceThreadId?: string;
+ resultsThreadId?: string;
+ threadId?: string;
+ startedAt?: number;
+ finishedAt?: number;
+ output?: string;
+ /** Catalog key for `output` when it is one of the server's fixed lines; `output` keeps the English. */
+ outputCode?: string;
+ /** Catalog key and params for `error` and for `attention` when the server wrote them from a fixed line. A client words
+ * one only while its field still reads as that line's English; the field always keeps the English. */
+ errorCode?: string;
+ errorParams?: ServerTextParams;
+ attentionCode?: string;
+ attentionParams?: ServerTextParams;
+ error?: string;
+ /** A failed run whose reply still came back: only a step it ran failed or wasn't allowed. */
+ partial?: boolean;
+ /** Set when the run used its one automatic second start, and why. */
+ retried?: RoutineRetryCause;
+ /** Concise, redacted question or approval reason while status is waiting,
+ * or why a queued run starts later. */
+ attention?: string;
+ cost?: number | null;
+ denials?: string[];
+ report?: RoutineRunReport;
+ access?: RoutineAccess;
+ deliver?: RoutineDelivery;
+ /** The items its routine's checks handed this run, so they are kept or released once it ends. */
+ checkKey?: string;
+ createdAt: number;
+ seenAt?: number;
+}
+
+export interface RoutineInput {
+ name: string;
+ prompt: string;
+ target?: RoutineTarget;
+ botId: string;
+ groupId?: string | null;
+ runOn?: RoutineRunOn;
+ enabled?: boolean;
+ schedule: RoutineScheduleInput;
+ durationMinutes?: number;
+ /** `null` explicitly removes the limit; omission preserves it on updates. */
+ timeoutMinutes?: number | null;
+ overlap?: "skip" | "queue";
+ /** Each run starts with the previous run's report. */
+ continuity?: boolean;
+ /** `null` removes it on updates; omission preserves it. */
+ modelSelection?: ModelSelection | null;
+ runOnStartup?: boolean;
+ /** `null` explicitly removes them on updates; omission preserves them. */
+ checks?: RoutineCheck[] | null;
+ access?: RoutineAccess | null;
+ deliver?: RoutineDelivery | null;
+ attachments?: RoutineContextAttachment[];
+ /** Omission preserves routing; null resets it to the bot's main thread (on a Team Cloud, a results chat everyone who
+ * sees the bot reads); RESULTS_JUST_ME, on a Team Cloud only, the person's own private chat with the bot. */
+ resultsThreadId?: string | null;
+}
+
+/** On a Team Cloud, "Just me": the routine reports into the person's own private chat with the bot, theirs alone. */
+export const RESULTS_JUST_ME = "just-me";
diff --git a/packages/phone-protocol/src/runtime-events.ts b/packages/phone-protocol/src/runtime-events.ts
new file mode 100644
index 0000000000..9c6e1bf2e5
--- /dev/null
+++ b/packages/phone-protocol/src/runtime-events.ts
@@ -0,0 +1,211 @@
+/** Canonical runtime-event shapes, as they ride the live wire and the
+ * inspector log. */
+import type { AskQuestion } from "./ask-question.ts";
+import type { ServerText, ServerTextParams } from "./server-text.ts";
+import type { LiveStep, TurnProgressFields } from "./turn-progress.ts";
+
+export type DriverKind = string;
+export type InstanceId = string;
+export type ThreadId = string;
+export type TurnId = string;
+
+export interface ModelVariantOption {
+ id: string;
+ label: string;
+}
+
+export interface ModelVariantState {
+ options: ModelVariantOption[];
+ currentValue?: string;
+}
+
+// A subset of upstream's ProviderRuntimeEvent union, sharing one base. `raw`
+// carries the native protocol message behind the normalization.
+export interface RuntimeEventBase {
+ eventId: string;
+ provider: DriverKind;
+ providerInstanceId?: InstanceId;
+ threadId: ThreadId;
+ createdAt: string;
+ turnId?: TurnId;
+ itemId?: string;
+ requestId?: string;
+ raw?: { source: string; payload: unknown };
+ /** Text the provider's own client produced instead of the model (an API
+ * error it reports as a reply). Rendered like any other item, but not a
+ * sign that the model received or acted on the prompt. */
+ synthetic?: boolean;
+}
+
+export type RuntimeEvent = RuntimeEventBase &
+ (
+ | {
+ type: "session.started"; sessionId: string | null; model?: string | null;
+ /** the provider refused the turn's resumeCursor and this new session
+ * was started from the turn's recoveryText */
+ rebuilt?: boolean;
+ /** the turn's `custom` MCP servers the engine reported could not connect */
+ mcpFailed?: string[];
+ }
+ | { type: "session.model-variants"; model: string; variants: ModelVariantState }
+ | { type: "session.exited"; reason?: string }
+ | { type: "turn.started" }
+ | {
+ type: "turn.retrying";
+ /** 1-based: the retry about to be launched (1 = first relaunch). */
+ attempt: number;
+ delayMs: number;
+ /** Why this failure was judged retry-worthy. */
+ reason: string;
+ }
+ | {
+ type: "turn.completed";
+ ok: boolean;
+ stopReason?: string | null;
+ cost?: number | null;
+ denials?: string[];
+ /** THIS turn's token total, as the provider reports it at the end: the
+ * one figure the harness accumulates. thread.token-usage.updated means
+ * something different per driver and must never be summed. */
+ usage?: { input: number; output: number; cachedInput?: number };
+ }
+ | {
+ /** A resumable terminal: the turn exhausted its model/tool budget and
+ * a structured handoff was persisted. */
+ type: "cap.exhausted";
+ /** Absolute path to the persisted handoff for the dead turn. */
+ handoffPath: string;
+ /** What stopped the turn without a final answer. */
+ reason: "cap";
+ }
+ | {
+ type: "turn.wait_started";
+ /** The computer or browser this turn queued behind (e.g. "computer:box:bx_…", "browser:bot-…"). */
+ resource: string;
+ /** Where this turn sat in the resource's arrival-ordered waitlist when
+ * the wait began. */
+ position?: number;
+ /** Who held the computer when the wait began, if the holder was known. */
+ holder?: { name: string; task?: string };
+ }
+ | {
+ type: "turn.wait_ended";
+ resource: string;
+ holder?: { name: string; task?: string };
+ /** How long the turn actually waited. */
+ waitedMs: number;
+ /** acquired: the claim landed; stopped: the turn was stopped or
+ * cancelled while waiting; parked: the wait ceiling settled the turn
+ * for resume; gave_up: only in older recorded logs. */
+ outcome: "acquired" | "gave_up" | "parked" | "stopped";
+ }
+ | {
+ type: "item.started";
+ itemType: "tool" | "reasoning";
+ title?: string;
+ /** The shell command the call runs, on one redacted line of at most
+ * 200 characters, for the chip and the Verify card. Absent for calls
+ * that run no command (a Read, a fetch). */
+ summary?: string;
+ /** Bounded, redacted display preview; never raw tool arguments. */
+ input?: string;
+ /** What the call works on, read from `summary` and `input` as the event passes the bus. */
+ step?: LiveStep;
+ }
+ | { type: "item.updated"; itemType: "tool" | "reasoning"; tokens?: number | null }
+ /** Output a running call printed, as its engine streams it: a chunk to append, or with `whole` all of it so far.
+ * Live only: the bus folds it into the status line's `tail` and never logs or forwards it. */
+ | { type: "item.output"; itemType: "tool"; text: string; whole?: boolean }
+ /** What the engine is doing right now (a tool call being written or run), for the chat's status line. Live only:
+ * the bus coalesces it and never writes it to the event log; nothing stores it. */
+ | Omit<TurnProgressFields, "itemId">
+ | { type: "item.completed"; itemType: "tool"; ok: boolean; output?: string }
+ | { type: "item.completed"; itemType: "assistant_text"; text: string }
+ /** Provider-generated raster bytes, folded into the private attachment
+ * store and never forwarded to renderer SSE. `fromTool`: a tool's result
+ * returned the image to the engine; the bot did not make or send it. */
+ | { type: "item.completed"; itemType: "assistant_image"; data: string; alt?: string; fromTool?: true }
+ | { type: "content.delta"; streamKind: "assistant_text" | "reasoning_text"; delta: string; /** A room reply as it goes out: the member speaking. */ botId?: string }
+ | {
+ type: "request.opened";
+ requestType: "permission" | "question";
+ tool: string;
+ summary: string;
+ /** Fixed `chat.notice.*` summary words beside their English fallback; absent for provider-authored text. */
+ summaryCode?: string;
+ summaryParams?: ServerTextParams;
+ /** Complete native shell input and its effective working directory.
+ * Used for exact-command grants; never reconstructed from a display
+ * summary, tool title, or argv. Absent when either value is unknown. */
+ command?: { command: string; cwd: string };
+ /** The shell command line exactly as the engine sent it, even when `command` is absent for want of a cwd.
+ * Read only by the safety floor; no grant is ever made from it, and like `command` it is never broadcast. */
+ commandLine?: string;
+ /** The files a read tool's ask reads (absolute): a request that reads only the bot's own files is answered
+ * without the person. Like `command`, never broadcast. */
+ reads?: string[];
+ choices?: string[];
+ /** A provider's structured ask (Claude's AskUserQuestion): the whole
+ * set of questions, each with its own options, so the card can offer
+ * them instead of an Allow/Deny a person cannot answer. */
+ questions?: AskQuestion[];
+ /** "tool" (or absent): a harness tool call; "output": a block parsed
+ * from model-authored final output. Untrusted-input rules apply either
+ * way. */
+ origin?: "tool" | "output";
+ approvalScope?: "local-computer";
+ /** Provider asks to widen its configured sandbox. Only explicit Full
+ * access may answer this automatically; Auto/remembered grants may not. */
+ requiresExplicitApproval?: boolean;
+ /** Whether the provider's own automatic reviewer was running when it
+ * raised this request. Claude reports its effective permission mode in
+ * its init frame and silently starts in Manual when Auto is unavailable
+ * for the model. "inactive": the app's own safe-Auto rules may answer;
+ * unset: nobody knows. */
+ nativeReview?: "active" | "inactive";
+ /** The provider can keep an allow for the rest of its session
+ * ("Always allow this session"): Claude through its own suggested
+ * permission rules, ACP agents through `allow_always` or the
+ * driver's per-session memory. Unset when answers are one-shot. */
+ allowSession?: boolean;
+ }
+ | {
+ type: "request.resolved";
+ behavior: "allow" | "deny" | "answer";
+ /** who decided: a person, auto mode, the ask's own timeout, the
+ * harness (turn ended / settings changed), or nobody — the answerer
+ * was already gone and the action never ran */
+ source: "user" | "auto" | "timeout" | "system" | "unavailable" | "peer";
+ approvalScope?: "local-computer";
+ }
+ | {
+ type: "thread.token-usage.updated"; input: number; output: number; cachedInput?: number;
+ /** What the model's window held on the most recent model call — the
+ * whole prompt, cache reads included — and the window's size when the
+ * driver knows it. The figure that predicts the next message's cost. */
+ contextTokens?: number; contextWindow?: number;
+ /** The part of `output` spent reasoning, where the engine reports it. A per-call report carries the call's own
+ * message id in `itemId`, repeated on every frame of that call. */
+ reasoning?: number;
+ }
+ // `setup`: fixed by installing or configuring something, not by retrying.
+ // `terminal`: the complete turn failed, not a transient error.
+ // `claudeUpdate`: this Claude Code is too old for the model.
+ // `trialCredit`: the trial's Claude credit refused the call.
+ // `stalled`: the engine went silent and the turn was stopped as stuck.
+ // `limitResetsAt`: epoch ms when the usage limit refusing this account resets, when the engine says.
+ // `limit`: a usage limit refused this turn: the account's on this engine ("engine"), one model's own window
+ // ("model"), or that model's extra usage credits ("credits"); the engine's other models still work for the last two.
+ // `limitModels`: the models a "model" limit holds, when one allowance is shared (OpenCode's free models).
+ | { type: "runtime.error"; message: string; partial?: boolean; setup?: boolean; terminal?: boolean; claudeUpdate?: boolean; trialCredit?: "used_up" | "ended" | "paused" | "too_low";
+ stalled?: boolean; limitResetsAt?: number; limit?: "engine" | "model" | "credits"; limitModels?: string[];
+ /** `message` as a `chat.notice.*` key and params, when it is one of the server's fixed sentences. */
+ text?: ServerText }
+ /** Something the person should know that did not fail the turn — for
+ * example, a saved model the engine no longer offers was replaced. */
+ | { type: "runtime.notice"; message: string; text?: ServerText }
+ /** The engine condensed the conversation into its own summary (Claude Code's compact_boundary); the chat marks it. */
+ | { type: "context.compacted" }
+ );
+
+export type RuntimeEventListener = (event: RuntimeEvent) => void;
diff --git a/packages/phone-protocol/src/saved-steps.ts b/packages/phone-protocol/src/saved-steps.ts
new file mode 100644
index 0000000000..fbaaf5a0e0
--- /dev/null
+++ b/packages/phone-protocol/src/saved-steps.ts
@@ -0,0 +1,3 @@
+/** Set on the reply of a request whose computer steps were saved (`learned`) or that was answered from saved steps
+ * with no AI (`replayed`), as `WireMessage.savedSteps`. Clients that do not know it ignore it. */
+export interface SavedStepsMark { recipeId: string; learned?: true; replayed?: true }
diff --git a/packages/phone-protocol/src/server-text.ts b/packages/phone-protocol/src/server-text.ts
new file mode 100644
index 0000000000..ec73f815f3
--- /dev/null
+++ b/packages/phone-protocol/src/server-text.ts
@@ -0,0 +1,60 @@
+/** Values for the `{placeholders}` of a sentence the server words. */
+export type ServerTextParams = Record<string, string | number>;
+
+/** A sentence the server words for a person, named by its key in
+ * src/locales/en.json so a client can say it in the person's language. The
+ * server always sends the English beside it, which is what a client that does
+ * not know the key shows. */
+export interface ServerText {
+ key: string;
+ params?: ServerTextParams;
+}
+
+/** A message's `text` the server wrote from a fixed line. */
+export interface ServerTextLine {
+ /** Catalog key (`chat.notice.*`) for `text`. `text` keeps the English, which phones, exports, the bot's own context
+ * and older clients read. */
+ textCode?: string;
+ /** Values for the placeholders of `textCode`. */
+ textParams?: ServerTextParams;
+}
+
+/** The fixed name and summary of an activity chip, beside their English fallbacks. */
+export interface ServerToolText {
+ /** Catalog key (`chat.notice.*`) for the words of `name` after any
+ * `error:` marker, when they are one of the server's fixed notices.
+ * `name` keeps the English, which phones, exports and older clients show. */
+ nameCode?: string;
+ /** Values for the placeholders of `nameCode`. */
+ nameParams?: ServerTextParams;
+ /** Fixed summary words, only while they rebuild `summary`. */
+ summaryCode?: string;
+ summaryParams?: ServerTextParams;
+}
+
+/** The JSON body of a refused request. */
+export interface ServerErrorBody {
+ /** English, always present: what a client that does not know `errorKey` shows. */
+ error: string;
+ /** A machine code clients branch on (`cloud_personal`, `managed_policy`, …). Never a catalog key. */
+ code?: string;
+ /** A `serverError.*` catalog key a client may show instead of `error`. */
+ errorKey?: string;
+ /** Values for the placeholders of `errorKey`. */
+ errorParams?: ServerTextParams;
+}
+
+const REFERENCE_PARAMS = new Set(["limit", "meanwhile", "why"]);
+const PART_KEY = /^(?:chat\.notice|routines\.server)\.part\.\w+$/;
+
+/** Only these params may name a catalog piece (`chat.notice.part.*`, `routines.server.part.*`) that a client words;
+ * every other param is data, such as a name, a quote or a failure, and is shown exactly as sent. */
+export function isReferenceParam(name: string, value: string | number): boolean {
+ return REFERENCE_PARAMS.has(name) && typeof value === "string" && PART_KEY.test(value);
+}
+
+export function formatServerText(template: string, params: ServerTextParams = {}): string {
+ return template.replace(/\{(\w+)\}/g, (match, name: string) =>
+ Object.hasOwn(params, name) ? String(params[name]) : match,
+ );
+}
diff --git a/packages/phone-protocol/src/setup-card.ts b/packages/phone-protocol/src/setup-card.ts
new file mode 100644
index 0000000000..3ca89c250b
--- /dev/null
+++ b/packages/phone-protocol/src/setup-card.ts
@@ -0,0 +1,19 @@
+/** What clients draw the setup card under a new bot's greeting from. */
+export interface SetupCardFields {
+ /** A new bot's greeting while it has no role or instructions: clients that know it draw the setup card under the
+ * text; `text` reads on its own for older ones. It stays once the card is answered, so the card can show the answer;
+ * closing the card clears it. */
+ setupOffer?: true;
+ /** The setup card's answers, in the app's language. Picking one sends its words; absent on older greetings, where a
+ * client offers its own. Replaced only in the change that clears setupChoicesPending or setupChoicesUpdating. */
+ setupChoices?: string[];
+ /** Personal answers for this card are being written: clients show the card without answers until it clears. The
+ * server clears it within 6 s, in the same change that sets setupChoices if they came in time; a client still seeing
+ * it 8 s after showing the card, or on a greeting older than 20 s, shows setupChoices. */
+ setupChoicesPending?: true;
+ /** Epoch ms the bot's latest rename started rewriting setupChoices, while the card was unanswered: clients keep
+ * showing them but take no pick until it clears. The server clears it within 7 s of the stamp, in the same change
+ * that sets the new setupChoices if they came in time; a client still seeing a stamp 8 s after it first saw it, or
+ * one older than 20 s, takes picks again. */
+ setupChoicesUpdating?: number;
+}
diff --git a/packages/phone-protocol/src/sign-in-request.ts b/packages/phone-protocol/src/sign-in-request.ts
new file mode 100644
index 0000000000..f15641fc05
--- /dev/null
+++ b/packages/phone-protocol/src/sign-in-request.ts
@@ -0,0 +1,80 @@
+/**
+ * A bot asking the person to sign in to a website themselves, in the place the
+ * bot works. OpenMausBot never receives a website password: the person types it
+ * into the page, and the bot uses the session the page keeps.
+ */
+import type { Surface } from "./wire.ts";
+
+/** Where the login has to happen: the place the asking turn worked in.
+ * The built-in browser keeps its own sign-ins, apart from any computer's
+ * browser, so a login made anywhere else would not reach the bot. */
+export type SignInPlace = Surface;
+
+/** The site as a page address and the host shown on the card. A bare
+ * domain means its https home page. Anything that is not a plain http(s)
+ * address — a script URL, a file, an address carrying a username or
+ * password — is refused, so the card can never open more than a page. */
+export function normalizeSignInSite(raw: unknown): { url: string; site: string } | null {
+ if (typeof raw !== "string") return null;
+ const text = raw.trim();
+ // eslint-disable-next-line no-control-regex -- Reject control characters and spaces before URL parsing normalizes them.
+ if (!text || text.length > 2048 || /[\u0000- \u007f\\]/u.test(text)) return null;
+ let url: URL;
+ try {
+ url = new URL(/^[a-z][a-z\d+.-]*:/i.test(text) ? text : `https://${text}`);
+ } catch {
+ return null;
+ }
+ if ((url.protocol !== "https:" && url.protocol !== "http:") || !url.hostname || url.username || url.password) return null;
+ // A bare word is no site ("example" would parse as a host); localhost and
+ // addresses are the exceptions a developer's own app needs.
+ if (!url.hostname.includes(".") && url.hostname !== "localhost" && !url.hostname.startsWith("[")) return null;
+ return { url: url.href, site: url.hostname.replace(/^www\./, "") };
+}
+
+/** A still-open sign-in card for this site — the set a newer request
+ * supersedes. Done, cancelled, already-superseded and answered-in-chat
+ * cards keep their settled state. In a room only the asking bot's own
+ * cards count. */
+export function isPendingSignInRequest(
+ message: {
+ kind?: unknown;
+ signIn?: { site?: unknown; done?: unknown; cancelled?: unknown; superseded?: unknown; answeredInChat?: unknown };
+ from?: { botId?: unknown };
+ },
+ site: string,
+ requestingBotId: string,
+ roomThread: boolean,
+): boolean {
+ return (
+ message.kind === "signin" &&
+ message.signIn?.site === site &&
+ signInWaits(message.signIn) &&
+ (!roomThread || message.from?.botId === requestingBotId)
+ );
+}
+
+/** Whether the card still waits on the person: not done, cancelled, superseded or answered in the chat. */
+export function signInWaits(card: { done?: unknown; cancelled?: unknown; superseded?: unknown; answeredInChat?: unknown }): boolean {
+ return card.done !== true && card.cancelled !== true && card.superseded !== true && card.answeredInChat !== true;
+}
+
+/** Whether a sign-in card, if there still is one, waits on the person: not stopped and still open. */
+export function signInCardWaits(card: ({ stopped?: unknown } & Parameters<typeof signInWaits>[0]) | undefined): boolean {
+ return card !== undefined && card.stopped !== true && signInWaits(card);
+}
+
+/** How a card ended, or null while it is open. */
+export function signInOutcome(state: { done?: unknown; cancelled?: unknown }): "done" | "cancelled" | null {
+ if (state.done === true) return "done";
+ if (state.cancelled === true) return "cancelled";
+ return null;
+}
+
+/** The line that resumes the bot, through the same continuation the
+ * credential card uses. */
+export function signInResumePrompt(site: string, outcome: "done" | "cancelled"): string {
+ return outcome === "done"
+ ? `OpenMausBot sign-in update: the person finished signing in to ${site}. Check you are signed in, then continue the task that paused for it. Never ask them for a password or a one-time code in chat.`
+ : `OpenMausBot sign-in update: the person declined to sign in to ${site}. Continue without it if you can, or briefly explain what you could not do. Never ask them for a password or a one-time code in chat.`;
+}
diff --git a/packages/phone-protocol/src/skill-request.ts b/packages/phone-protocol/src/skill-request.ts
new file mode 100644
index 0000000000..0a70e54026
--- /dev/null
+++ b/packages/phone-protocol/src/skill-request.ts
@@ -0,0 +1,73 @@
+/**
+ * Durable payload on a learned-skill confirmation card. None of the staged
+ * SKILL.md reaches the bot's enabled skill index until the user confirms; during
+ * an update the approved version stays live.
+ */
+export type SkillRequestAction = "create" | "update" | SkillSwitchAction;
+
+/** Turning one of the bot's existing skills on or off, or deleting it: no new
+ * SKILL.md, so the card shows the current one and approval binds to it. */
+export type SkillSwitchAction = "enable" | "disable" | "delete";
+
+export function isSkillSwitchAction(action: unknown): action is SkillSwitchAction {
+ return action === "enable" || action === "disable" || action === "delete";
+}
+
+export function skillSwitchVerb(action: SkillSwitchAction): string {
+ return action === "enable" ? "turn on" : action === "disable" ? "turn off" : "delete";
+}
+
+/** Kept on the receipt so Undo reverts the library write and the assignments together. */
+export interface SkillShareRecord {
+ /** deduplicated: identical bytes were already in the library; assigned: it already was a library skill. */
+ library: "installed" | "deduplicated" | "assigned" | "updated";
+ sha256: string;
+ sharedAt: number;
+ assigned: Array<{ botId: string; name: string }>;
+ skipped: Array<{ botId: string; name: string; reason: string }>;
+}
+
+export interface SkillRequestCardData {
+ version: 1;
+ requestId: string;
+ botId: string;
+ threadId: string;
+ stagedId: string;
+ action: SkillRequestAction;
+ name: string;
+ gist: string;
+ /** Human-readable provenance retained with the installed skill. */
+ source?: string;
+ /** Exact, secret-scrubbed SKILL.md shown as plain text before approval. */
+ preview?: string;
+ /** Binds approval to the exact bytes shown in preview. */
+ sha256?: string;
+ /** references/<topic>.md files shown in full beside the SKILL.md; absent when the skill is SKILL.md alone. */
+ references?: Array<{ path: string; content: string }>;
+ /** Binds approval to the exact references shown. */
+ referencesSha256?: string;
+ warnings: string[];
+ createdAt: number;
+ /** An update or delete that applied without a person: the SKILL.md it replaced or removed, so
+ * Undo can put it back while the skill is unchanged since. enabled is false for a deleted skill that was off. */
+ previous?: { preview: string; source: string; references?: Array<{ path: string; content: string }>; enabled?: boolean };
+ shared?: SkillShareRecord;
+ shareError?: string;
+}
+
+/** The hash a current client may echo after it displayed the complete
+ * proposal. Old cards deliberately return undefined and remain deny-only. */
+export function reviewedSkillSha256(request: SkillRequestCardData): string | undefined {
+ if (!request.preview || !request.sha256 || !/^[a-f0-9]{64}$/i.test(request.sha256)) return undefined;
+ return request.sha256;
+}
+
+/** Map the server-authored affirmative labels explicitly and fail closed for
+ * anything else. This keeps new Update/Apply wording working without turning
+ * an unknown or corrupted card answer into approval. */
+export function skillRequestBehavior(answer: string): "allow" | "deny" {
+ const normalized = answer.trim().toLowerCase();
+ return ["enable", "turn on", "turn off", "delete", "update", "apply", "allow", "allow once", "confirm", "yes"].includes(normalized)
+ ? "allow"
+ : "deny";
+}
diff --git a/packages/phone-protocol/src/task-provenance.ts b/packages/phone-protocol/src/task-provenance.ts
new file mode 100644
index 0000000000..f08c97af82
--- /dev/null
+++ b/packages/phone-protocol/src/task-provenance.ts
@@ -0,0 +1,33 @@
+/** The bot that opened a thread on itself or a teammate. */
+export interface TaskOpenedBy {
+ botId: string;
+ name: string;
+ delegationId?: string;
+ /** What kind of conversation the opener made this: "pair" is the one
+ * durable conversation between two bots; "work" closes itself once its
+ * result has been reported. */
+ kind?: "pair" | "work";
+ /** The burst this thread is one part of: it is listed under that burst's card. */
+ burstId?: string;
+ /** The opener's own conversation this "work" thread was opened from.
+ * Everything that conversation later sends this bot continues here. */
+ threadId?: string;
+ /** A parallel room job's thread: `threadId` is the room thread it came from, and the member must stay in that room. */
+ roomLane?: true;
+ /** Security invariant: harness-set only when the opening turn could use the owner's lent computer. */
+ forOwner?: true;
+ at: number;
+}
+
+/** The bot that closed a thread it opened (or one of its own). */
+export interface TaskClosedBy {
+ botId: string;
+ name: string;
+ at: number;
+}
+
+/** The completed message whose visible history seeded an independent conversation. */
+export interface ForkOrigin {
+ threadId: string;
+ messageId: string;
+}
diff --git a/packages/phone-protocol/src/team-presence.ts b/packages/phone-protocol/src/team-presence.ts
new file mode 100644
index 0000000000..ac18129267
--- /dev/null
+++ b/packages/phone-protocol/src/team-presence.ts
@@ -0,0 +1,44 @@
+// Who is here on a Team Cloud (docs/team-cloud.md "Who is here"): the wire between the server and the app. A person is
+// named by their address, as in GET /api/team/people. Nothing here ever names a private chat: a conversation only one
+// person can read is never reported, and its person only counts as here.
+
+/** POST {tab, threadId}: this app window is open, with that conversation in front of the person (null: none, or one that
+ * is theirs alone). `tab` is the window's own id, made when it loads. Sent when the conversation changes and every
+ * HERE_REPEAT_MS while the window shows. */
+export const PRESENCE_HERE_PATH = "/api/presence/here";
+
+export interface PresenceHereBody {
+ tab: string;
+ threadId: string | null;
+}
+
+/** How often a showing window repeats its POST; a window not heard from for a few of these no longer counts. */
+export const HERE_REPEAT_MS = 60_000;
+
+/** A person on GET /api/team/people, with presence: `here` while one of their apps is open. A server that sends no
+ * `here` has no presence, and the app shows none. */
+export interface PersonPresence {
+ here?: boolean;
+}
+
+/** A teammate came or went. Sent to everyone signed in to the team, at most once every few seconds per person. */
+export interface TeamPresenceFrame {
+ kind: "team.presence";
+ email: string;
+ here: boolean;
+}
+
+/** Who has a shared conversation (a bot's shared chat, a group chat) open now, the receiver included. Sent only to the
+ * people listed, each of whom may read it; never for a conversation that is one person's own. */
+export interface ThreadPresenceFrame {
+ kind: "thread.presence";
+ threadId: string;
+ people: string[];
+}
+
+/** Someone joined the team, left it or changed role: the app reads the people and its own session again. */
+export interface TeamPeopleFrame {
+ kind: "team.people";
+}
+
+export type PresenceFrame = TeamPresenceFrame | ThreadPresenceFrame | TeamPeopleFrame;
diff --git a/packages/phone-protocol/src/team-setup.ts b/packages/phone-protocol/src/team-setup.ts
new file mode 100644
index 0000000000..c4a01a30f0
--- /dev/null
+++ b/packages/phone-protocol/src/team-setup.ts
@@ -0,0 +1,70 @@
+import type { ModelSelection } from "./wire.ts";
+
+export interface TeamSetupFields {
+ name?: string;
+ title?: string;
+ description?: string;
+ soul?: string;
+ /** Create only: the folder the new bot's tools work in. "" = private workspace. */
+ cwd?: string;
+ section?: string;
+ modelSelection?: ModelSelection;
+ chiefOfStaff?: boolean;
+}
+
+export interface TeamSetupOperation {
+ action: "create" | "update";
+ botId: string;
+ threadId?: string;
+ fields: TeamSetupFields;
+ expectedRevision?: string;
+}
+
+export interface TeamSetupResult {
+ state: "applied" | "denied" | "cancelled" | "failed";
+ bots: Array<{ id: string; name: string; action: "created" | "updated" | "deleted"; section?: string; modelSelection?: ModelSelection; chiefOfStaff?: boolean }>;
+ newTeams: string[];
+ error?: string;
+}
+
+/** The complete, reviewed operation. It never accepts executable permissions. */
+export interface TeamSetupRequest {
+ version: 1;
+ requestId: string;
+ botId: string;
+ threadId: string;
+ reason: string;
+ createdAt: number;
+ requesterRevision: string;
+ operations: TeamSetupOperation[];
+ newTeams: string[];
+ deletion?: { botId: string; name: string; expectedRevision: string };
+ result?: TeamSetupResult;
+ resumed?: boolean;
+ /** Set when the setup applied on its own (direct-apply.ts) and Undo can reverse it. */
+ undo?: TeamSetupUndo;
+}
+
+/** Undo deletes the bots a setup created while still unused, gives each updated bot back the values the card showed and
+ * the Chief its earlier teams; `revisions` pin every bot it touched as it applied, so a later change refuses Undo. */
+export interface TeamSetupUndo {
+ created: string[];
+ before: Array<{ botId: string; fields: TeamSetupFields; managedSections?: string[] | null }>;
+ revisions: Record<string, string>;
+}
+
+/** A new bot gets no cloud computer until the person writes in its chat, unless it is set to work on one (it then starts one on its first turn), uses a VPS or the team's computer. */
+export function startsWithoutCloudComputer(bot: { computer?: string; cloudBackend?: string }, place: { cloudOn: boolean; teamComputer: boolean }): boolean {
+ return place.cloudOn && !place.teamComputer && bot.cloudBackend !== "vps" && bot.computer !== "cloud";
+}
+
+/** Told to a Chief about a bot it just made that has no cloud computer of its own yet. */
+export function noCloudComputerNote(name: string): string {
+ return ` @${name} has no cloud computer yet: work you hand it runs without one until the person writes to it in its own chat, which sets one up. If its first job needs a computer, tell the person that in one line.`;
+}
+
+/** The Chief's resumed turn once its team setup card is decided. `lacksComputer` names newly created bots with no cloud computer yet. */
+export function teamSetupDecisionText(request: TeamSetupRequest, lacksComputer: (botId: string) => boolean): string {
+ const bare = request.result?.state === "applied" ? request.result.bots.filter((bot) => bot.action === "created" && lacksComputer(bot.id)) : [];
+ return `OpenMausBot team setup decision ${request.requestId}: ${JSON.stringify(request.result)}. Report this exact result and continue the user's already requested work. Do not ask for confirmation again or repeat this setup/deletion. A denied or cancelled operation did not authorize any substitute action. Existing thread models were not changed.${bare.map((bot) => noCloudComputerNote(bot.name)).join("")}`;
+}
diff --git a/packages/phone-protocol/src/tool-scope.ts b/packages/phone-protocol/src/tool-scope.ts
new file mode 100644
index 0000000000..d798c4cb5c
--- /dev/null
+++ b/packages/phone-protocol/src/tool-scope.ts
@@ -0,0 +1,148 @@
+import { agentsCallIdentities } from "./agents-tool-names.ts";
+import { PHONE_STEP_TOOLS } from "./phone-steps.ts";
+
+export type ToolScope = {
+ allow?: string[];
+ deny?: string[];
+};
+
+export type ToolIdentity =
+ | { kind: "native"; name: string }
+ | { kind: "mcp"; server: string; name: string };
+
+type ParsedToolScope = { ok: true; scope: ToolScope | undefined } | { ok: false; error: string };
+
+const SERVER_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
+// Selectors must never contain protocol control characters.
+// eslint-disable-next-line no-control-regex
+const CONTROL_CHARACTER = /[\x00-\x1f\x7f]/;
+const MAX_SELECTORS = 256;
+const MAX_SELECTOR_LENGTH = 1024;
+
+function validName(name: unknown): name is string {
+ return typeof name === "string" && name.trim().length > 0
+ && name.length <= MAX_SELECTOR_LENGTH && !CONTROL_CHARACTER.test(name)
+ && !name.includes("*");
+}
+
+function selectorIdentity(selector: string): ToolIdentity | undefined {
+ if (selector.length > MAX_SELECTOR_LENGTH || CONTROL_CHARACTER.test(selector)) return;
+ if (selector.startsWith("native:")) {
+ const name = selector.slice(7);
+ if (name === "*" || validName(name)) return { kind: "native", name };
+ } else if (selector.startsWith("mcp:")) {
+ const separator = selector.indexOf(":", 4);
+ if (separator < 0) return;
+ const server = selector.slice(4, separator);
+ const name = selector.slice(separator + 1);
+ if (SERVER_NAME.test(server) && (name === "*" || validName(name))) {
+ return { kind: "mcp", server, name };
+ }
+ }
+}
+
+/** Undefined inherits the existing catalog. A present invalid value never does. */
+export function parseToolScope(value: unknown): ParsedToolScope {
+ if (value === undefined) return { ok: true, scope: undefined };
+ const invalid = { ok: false, error: "Tool selection must contain only valid allow and deny lists." } as const;
+ if (!value || typeof value !== "object" || Array.isArray(value)) return invalid;
+ const prototype = Object.getPrototypeOf(value);
+ if (prototype !== Object.prototype && prototype !== null) return invalid;
+ const scope: ToolScope = {};
+ for (const key of Reflect.ownKeys(value)) {
+ if (key !== "allow" && key !== "deny") return invalid;
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
+ if (!descriptor || !("value" in descriptor)) return invalid;
+ const list: unknown = descriptor.value;
+ if (!Array.isArray(list) || list.length > MAX_SELECTORS) return invalid;
+ // Array.from exposes holes as undefined instead of silently skipping them.
+ if (!Array.from(list).every((entry: unknown) => typeof entry === "string" && selectorIdentity(entry))) return invalid;
+ scope[key] = [...new Set(list as string[])];
+ }
+ return { ok: true, scope };
+}
+
+function matches(selector: string, tool: ToolIdentity, names: readonly string[] = [tool.name]): boolean {
+ const selected = selectorIdentity(selector);
+ return selected?.kind === tool.kind
+ && (selected.kind !== "mcp" || (tool.kind === "mcp" && selected.server === tool.server))
+ && (selected.name === "*" || names.includes(selected.name));
+}
+
+function permitsNamed(scope: ToolScope | undefined, tool: ToolIdentity, names: readonly string[]): boolean {
+ return (scope?.allow === undefined || scope.allow.some((selector) => matches(selector, tool, names)))
+ && !scope?.deny?.some((selector) => matches(selector, tool, names));
+}
+
+function permits(scope: ToolScope | undefined, tool: ToolIdentity, args?: unknown): boolean {
+ if (!validName(tool.name) || (tool.kind === "mcp" && !SERVER_NAME.test(tool.server))) return false;
+ // A phone batch runs the step tools, so a selection that refuses any of them refuses the batch.
+ if (tool.kind === "mcp" && tool.server === "phone" && tool.name === "batch") {
+ return ["batch", ...PHONE_STEP_TOOLS].every((name) => permitsNamed(scope, tool, [name]));
+ }
+ // An agents call is named by what it does: a selector naming one action's own tool name allows or refuses that action.
+ const named = tool.kind === "mcp" && tool.server === "agents" ? agentsCallIdentities(tool.name, args) : [[tool.name]];
+ return named.some((names) => permitsNamed(scope, tool, names));
+}
+
+/** Whether the selection lets this tool run: with the call's arguments, this call; without them, any call it makes. */
+export function allowsTool(scope: unknown, tool: ToolIdentity, args?: unknown): boolean {
+ const parsed = parseToolScope(scope);
+ return parsed.ok && permits(parsed.scope, tool, args);
+}
+
+/** Whether an engine needs a native catalog contract, in addition to MCP gates. */
+export function narrowsNativeTools(value: unknown): boolean {
+ const parsed = parseToolScope(value);
+ if (!parsed.ok) return true;
+ const scope = parsed.scope;
+ return scope !== undefined && ((scope.allow !== undefined && !scope.allow.includes("native:*"))
+ || Boolean(scope.deny?.some((selector) => selector.startsWith("native:"))));
+}
+
+/** Without a catalog, asks whether this server could have a permitted tool. */
+export function canUseMcpServer(scope: unknown, server: string, names?: readonly string[]): boolean {
+ const parsed = parseToolScope(scope);
+ if (!parsed.ok || !SERVER_NAME.test(server)) return false;
+ if (names !== undefined) {
+ return names.some((name) => permits(parsed.scope, { kind: "mcp", server, name }));
+ }
+ if (parsed.scope?.deny?.includes(`mcp:${server}:*`)) return false;
+ if (parsed.scope?.allow === undefined) return true;
+ return parsed.scope.allow.some((selector) => {
+ const selected = selectorIdentity(selector);
+ return selected?.kind === "mcp" && selected.server === server
+ && (selected.name === "*" || permits(parsed.scope, selected));
+ });
+}
+
+/** Compare the selector partitions, including a tool/server outside all exact names. */
+export function toolScopeWidens(previous: unknown, next: unknown): boolean {
+ const before = parseToolScope(previous);
+ const after = parseToolScope(next);
+ if (!after.ok) return false;
+ const namespaces = new Map<string, Set<string>>([["native", new Set()]]);
+ const scopes = [before.ok ? before.scope : undefined, after.scope];
+ for (const scope of scopes) {
+ for (const selector of [...(scope?.allow ?? []), ...(scope?.deny ?? [])]) {
+ const tool = selectorIdentity(selector)!;
+ const namespace = tool.kind === "native" ? "native" : `mcp:${tool.server}`;
+ if (!namespaces.has(namespace)) namespaces.set(namespace, new Set());
+ if (tool.name !== "*") namespaces.get(namespace)!.add(tool.name);
+ }
+ }
+ let server = "unlisted";
+ for (let i = 0; namespaces.has(`mcp:${server}`); i++) server = `unlisted${i}`;
+ namespaces.set(`mcp:${server}`, new Set());
+ for (const [namespace, names] of namespaces) {
+ let other = "__unlisted_tool__";
+ for (let i = 0; names.has(other); i++) other = `__unlisted_tool_${i}__`;
+ names.add(other);
+ for (const name of names) {
+ const tool: ToolIdentity = namespace === "native" ? { kind: "native", name }
+ : { kind: "mcp", server: namespace.slice(4), name };
+ if (permits(after.scope, tool) && (!before.ok || !permits(before.scope, tool))) return true;
+ }
+ }
+ return false;
+}
diff --git a/packages/phone-protocol/src/turn-progress.ts b/packages/phone-protocol/src/turn-progress.ts
new file mode 100644
index 0000000000..0cc6e1e1aa
--- /dev/null
+++ b/packages/phone-protocol/src/turn-progress.ts
@@ -0,0 +1,68 @@
+// The live status line's vocabulary, shared by the drivers that report it, the bus that coalesces it and the chat that
+// shows it. A turn.progress event is live only: it is never written to the event log or the message log.
+
+/** What a tool call is doing, in the status line's words: writing or changing a file, running a command, searching the
+ * web, reading a file or a page, searching files, or any other tool. */
+export type TurnProgressActivity = "write" | "edit" | "command" | "web" | "read" | "fetch" | "search" | "tool";
+
+/** What one tool call works on, in the words the status line, its chip and the sidebar use: a command's program and
+ * main target ("scrape.py", "pnpm test"), a web search's query, a page's site, a file's name. Server-made from redacted
+ * text and redacted again: never an environment variable's value or a credential. */
+export interface LiveStep {
+ activity: TurnProgressActivity;
+ /** At most 60 characters. */
+ target: string;
+ /** The whole command, query or page address the target was read from, environment values left out; at most 200
+ * characters, and absent when it says no more than the target. */
+ detail?: string;
+}
+
+/** How a call that has run a while is doing: when its output last arrived (epoch ms), or, while it has sent none, what
+ * its processes show: holding a network connection, using the CPU, or neither. */
+export type StepQuiet = { kind: "output"; at: number } | { kind: "network" | "busy" | "idle" };
+
+export interface TurnProgressFields {
+ type: "turn.progress";
+ activity: TurnProgressActivity;
+ /** The engine's own tool name, for a tool the activity does not name. */
+ tool?: string;
+ /** The bare file name the call works on, once the engine has said it. */
+ file?: string;
+ /** Bytes of the call's input generated so far: for a write, about the size of the file. */
+ bytes?: number;
+ itemId?: string;
+ /** The call's LiveStep target, once the server has read one from the call. */
+ target?: string;
+ /** The call's LiveStep detail, for the phrase's tooltip. */
+ detail?: string;
+ /** Set once the call has run past the quiet notice. */
+ quiet?: StepQuiet;
+ /** A running command's last lines of output, redacted, oldest first. */
+ tail?: string[];
+}
+
+const KB = 1024;
+const MB = 1024 * KB;
+
+/** The size the status line shows: whole KB under a megabyte, tenths of a MB above; nothing under 1 KB. */
+export function progressSize(bytes: number | undefined): { unit: "kb" | "mb"; count: number } | null {
+ if (typeof bytes !== "number" || !Number.isFinite(bytes) || bytes < KB) return null;
+ if (bytes < MB) return { unit: "kb", count: Math.floor(bytes / KB) };
+ return { unit: "mb", count: Math.floor((bytes / MB) * 10) / 10 };
+}
+
+/** A path's last part, without control characters and at most 60 characters: never a whole path on the wire. */
+export function progressFile(path: unknown): string | undefined {
+ if (typeof path !== "string") return undefined;
+ const name = path.replace(/[\\/]+$/, "").split(/[\\/]/).pop()?.replace(/\p{Cc}/gu, "").trim();
+ if (!name) return undefined;
+ return name.length > 60 ? `${name.slice(0, 57)}…` : name;
+}
+
+/** Two reports that read the same on screen share a key, so only a visible change is worth a frame. */
+export function progressKey(event: Omit<TurnProgressFields, "type" | "activity"> & { activity: string; turnId?: string }): string {
+ const size = progressSize(event.bytes);
+ const quiet = event.quiet ? `${event.quiet.kind}${event.quiet.kind === "output" ? `@${event.quiet.at}` : ""}` : "";
+ return [event.turnId ?? "", event.itemId ?? "", event.activity, event.tool ?? "", event.file ?? "", size ? `${size.count}${size.unit}` : "",
+ event.target ?? "", event.detail ?? "", quiet, (event.tail ?? []).join("\n")].join("|");
+}
diff --git a/packages/phone-protocol/src/vega-config.ts b/packages/phone-protocol/src/vega-config.ts
new file mode 100644
index 0000000000..e2fe2fea5f
--- /dev/null
+++ b/packages/phone-protocol/src/vega-config.ts
@@ -0,0 +1,95 @@
+// The one Vega config every chart is drawn with (the Data panel, the server's
+// SVG/PNG, the headless render check): Vega-Lite's `config`, or Vega's runtime
+// config. Light and dark only. Skin accents are not used for marks, so a series
+// keeps its colour between the panel and a PNG in an email.
+
+export type VegaTheme = "light" | "dark";
+
+/** The app's `--font-sans` stack. Node renders through resvg, which walks
+ * the list against the system fonts it finds, so the stack ends in a
+ * generic family. */
+export const VEGA_FONT = '"Inter", -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui, sans-serif';
+
+/** Ten categorical colours of middling luminance, each ≥ 3:1 on both #111111
+ * and white. Hue order alternates warm and cool so neighbouring series differ. */
+export const VEGA_CATEGORY_RANGE: readonly string[] = [
+ "#3b82f6", // blue
+ "#ea580c", // orange
+ "#059669", // emerald
+ "#c026d3", // fuchsia
+ "#a16207", // gold
+ "#8b5cf6", // violet
+ "#0d9488", // teal
+ "#e11d48", // rose
+ "#4d7c0f", // olive
+ "#6b7280", // grey
+];
+
+const INK = {
+ dark: { text: "#fcfcfc", muted: "#a3a3a3", hairline: "#333333", surface: "#111111" },
+ light: { text: "#1a1a18", muted: "#6b6559", hairline: "#c8bda8", surface: "#fbf8f2" },
+} as const;
+
+/** The surface a PNG is laid on when it cannot be transparent (email, Slack). */
+export function vegaSurface(theme: VegaTheme): string {
+ return INK[theme].surface;
+}
+
+export function vegaConfig(theme: VegaTheme): Record<string, unknown> {
+ const ink = INK[theme];
+ const text = { font: VEGA_FONT, labelFont: VEGA_FONT, titleFont: VEGA_FONT, labelFontSize: 11, titleFontSize: 11, titleFontWeight: 500 };
+ return {
+ // The panel's card and the phone's view supply the ground; a PNG adds its own.
+ background: "transparent",
+ font: VEGA_FONT,
+ padding: 8,
+ view: { stroke: null },
+ title: { color: ink.text, subtitleColor: ink.muted, font: VEGA_FONT, fontSize: 13, fontWeight: 600, anchor: "start", offset: 12 },
+ axis: {
+ ...text,
+ labelColor: ink.muted,
+ titleColor: ink.muted,
+ titlePadding: 8,
+ labelPadding: 6,
+ domainColor: ink.hairline,
+ domainWidth: 1,
+ tickColor: ink.hairline,
+ tickSize: 4,
+ gridColor: ink.hairline,
+ gridWidth: 1,
+ gridOpacity: 0.6,
+ },
+ // Hairline grid behind the values only; the category axis keeps its baseline.
+ axisX: { grid: false },
+ axisY: { grid: true, domain: false, ticks: false },
+ legend: {
+ ...text,
+ labelColor: ink.muted,
+ titleColor: ink.muted,
+ symbolSize: 60,
+ symbolType: "circle",
+ labelLimit: 140,
+ padding: 0,
+ rowPadding: 2,
+ columnPadding: 8,
+ offset: 12,
+ },
+ range: {
+ category: [...VEGA_CATEGORY_RANGE],
+ // High values must pop against the ground: light-to-dark blues on
+ // paper, dark-to-bright viridis on a dark surface.
+ heatmap: { scheme: theme === "dark" ? "viridis" : "blues" },
+ ramp: { scheme: theme === "dark" ? "viridis" : "blues" },
+ },
+ mark: { color: VEGA_CATEGORY_RANGE[0] },
+ line: { strokeWidth: 2, strokeJoin: "round", strokeCap: "round" },
+ area: { opacity: 0.75, line: false },
+ point: { filled: true, size: 36, opacity: 0.8 },
+ circle: { size: 36, opacity: 0.8 },
+ // A hairline in the surface colour separates pie slices and heatmap cells.
+ arc: { stroke: ink.surface, strokeWidth: 1 },
+ rect: { stroke: ink.surface, strokeWidth: 1 },
+ text: { color: ink.text, font: VEGA_FONT },
+ scale: { bandPaddingInner: 0.25 },
+ };
+}
diff --git a/packages/phone-protocol/src/wait-request.ts b/packages/phone-protocol/src/wait-request.ts
new file mode 100644
index 0000000000..a8ee36bf5b
--- /dev/null
+++ b/packages/phone-protocol/src/wait-request.ts
@@ -0,0 +1,23 @@
+/** The line a wait (wait_until) posted when it ended (`WireMessage.wait`). */
+export interface WaitLine {
+ id: string;
+ status: "fired" | "expired" | "stopped";
+}
+
+/** `WireMessage.wait`: set on the line a wait posted when it ended. */
+export interface WaitLineField {
+ wait?: WaitLine;
+}
+
+/** A wait with a follow-up a bot set up from chat (wait_until, `OptionCardData.waitRequest`); its Cancel stops it until it settles. */
+export interface WaitCardData {
+ waitId: string;
+ label: string;
+ followUp: string;
+ settled?: "fired" | "expired" | "cancelled";
+}
+
+/** `OptionCardData.waitRequest`: set on the card a wait with a follow-up showed. */
+export interface WaitCardField {
+ waitRequest?: WaitCardData;
+}
diff --git a/packages/phone-protocol/src/webhook-request.ts b/packages/phone-protocol/src/webhook-request.ts
new file mode 100644
index 0000000000..8e5162cd69
--- /dev/null
+++ b/packages/phone-protocol/src/webhook-request.ts
@@ -0,0 +1,45 @@
+/**
+ * Durable payload of a webhook trigger change a bot made from chat. Every change applies at once (there is no
+ * confirmation), so the card is a receipt: what changed, and what Undo needs to put it back.
+ */
+
+export interface WebhookRequestDefinition {
+ name: string;
+ /** Instructions for every call; empty means each call's own task is used. */
+ instructions: string;
+ runOn: "maus" | "cloud";
+ eventTypes?: string[];
+ /** Field path -> text it must have; all must match before a run starts. Empty removes it on an update. */
+ payloadFilter?: Record<string, string>;
+ /** Each run continues the webhook's previous run conversation. */
+ sameConversation?: boolean;
+}
+
+export type WebhookRequestOperation =
+ | { action: "create"; webhook: WebhookRequestDefinition; forBot?: { botId: string; name: string } }
+ | { action: "update"; webhookId: string; changes: Partial<WebhookRequestDefinition>; forBot?: { botId: string; name: string } }
+ | { action: "pause" | "resume" | "run_now" | "delete"; webhookId: string; forBot?: { botId: string; name: string } };
+
+/** The webhook as it stood before an update, so Undo can restore it. */
+export interface WebhookRequestSnapshot extends WebhookRequestDefinition {
+ enabled: boolean;
+}
+
+export interface WebhookRequestUndo {
+ name: string;
+ /** The webhook's revision right after the change; Undo refuses once it moved. */
+ appliedUpdatedAt?: number;
+ before?: WebhookRequestSnapshot;
+}
+
+export interface WebhookRequestCardData {
+ version: 1;
+ requestId: string;
+ botId: string;
+ threadId: string;
+ createdAt: number;
+ operation: WebhookRequestOperation;
+ /** The webhook the change applied to (the new one for a create). */
+ resultId?: string;
+ undo?: WebhookRequestUndo;
+}
diff --git a/packages/phone-protocol/src/webhooks.ts b/packages/phone-protocol/src/webhooks.ts
new file mode 100644
index 0000000000..7871008830
--- /dev/null
+++ b/packages/phone-protocol/src/webhooks.ts
@@ -0,0 +1,90 @@
+/** Webhook wire shapes: triggers and delivery attempts as they ride the REST
+ * snapshot and the `webhook` / `webhook.attempt` live frames. */
+import type { RoutineRunOn } from "./routines.ts";
+
+export interface WebhookTrigger {
+ id: string;
+ endpointId: string;
+ name: string;
+ prompt: string;
+ botId: string;
+ runOn: RoutineRunOn;
+ enabled: boolean;
+ createdAt: number;
+ updatedAt: number;
+ lastReceivedAt?: number;
+ lastRunId?: string;
+ /** delivery:"post" only: the stable thread this webhook's messages land in,
+ * created on first delivery and reused after, never the bot's
+ * currently-selected thread. Unset on a room webhook (`groupId`), whose
+ * messages land in the room's own thread. */
+ resultsThreadId?: string;
+ /** delivery:"post" only, optional: a room id. Set, each delivery appends
+ * one bot-authored message (plus optional voice note and images) straight
+ * into that room, starting no turn and creating no task thread. The
+ * trigger's bot must be a member of the room, checked on create, on edit,
+ * and again at every delivery. */
+ groupId?: string;
+ deliveryCount: number;
+ verificationPending?: boolean;
+ verifiedAt?: number;
+ verificationSample?: WebhookVerificationSample;
+ eventTypes?: string[];
+ /** Field path in the call's JSON (dots for nesting, e.g. "pull_request.state") -> the text it must have. Every field must
+ * match (case-insensitive; a list matches when any item does), else the call is recorded as ignored and starts no run. */
+ payloadFilter?: Record<string, string>;
+ /** Unfinished runs this webhook may hold before new deliveries get 429.
+ * Absent means the default (3). */
+ maxPendingRuns?: number;
+ /** Each run continues this webhook's previous run conversation instead of starting a new one. */
+ sameConversation?: boolean;
+}
+
+export interface WebhookTriggerInput {
+ name: string;
+ prompt: string;
+ botId: string;
+ runOn?: RoutineRunOn;
+ /** Requires `delivery: "post"`; a room webhook with any other delivery is refused. `null` on an edit
+ * takes the room off, so deliveries go back to the webhook's own thread. */
+ groupId?: string | null;
+ enabled?: boolean;
+ verificationPending?: boolean;
+ eventTypes?: string[];
+ /** `null` or `{}` on an edit removes the filter. */
+ payloadFilter?: Record<string, string> | null;
+ /** 1–50; `null` goes back to the default. */
+ maxPendingRuns?: number | null;
+ sameConversation?: boolean;
+}
+
+export interface WebhookVerificationSample {
+ receivedAt: number;
+ eventName?: string;
+ contentType?: string;
+ preview: string;
+}
+
+export type WebhookAttemptOutcome = "accepted" | "captured" | "duplicate" | "ignored" | "rejected";
+
+export interface WebhookAttempt {
+ id: string;
+ webhookId: string;
+ receivedAt: number;
+ outcome: WebhookAttemptOutcome;
+ statusCode: number;
+ eventName?: string;
+ preview?: string;
+ deliveryId?: string;
+ runId?: string;
+ /** room post deliveries: the room whose thread received the message. */
+ threadId?: string;
+ reason?: string;
+}
+
+export interface WebhookIngressStatus {
+ available: boolean;
+ baseUrl: string;
+ error?: string;
+}
+
diff --git a/packages/phone-protocol/src/widget-button-style.ts b/packages/phone-protocol/src/widget-button-style.ts
new file mode 100644
index 0000000000..43f0efcace
--- /dev/null
+++ b/packages/phone-protocol/src/widget-button-style.ts
@@ -0,0 +1,6 @@
+export function buttonStyle(raw: Record<string, unknown>): string {
+ if (raw.color === "danger" || raw.style === "danger") return "danger";
+ if (raw.variant === "ghost" || raw.style === "quiet") return "quiet";
+ if (raw.style === "secondary" || raw.variant === "outline" || raw.variant === "soft" || raw.color === "secondary") return "secondary";
+ return raw.style === "primary" || raw.color === "primary" || raw.variant === "solid" || raw.submit === true ? "primary" : "secondary";
+}
diff --git a/packages/phone-protocol/src/widget-chart.ts b/packages/phone-protocol/src/widget-chart.ts
new file mode 100644
index 0000000000..fa7f771ac0
--- /dev/null
+++ b/packages/phone-protocol/src/widget-chart.ts
@@ -0,0 +1,126 @@
+// A widget's Chart as a Vega-Lite spec, drawn with the same config as every
+// other chart, so its palette, type and hairlines match the Data panel's. Pure,
+// so the server can render the same spec headless for a client that cannot.
+import { widgetNumber, type WidgetNode } from "./widget.ts";
+
+interface ChartSeries {
+ type: "bar" | "line" | "area";
+ dataKey: string;
+ label: string;
+ stack?: string;
+}
+
+/** The inside of a 600px card, used until the chart has been measured. */
+export const WIDGET_CHART_WIDTH = 560;
+/** The legend's line under the plot. */
+const LEGEND_BAND = 24;
+
+function readChart(node: WidgetNode): { rows: Array<Record<string, unknown>>; series: ChartSeries[]; xKey: string } {
+ const rows = (Array.isArray(node.data) ? node.data as unknown[] : []).filter((row): row is Record<string, unknown> => Boolean(row) && typeof row === "object" && !Array.isArray(row));
+ const series = (Array.isArray(node.series) ? node.series as unknown[] : []).flatMap((item): ChartSeries[] => {
+ const record: Record<string, unknown> = item && typeof item === "object" ? item as Record<string, unknown> : {};
+ if (typeof record.dataKey !== "string") return [];
+ return [{
+ type: record.type === "line" || record.type === "area" ? record.type : "bar",
+ dataKey: record.dataKey,
+ label: typeof record.label === "string" ? record.label : record.dataKey,
+ ...(typeof record.stack === "string" ? { stack: record.stack } : {}),
+ }];
+ }).slice(0, 4);
+ const axis = node.xAxis && typeof node.xAxis === "object" ? node.xAxis as { dataKey?: unknown } : {};
+ return { rows, series, xKey: typeof axis.dataKey === "string" ? axis.dataKey : "" };
+}
+
+/** A legend is worth its line when there is more than one series, or the one
+ * series has a name of its own. */
+function hasLegend(node: WidgetNode, series: ChartSeries[]): boolean {
+ return node.showLegend !== false && (series.length > 1 || (series.length === 1 && series[0]!.label !== series[0]!.dataKey));
+}
+
+/** The chart's height, legend included, for a card `width` wide: its own
+ * height, else its aspect ratio, else 160; the plot never under 80 or over 400. */
+export function widgetChartHeight(node: WidgetNode, width: number): number {
+ const ratio = widgetNumber(node, "aspectRatio");
+ const plot = Math.round(Math.min(400, Math.max(80, widgetNumber(node, "height") ?? (ratio ? width / ratio : 160))));
+ return plot + (hasLegend(node, readChart(node).series) ? LEGEND_BAND : 0);
+}
+
+/** The Vega-Lite spec for a Chart node, its rows inline and its width the
+ * container's; null when there is nothing to draw. Bars that share a `stack`
+ * pile up in one slot of the row's band (rising and falling piles apart); the
+ * rest sit side by side. Lines and areas break where a row has no value. */
+export function widgetChartSpec(node: WidgetNode, width = WIDGET_CHART_WIDTH): Record<string, unknown> | null {
+ const { rows, series, xKey } = readChart(node);
+ if (!rows.length || !series.length) return null;
+ const compact = new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 2 });
+ const rowLabels = rows.map((row) => {
+ const value = row[xKey];
+ return typeof value === "string" || typeof value === "number" ? String(value) : "";
+ });
+ // Rows and series are keyed by position, so two rows named alike stay two
+ // bands and two series labelled alike keep their own colours.
+ const groups: string[] = [];
+ const values = rows.flatMap((row, at) => series.map((item, index) => {
+ const raw = row[item.dataKey];
+ const value = typeof raw === "number" && Number.isFinite(raw) ? raw : null;
+ const group = item.stack ? `stack:${item.stack}` : `series:${index}`;
+ if (item.type === "bar" && !groups.includes(group)) groups.push(group);
+ return { row: at, series: index, group, mark: item.type, value, tip: value === null ? null : `${rowLabels[at]} · ${item.label}: ${compact.format(value)}` };
+ }));
+ const highest = Math.max(0, ...values.map((datum) => Math.abs(datum.value ?? 0)));
+ const showGrid = node.showGrid !== false;
+ const yAxis = node.showYAxis === true
+ ? { title: null, grid: showGrid, tickCount: 4, ...(highest >= 10_000 ? { format: "~s", labelExpr: "replace(datum.label, 'G', 'B')" } : {}) }
+ : showGrid ? { title: null, grid: true, tickCount: 4, labels: false, ticks: false, domain: false } : null;
+ const y = (stack: "zero" | null) => ({ field: "value", type: "quantitative", stack, axis: yAxis });
+ const has = (type: ChartSeries["type"]) => series.some((item) => item.type === type);
+ const stacked = series.some((item) => item.type === "bar" && item.stack);
+ const point = rows.length > 40 ? false : { size: rows.length > 16 ? 8 : 24 };
+ const layer = [
+ has("bar") && {
+ transform: [{ filter: "datum.mark === 'bar' && datum.value !== null" }],
+ mark: { type: "bar", ...(stacked ? {} : { cornerRadiusEnd: 3 }) },
+ encoding: {
+ y: y("zero"),
+ // the first series at the foot of its pile, as it is listed
+ order: { field: "series", type: "quantitative" },
+ ...(groups.length > 1 ? { xOffset: { field: "group", type: "nominal", scale: { domain: groups, paddingInner: 0.08 } } } : {}),
+ },
+ },
+ has("area") && {
+ transform: [{ filter: "datum.mark === 'area'" }],
+ mark: { type: "area", opacity: 0.18, line: false },
+ encoding: { y: y(null) },
+ },
+ (has("line") || has("area")) && {
+ transform: [{ filter: "datum.mark !== 'bar'" }],
+ mark: { type: "line", point },
+ encoding: { y: y(null) },
+ },
+ ].filter(Boolean);
+ const legend = hasLegend(node, series)
+ ? { title: null, orient: "bottom", direction: "horizontal", symbolOpacity: 1, labelExpr: "seriesLabels[datum.value]", ...(series.reduce((sum, item) => sum + item.label.length, 0) > 48 ? { columns: 2 } : {}) }
+ : null;
+ return {
+ $schema: "https://vega.github.io/schema/vega-lite/v6.json",
+ width: "container",
+ height: widgetChartHeight(node, width),
+ autosize: { type: "fit", contains: "padding" },
+ padding: { top: 4, right: 0, bottom: 0, left: 0 },
+ params: [{ name: "rowLabels", value: rowLabels }, { name: "seriesLabels", value: series.map((item) => item.label) }],
+ data: { values },
+ encoding: {
+ x: {
+ field: "row",
+ type: "ordinal",
+ scale: { domain: rows.map((_, at) => at) },
+ axis: { title: null, labelAngle: 0, labelLimit: 90, labelOverlap: "greedy", labelExpr: "rowLabels[datum.value]" },
+ },
+ color: { field: "series", type: "nominal", scale: { domain: series.map((_, index) => index) }, legend },
+ // what a mark says on hover is also what it is called to a screen reader
+ tooltip: { field: "tip", type: "nominal" },
+ description: { field: "tip", type: "nominal" },
+ },
+ layer,
+ };
+}
diff --git a/packages/phone-protocol/src/widget-text.ts b/packages/phone-protocol/src/widget-text.ts
new file mode 100644
index 0000000000..6f118ad83f
--- /dev/null
+++ b/packages/phone-protocol/src/widget-text.ts
@@ -0,0 +1,58 @@
+/** A moment a client words in the reader's language: `clock` "10:30 AM" (marked UTC when there is no zone),
+ * `bareClock` the same never marked, `longDate` "Thursday, October 22", `shortDate` "Thu, Oct 22". */
+export interface WidgetMoment {
+ at: number;
+ style: "clock" | "bareClock" | "longDate" | "shortDate";
+ zone?: string;
+}
+
+export type WidgetTextParam = string | number | WidgetText | WidgetMoment;
+
+/** A server card's words as a `brief.*` or `server.meetings.*` (or a cause's `chat.notice.*`) catalog key and its params, which may name other keys or moments. The node
+ * keeps its English beside it, which older clients and every bot widget show. */
+export interface WidgetText {
+ key: string;
+ params?: Record<string, WidgetTextParam>;
+}
+
+/** The fields of one widget node a server card names by key. */
+export type WidgetTextFields = Partial<Record<"value" | "label" | "title" | "caption", WidgetText>>;
+
+const FIELDS = ["value", "label", "title", "caption"] as const;
+const KEY = /^(?:brief|chat\.notice|server\.meetings)\.[\w.]{1,80}$/;
+const STYLES = new Set<WidgetMoment["style"]>(["clock", "bareClock", "longDate", "shortDate"]);
+const MAX_PARAMS = 8;
+const MAX_DEPTH = 3;
+const MAX_STRING = 400;
+
+const isRecord = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);
+
+function readParam(raw: unknown, depth: number): WidgetTextParam | undefined {
+ if (typeof raw === "string") return raw.slice(0, MAX_STRING);
+ if (typeof raw === "number") return Number.isFinite(raw) ? raw : undefined;
+ if (!isRecord(raw)) return undefined;
+ if (typeof raw.at === "number" && Number.isFinite(raw.at) && STYLES.has(raw.style as WidgetMoment["style"])) {
+ return { at: raw.at, style: raw.style as WidgetMoment["style"], ...(typeof raw.zone === "string" && raw.zone.length <= 64 ? { zone: raw.zone } : {}) };
+ }
+ return readText(raw, depth + 1);
+}
+
+function readText(raw: unknown, depth: number): WidgetText | undefined {
+ if (!isRecord(raw) || typeof raw.key !== "string" || !KEY.test(raw.key) || depth > MAX_DEPTH) return undefined;
+ if (raw.params === undefined) return { key: raw.key };
+ if (!isRecord(raw.params)) return undefined;
+ const entries = Object.entries(raw.params).slice(0, MAX_PARAMS).map(([name, value]) => [name, readParam(value, depth)] as const);
+ if (entries.some(([name, value]) => value === undefined || !/^\w{1,32}$/.test(name))) return undefined;
+ return { key: raw.key, params: Object.fromEntries(entries) as Record<string, WidgetTextParam> };
+}
+
+/** A node's `i18n` as it may be kept: anything malformed is dropped, and the node keeps its English. */
+export function readWidgetText(raw: unknown): WidgetTextFields | undefined {
+ if (!isRecord(raw)) return undefined;
+ const fields: WidgetTextFields = {};
+ for (const field of FIELDS) {
+ const text = readText(raw[field], 0);
+ if (text) fields[field] = text;
+ }
+ return Object.keys(fields).length ? fields : undefined;
+}
diff --git a/packages/phone-protocol/src/widget.ts b/packages/phone-protocol/src/widget.ts
new file mode 100644
index 0000000000..7311f281fd
--- /dev/null
+++ b/packages/phone-protocol/src/widget.ts
@@ -0,0 +1,996 @@
+// A bot-authored chat widget: the JSON tree `show_widget` posts as a message
+// of kind "widget". Node names and props follow ChatKit's widget components.
+// Model input is normalised here once; every renderer reads canonical trees only.
+import type { JsonValue } from "./json.ts";
+import { readWidgetText } from "./widget-text.ts";
+import { buttonStyle } from "./widget-button-style.ts";
+
+export const WIDGET_VERSION = 1;
+
+/** Past any of these, model input is refused with the path of the problem. */
+export const WIDGET_LIMITS = {
+ bytes: 32_000,
+ nodes: 250,
+ depth: 10,
+ listItems: 40,
+ options: 40,
+ fields: 20,
+ tableRows: 60,
+ tableCols: 8,
+ chartRows: 100,
+ chartSeries: 4,
+ images: 6,
+ text: 2_000,
+ markdown: 6_000,
+ title: 120,
+ caption: 240,
+ label: 80,
+ actionPayloadBytes: 2_000,
+ fieldValue: 2_000,
+ fallback: 1_500,
+} as const;
+
+/** ChatKit's icon names, plus a few this app needs. Each platform maps them
+ * to its own set; a name outside this list never reaches a renderer. */
+export const WIDGET_ICON_NAMES: readonly string[] = [
+ "info", "agent", "analytics", "atom", "batch", "bolt", "book-open", "book-closed", "book-clock", "bug", "calendar",
+ "chart", "check", "check-circle", "check-circle-filled", "chevron-left", "chevron-right", "circle-question", "compass",
+ "confetti", "cube", "desktop", "document", "dot", "dots-horizontal", "dots-vertical", "empty-circle", "external-link",
+ "globe", "keys", "lab", "images", "lifesaver", "lightbulb", "mail", "map-pin", "maps", "mobile", "name", "notebook",
+ "notebook-pencil", "page-blank", "phone", "play", "plus", "profile", "profile-card", "reload", "star", "star-filled",
+ "search", "sparkle", "sparkle-double", "square-code", "square-image", "square-text", "suitcase", "settings-slider",
+ "user", "wreath", "write", "write-alt", "write-alt2",
+ "pull-request", "upload", "download", "clock", "lock", "link", "file", "folder", "bell", "warning", "close", "arrow-right",
+];
+
+export interface WidgetAction {
+ type: string;
+ payload?: JsonValue;
+}
+
+/** The shape of a thread id a widget action may name. */
+export const THREAD_ID = /^[\w-]{1,128}$/;
+
+/** `open_thread` is handled on the device. The ids are written by a bot: untrusted, and only their shape is checked here. */
+export function threadActionTarget(action: WidgetAction): { botId?: string; groupId?: string; threadId: string } | undefined {
+ if (action.type !== "open_thread" || !isRecord(action.payload)) return undefined;
+ const { botId, groupId, threadId } = action.payload;
+ if (typeof threadId !== "string" || !THREAD_ID.test(threadId)) return undefined;
+ if (typeof botId === "string" && THREAD_ID.test(botId) && groupId === undefined) return { botId, threadId };
+ if (typeof groupId === "string" && THREAD_ID.test(groupId) && botId === undefined) return { groupId, threadId };
+ return undefined;
+}
+
+export const isThreadAction = (action: WidgetAction): boolean => threadActionTarget(action) !== undefined;
+
+/** `open_phone_pairing` opens the app's own phone pairing (the QR code and link) on the device. */
+export const PHONE_PAIRING_ACTION = "open_phone_pairing";
+const CLIENT_ACTION = (action: WidgetAction): boolean => action.type === "open_url" || action.type === "open_thread" || action.type === PHONE_PAIRING_ACTION;
+
+/** `confirm` and `cancel` on a root: the buttons under the card. */
+export interface WidgetButtonSpec {
+ label: string;
+ action: WidgetAction;
+}
+
+/** One canonical node. `id` is assigned here ("n1", "n2", ... in document
+ * order) and is how a press names its button. */
+export interface WidgetNode {
+ type: string;
+ id: string;
+ children?: WidgetNode[];
+ [prop: string]: unknown;
+}
+
+/** A canonical root: type "Card" or "ListView". */
+export type WidgetRoot = WidgetNode;
+
+/** A widget that took its one answer: it folds to a line and takes no more presses. */
+export interface WidgetSettled {
+ ref: string;
+ label: string;
+ tone: "confirm" | "cancel" | "submit";
+ at: number;
+ sendId?: string;
+ /** The field values that went with the press, for the read-only Details view. */
+ values?: WidgetValues;
+ /** The person's own words for a choice they answered with Other, by field name. */
+ other?: WidgetOther;
+ /** Set while the press waits in the steer queue behind a running turn:
+ * cancelling that queued message reopens the widget. */
+ queueId?: string;
+}
+
+export interface WidgetPayload {
+ v: 1;
+ root: WidgetRoot;
+ /** How many times show_widget has replaced the tree (absent: never). An
+ * update renumbers node ids, so a press names the revision it was made on
+ * and one made on an older tree is refused instead of landing on whatever
+ * now holds that id. */
+ rev?: number;
+ settled?: WidgetSettled;
+}
+
+export type WidgetValues = Record<string, string | boolean>;
+
+/** A press's answers in the person's own words, by field name: only for a field where
+ * `widgetTakesOther` holds, and that field's own value is then "". */
+export type WidgetOther = Record<string, string>;
+
+export type ParsedWidgetInput = { ok: true; value: WidgetRoot } | { ok: false; error: string };
+
+const ROOT_TYPES = new Set(["Card", "ListView"]);
+const FIELD_TYPES = new Set(["Select", "DatePicker", "TimePicker", "DayPicker", "Checkbox", "RadioGroup", "Input", "Textarea"]);
+const TYPE_ALIASES: Record<string, string> = { TableRow: "Table.Row", TableCell: "Table.Cell" };
+const ACTION_TYPE = /^[A-Za-z0-9_.:-]{1,64}$/;
+const FIELD_NAME = /^[A-Za-z0-9_.-]{1,64}$/;
+const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
+const TIME_OF_DAY = /^([01]\d|2[0-3]):[0-5]\d$/;
+/** Days of the week as a DayPicker stores them, in the order it draws them. */
+export const WIDGET_WEEKDAYS: readonly string[] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
+
+class WidgetInputError extends Error {}
+
+function fail(path: string, message: string): never {
+ throw new WidgetInputError(`${path}: ${message}`);
+}
+
+function isRecord(value: unknown): value is Record<string, unknown> {
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
+}
+
+const clamp = (value: number, low: number, high: number) => Math.min(high, Math.max(low, value));
+
+// A reader turns one raw prop into its canonical value. `undefined` drops the
+// prop (a lenient miss: an unknown token, a CSS value this app does not take).
+// A reader throws only where a silently dropped value would post a broken or
+// misleading card (a missing label, a bad action, a password field).
+
+type Reader = (raw: unknown, path: string) => unknown;
+
+function text(max: number, mode: "optional" | "required" | "nonEmpty" = "optional"): Reader {
+ return (raw, path) => {
+ if (raw === undefined || raw === null) return mode === "optional" ? undefined : fail(path, "is required");
+ if (typeof raw !== "string" && typeof raw !== "number") return fail(path, "must be a string");
+ const value = String(raw).trim();
+ if (value.length > max) return fail(path, `must be at most ${max} characters`);
+ if (!value && mode === "nonEmpty") return fail(path, "must not be blank");
+ if (!value && mode === "optional") return undefined;
+ return value;
+ };
+}
+
+/** One line of text: a label, a title, a placeholder. A run of whitespace,
+ * line breaks included, becomes one space, so nothing a bot writes into a
+ * label can add a line to the message a press is recorded as. */
+function line(max: number, mode: "optional" | "required" | "nonEmpty" = "optional"): Reader {
+ const read = text(max, mode);
+ return (raw, path) => read(typeof raw === "string" ? raw.replace(/\s+/g, " ") : raw, path);
+}
+
+function oneOf(...values: string[]): Reader {
+ return (raw) => (typeof raw === "string" && values.includes(raw) ? raw : undefined);
+}
+
+function mapped(map: Record<string, string>): Reader {
+ return (raw) => (typeof raw === "string" && Object.hasOwn(map, raw) ? map[raw] : undefined);
+}
+
+const on: Reader = (raw) => (raw === true ? true : undefined);
+/** For props whose default is on: only an explicit `false` is kept. */
+const off: Reader = (raw) => (raw === false ? false : undefined);
+
+function pxOf(raw: unknown): number | undefined {
+ const match = typeof raw === "string" ? /^(\d+(?:\.\d+)?)px$/.exec(raw.trim()) : null;
+ return match ? Number(match[1]) : undefined;
+}
+
+/** A ChatKit spacing value: a unit (4px each) or a px string. */
+function spacing(max = 64): Reader {
+ return (raw) => {
+ const px = typeof raw === "number" && Number.isFinite(raw) ? raw * 4 : pxOf(raw);
+ return px === undefined ? undefined : clamp(Math.round(px), 0, max);
+ };
+}
+
+/** A ChatKit size: px as a number or a px string; "100%" is "full". */
+function length(max = 2_000): Reader {
+ return (raw) => {
+ if (raw === "100%" || raw === "full") return "full";
+ const px = typeof raw === "number" && Number.isFinite(raw) ? raw : pxOf(raw);
+ // under a pixel is not a size: it is how content gets hidden
+ return px === undefined || px < 1 ? undefined : clamp(Math.round(px), 1, max);
+ };
+}
+
+function integer(min: number, max: number): Reader {
+ return (raw) => {
+ const value = typeof raw === "string" && raw.trim() ? Number(raw) : raw;
+ return typeof value === "number" && Number.isFinite(value) ? clamp(Math.round(value), min, max) : undefined;
+ };
+}
+
+function decimal(min: number, max: number): Reader {
+ return (raw) => {
+ const value = typeof raw === "string" && raw.trim() ? Number(raw) : raw;
+ return typeof value === "number" && Number.isFinite(value) ? clamp(value, min, max) : undefined;
+ };
+}
+
+const padding: Reader = (raw) => {
+ const side = spacing();
+ if (!isRecord(raw)) {
+ const all = side(raw, "");
+ return typeof all === "number" ? [all, all, all, all] : undefined;
+ }
+ const pick = (...keys: string[]) => {
+ for (const key of keys) {
+ const value = side(raw[key], "");
+ if (typeof value === "number") return value;
+ }
+ return 0;
+ };
+ const sides = [pick("top", "y"), pick("right", "x"), pick("bottom", "y"), pick("left", "x")];
+ return sides.some(Boolean) ? sides : undefined;
+};
+
+const RADII: Record<string, number> = { none: 0, "2xs": 2, xs: 4, sm: 6, md: 8, lg: 12, xl: 16, "2xl": 20, "3xl": 24, "4xl": 28, full: 999, "100%": 999 };
+const radius: Reader = (raw) => (typeof raw === "number" && Number.isFinite(raw) ? clamp(Math.round(raw), 0, 999) : typeof raw === "string" && Object.hasOwn(RADII, raw) ? RADII[raw] : undefined);
+
+const aspectRatio: Reader = (raw) => {
+ const parts = typeof raw === "string" ? /^(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)$/.exec(raw.trim()) : null;
+ const value = parts ? Number(parts[1]) / Number(parts[2]) : typeof raw === "string" ? Number(raw) : raw;
+ return typeof value === "number" && Number.isFinite(value) && value > 0 ? clamp(value, 0.1, 10) : undefined;
+};
+
+const background = mapped({
+ surface: "surface", secondary: "secondary", tertiary: "tertiary", elevated: "elevated",
+ "surface-secondary": "secondary", "surface-tertiary": "tertiary", "surface-elevated": "elevated", "surface-elevated-secondary": "elevated",
+});
+const inkColor = mapped({ prose: "primary", primary: "primary", emphasis: "primary", secondary: "secondary", tertiary: "tertiary", success: "success", warning: "warning", danger: "danger" });
+const border: Reader = (raw) => {
+ const size = isRecord(raw) ? raw.size : raw;
+ return typeof size === "number" && Number.isFinite(size) && size > 0 ? clamp(Math.round(size), 1, 2) : undefined;
+};
+const weight = oneOf("normal", "medium", "semibold", "bold");
+const textAlign = oneOf("start", "center", "end");
+
+function icon(fallback?: string): Reader {
+ return (raw) => (typeof raw === "string" && WIDGET_ICON_NAMES.includes(raw) ? raw : raw === undefined || raw === null ? undefined : fallback);
+}
+
+/** A layout share. Two decimals is finer than any screen; a share that rounds
+ * to nothing is dropped, because a zero weight is an error in a renderer. */
+const flexShare: Reader = (raw, path) => {
+ const share = decimal(0, 12)(raw, path);
+ const rounded = typeof share === "number" ? Math.round(share * 100) / 100 : 0;
+ return rounded > 0 ? rounded : undefined;
+};
+
+/** The dates a picker may be asked to show. Far outside them a platform's own
+ * calendar range runs out. */
+const DATE_YEARS = { min: 1900, max: 2200 } as const;
+
+const isoDate: Reader = (raw) => {
+ if (typeof raw !== "string" || !ISO_DATE.test(raw) || Number.isNaN(Date.parse(`${raw}T00:00:00Z`))) return undefined;
+ const year = Number(raw.slice(0, 4));
+ return year >= DATE_YEARS.min && year <= DATE_YEARS.max ? raw : undefined;
+};
+
+/** A time of day, "HH:MM" on a 24-hour clock. "9:05" and "09:05:00" are read as 09:05. */
+const timeOfDay: Reader = (raw) => {
+ const match = typeof raw === "string" ? /^(\d{1,2}):(\d{2})(?::\d{2})?$/.exec(raw.trim()) : null;
+ const value = match ? `${match[1].padStart(2, "0")}:${match[2]}` : undefined;
+ return value && TIME_OF_DAY.test(value) ? value : undefined;
+};
+
+/** Days of the week: an array or a comma list of names ("mon", "Monday",
+ * "MON"), stored as a comma list in week order with no repeats. */
+function weekdays(raw: unknown): string | undefined {
+ const items = Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : [];
+ const picked = new Set(items.filter((item): item is string => typeof item === "string").map((item) => item.trim().toLowerCase().slice(0, 3)));
+ const days = WIDGET_WEEKDAYS.filter((day) => picked.has(day));
+ return days.length ? days.join(",") : undefined;
+}
+const weekdaysReader: Reader = (raw) => weekdays(raw);
+
+/** A Progress value: a fraction from 0 to 1. A bot that writes a percentage
+ * (75, or "75%") means a percentage. */
+const progressValue: Reader = (raw) => {
+ const percent = typeof raw === "string" ? /^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(raw) : null;
+ const value = percent ? Number(percent[1]) / 100 : typeof raw === "string" && raw.trim() ? Number(raw) : raw;
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return undefined;
+ return clamp(value > 1 && value <= 100 ? value / 100 : value, 0, 1);
+};
+
+const action: Reader = (raw, path) => {
+ if (raw === undefined || raw === null) return undefined;
+ if (!isRecord(raw) || typeof raw.type !== "string" || !ACTION_TYPE.test(raw.type)) {
+ return fail(path, 'must be {type, payload?} with a type of letters, digits and "_.:-"');
+ }
+ const out: WidgetAction = { type: raw.type };
+ if (raw.payload !== undefined) {
+ const json = JSON.stringify(raw.payload);
+ if (json === undefined) return fail(`${path}.payload`, "must be JSON");
+ if (json.length > WIDGET_LIMITS.actionPayloadBytes) return fail(`${path}.payload`, `must be at most ${WIDGET_LIMITS.actionPayloadBytes} characters of JSON`);
+ out.payload = JSON.parse(json) as JsonValue;
+ }
+ if (out.type === "open_url" && !isWebUrl(isRecord(out.payload) ? out.payload.url : undefined, ["http:", "https:"])) {
+ return fail(`${path}.payload.url`, "open_url needs an http or https url");
+ }
+ if (out.type === "open_thread" && !threadActionTarget(out)) {
+ return fail(`${path}.payload`, "open_thread needs {botId, threadId} or {groupId, threadId}");
+ }
+ return out;
+};
+
+/** The longest url a widget action or image may carry. */
+export const WEB_URL_MAX = 2_000;
+
+function isWebUrl(value: unknown, protocols: string[]): value is string {
+ if (typeof value !== "string" || value.length > WEB_URL_MAX) return false;
+ try {
+ return protocols.includes(new URL(value).protocol);
+ } catch {
+ return false;
+ }
+}
+
+const buttonSpec: Reader = (raw, path) => {
+ if (raw === undefined || raw === null) return undefined;
+ if (!isRecord(raw)) return fail(path, "must be {label, action}");
+ const spec: WidgetButtonSpec = {
+ label: line(WIDGET_LIMITS.label, "nonEmpty")(raw.label, `${path}.label`) as string,
+ action: (action(raw.action, `${path}.action`) ?? fail(`${path}.action`, "is required")) as WidgetAction,
+ };
+ return spec;
+};
+
+const status: Reader = (raw, path) => {
+ if (raw === undefined || raw === null) return undefined;
+ const record: Record<string, unknown> = isRecord(raw) ? raw : { text: raw };
+ const label = line(WIDGET_LIMITS.caption, "nonEmpty")(record.text, `${path}.text`);
+ const name = icon()(record.icon, `${path}.icon`);
+ return name ? { text: label, icon: name } : { text: label };
+};
+
+const options: Reader = (raw, path) => {
+ if (!Array.isArray(raw) || raw.length < 1 || raw.length > WIDGET_LIMITS.options) return fail(path, `needs 1 to ${WIDGET_LIMITS.options} items`);
+ const seen = new Set<string>();
+ return raw.map((item, index) => {
+ const at = `${path}[${index}]`;
+ const record: Record<string, unknown> = isRecord(item) ? item : { value: item };
+ const value = line(200, "nonEmpty")(typeof record.value === "boolean" ? String(record.value) : record.value, `${at}.value`) as string;
+ if (seen.has(value)) return fail(at, `repeats the value ${JSON.stringify(value)}`);
+ seen.add(value);
+ return { label: (line(WIDGET_LIMITS.label)(record.label, `${at}.label`) as string | undefined) ?? value, value };
+ });
+};
+
+/** Names that would write to an object's prototype instead of naming a value. */
+const UNSAFE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
+const fieldName: Reader = (raw, path) => (typeof raw === "string" && FIELD_NAME.test(raw) && !raw.split(".").some((part) => UNSAFE_KEYS.has(part))
+ ? raw
+ : fail(path, 'is required: letters, digits and "_.-", at most 64'));
+
+const optionalFieldName: Reader = (raw, path) => (raw === undefined || raw === null ? undefined : fieldName(raw, path));
+
+const inputType: Reader = (raw, path) => {
+ if (raw === "password") return fail(path, "password fields are not allowed in a widget; use request_credential for secrets");
+ return oneOf("text", "number", "email", "tel", "url")(raw, path);
+};
+
+const imageSrc: Reader = (raw, path) => (isWebUrl(raw, ["https:"]) ? raw : fail(path, "must be an https url"));
+
+const CHART_MAX = 1e12;
+
+const chartData: Reader = (raw, path) => {
+ if (!Array.isArray(raw) || raw.length < 1 || raw.length > WIDGET_LIMITS.chartRows) return fail(path, `needs 1 to ${WIDGET_LIMITS.chartRows} rows`);
+ return raw.map((row, index) => {
+ if (!isRecord(row)) return fail(`${path}[${index}]`, "must be an object");
+ const out: Record<string, string | number | null> = {};
+ for (const [key, value] of Object.entries(row).slice(0, 12)) {
+ if (UNSAFE_KEYS.has(key)) continue;
+ if (typeof value === "number" ? Number.isFinite(value) : typeof value === "string" || value === null) {
+ // a chart library lays out what it is given: keep numbers within what every one of them can
+ out[key.slice(0, 64)] = typeof value === "string" ? value.slice(0, 120) : typeof value === "number" ? clamp(value, -CHART_MAX, CHART_MAX) : null;
+ }
+ }
+ return out;
+ });
+};
+
+const chartSeries: Reader = (raw, path) => {
+ if (!Array.isArray(raw) || raw.length < 1 || raw.length > WIDGET_LIMITS.chartSeries) return fail(path, `needs 1 to ${WIDGET_LIMITS.chartSeries} series`);
+ return raw.map((item, index) => {
+ const at = `${path}[${index}]`;
+ if (!isRecord(item)) return fail(at, "must be {type, dataKey}");
+ const series: Record<string, string> = {
+ type: (oneOf("bar", "line", "area")(item.type, at) as string | undefined) ?? "bar",
+ dataKey: text(64, "nonEmpty")(item.dataKey, `${at}.dataKey`) as string,
+ };
+ const label = line(WIDGET_LIMITS.label)(item.label, `${at}.label`);
+ if (typeof label === "string") series.label = label;
+ const stack = text(32)(item.stack, `${at}.stack`);
+ if (typeof stack === "string") series.stack = stack;
+ return series;
+ });
+};
+
+const chartAxis: Reader = (raw, path) => ({ dataKey: text(64, "nonEmpty")(isRecord(raw) ? raw.dataKey : raw, `${path}.dataKey`) });
+
+
+const LAYOUT: Record<string, Reader> = {
+ gap: spacing(),
+ padding,
+ align: oneOf("start", "center", "end", "baseline", "stretch"),
+ justify: oneOf("start", "center", "end", "between", "around", "evenly", "stretch"),
+ wrap: (raw) => (raw === true || raw === "wrap" ? true : undefined),
+ flex: flexShare,
+ width: length(), height: length(), minWidth: length(), maxWidth: length(), minHeight: length(), maxHeight: length(),
+ aspectRatio, background, border, radius,
+};
+const TEXT_STYLE: Record<string, Reader> = { weight, color: inkColor, textAlign, truncate: on, maxLines: integer(1, 20), width: length() };
+const ROOT: Record<string, Reader> = {
+ title: line(WIDGET_LIMITS.title), caption: line(WIDGET_LIMITS.caption), meta: line(WIDGET_LIMITS.label), status,
+ confirm: buttonSpec, cancel: buttonSpec,
+};
+/** Every control: its name, and a label drawn with it, which also names it in
+ * the message a press is recorded as. */
+const FIELD: Record<string, Reader> = { name: fieldName, label: line(WIDGET_LIMITS.title), disabled: on, required: on };
+const PLACEHOLDER = line(WIDGET_LIMITS.title);
+
+interface NodeSpec {
+ props: Record<string, Reader>;
+ children?: "any" | "items" | "rows" | "cells" | "one";
+}
+
+const SPECS: Record<string, NodeSpec> = {
+ Card: { props: { ...ROOT, size: oneOf("sm", "md", "lg", "full"), padding }, children: "any" },
+ // `name` makes the list a choice: its rows are selectable, one at a time, and
+ // the chosen row's `value` travels with confirm like any other field.
+ ListView: { props: { ...ROOT, limit: integer(1, WIDGET_LIMITS.listItems), name: optionalFieldName, defaultValue: line(200) }, children: "items" },
+ ListViewItem: { props: { gap: spacing(), align: LAYOUT.align, onClickAction: action, value: line(200) }, children: "any" },
+ Box: { props: { ...LAYOUT, direction: oneOf("row", "col") }, children: "any" },
+ Row: { props: LAYOUT, children: "any" },
+ Col: { props: LAYOUT, children: "any" },
+ Form: { props: { ...LAYOUT, direction: oneOf("row", "col"), onSubmitAction: action }, children: "any" },
+ Spacer: { props: { minSize: length(400) } },
+ Divider: { props: { spacing: spacing(), flush: on } },
+ Table: { props: {}, children: "rows" },
+ "Table.Row": { props: { header: on }, children: "cells" },
+ "Table.Cell": {
+ props: { align: textAlign, vAlign: textAlign, colSpan: integer(1, WIDGET_LIMITS.tableCols), rowSpan: integer(1, 20), width: length(), colSize: oneOf("xs", "sm", "md", "lg", "xl"), padding },
+ children: "any",
+ },
+ Text: { props: { value: text(WIDGET_LIMITS.text, "required"), size: oneOf("xs", "sm", "md", "lg", "xl"), ...TEXT_STYLE, italic: on, lineThrough: on, minLines: integer(1, 20) } },
+ Title: { props: { value: text(WIDGET_LIMITS.text, "required"), size: oneOf("sm", "md", "lg", "xl", "2xl", "3xl", "4xl", "5xl"), ...TEXT_STYLE } },
+ Caption: { props: { value: text(WIDGET_LIMITS.text, "required"), size: oneOf("sm", "md", "lg"), ...TEXT_STYLE } },
+ Label: { props: { value: line(WIDGET_LIMITS.title, "nonEmpty"), fieldName: text(64), size: oneOf("xs", "sm", "md", "lg", "xl"), weight, color: inkColor, textAlign, width: length() } },
+ Markdown: { props: { value: text(WIDGET_LIMITS.markdown, "required") } },
+ Image: {
+ props: {
+ src: imageSrc, alt: line(WIDGET_LIMITS.caption), fit: oneOf("none", "fill", "cover", "contain", "scale-down"),
+ position: oneOf("center", "top", "bottom", "left", "right", "top left", "top right", "bottom left", "bottom right"),
+ frame: on, flush: on, width: length(), height: length(), minWidth: length(), maxWidth: length(), minHeight: length(), maxHeight: length(), aspectRatio, radius,
+ },
+ },
+ Icon: { props: { name: icon("dot"), color: inkColor, size: oneOf("xs", "sm", "md", "lg", "xl", "2xl", "3xl") } },
+ Chart: { props: { data: chartData, series: chartSeries, xAxis: chartAxis, showYAxis: on, showLegend: off, showGrid: off, height: length(400), aspectRatio, flex: flexShare, width: length() } },
+ Badge: { props: { label: line(WIDGET_LIMITS.label, "nonEmpty"), color: oneOf("secondary", "success", "danger", "warning", "info", "discovery"), variant: oneOf("soft", "solid", "outline", "dot"), size: oneOf("sm", "md", "lg"), pill: off } },
+ Progress: { props: { value: progressValue, label: line(WIDGET_LIMITS.caption) } },
+ Button: { props: { label: line(WIDGET_LIMITS.label), iconStart: icon(), iconEnd: icon(), block: on, disabled: on, submit: on, onClickAction: action } },
+ Select: { props: { ...FIELD, options, placeholder: PLACEHOLDER, defaultValue: text(200), clearable: on, block: on } },
+ DatePicker: { props: { ...FIELD, placeholder: PLACEHOLDER, defaultValue: isoDate, min: isoDate, max: isoDate, clearable: on, block: on } },
+ // MausBot additions: a time of day, and days of the week
+ TimePicker: { props: { ...FIELD, placeholder: PLACEHOLDER, defaultValue: timeOfDay, min: timeOfDay, max: timeOfDay, step: integer(1, 60), clearable: on, block: on } },
+ DayPicker: { props: { ...FIELD, defaultValue: weekdaysReader } },
+ Checkbox: { props: { ...FIELD, defaultChecked: on } },
+ RadioGroup: { props: { ...FIELD, options, defaultValue: text(200), direction: oneOf("row", "col"), ariaLabel: line(WIDGET_LIMITS.title) } },
+ Input: { props: { ...FIELD, inputType, placeholder: PLACEHOLDER, defaultValue: text(WIDGET_LIMITS.fieldValue), pattern: text(200) } },
+ Textarea: { props: { ...FIELD, placeholder: PLACEHOLDER, defaultValue: text(WIDGET_LIMITS.fieldValue), rows: integer(1, 12), maxRows: integer(1, 20), autoResize: on } },
+ Transition: { props: {}, children: "one" },
+};
+
+/** Every node type a widget may contain, roots first. */
+export const WIDGET_NODE_TYPES: readonly string[] = Object.keys(SPECS);
+
+interface Context {
+ nodes: number;
+ images: number;
+ fields: Set<string>;
+}
+
+function typeOf(raw: Record<string, unknown>): string {
+ return typeof raw.type === "string" ? TYPE_ALIASES[raw.type] ?? raw.type : "";
+}
+
+function normalize(input: unknown, path: string, depth: number, slot: "root" | "any" | "items" | "rows" | "cells", context: Context): WidgetNode {
+ if (!isRecord(input)) return fail(path, "must be an object with a type");
+ let raw = input;
+ let type = typeOf(raw);
+ if (!Object.hasOwn(SPECS, type)) return fail(path, `unknown type ${JSON.stringify(raw.type)}; use one of ${WIDGET_NODE_TYPES.join(", ")}`);
+ if (slot === "items" && type !== "ListViewItem") [raw, type] = [{ type: "ListViewItem", children: [raw] }, "ListViewItem"];
+ if (slot === "cells" && type !== "Table.Cell") [raw, type] = [{ type: "Table.Cell", children: [raw] }, "Table.Cell"];
+ if (slot === "rows" && type !== "Table.Row") return fail(path, "a Table takes Table.Row children");
+ if (slot !== "root" && ROOT_TYPES.has(type)) return fail(path, `${type} is a root and cannot be nested`);
+ if (slot === "any" && (type === "Table.Row" || type === "Table.Cell")) return fail(path, `${type} belongs inside a Table`);
+ if (depth > WIDGET_LIMITS.depth) return fail(path, `is nested deeper than ${WIDGET_LIMITS.depth} levels`);
+ context.nodes += 1;
+ if (context.nodes > WIDGET_LIMITS.nodes) return fail(path, `the widget has more than ${WIDGET_LIMITS.nodes} nodes`);
+
+ const spec = SPECS[type];
+ const node: WidgetNode = { type, id: `n${context.nodes}` };
+ const source: Record<string, unknown> = { ...raw };
+ // ChatKit's shorthands for both axes.
+ for (const [shorthand, a, b] of [["size", "width", "height"], ["minSize", "minWidth", "minHeight"], ["maxSize", "maxWidth", "maxHeight"]] as const) {
+ const both = source[shorthand];
+ // `size` on text, icons and badges is a token, not a length.
+ if (type === "Card" || type === "Spacer" || !(typeof both === "number" || both === "100%" || pxOf(both) !== undefined)) continue;
+ source[a] ??= both;
+ source[b] ??= both;
+ }
+ for (const [key, read] of Object.entries(spec.props)) {
+ const value = read(source[key], `${path}.${key}`);
+ if (value !== undefined) node[key] = value;
+ }
+ if (type === "Button") node.style = buttonStyle(raw);
+ if (raw.i18n !== undefined) node.i18n = readWidgetText(raw.i18n);
+ if (type === "Icon") node.name ??= "dot";
+ if (type === "Progress") {
+ const max = typeof raw.max === "number" && Number.isFinite(raw.max) && raw.max > 0 ? raw.max : undefined;
+ const given = typeof raw.value === "number" && Number.isFinite(raw.value) ? raw.value : undefined;
+ // {value: 3, max: 4} is three quarters
+ if (max !== undefined && given !== undefined) node.value = clamp(given / max, 0, 1);
+ if (node.value === undefined) return fail(`${path}.value`, "is required: a number from 0 to 1");
+ }
+ if (type === "Image" && ++context.images > WIDGET_LIMITS.images) return fail(path, `the widget has more than ${WIDGET_LIMITS.images} images`);
+ if (FIELD_TYPES.has(type)) {
+ const name = node.name as string;
+ if (context.fields.has(name)) return fail(`${path}.name`, `repeats the field name ${JSON.stringify(name)}`);
+ context.fields.add(name);
+ if (context.fields.size > WIDGET_LIMITS.fields) return fail(path, `the widget has more than ${WIDGET_LIMITS.fields} fields`);
+ if (type === "TimePicker" || type === "DatePicker") {
+ if (typeof node.min === "string" && typeof node.max === "string" && node.min > node.max) delete node.max;
+ const picked = node.defaultValue;
+ if (typeof picked === "string" && ((typeof node.min === "string" && picked < node.min) || (typeof node.max === "string" && picked > node.max))) delete node.defaultValue;
+ }
+ const chosen = node.defaultValue;
+ if ((type === "Select" || type === "RadioGroup") && chosen !== undefined && !(node.options as Array<{ value: string }>).some((option) => option.value === chosen)) delete node.defaultValue;
+ if (type === "Select" || type === "RadioGroup") node.allowOther = raw.allowOther !== false;
+ }
+
+ if (spec.children) {
+ const list = raw.children === undefined || raw.children === null ? [] : Array.isArray(raw.children) ? raw.children : [raw.children];
+ const kept = spec.children === "one" ? list.slice(0, 1) : list;
+ if (type === "ListView" && kept.length > WIDGET_LIMITS.listItems) return fail(`${path}.children`, `a list takes at most ${WIDGET_LIMITS.listItems} items`);
+ if (type === "Table" && kept.length > WIDGET_LIMITS.tableRows) return fail(`${path}.children`, `a table takes at most ${WIDGET_LIMITS.tableRows} rows`);
+ if (type === "Table.Row" && kept.length > WIDGET_LIMITS.tableCols) return fail(`${path}.children`, `a row takes at most ${WIDGET_LIMITS.tableCols} cells`);
+ const childSlot = spec.children === "one" ? "any" : spec.children;
+ node.children = kept.map((child, index) => normalize(child, `${path}.children[${index}]`, depth + 1, childSlot, context));
+ }
+ if (type === "ListView") {
+ if (typeof node.name === "string") selectable(node, raw, path, context);
+ else {
+ // not a choice: a row's value and a default mean nothing here
+ delete node.defaultValue;
+ for (const row of node.children ?? []) delete row.value;
+ }
+ }
+ if (type === "ListViewItem" && slot !== "items") delete node.value;
+ return node;
+}
+
+/** A list with a `name`: each row gets a distinct `value` (its own, else the
+ * row's name, else its position), a press on a row selects it, and the list
+ * is required unless it says otherwise. It needs `confirm`, the only thing
+ * that can send the choice. */
+function selectable(list: WidgetNode, raw: Record<string, unknown>, path: string, context: Context): void {
+ const name = list.name as string;
+ if (context.fields.has(name)) fail(`${path}.name`, `repeats the field name ${JSON.stringify(name)}`);
+ context.fields.add(name);
+ if (context.fields.size > WIDGET_LIMITS.fields) fail(path, `the widget has more than ${WIDGET_LIMITS.fields} fields`);
+ if (!isRecord(list.confirm)) fail(`${path}.confirm`, "a list with a name lets the person choose a row; it needs confirm: {label, action} to send the choice");
+ const rows = list.children ?? [];
+ if (rows.length < 2) fail(`${path}.children`, "a list with a name needs at least two rows to choose from");
+ const seen = new Set<string>();
+ rows.forEach((row, index) => {
+ const at = `${path}.children[${index}]`;
+ if (row.onClickAction !== undefined) fail(`${at}.onClickAction`, "the rows of a list with a name are selected, not pressed; remove onClickAction from the rows, or remove name from the list");
+ const value = widgetString(row, "value") ?? (firstText(row) || String(index + 1));
+ if (seen.has(value)) fail(`${at}.value`, `repeats the value ${JSON.stringify(value)}; give each row its own value`);
+ seen.add(value);
+ row.value = value;
+ });
+ if (raw.required !== false) list.required = true;
+ list.allowOther = raw.allowOther !== false;
+ if (typeof list.defaultValue === "string" && !seen.has(list.defaultValue)) delete list.defaultValue;
+}
+
+/** Whether a field offers Other: the person may answer in their own words instead of an option. A tree stored
+ * before this existed has no `allowOther`, so it offers only its options. */
+export function widgetTakesOther(node: WidgetNode): boolean {
+ return node.allowOther === true && (node.type === "Select" || node.type === "RadioGroup" || (node.type === "ListView" && typeof node.name === "string"));
+}
+
+/** Normalise untrusted model input into a canonical tree, or say what is
+ * wrong with it in one sentence that names the path. */
+export function parseWidgetInput(value: unknown): ParsedWidgetInput {
+ let raw = value;
+ if (typeof raw === "string") {
+ try {
+ raw = JSON.parse(raw);
+ } catch {
+ return { ok: false, error: "widget: must be a JSON object, not text." };
+ }
+ }
+ if (!isRecord(raw)) return { ok: false, error: "widget: must be an object with a type." };
+ let bytes: number;
+ try {
+ bytes = JSON.stringify(raw).length;
+ } catch {
+ return { ok: false, error: "widget: must be plain JSON." };
+ }
+ if (bytes > WIDGET_LIMITS.bytes) return { ok: false, error: `widget: is ${bytes} characters of JSON; keep it under ${WIDGET_LIMITS.bytes}.` };
+ try {
+ const rooted = ROOT_TYPES.has(typeOf(raw)) ? raw : { type: "Card", children: [raw] };
+ const root = normalize(rooted, "widget", 1, "root", { nodes: 0, images: 0, fields: new Set() });
+ const seen = new Map<string, string>();
+ for (const entry of collectActions(root, true)) {
+ if (!entry.label) return { ok: false, error: `widget: the ${entry.kind} at ${entry.ref} has an action but no label; give it a label (a list item takes its first Text or Title).` };
+ if (entry.client) continue;
+ if (seen.has(entry.label)) return { ok: false, error: `widget: two actions are both labelled ${JSON.stringify(entry.label)}; give each a distinct label.` };
+ seen.set(entry.label, entry.ref);
+ }
+ return { ok: true, value: root };
+ } catch (error) {
+ if (error instanceof WidgetInputError) return { ok: false, error: `${error.message}.` };
+ throw error;
+ }
+}
+
+
+export const widgetString = (node: WidgetNode, key: string): string | undefined => (typeof node[key] === "string" ? node[key] as string : undefined);
+export const widgetNumber = (node: WidgetNode, key: string): number | undefined => (typeof node[key] === "number" ? node[key] as number : undefined);
+
+function buttonSpecOf(root: WidgetRoot, key: "confirm" | "cancel"): WidgetButtonSpec | undefined {
+ const spec = root[key];
+ return isRecord(spec) && typeof spec.label === "string" && isRecord(spec.action) ? spec as unknown as WidgetButtonSpec : undefined;
+}
+
+function walk(node: WidgetNode, visit: (node: WidgetNode, ancestors: WidgetNode[]) => void, ancestors: WidgetNode[] = []): void {
+ visit(node, ancestors);
+ const next = [...ancestors, node];
+ for (const child of Array.isArray(node.children) ? node.children : []) if (isRecord(child)) walk(child, visit, next);
+}
+
+function lastOf<T>(items: readonly T[], match: (item: T) => boolean): T | undefined {
+ for (let index = items.length - 1; index >= 0; index -= 1) if (match(items[index])) return items[index];
+ return undefined;
+}
+
+/** What a row is called: its first Title or Text, on one line. A text held
+ * to a fixed width is a column label ("TO"), or can be squeezed to nothing,
+ * so it never names the row; and the name stops at the label limit, so what
+ * is recorded for a press is what fits on the row the person pressed. */
+function firstText(node: WidgetNode): string {
+ let found = "";
+ walk(node, (inner) => {
+ if (found || (inner.type !== "Title" && inner.type !== "Text") || typeof inner.value !== "string" || typeof inner.width === "number") return;
+ found = inner.value.replace(/\s+/g, " ").trim().slice(0, WIDGET_LIMITS.label);
+ });
+ return found;
+}
+
+export interface WidgetActionEntry {
+ /** "confirm", "cancel", or the node id of the button or list item. */
+ ref: string;
+ /** What the person is recorded as having said. */
+ label: string;
+ action: WidgetAction;
+ /** Present when the press settles the widget. */
+ tone?: "confirm" | "cancel" | "submit";
+ /** Handled on the device and never sent (open_url, open_thread, open_phone_pairing). */
+ client?: true;
+ kind: "button" | "item" | "confirm" | "cancel";
+}
+
+function collectActions(root: WidgetRoot, strict: boolean): WidgetActionEntry[] {
+ const found: Array<WidgetActionEntry & { row?: string }> = [];
+ walk(root, (node, ancestors) => {
+ if (node.type === "Button") {
+ if (node.disabled === true) return;
+ const form = lastOf(ancestors, (ancestor) => ancestor.type === "Form");
+ const own = isRecord(node.onClickAction) ? node.onClickAction as unknown as WidgetAction : undefined;
+ const submitted = node.submit === true && isRecord(form?.onSubmitAction) ? form.onSubmitAction as unknown as WidgetAction : undefined;
+ const picked = own ?? submitted;
+ if (!picked) {
+ if (strict && node.submit === true) throw new WidgetInputError(`widget: the submit Button at ${node.id} needs a Form with onSubmitAction around it`);
+ return;
+ }
+ const row = lastOf(ancestors, (ancestor) => ancestor.type === "ListViewItem" || ancestor.type === "Table.Row" || ancestor.type === "Row");
+ found.push({ ref: node.id, label: widgetString(node, "label") ?? "", action: picked, kind: "button", ...(node.submit === true ? { tone: "submit" as const } : {}), ...(row ? { row: firstText(row) } : {}) });
+ } else if (node.type === "ListViewItem" && isRecord(node.onClickAction)) {
+ found.push({ ref: node.id, label: firstText(node), action: node.onClickAction as unknown as WidgetAction, kind: "item" });
+ }
+ });
+ for (const key of ["confirm", "cancel"] as const) {
+ const spec = buttonSpecOf(root, key);
+ if (spec) found.push({ ref: key, label: spec.label, action: spec.action, tone: key, kind: key });
+ }
+ // "View" on three rows is three presses: each takes its row's name.
+ const counts = new Map<string, number>();
+ for (const entry of found) counts.set(entry.label, (counts.get(entry.label) ?? 0) + 1);
+ return found.map(({ row, ...entry }) => ({
+ ...entry,
+ ...(CLIENT_ACTION(entry.action) ? { client: true as const } : {}),
+ label: row && entry.label && (counts.get(entry.label) ?? 0) > 1 ? `${entry.label}: ${row}`.slice(0, WIDGET_LIMITS.label * 2) : entry.label,
+ }));
+}
+
+/** Every pressable thing in a canonical widget, in document order. */
+export function widgetActions(root: WidgetRoot): WidgetActionEntry[] {
+ return collectActions(root, false);
+}
+
+/** The action a recorded label stands for, for the model's reading of a press. */
+export function widgetActionByLabel(root: WidgetRoot, label: string): WidgetActionEntry | undefined {
+ return widgetActions(root).find((entry) => !entry.client && entry.label === label);
+}
+
+/** Where a press collects its values: the nearest Form around the pressed
+ * node, or the whole widget. */
+export function widgetScope(root: WidgetRoot, ref: string): WidgetNode {
+ let scope: WidgetNode = root;
+ walk(root, (node, ancestors) => {
+ if (node.id === ref) scope = lastOf(ancestors, (ancestor) => ancestor.type === "Form") ?? root;
+ });
+ return scope;
+}
+
+export interface WidgetField {
+ name: string;
+ type: string;
+ /** Its Label's text, else a Checkbox's own label, else its name: only words
+ * drawn beside the field, because this is how the field is named in the
+ * message a press is recorded as. */
+ label: string;
+ node: WidgetNode;
+}
+
+/** The named fields under `scope`. Labels are looked up across `root`. */
+export function widgetFields(scope: WidgetNode, root: WidgetRoot = scope): WidgetField[] {
+ const labels = new Map<string, string>();
+ walk(root, (node) => {
+ if (node.type === "Label" && typeof node.fieldName === "string" && typeof node.value === "string") labels.set(node.fieldName, node.value);
+ });
+ const fields: WidgetField[] = [];
+ walk(scope, (node) => {
+ if (typeof node.name !== "string" || !(FIELD_TYPES.has(node.type) || node.type === "ListView")) return;
+ const own = node.type === "ListView" ? widgetString(node, "title") : widgetString(node, "label");
+ fields.push({ name: node.name, type: node.type, node, label: labels.get(node.name) ?? own ?? node.name });
+ });
+ return fields;
+}
+
+/** What a choice field offers: a Select's or RadioGroup's options, or the
+ * rows of a list with a name (each row's name, and the value it stands for). */
+export function widgetFieldOptions(node: WidgetNode): Array<{ label: string; value: string }> {
+ if (node.type === "ListView") {
+ return (Array.isArray(node.children) ? node.children : []).filter(isRecord).map((row) => {
+ const value = String((row as WidgetNode).value ?? "");
+ return { label: firstText(row as WidgetNode) || value, value };
+ });
+ }
+ return Array.isArray(node.options) ? node.options as Array<{ label: string; value: string }> : [];
+}
+
+/** What each field holds before the person touches it. */
+export function widgetInitialValues(scope: WidgetNode): WidgetValues {
+ const values: WidgetValues = {};
+ for (const field of widgetFields(scope)) {
+ values[field.name] = field.type === "Checkbox" ? field.node.defaultChecked === true : widgetString(field.node, "defaultValue") ?? "";
+ }
+ return values;
+}
+
+export type ResolvedWidgetAction =
+ | { ok: true; ref: string; label: string; action: WidgetAction; values: WidgetValues; other?: WidgetOther; text: string; tone?: "confirm" | "cancel" | "submit" }
+ | { ok: false; status: 400 | 404 | 409; error: string };
+
+/** Check one press against the stored widget. `text` is the user message it
+ * becomes: the label, then one "Field: value" line per filled field. `other`
+ * holds answers in the person's own words (see `WidgetOther`). */
+export function resolveWidgetAction(payload: WidgetPayload, ref: string, values: unknown, other?: unknown): ResolvedWidgetAction {
+ if (payload.settled) return { ok: false, status: 409, error: "This was already answered." };
+ const entry = widgetActions(payload.root).find((candidate) => candidate.ref === ref);
+ if (!entry) return { ok: false, status: 404, error: "That button is no longer on this widget." };
+ if (entry.client) return { ok: false, status: 400, error: "That action opens on the device and is not sent." };
+ const done = (clean: WidgetValues, own: WidgetOther, lines: string[]): ResolvedWidgetAction => ({
+ ok: true, ref, label: entry.label, action: entry.action, values: clean, ...(Object.keys(own).length ? { other: own } : {}),
+ text: [entry.label, ...lines].join("\n"), ...(entry.tone ? { tone: entry.tone } : {}),
+ });
+ if (entry.tone === "cancel") return done({}, {}, []);
+
+ const scope = widgetScope(payload.root, ref);
+ const fields = widgetFields(scope, payload.root);
+ const given = values === undefined || values === null ? {} : values;
+ if (!isRecord(given)) return { ok: false, status: 400, error: "values must be an object of field names." };
+ const typed = other === undefined || other === null ? {} : other;
+ if (!isRecord(typed)) return { ok: false, status: 400, error: "other must be an object of field names." };
+ const known = new Set(fields.map((field) => field.name));
+ for (const key of [...Object.keys(given), ...Object.keys(typed)]) if (!known.has(key)) return { ok: false, status: 400, error: `There is no field named ${JSON.stringify(key)} here.` };
+
+ const initial = widgetInitialValues(scope);
+ const clean: WidgetValues = {};
+ const own: WidgetOther = {};
+ const lines: string[] = [];
+ const mustFill = entry.tone === "confirm" || entry.tone === "submit";
+ for (const field of fields) {
+ const words = Object.hasOwn(typed, field.name) ? typed[field.name] : undefined;
+ if (words !== undefined && (field.node.disabled === true || !widgetTakesOther(field.node))) {
+ return { ok: false, status: 400, error: `${field.label} takes only the offered options.` };
+ }
+ if (words !== undefined && typeof words !== "string") return { ok: false, status: 400, error: `${field.label} must be text.` };
+ const answer = typeof words === "string" ? words.trim().replace(/\s+/g, " ") : "";
+ if (answer.length > WIDGET_LIMITS.fieldValue) return { ok: false, status: 400, error: `${field.label} must be at most ${WIDGET_LIMITS.fieldValue} characters.` };
+ // a field the person could not change keeps what it was drawn with
+ const raw = Object.hasOwn(given, field.name) && field.node.disabled !== true ? given[field.name] : initial[field.name];
+ if (answer) {
+ if (typeof raw !== "string") return { ok: false, status: 400, error: `${field.label} must be text.` };
+ if (raw.trim()) return { ok: false, status: 400, error: `${field.label} is one of the options or their own answer, not both.` };
+ clean[field.name] = "";
+ own[field.name] = answer;
+ lines.push(`${field.label}: ${answer}`);
+ continue;
+ }
+ if (field.type === "Checkbox") {
+ if (typeof raw !== "boolean") return { ok: false, status: 400, error: `${field.label} must be on or off.` };
+ if (mustFill && field.node.required === true && !raw) return { ok: false, status: 400, error: `${field.label} is required.` };
+ clean[field.name] = raw;
+ if (raw) lines.push(`${field.label}: yes`);
+ continue;
+ }
+ if (typeof raw !== "string") return { ok: false, status: 400, error: `${field.label} must be text.` };
+ const value = field.type === "Textarea" ? raw.trim() : raw.trim().replace(/\s+/g, " ");
+ if (value.length > WIDGET_LIMITS.fieldValue) return { ok: false, status: 400, error: `${field.label} must be at most ${WIDGET_LIMITS.fieldValue} characters.` };
+ if (mustFill && field.node.required === true && !value) return { ok: false, status: 400, error: `${field.label} is required.` };
+ let shown = value;
+ let kept = value;
+ if (value && (field.type === "Select" || field.type === "RadioGroup" || field.type === "ListView")) {
+ const option = widgetFieldOptions(field.node).find((candidate) => candidate.value === value);
+ if (!option) return { ok: false, status: 400, error: `${field.label} must be one of the offered options.` };
+ shown = option.label;
+ }
+ if (value && field.type === "TimePicker") {
+ const time = timeOfDay(value, "");
+ if (time === undefined) return { ok: false, status: 400, error: `${field.label} must be a time like 09:30.` };
+ const min = widgetString(field.node, "min");
+ const max = widgetString(field.node, "max");
+ if ((min && (time as string) < min) || (max && (time as string) > max)) return { ok: false, status: 400, error: `${field.label} is outside the times offered.` };
+ kept = shown = time as string;
+ }
+ if (field.type === "DayPicker" && value) {
+ const days = weekdays(value);
+ if (!days || days.split(",").length !== value.split(",").length) return { ok: false, status: 400, error: `${field.label} must be days of the week.` };
+ kept = days;
+ shown = dayList(days);
+ }
+ if (value && field.type === "DatePicker") {
+ if (isoDate(value, "") === undefined) return { ok: false, status: 400, error: `${field.label} must be a date like 2026-10-14.` };
+ const min = widgetString(field.node, "min");
+ const max = widgetString(field.node, "max");
+ if ((min && value < min) || (max && value > max)) return { ok: false, status: 400, error: `${field.label} is outside the dates offered.` };
+ }
+ clean[field.name] = kept;
+ // whole: this line is all the bot reads of what the person typed
+ if (value) lines.push(`${field.label}: ${shown}`);
+ }
+ return done(clean, own, lines);
+}
+
+/** A word to the bot about a widget that parses but does not do what it
+ * looks like it is for: rows to choose between and no way to choose, or one
+ * time, date or set of days typed in a one-line field (a Textarea may list
+ * several). Undefined when there is nothing to say. */
+export function widgetAdvice(root: WidgetRoot): string | undefined {
+ const notes: string[] = [];
+ const rows = Array.isArray(root.children) ? root.children.length : 0;
+ if (root.type === "ListView" && rows >= 2 && buttonSpecOf(root, "confirm") && widgetFields(root).length === 0
+ && !widgetActions(root).some((entry) => entry.kind === "item" || entry.kind === "button")) {
+ notes.push("No row of this list can be chosen: the person can only confirm or cancel it as a whole. If they are meant to pick one row, show it again with its widget_id and give the ListView a name (and each row a value), so the rows become selectable and confirm sends the pick.");
+ }
+ const fields = widgetFields(root);
+ const sending = widgetActions(root).filter((entry) => !entry.client && entry.tone !== "cancel");
+ if (fields.length > 0 && !sending.length) {
+ notes.push("Nothing in this widget sends what the person fills in. Show it again with its widget_id and confirm: {label, action} (and cancel if they may decline) so they can send it.");
+ } else if (fields.length > 0) {
+ const sent = new Set(sending.flatMap((entry) => widgetFields(widgetScope(root, entry.ref), root).map((field) => field.name)));
+ const unsent = fields.filter((field) => !sent.has(field.name)).map((field) => JSON.stringify(field.label));
+ if (unsent.length) notes.push(`${unsent.join(", ")} sits outside the Form whose button is the only way to send, so it is never sent. Show it again with its widget_id, with it inside that Form or with confirm on the Card.`);
+ }
+ const typed = fields.filter((field) => field.type === "Input");
+ // "each time", "every time" and "how many times" are not a time of day
+ const phrase = (field: WidgetField) => `${field.name} ${field.label} ${widgetString(field.node, "placeholder") ?? ""}`
+ .replace(/\b(each|every|this|next|first|last|any|some|one|other|same|spare|free|full|part|lead|over|down)[\s-]+times?\b/gi, " ")
+ .replace(/\btimes\b/gi, " ");
+ const asks = (pattern: RegExp) => typed.filter((field) => pattern.test(phrase(field))).map((field) => field.label);
+ const pickers: Array<[RegExp, string]> = [
+ [/\b(time|o'?clock|hh:mm)\b|\b\d{1,2}(:\d{2})?\s?[ap]m\b|\b\d{1,2}:\d{2}\b/i, "TimePicker"],
+ [/\b(days|weekdays?|weekly|repeats?|repeating|(which|what) days?|days? of the week)\b/i, "DayPicker"],
+ [/\b(dates?|deadline|due)\b/i, "DatePicker"],
+ ];
+ const seen = new Set<string>();
+ for (const [pattern, picker] of pickers) {
+ const labels = asks(pattern).filter((label) => !seen.has(label));
+ labels.forEach((label) => seen.add(label));
+ if (labels.length) notes.push(`${labels.map((label) => JSON.stringify(label)).join(", ")} asks the person to type what a ${picker} lets them pick. Show it again with its widget_id and a ${picker} in its place.`);
+ }
+ return notes.length ? notes.join(" ") : undefined;
+}
+
+/** Days as a person says them: "Every day", "Weekdays", "Weekends", or the names. */
+export function dayList(days: string): string {
+ const picked = days.split(",").filter(Boolean);
+ if (picked.length === 7) return "Every day";
+ if (picked.join(",") === "mon,tue,wed,thu,fri") return "Weekdays";
+ if (picked.join(",") === "sat,sun") return "Weekends";
+ const names: Record<string, string> = { mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", fri: "Fri", sat: "Sat", sun: "Sun" };
+ return picked.map((day) => names[day] ?? day).join(", ");
+}
+
+
+function inlineText(node: WidgetNode): string {
+ switch (node.type) {
+ case "Text": case "Title": case "Caption": case "Label":
+ return widgetString(node, "value") ?? "";
+ case "Markdown":
+ return (widgetString(node, "value") ?? "").replace(/\s+/g, " ");
+ case "Badge":
+ return widgetString(node, "label") ?? "";
+ case "Button":
+ return node.label ? `[${String(node.label)}]` : "";
+ case "Image":
+ return node.alt ? `[image: ${String(node.alt)}]` : "[image]";
+ case "Progress":
+ return [widgetString(node, "label"), `${Math.round((widgetNumber(node, "value") ?? 0) * 100)}%`].filter(Boolean).join(" ");
+ case "Chart":
+ return `[chart: ${(Array.isArray(node.series) ? node.series as Array<{ label?: string; dataKey: string }> : []).map((series) => series.label ?? series.dataKey).join(", ")}]`;
+ case "Checkbox":
+ return `[ ] ${widgetString(node, "label") ?? String(node.name)}`;
+ case "Select": case "RadioGroup":
+ return `(${(Array.isArray(node.options) ? node.options as Array<{ label: string }> : []).slice(0, 6).map((option) => option.label).join(" / ")})`;
+ case "DayPicker":
+ return `[${typeof node.defaultValue === "string" ? dayList(node.defaultValue) : "days"}]`;
+ case "Input": case "Textarea": case "DatePicker": case "TimePicker":
+ return `[${widgetString(node, "placeholder") ?? String(node.name)}]`;
+ default:
+ return (Array.isArray(node.children) ? node.children : []).map(inlineText).filter(Boolean).join(" · ");
+ }
+}
+
+function blockLines(node: WidgetNode): string[] {
+ const children = Array.isArray(node.children) ? node.children : [];
+ if (node.type === "ListViewItem") return [`- ${inlineText(node)}`];
+ if (node.type === "Table") return children.map((row) => (Array.isArray(row.children) ? row.children : []).map(inlineText).join(" | "));
+ if (node.type === "Markdown") return [widgetString(node, "value") ?? ""];
+ const stacked = node.type === "Col" || node.type === "Form" || node.type === "Transition" || (node.type === "Box" && node.direction !== "row");
+ return stacked ? children.flatMap(blockLines) : [inlineText(node)];
+}
+
+/** The readable version of a widget: the message `text`, read by previews,
+ * notifications, exports, replayed history and clients that do not know the kind. */
+export function widgetToText(root: WidgetRoot): string {
+ const lines: string[] = [];
+ const statusText = isRecord(root.status) && typeof root.status.text === "string" ? root.status.text : "";
+ if (statusText) lines.push(statusText);
+ const title = widgetString(root, "title");
+ const head = [title ? `**${title}**` : "", widgetString(root, "caption"), widgetString(root, "meta")].filter(Boolean).join(" · ");
+ if (head) lines.push(head);
+ for (const child of Array.isArray(root.children) ? root.children : []) lines.push(...blockLines(child));
+ const buttons = (["confirm", "cancel"] as const).map((key) => buttonSpecOf(root, key)?.label).filter(Boolean).map((label) => `[${label}]`).join(" ");
+ if (buttons) lines.push(buttons);
+ const out = lines.map((line) => line.trimEnd()).filter(Boolean).join("\n");
+ return out.length <= WIDGET_LIMITS.fallback ? out : `${out.slice(0, WIDGET_LIMITS.fallback - 1).trimEnd()}…`;
+}
diff --git a/packages/phone-protocol/src/wire-tool.ts b/packages/phone-protocol/src/wire-tool.ts
new file mode 100644
index 0000000000..f0fb4cfb1c
--- /dev/null
+++ b/packages/phone-protocol/src/wire-tool.ts
@@ -0,0 +1,23 @@
+import type { PlaceRow } from "./place-view.ts";
+import type { ServerToolText } from "./server-text.ts";
+
+/** An activity chip serialized beside a transcript line. */
+export interface WireTool extends ServerToolText {
+ name: string; ok?: boolean; spoken?: string; setup?: boolean; terminal?: boolean; summary?: string; input?: string; output?: string;
+ /** What the call works on, as its live status said it: the chip's and the "Now" card's specific words. `whose`: the person whose own app or MCP server the call used. */
+ step?: import("./turn-progress.ts").LiveStep; whose?: { person: string; app: string };
+ /** error rows: the installed Claude Code is too old for the model, and
+ * the UI can offer to update it in place. notice rows: `rescue`, a turn that heard nothing from its AI for a while. */
+ claudeUpdate?: boolean; rescue?: import("./first-reply-rescue.ts").FirstReplyRescue;
+ /** error rows: the place this turn could not use. */
+ place?: PlaceRow;
+ /** error rows: epoch ms when the usage limit that stopped the turn resets. */
+ limitResetsAt?: number;
+ /** A failed step on an MCP server, in the reader's language: which server, why, and what to do. */
+ problem?: string;
+ /** Provider item identity, scoped to the owning turn. */
+ itemId?: string;
+ /** Whether the harness captured the full redacted result. Private
+ * server-local spill paths are not exposed to clients. */
+ fullResult?: boolean;
+}
diff --git a/packages/phone-protocol/src/wire.ts b/packages/phone-protocol/src/wire.ts
new file mode 100644
index 0000000000..5148411e44
--- /dev/null
+++ b/packages/phone-protocol/src/wire.ts
@@ -0,0 +1,991 @@
+/** The client-visible wire model for tasks, bots, messages and rooms. A field
+ * here is one the server emits in every response and SSE frame that carries
+ * the shape. */
+import type { PresenceFrame } from "./team-presence.ts";
+import type { DataBroadcast } from "./data-surface.ts";
+import type { ApprovalMode } from "./approval-mode.ts";
+import type { ToolScope } from "./tool-scope.ts";
+import type { CommandAllowlistCandidate } from "./command-allowlist.ts";
+import type { TurnDigest } from "./digest.ts";
+import type { BotAvatarCrop, MascotFaceColor } from "./bot-avatar.ts";
+import type { BotBodyId } from "./bot-body.ts";
+import type { ReplyStyle } from "./reply-style.ts";
+import type { CredentialTargetId, CUSTOM_SECRET_TARGET, SecretDelivery } from "./credential-request.ts"; import type { EmailOutgoingFields } from "./email.ts";
+import type { TeamSetupRequest } from "./team-setup.ts"; import type { DefaultBotFields, HelperIntroField } from "./default-bot.ts";
+import type { SetupCardFields } from "./setup-card.ts"; import type { BugReportField } from "./devs-report-status.ts"; import type { AccessRequestCardField, BotAccessFields } from "./bot-access.ts";
+import type { RoutineRequestCardData } from "./routine-request.ts"; import type { SavedStepsMark } from "./saved-steps.ts";
+import type { WebhookRequestCardData } from "./webhook-request.ts"; import type { WaitCardField, WaitLineField } from "./wait-request.ts"; import type { ComputerAskField } from "./computer-ask.ts";
+import type { AppEventAttempt, AppTrigger, AppTriggerRequestCardData, AppTriggerService } from "./app-triggers.ts";
+import type { ProfileRequestCardData } from "./profile-request.ts";
+import type { ServerTextLine, ServerTextParams } from "./server-text.ts";
+import type { WireTool } from "./wire-tool.ts";
+import type { ModelRequestCardData } from "./model-request.ts";
+import type { ConnectorCardData } from "./connector-card.ts"; import type { McpChangeRequest } from "./mcp-request.ts"; import type { AppSettingCardField, WindowPrefFrame } from "./app-settings.ts";
+import type { SkillRequestCardData } from "./skill-request.ts"; import type { OutsideWriteCardField } from "./outside-write.ts";
+import type { QuestionRequestCardData } from "./ask-question.ts";
+import type { AutomationLine, RoutineRunCardData } from "./routine-run.ts";
+import type { WidgetPayload } from "./widget.ts";
+import type { AppFromRef, AppPayload, AppPointedRef } from "./app.ts";
+import type { GroupGoalRunCardData } from "./group-goal-run.ts"; import type { BurstCardData } from "./burst.ts";
+import type { RuntimeEvent } from "./runtime-events.ts";
+import type { NotificationLogEntry } from "./notification.ts";
+import type { Routine, RoutineRun } from "./routines.ts";
+import type { WebhookAttempt, WebhookTrigger } from "./webhooks.ts";
+import type { PublishedPageCard } from "./published-page.ts";
+import type { InboxItem, InboxTask } from "./inbox.ts";
+import type { LiveCallRecord, LiveCallState } from "./live-call-wire.ts";
+import type { ForkOrigin, TaskClosedBy, TaskOpenedBy } from "./task-provenance.ts";
+import type { CompanionEndpointsSnapshot } from "./responses.ts";
+/** What a team bot's main chat is called, beside each person's own chats. */
+export const SHARED_CHAT_TITLE = "Shared chat";
+
+export type { LiveCallRecord, LiveCallState, LiveCallStatus, LiveClient, LiveEndReason, LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken, LiveFishTransport, LiveKeySource, LiveProvider, LiveSettings } from "./live-call-wire.ts";
+export type { ForkOrigin, TaskClosedBy, TaskOpenedBy } from "./task-provenance.ts";
+export type { AuthPairResponse, BotsResponse, CompanionE2EDescriptor, CompanionEndpointsSnapshot, PairedDevice, PairedSession, PairResponse, WireComputerControl, WireMessagePage } from "./responses.ts";
+
+/** Reasoning-effort levels, ascending: a union of what any engine accepts;
+ * each driver declares the subset its CLI will take. */
+export const EFFORT_LEVELS = ["none", "low", "medium", "high", "xhigh", "max"] as const;
+export type EffortLevel = (typeof EFFORT_LEVELS)[number];
+
+export function isEffortLevel(value: unknown): value is EffortLevel {
+ return typeof value === "string" && (EFFORT_LEVELS as readonly string[]).includes(value);
+}
+
+/** instanceId is the routing key. */
+export interface ModelSelection {
+ instanceId: string;
+ model: string;
+ /** Optional: no effort means no flag, and the CLI keeps its own default. */
+ effort?: EffortLevel;
+ /** Explicit model-specific variant. Omitted leaves the native session alone. */
+ variant?: string;
+}
+
+/** Which cloud computer backs computer: "cloud"; absent means Boat. */
+export type CloudBackend = "box" | "vps";
+
+/** A place a bot can act. `cloud` covers both cloud backends. */
+export type Surface = "cloud" | "vm" | "local" | "browser";
+
+export const MAUS_COLOR_NAMES = [
+ "green", "blue", "red", "orange", "purple", "cyan", "pink",
+ "yellow", "teal", "coral", "silver", "chrome",
+] as const;
+export type MausColor = (typeof MAUS_COLOR_NAMES)[number];
+
+export function isMausColor(value: unknown): value is MausColor {
+ return typeof value === "string" && (MAUS_COLOR_NAMES as readonly string[]).includes(value);
+}
+
+/** The face a bot rests on, as one of the engine's state names. */
+export type MausExpression = string;
+
+/** What the bot is doing right now, as the harness sees it. `parked.computer`
+ * is task-level only: a turn that settled at the computer wait ceiling and
+ * resumes when the seat frees. It never elevates the bot-level activity and
+ * never counts as busy. */
+export type BotActivity = "working" | "waiting-on-you" | "idle" | "no-signal" | "dead" | "parked.computer";
+
+/** What a task has spent, banked once per settled turn. */
+export interface TaskUsage {
+ input: number;
+ output: number;
+ /** cached share of input (context the model re-read) */
+ cachedInput?: number;
+ /** null until any turn reported a cost — most engines never do */
+ costUsd: number | null;
+ turns: number;
+ /** the most recent settled turn on its own */
+ lastTurn?: { input: number; output: number; cachedInput?: number; costUsd: number | null };
+ /** what filled the model's window on the last model call, and the window's size when known */
+ context?: { tokens: number; window?: number };
+}
+
+/** Accounting for the currently displayed room thread, across all speakers. */
+export interface GroupThreadUsage extends TaskUsage {
+ lastSpeaker?: { botId: string; name: string };
+}
+
+export interface BotMovedTo {
+ team: { id: string; name: string };
+ state: "moving" | "moved";
+ at: number;
+}
+
+/** One task = one conversation with its own context, thread and provider session. */
+export interface WireTask extends InboxTask {
+ /** Outstanding handoffs, not an active provider turn. */
+ waitingForTeammates?: boolean;
+ threadId: string;
+ /** The completed message whose visible history seeded this conversation. */
+ origin?: ForkOrigin;
+ title: string;
+ createdAt: number;
+ /** The first message already drove a title attempt for this thread, so a
+ * later one does not rename a thread the person may have retitled. */
+ titleFromFirstMessage?: true;
+ /** Team Cloud only: this is the bot's main chat, everyone's who sees the bot. Its title is SHARED_CHAT_TITLE on every
+ * person's copy, whatever is stored, and it can't be renamed. */
+ sharedChat?: true;
+ /** Organizational grouping only; never a directory or provider context. */
+ projectId?: string;
+ /** Detached routine execution, reachable through its visible results card. */ routineRunId?: string;
+ /** Work from outside (a webhook, an app's event) reached this conversation: what it starts or runs stays confined, for good. */ outside?: true;
+ /** An outside caller opened this thread through the bot's API, so only it may continue it; such a thread is outside too. */ botApi?: true;
+ /** Set when a bot, not a person, opened this thread. */ openedBy?: TaskOpenedBy;
+ /** On a team's server: one person's conversation, seen by them alone (never by another member or an admin). */
+ private?: true;
+ /** On a team's server: a private conversation its person shared, never private again. `sharedWith`: shared with one person,
+ * the other reader as this viewer sees them (`byYou` to the one who shared it); nobody else, an admin included, is sent it. */
+ shared?: true; sharedWith?: { name: string; byYou?: true };
+ /** Team Cloud, where several people write, while it works: whose request runs (they or an Owner or Admin stop it). */ askedBy?: ResolvedSender;
+ /** Set by close_thread; absent while the thread is open. */
+ closedBy?: TaskClosedBy;
+ archivedAt?: number;
+ /** Only true is stored; absent means unpinned. */
+ pinned?: boolean;
+ link?: string;
+ linkAuto?: boolean;
+ /** Epoch ms of the newest message, or createdAt when the thread has none.
+ * Server-derived. Clients must not write it. */
+ updatedAt?: number;
+ lastThreadOrderAt?: number;
+ /** 0 means "until new activity"; a future epoch ms means "until then", and
+ * an expired value reads as absent. Absent = not snoozed. */
+ snoozedUntil?: number;
+ /** The thread's own model when a person picked one in it, else its bot's.
+ * Always the effective one on the wire. */
+ modelSelection?: ModelSelection;
+ /** true: the thread runs on its bot's model and moves with it; false: a
+ * person picked this thread's model. Derived at projection, never stored. */
+ followsBotModel?: boolean;
+ approvalMode?: ApprovalMode;
+ autoApprove?: boolean;
+ alwaysAllow?: string[];
+ unread?: boolean;
+ /** The newest message on screen the last time the person read this
+ * conversation. The New divider goes after it. */
+ lastReadMessageId?: string;
+ /** true after an edit/branch-switch rewound the visible conversation. */
+ rewound?: boolean;
+ pinnedMessageId?: string;
+ /** Runtime-only state, reset on load and never persisted. */
+ activity?: BotActivity;
+ busy?: boolean;
+ /** Epoch ms when this task's current busy stretch began; runtime-only. */
+ turnStartedAt?: number;
+ /** Where this conversation works when pinned; absent = follow the bot. */
+ surface?: Surface;
+ /** The pin above was set by the machine (an Auto turn or the bot's
+ * select_computer), not a person, so the next Works on change moves it.
+ * Derived at projection, never stored. */
+ surfaceAuto?: true;
+ usage?: TaskUsage;
+ /** Prompt-cache keep-warm status for this thread, derived at projection;
+ * absent when no window is open. */
+ cacheKeepWarm?: CacheKeepWarmStatus;
+ /** the folder this task's turns run in, pinned on its first turn; one in its own folder moves to its bot's working folder. */
+ cwd?: string | null;
+ /** Set me up was pressed here (server/setup-request.ts): the person's next line in this conversation runs as a
+ * setup request. Server-owned; a client only shows it. `by`: who pressed, where several people share the place (their
+ * reactor key); only their next line takes it, and only they see its chip. */
+ setupRequest?: { at: number; by?: string };
+}
+
+/** One thread's keep-warm window as a client shows it. Times are epoch ms. */
+export interface CacheKeepWarmStatus {
+ state: "warm" | "stopped";
+ until?: number;
+ nextPingAt?: number;
+ last?: { at: number; read: number; write: number; costUsd: number | null };
+ stopped?: string;
+}
+
+/** A lightweight organizational label within one bot. */
+export interface BotProject {
+ id: string;
+ name: string;
+ emoji?: string;
+}
+
+/** Public, package-authored playbooks installed for a bot. Process
+ * guidance only — never executable code, credentials, or grants. */
+export interface InstalledPlaybook {
+ key: string;
+ name: string;
+ summary: string;
+ triggers: string[];
+ instructions: string;
+}
+
+/** Listing provenance and connector intent. It never means the apps are
+ * authorized. */
+export interface InstalledPackageMetadata {
+ id: string;
+ name: string;
+ release: string;
+ requiredApps: Array<{ slug: string; label: string; reason: string; optional?: boolean }>;
+ /** Absent means "file". */
+ source?: "file" | "org";
+ /** file: a random id per import; org: derived from the organization and package. */
+ installId?: string;
+ /** This bot's key in the package, so a re-export keeps its identity. */
+ agentKey?: string;
+ /** Set when the bot was created from a package preset. */
+ presetKey?: string;
+ /** What the package suggested. Never applied: imported bots start at the default level. */
+ suggestedApproval?: "ask" | "auto";
+ /** org only */
+ publisher?: { organizationId: string; slug: string; name: string };
+ /** org only: "<publisher slug>/<package id>" */
+ ref?: string;
+ /** org only: the release bytes that were applied */
+ sha256?: string;
+}
+
+/** One service's connector tool grant: `"*"` widens to every tool on the
+ * service, an explicit list names exact tools. */
+export interface ConnectorToolGrant {
+ tools: "*" | string[];
+}
+
+/** Lowercased Composio service slug, e.g. `gmail`. */
+export const CONNECTOR_SLUG_PATTERN = /^[a-z0-9][a-z0-9_-]{0,80}$/;
+/** Composio tool names are upper-snake, e.g. `GMAIL_SEND_EMAIL`. */
+export const CONNECTOR_TOOL_NAME_PATTERN = /^[A-Z][A-Z0-9_]{0,127}$/;
+
+/** Fails closed: only an absent switch or a strict true allows the helper model; a hand-edited "false" or 0 reads as never. */
+export const helperModelAllowed = (bot: { helperModel?: unknown }): boolean => bot.helperModel === undefined || bot.helperModel === true;
+
+/** A bot as a client may see it. avatarUrl is always present (null when the
+ * bot has none). */
+export interface WireBot extends DefaultBotFields, BotAccessFields {
+ waitingForTeammates?: boolean;
+ id: string;
+ /** The task selected in the UI; running turns keep their own thread id. */
+ threadId: string;
+ /** Where a routine without a thread of its own reports. Absent only for a
+ * bot without threads. */
+ mainThreadId?: string;
+ /** newest first */
+ tasks?: WireTask[];
+ projects?: BotProject[];
+ name: string;
+ title: string;
+ description: string;
+ /** Standing instructions — the persona body. */
+ soul?: string;
+ /** sha256 of soul, for spotting a SOUL.md edited outside the app. */
+ soulHash?: string;
+ /** The SOUL.md mirror differed from soul at the last turn dispatch. */
+ soulDrift?: boolean;
+ notifications: boolean;
+ color: MausColor;
+ mascotExpression?: MausExpression | null;
+ mascotBody?: BotBodyId | null;
+ /** Overrides both eyes and mouth. Absent or null preserves the body's default inks. */
+ mascotFaceColor?: MascotFaceColor | null;
+ /** App-owned attachment served as this bot's custom profile image;
+ * always present on the wire, null when the bot has none. */
+ avatarUrl: string | null;
+ /** Mascot, or the crop applied to avatarUrl. */
+ avatarCrop?: BotAvatarCrop;
+ /** Zoom of a custom image. Absent means 1, the unzoomed cover crop. */
+ avatarZoom?: number;
+ /** Horizontal point of the image kept in the crop, 0–1. Absent means center. */
+ avatarFocusX?: number;
+ /** Vertical point of the image kept in the crop, 0–1. Absent means center. */
+ avatarFocusY?: number;
+ /** True when any task has unread output. */
+ unread: boolean;
+ /** The bot's model: every thread without a model of its own runs on it
+ * and moves with it. Navigating tasks never changes this value. */
+ modelSelection: ModelSelection;
+ /** where the bot works ("Works on"). Unset = auto. */
+ computer?: Surface | "off";
+ /** Which cloud computer backs computer: "cloud"; absent means Boat. */
+ cloudBackend?: CloudBackend;
+ /** Auto mode may prepare/start this bot's managed VPS container. */
+ autoStartVps?: boolean;
+ /** This bot's own SSH config alias for its managed VPS computer; absent
+ * means the default server from Settings → API keys. */
+ vpsAlias?: string;
+ /** where its tasks run their tools; absent = each task's own folder. Its .claude/settings.json (else the bot folder's) applies in all. */
+ cwd?: string;
+ /** Auto mode: the bot approves its own tool permissions. */
+ autoApprove?: boolean;
+ /** Canonical approval level. Missing resolves through autoApprove. */
+ approvalMode?: ApprovalMode;
+ /** Tools this bot may always use without asking. */
+ alwaysAllow?: string[];
+ /** Speak this bot's replies aloud as they settle, without being asked. */
+ speakReplies?: boolean;
+ /** How replies are shaped. Absent = "default". */
+ replyStyle?: ReplyStyle;
+ /** This bot's own voice id, so a room of bots doesn't sound like one person. */
+ voice?: string;
+ /** Whether this bot may send voice notes. Absent/true = allowed; false
+ * hides the tool and refuses the route even with a voice configured. */
+ voiceNotes?: boolean; /** The harness speaks each reply as a voice note; absent follows the installation's `tts.everyReply`. */ voiceNoteEveryReply?: boolean;
+ /** Whether this bot may use the X research tools (x_search and its
+ * actions), which spend the workspace's treg balance.
+ * Absent/false = off: the person turns it on per bot. */
+ xResearch?: boolean;
+ /** Whether this bot uses native memory. Absent/true = enabled. */
+ memoryEnabled?: boolean;
+ /** Queue direct-chat messages behind outstanding delegated work. */
+ parkDirectMessages?: boolean;
+ /** true after an edit/branch-switch rewound the visible conversation. */
+ rewound?: boolean;
+ pinned?: boolean;
+ hidden?: boolean;
+ /** On My Cloud, a bot its person moved into one of their teams: `moving` while it goes (no turns, its routines off),
+ * `moved` once it lives there (archived here, shown as a line that opens the team). */
+ movedTo?: BotMovedTo;
+ /** Optional labeled divider used to organize this bot in the sidebar. */
+ section?: string;
+ /** the one message pinned to the top of this bot's active thread */
+ pinnedMessageId?: string;
+ /** The coordinator for this bot's sidebar section. */
+ chiefOfStaff?: boolean;
+ /** Owner-selected additional teams this Chief may coordinate. */
+ managedSections?: string[];
+ /** Team Cloud only: the lowercased email of the member who created the bot (or moved it in). */
+ createdBy?: string;
+ /** Team Cloud only: the lowercased email of the member the bot reports to, whose inbox its questions, approvals,
+ * failures and routine results reach. Absent: it reports to `createdBy`. */
+ reportsTo?: string;
+ /** Whether this bot may use the workspace's connected apps. */
+ composio?: boolean;
+ /** Which connected-app tools this bot may call, by service slug. Absent
+ * defers to `composio` (unset/true = every tool, false = none); `{}` grants
+ * none. Grants never travel in shareable exports. */
+ connectorTools?: Record<string, ConnectorToolGrant>;
+ connectorScopes?: { apps: Record<string, "read" | "write"> };
+ outbound?: { policy: "ask" | "allow" };
+ /** Which of a paired phone's apps this bot may use; absent: every bot may use what the phone allows (shared/phone-apps.ts). */
+ phoneApps?: import("./phone-apps.ts").PhoneApps;
+ /** Ordered backups used only by opt-in, pre-prompt startup recovery. */
+ fallback?: Array<{ instanceId: string; model: string }>;
+ /** Whether this bot gets the app's built-in browser. */
+ browser?: boolean;
+ /** Record a screenshot and a short note of each browser action, kept with
+ * the conversation. Off unless true. */
+ recordBrowserSteps?: boolean;
+ /** Memory upkeep: the harness captures facts from finished chats into
+ * MEMORY.md and topic files, adds facts about the person to About me and
+ * tidies nightly. On unless explicitly false. */
+ memoryUpkeep?: boolean;
+ /** Prompt-cache keep-warm for this bot's Claude threads: true or false
+ * overrides the workspace setting; absent follows it. */
+ cacheKeepWarm?: boolean;
+ /** false: the workspace's helper model never writes this bot's background texts. Absent or true: allowed. */
+ helperModel?: boolean;
+ /** Which of the app-wide MCP servers this bot mounts, by name. */
+ mcpServers?: string[];
+ /** Owner-selected original tool identities. An empty allowlist permits none. */
+ toolScope?: ToolScope;
+ /** Id of a named browser profile; absent = the bot's own private session. */
+ browserProfile?: string;
+ playbooks?: InstalledPlaybook[];
+ installedPackage?: InstalledPackageMetadata;
+ /** Aggregate of task and room activity; transient, reset on load. */
+ busy?: boolean;
+ /** What the bot is doing right now; transient like busy. */
+ activity?: BotActivity;
+ createdAt: number;
+ /** Who may see this bot on a workspace several people share. Absent means
+ * everyone. Sent to admins only; a member's copy of a bot never carries it. */
+ visibility?: BotVisibility;
+}
+
+/** Who may see a bot: every signed-in person, admins only, or the listed
+ * addresses (and `@domain` entries) plus admins. */
+export type BotVisibility = "everyone" | "admins" | { people: string[] };
+
+/** The person a user message is from, as the server resolved it from their
+ * own session; no request body can supply it. `name` is attribution only:
+ * nothing may be allowed or refused because of it. `id` is an opaque
+ * server-derived key that decides only whose session may answer a card this
+ * request raised. */
+export interface ResolvedSender {
+ name: string;
+ id?: string;
+}
+
+/** Who answered a card: a signed-in person (named as their messages are), the owner on this machine, a session-less
+ * local caller on a shared server (`worker`: the Slack worker, or any other process on that machine), or at Full access
+ * the bot that decides a teammate's question (`bot`: no `answeredText` yet while it decides; "" when it picks itself). */
+export type CardAnswerer = (
+ /** `person`: the answering session's opaque person key, so the owner checks
+ * can tell whose answer it was. */
+ | { kind: "session"; name: string; person?: string }
+ | { kind: "loopback" }
+ | { kind: "worker" } | { kind: "bot"; name: string }
+) & {
+ /** "call": decided by voice on a Live call; "reaction": by a 👍 or 👎 on the
+ * card. Absent: tapped. */
+ via?: "call" | "reaction";
+};
+
+/** Opens every compaction summary written without a model (recent excerpts only); the chat labels stored records by it. */
+export const EXCERPT_SUMMARY_HEADER = "Historical excerpts in chronological order; newer corrections override older requests. These excerpts may omit earlier details.";
+
+/** One transcript line, serialized as stored. */
+export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCardFields, WaitLineField, BugReportField {
+ roomRequest?: { id: string; phase: "request" | "result" };
+ id: string;
+ role: "bot" | "user";
+ kind: "text" | "options" | "activity" | "screen" | "connector" | "secret" | "signin" | "routine.run" | "goal.run" | "burst" | "digest" | "compaction" | "call" | "widget" | "app";
+ text?: string;
+ digest?: TurnDigest;
+ /** kind "compaction" with no `compaction` record: the engine condensed its own session. A marker for people, never context. */
+ engineCompaction?: true;
+ compaction?: { summary: string; firstKeptId: string; foldedThroughId: string; tokensBefore: number; by: "person" | "harness";
+ /** The divider "Start fresh" leaves: no summary, and a provider reads nothing before it. */ fresh?: true };
+ /** Renderers receive only the allowlisted /api/attachments URL. `file` entries are opened through the message-scoped
+ * file route, never by path. `source`: a bot attach-file copy's original path on the server, for Show in folder.
+ * `fromTool`: an image a tool's result returned while the bot worked, which it did not make or send. */
+ attachments?: Array<
+ | { kind: "image"; path: string; mime: string; name?: string; source?: string; fromTool?: true }
+ | { kind: "file"; path: string; mime: string; name: string; source?: string }
+ /** `text` is the words the note speaks (secret-redacted when stored): clients show it behind a
+ * collapsed transcript, never as message body, and the model's replay folds it back after `text`. */
+ | { kind: "audio"; path: string; mime: string; durationMs?: number; text?: string }
+ >;
+ card?: OptionCardData;
+ /** widget rows (kind "widget"): a bot-authored UI tree. `text` is its
+ * readable fallback for clients that do not know the kind. */
+ widget?: WidgetPayload;
+ /** widget rows the server built from records (mail, calendar, other
+ * bots' work) rather than the bot: replayed to the bot only as labelled
+ * data, never as its own words, and never edited by a bot. */
+ serverCard?: true;
+ /** A setup suggestion the device renders in its own words (server/host/helper-suggestion.ts); `text` is the English. */
+ setupSuggestion?: { kind: "helperKey"; answer?: "notNow" };
+ /** A person's line Set me up turned into a setup request: the bot reads it as `/setup <text>`; the chat shows `text`. */
+ setupRequest?: true;
+ /** app rows (kind "app"): bot HTML or an MCP server's UI. `text` is always the readable fallback. */
+ app?: AppPayload;
+ /** user rows sent by an app's ui/message: the app row that sent them. Every client draws "Sent from <title>". */
+ fromApp?: AppFromRef;
+ /** user rows sent with parts of a bot's page the person pointed at in the preview: what each chip said. */
+ pointed?: AppPointedRef[];
+ connector?: ConnectorCardData;
+ secret?: SecretRequestCardData;
+ /** signin rows: the bot asked the person to sign in to a site themselves. */
+ signIn?: SignInRequestCardData;
+ /** One idempotently updated status card for a routine run. */
+ routineRun?: RoutineRunCardData; /** The card a burst shows in its parent chat: first a preview, then its progress. */ burst?: BurstCardData;
+ automation?: AutomationLine;
+ /** Terminal receipt for a bounded multi-bot channel goal. */
+ goalRun?: GroupGoalRunCardData;
+ /** call rows (kind "call"): the finished Live call this row records. */
+ call?: LiveCallRecord;
+ /** activity messages: tool name + outcome. */
+ tool?: WireTool & {
+ clipped?: boolean;
+ /** Words the harness wrote for what the call did, shown in place of `name`; `name` stays the tool's own. */
+ label?: string;
+ /** error rows: the reply came back; only a step the turn ran failed or wasn't allowed. */
+ partial?: boolean;
+ };
+ /** A bot line a "post" webhook wrote: whoever called the webhook chose
+ * its words. On a room line this also carries `from`, so the room renders
+ * the webhook's bot as the speaker. */
+ webhookPost?: boolean;
+ /** user messages sent INTO a running turn (capabilities.queueing). */
+ steered?: boolean;
+ /** user messages a peer bot handed to this thread's RUNNING turn: peer
+ * context folded in mid-turn, never a new request. The text is stored
+ * enveloped exactly as injected. */
+ aside?: boolean;
+ /** A user-role message that arrived through the server's HTTP API
+ * ("api"), or a request a person spoke on a Live call ("call"). */
+ via?: "api" | "call";
+ /** The Live call a "call" line was spoken on (LiveCallState.callId). Set
+ * only on user messages with `via: "call"`; a turn's own messages point
+ * at their request through `requestMessageId` instead. */
+ callId?: string;
+ /** A user line an external interface relayed through the guarded send
+ * route (the Slack worker): nobody typed it in one of this workspace's
+ * clients. A Live call never reads it back as what the caller typed. */
+ relayed?: boolean;
+ /** Which person sent this user message, when the workspace has more than
+ * one. Absent reads as the profile name. */
+ sender?: ResolvedSender;
+ /** Provider turn that produced this message. */
+ turnId?: string; /** A stopped row where several people use the server: who pressed Stop. */ stoppedBy?: ResolvedSender; /** A bot reply: the `itemId` its words streamed under, so a client swaps the streamed text for this message. */ itemId?: string;
+ /** Server-proven originating user message, including supported harness
+ * continuations. Absent means external clients must not infer ownership. */
+ requestMessageId?: string;
+ /** Provider completion outcome, independent of whether it emitted text. */
+ turnSucceeded?: boolean;
+ /** An exact request was stopped; a restart must not revive an old result. */
+ requestCancelled?: boolean;
+ /** Set before execution and cleared only after the request's verified
+ * final turn and dependencies settle. A restart never clears it. */
+ requestPending?: boolean;
+ /** The last assistant text item from a settled provider turn. */
+ turnTerminal?: boolean;
+ turnCompletedAt?: number; savedSteps?: SavedStepsMark;
+ /** screen messages: a frame of the bot's computer (base64 image) */
+ png?: string;
+ mime?: string;
+ at: number;
+ /** the message this one follows; null = thread root. */
+ parentId?: string | null;
+ /** Optional flat reply reference for an inline quote. */
+ replyToId?: string;
+ /** Stable client identity for at-most-once chat POST retries. */
+ sendId?: string;
+ /** Per-send channel behavior. Absent is legacy quick chat. */
+ channelMode?: "chat" | "goal";
+ /** from: which member said this (group threads, and post_to_thread). threadPost: a bot posted this row with post_to_thread; seen once a run has read it. */
+ from?: { botId: string; name: string; color: string }; threadPost?: { deliveryId: string; fromBotId: string; fromThreadId: string; seen?: boolean };
+ /** Set on a room message a bot pushed in with post_to_room. */
+ peerPost?: { unattended?: boolean };
+ /** A room reply whose speaker the decision model picked (an Auto room),
+ * with how sure it was. Absent on every other message; clients that do
+ * not know it ignore it. */
+ routedBy?: { provider: "jev" | "workersai" | "openrouter"; probability: number };
+ /** On a conversational bot's user line: the picker label of the quick model its reply ran on. */
+ quickModel?: string;
+ /** On a "Sent to" hand-off row: the done_when the sender set, redacted, so the chip can show what counts as finished. */
+ doneWhen?: string;
+ /** Set on the user-role line another bot delivered into this bot's own
+ * conversation (coordinate_bots, start_thread). `incident`: the line is a
+ * Team incidents report about that bot's thread
+ * in `threadId`, not its words; `notified`: the person was already buzzed. */
+ peerAsk?: { botId: string; name: string; unattended?: boolean; incident?: { threadId: string; notified?: boolean } };
+ /** One reaction per person (shared/reactions.ts REACTIONS). `by` is "user"
+ * on a workspace one person uses, otherwise that person's opaque key, the
+ * one GET /api/auth/session returns as `reactor`. `name` is attribution
+ * only; `at` is when they chose it. */
+ reactions?: Array<{ emoji: string; by: string; name?: string; at?: number }>;
+ /** user lines a 👍 or 👎 made: the person reacted with this emoji to
+ * `replyToId` instead of typing. Clients show the reaction on that message
+ * and draw no bubble for this line. */
+ reaction?: string;
+ /** comm chips: "Messaged @X", linking to the bot-bot channel. */
+ comm?: { groupId: string; threadId?: string; withBotId: string; withName: string; withColor: string };
+ /** On a Team Cloud, a message passed between people: "told" on the chip in the asking conversation names whose inbox
+ * got it, "reply" on an answer that came back names who answered, "assistant" one their assistant answered for them. */
+ relay?: { kind: "told" | "reply" | "assistant"; email: string; name: string };
+ /** On a Team Cloud, a line in its person's inbox: who it is from and where it came from. */
+ inbox?: InboxItem;
+ /** thread chips: "Opened thread #Title on @X". */
+ threadRef?: { botId: string; threadId: string; title: string };
+ /** A "Sent to" row for work addressed into a room the bot `name` isn't in, so it went to the bot directly. `room`
+ * names that room when this row is not in it. Clients say it in their own words; `tool.name` is the English. */
+ sentDirectly?: { name: string; room?: string };
+ /** A page the bot published to a public link (publish_page), or why it couldn't. `text` carries the link too. */
+ publishedPage?: PublishedPageCard;
+ /** A published Data result, linked to its bot's main viewer. */
+ dataResult?: { botId: string; cardId: string; title: string; kind: "table" | "chart" | "text"; sql?: string };
+ /** user messages: the Data result the person was viewing when they sent
+ * this. `text` stays exactly what they typed. */
+ dataContext?: { cardId: string; draftSql?: string };
+ /** user messages waiting in the steer-queue while the bot is mid-turn. */
+ queued?: boolean;
+ /** steer-queue entry this drained user line came from. */
+ queueId?: string;
+}
+
+export const movesThreadToTop = (message: Pick<WireMessage, "role" | "kind" | "peerAsk" | "turnId" | "turnTerminal">): boolean =>
+ message.role === "user" ? !message.peerAsk : message.kind === "text" && (message.turnTerminal === true || !message.turnId);
+
+export function orderedThreadList<T extends { pinned?: boolean; lastThreadOrderAt?: number; createdAt?: number }>(tasks: readonly T[]): T[] {
+ return tasks
+ .map((task, index) => ({ task, index }))
+ .sort((a, b) => {
+ const pin = Number(b.task.pinned === true) - Number(a.task.pinned === true);
+ if (pin) return pin;
+ const recency = (b.task.lastThreadOrderAt ?? b.task.createdAt ?? 0) - (a.task.lastThreadOrderAt ?? a.task.createdAt ?? 0);
+ if (recency) return recency;
+ return a.index - b.index;
+ })
+ .map((entry) => entry.task);
+}
+
+/** 0 is the "until new activity" sentinel. The event stream never drops an expired snooze, so check the clock too. */
+export const isSnoozed = (task: Pick<WireTask, "snoozedUntil">, now = Date.now()): boolean =>
+ task.snoozedUntil !== undefined && (task.snoozedUntil === 0 || task.snoozedUntil > now);
+
+type OpenThreadCandidate = Pick<WireTask, "routineRunId" | "archivedAt" | "closedBy" | "openedBy" | "snoozedUntil" | "pinned" | "lastThreadOrderAt" | "createdAt">;
+
+/** The top row of the bot's thread list, so deleting the open thread never pulls a hidden one into view. */
+export function nextOpenThread<T extends OpenThreadCandidate>(tasks: readonly T[], now = Date.now()): T | undefined {
+ const own = tasks.filter((task) => !task.routineRunId);
+ const open = own.filter((task) => task.archivedAt === undefined);
+ const listed = open.filter((task) => task.pinned === true || !(task.closedBy || task.openedBy || isSnoozed(task, now)));
+ return [listed, open, own].map((candidates) => orderedThreadList(candidates)[0]).find((task) => task !== undefined);
+}
+
+export interface OptionCardData extends WaitCardField, ComputerAskField, AccessRequestCardField, OutsideWriteCardField, AppSettingCardField {
+ /** The harness asks the owner to let this line of theirs use the lent computer (server/host/lending-lifts.ts). */ lendingLift?: { requestMessageId: string; memoryToken?: string; outside?: true; botOpened?: true; allowedAt?: number };
+ /** calls: one per outbound call the card covers, in subtitle order. */
+ outboundRequest?: { tool: string; app: string | null; calls?: Array<{ app: string | null; label: string }> };
+ /** `revision`: the entry as it applied without a person, so Undo can tell it changed since. */
+ teamMemoryRequest?: { section: string; entryId: string; kind: string; revision?: string };
+ title: string;
+ subtitle: string;
+ /** Fixed `chat.notice.*` words for `subtitle`; the English fallback stays stored in `subtitle`. */
+ summaryCode?: string;
+ summaryParams?: ServerTextParams;
+ options: string[];
+ /** Distinguishes a provider question from an approval after its live run ends. */
+ requestType?: "permission" | "question";
+ answered?: string;
+ /** What was actually answered, when the answer is words rather than a
+ * verdict. */
+ answeredText?: string;
+ dismissed?: boolean;
+ /** Who settled the card, when a person or service answered it. */
+ answeredBy?: CardAnswerer;
+ /** Present when this card is a live provider ask (approval/question). */
+ requestId?: string;
+ /** permission cards: the tool being requested. */
+ tool?: string;
+ /** why this card is waiting: guard, mode, sandbox or delivery error. */
+ held?: string;
+ /** Terminal: no answer came in time, or this proposal went stale while open (revision mismatch or a superseding
+ * request). Nothing can answer it; a fresh proposal is needed, and clients must not offer its options. */
+ expired?: boolean;
+ /** Stop ended the work that asked: nothing can answer it any more. */
+ stopped?: boolean;
+ /** Catalog key for held when it is one of the fixed notes. */
+ heldCode?: string;
+ /** the narrow grant "always allow" remembers for a harness-native card. */
+ allowKey?: string;
+ /** the provider can remember an allow for the rest of its session. */
+ allowSession?: boolean;
+ /** Exact native command offered for an owner/admin to remember. */
+ commandAllowlist?: CommandAllowlistCandidate;
+ /** Local actions never share remembered grants with cloud/tool approvals. */
+ approvalScope?: "local-computer";
+ /** The bot's change applied without a person (a change to the bot itself,
+ * or Full access): clients show a one-line receipt with Undo instead of
+ * the approval box. */
+ autoApplied?: boolean;
+ /** A person undid that change. */
+ undone?: boolean;
+ /** A durable chat-created routine proposal. */
+ routineRequest?: RoutineRequestCardData;
+ /** A webhook trigger a bot made or changed from chat. */
+ webhookRequest?: WebhookRequestCardData;
+ /** An app-event automation a bot made or changed from chat. */
+ appTriggerRequest?: AppTriggerRequestCardData;
+ /** A durable profile-change proposal (propose_profile). */
+ profileRequest?: ProfileRequestCardData;
+ /** A durable default-model proposal (propose_model). */
+ modelRequest?: ModelRequestCardData;
+ teamSetupRequest?: TeamSetupRequest;
+ /** A bot's MCP server change waiting on the person (Ask, Edits or Auto). */
+ mcpRequest?: McpChangeRequest;
+ /** A durable learned-skill proposal. */
+ skillRequest?: SkillRequestCardData;
+ /** A provider's structured question set. */
+ questionRequest?: QuestionRequestCardData;
+ /** The options are the whole answer: clients offer no free-text reply. */
+ fixedOptions?: boolean;
+ quotaSwitch?: QuotaSwitchCardData;
+ /** Asks before a bot uses the person's own computer; what its first call names, for the question in their language. */
+ yourComputer?: { app?: string; site?: string };
+}
+
+/** Kept on the card so the offer survives a restart. `engines` follow the card's options; `messageId` is the
+ * message to resend, `rootId` the failed request's job-runtime root. */
+export interface QuotaSwitchCardData {
+ engines: Array<{ instanceId: string; name: string }>;
+ messageId?: string;
+ rootId?: string;
+}
+
+export interface SecretRequestCardData {
+ /** Fixed allowlisted credential id, never a config path; CUSTOM_SECRET_TARGET: a secret the bot names, kept off Settings. */
+ target: CredentialTargetId | typeof CUSTOM_SECRET_TARGET;
+ label: string;
+ description: string;
+ /** Optional named-key copy for client localization; `description` remains the complete fallback for English and older cards. */
+ descriptionParts?: {
+ baseCode: "secretCard.greenference.description" | "secretCard.modelgo.description" | "secretCard.geminiTts.description";
+ reason: string;
+ bot: string;
+ };
+ placeholder: string;
+ helpUrl: string;
+ /** A custom secret's use: "ref", OpenMausBot's own tools only; "file", the bot's commands; "email", the Email connector, never a bot. */ delivery?: SecretDelivery | "email";
+ /** An email card: the mailbox it is for, when known; off a phone the person can change it on the card. */ address?: string;
+ /** An email card: the incoming server that took the password, once it did, while sending is still being checked. */
+ emailReading?: string;
+ /** An email card for a connected mailbox that can't send: only its outgoing server, from what is known, never a password. */ emailOutgoing?: EmailOutgoingFields;
+ /** A custom secret: the bot's own words on why; `description` adds what the bot may do with it, and helpUrl is empty. */
+ reason?: string;
+ /** A file secret's Local VM target key, when the asking turn ran in one. */
+ vm?: string;
+ /** When a custom secret was saved; its file goes a day later. */
+ savedAt?: number;
+ requestKey: string;
+ phoneOperationId?: string;
+ provided?: boolean;
+ dismissed?: boolean;
+ /** A newer request for the same credential replaced this card; it no
+ * longer offers entry and cannot be provided or dismissed. */
+ superseded?: boolean;
+ resumed?: boolean;
+ error?: string;
+ /** Stop ended the turn this card paused: it offers no entry, and a key
+ * saved afterwards is kept but continues nothing. */
+ stopped?: boolean;
+}
+
+/** A bot asked the person to sign in to a website themselves: they type the
+ * password into the page, or save a login the server fills for the bot. The
+ * bot never sees the password either way. */
+export interface SignInRequestCardData {
+ /** The page to open, an http(s) address. */
+ url: string;
+ /** Its host, the card's headline. */
+ site: string;
+ /** The bot's own words: why it needs the sign-in. */
+ reason?: string;
+ /** Where the login has to happen: the place the asking turn worked in. */
+ place: Surface;
+ done?: boolean;
+ cancelled?: boolean;
+ /** A newer request for the same site in this conversation replaced this
+ * card; it no longer offers Done or Cancel. */
+ superseded?: boolean;
+ /** Answered by saving a login: the site it was saved for (and a sign-in
+ * host on another site the person confirmed), which the bot then fills
+ * with fill_login. */
+ savedLogin?: string;
+ resumed?: boolean;
+ error?: string;
+ /** Stop ended the turn this card paused: it offers no Done or Cancel,
+ * and an answer given afterwards is kept but continues nothing. */
+ stopped?: boolean;
+ /** The person answered in the conversation instead of pressing Done: it
+ * offers no Done or Cancel, and the turn their line started goes on. */
+ answeredInChat?: boolean;
+}
+
+/** The open sign-in request a bot's computer plea stands for, so whichever
+ * panel shows the plea can settle that card. */
+export interface ComputerHelpRef {
+ /** The asking bot: a team computer's plea reaches every member's panel. */
+ botId: string;
+ threadId: string;
+ messageId: string;
+ site: string;
+ place: Surface;
+}
+
+/** Who answers a room message nobody was @mentioned in. `auto` asks the
+ * decision model and falls back to `fallbackBotId` (else the first member)
+ * whenever it is off or unsure. Readers must treat any kind they do not know
+ * as the default lead. */
+export type GroupDefaultResponder =
+ | { kind: "member"; botId: string }
+ | { kind: "everyone" }
+ | { kind: "mentions" }
+ | { kind: "auto"; fallbackBotId?: string };
+
+/** One independent conversation inside a user-created channel. */
+export interface GroupTask {
+ threadId: string;
+ /** Replies in this conversation that have not been read. */
+ unread?: boolean;
+ lastReadMessageId?: string;
+ /** The completed message whose visible history seeded this conversation. */
+ origin?: ForkOrigin;
+ title: string;
+ createdAt: number;
+ pinnedCwd?: string | null;
+ pinnedMessageId?: string;
+ /** The person pinned this channel thread above the update-ordered list. */
+ pinned?: boolean;
+ /** This conversation's own turn limit: whole minutes a turn may go without progress. Absent uses
+ * the global group turn limit. Direct chats do not use this limit. */
+ turnTimeoutMinutes?: number;
+ /** Epoch ms when the person archived this thread; absent while it is in the list. */ archivedAt?: number;
+ /** A card in this thread waits on the person, with no turn running. */ activity?: "waiting-on-you";
+ /** Epoch ms of the newest message, or createdAt when the thread has none. */
+ updatedAt?: number;
+ lastThreadOrderAt?: number;
+ /** The first message already drove a title attempt for this thread, so a
+ * later one does not rename a room the person may have retitled. */
+ titleFromFirstMessage?: true;
+ /** Whether a turn is actively running in this thread. */
+ working?: boolean;
+ /** The member bot currently speaking or generating in this thread, if any. */
+ busyBotId?: string | null;
+}
+
+/** A room as a client may see it: the record plus the computed working flag. */
+export interface WireGroup {
+ /** Computed from the usage ledger, not stored in groups.json. */
+ usage?: GroupThreadUsage | null; /** Transient: the department's Chief of Staff, when this room is without it. Null clears an earlier value. */ chiefAbsent?: { botId: string; name: string } | null;
+ /** transient: each member's context in the active thread, from its last
+ * turn there, and whether its next turn there was asked to start
+ * compacted. */
+ memberContext?: Record<string, { tokens: number; window: number; compactRequested?: true }> | null;
+ id: string;
+ /** The active task's thread. Direct-message channels stay single-threaded. */
+ threadId: string;
+ /** User-created channels have independent tasks, newest first. */
+ tasks?: GroupTask[];
+ name: string;
+ memberIds: string[];
+ defaultResponder: GroupDefaultResponder;
+ /** The room's shared instructions. */
+ bulletin: string;
+ /** Short one-line description shown under the room name; distinct from
+ * the bulletin (long-form instructions) and any member bot's title.
+ * null = explicitly cleared, so a client's shallow merge drops a stale value. */
+ description?: string | null;
+ unread: boolean;
+ /** The newest message on screen the last time the person read this
+ * conversation. The New divider goes after it. */
+ lastReadMessageId?: string;
+ createdAt: number;
+ /** true for auto-created bot-bot channels. */
+ dm?: boolean;
+ /** transient: the member currently running a turn. */
+ busyBotId?: string | null;
+ /** transient: when the busy member's turn started; never persisted. */
+ turnStartedAt?: number;
+ /** the room's shared desk; absent = each member's own default. */
+ cwd?: string;
+ pinnedCwd?: string | null;
+ pinnedMessageId?: string;
+ /** sidebar section heading this room is filed under. */
+ section?: string;
+ /** New user-created rooms start with setup pending. */
+ setupCompletedAt?: number | null;
+ setupSkippedAt?: number | null;
+ /** The narrowest audience this room has ever had: a bot leaving never
+ * widens who may see the transcript. Sent to admins only. */
+ audienceFloor?: BotVisibility;
+ /** True while any member (or hand-off) is mid-turn. Computed at
+ * projection time, never persisted. */
+ working: boolean;
+ /** A direct-message channel's turn limit (minutes without progress). Null on the wire means the
+ * global group limit. Channel conversations store theirs on each task. */
+ turnTimeoutMinutes?: number | null;
+ /** Members the person stopped in this room ("stop @Bot"), by bot id. A
+ * held member gets no turn until it is @mentioned again or resumed. */
+ holds?: Record<string, RoomHold>;
+ /** Room messages addressed to a member while it was held, by bot id;
+ * its next turn is shown them, then they are cleared. */
+ heldMessages?: Record<string, RoomHeldMessage[]>;
+ /** transient: who waits in each of the room's threads, and on whom; absent or empty when nobody waits. */
+ queue?: RoomQueueEntry[];
+}
+
+export interface RoomQueueEntry {
+ botId: string;
+ threadId: string;
+ state: "running" | "queued";
+ /** 1-based place in that thread's line; `of` counts the whole line. */
+ position: number;
+ of: number;
+ /** Who a queued member waits on: the member running now, else the one speaking (or the one ahead). */
+ waitingForBotId?: string;
+ assignmentId?: string;
+}
+
+/** One member's hold in a room: when the person stopped it, and whether the
+ * room has already said so (the held line is written once per hold). */
+export interface RoomHold {
+ at: number;
+ noted?: boolean;
+}
+
+/** A room message that reached a member while it was held. */
+export interface RoomHeldMessage {
+ threadId: string;
+ messageId: string;
+}
+
+/** Why a steer-queue entry waits: a shared thread slot, or the bot's room
+ * turn (which runs one at a time per bot). */
+export type SteerQueueReason = "capacity" | "group-turn";
+
+/** Pending steer-queue chips, as `queuedSteerSnapshot` emits them and the `bot.queued` frame carries them: threadId → queued items. */
+export type BotQueuedMessages = Record<string, Array<{ queueId: string; text: string; reason?: SteerQueueReason; /** The reason in plain words, shown as it is. */ why?: string;
+ /** Team Cloud, where several people write: whose line waits; only they remove it, and it runs after as their own turn. */ sender?: ResolvedSender }>>;
+
+/** Skills library browse surface: one row per library entry, with the bots
+ * currently assigned to it. Version is null for locally imported skills. */
+export interface SkillsLibrarySkillWire {
+ name: string;
+ description: string;
+ source: string;
+ enabled: boolean;
+ everyBot: boolean;
+ tags: string[];
+ version: string | null;
+ importedAt: string;
+ license?: string;
+ compatibility?: string;
+ warnings: string[];
+ assignedBots: Array<{ id: string; name: string }>;
+}
+
+/** PUT body for a bot's assignment list: the full list, applied
+ * idempotently. */
+export interface BotAssignedSkillsWire {
+ skills: string[];
+}
+
+export type ServerFrame =
+ /** Always the first frame of an event stream. `cursor` is `<stream id>:<last seq>`; `resumed`: the frames after the
+ * client's `since` follow, so it keeps what it has; otherwise it loads everything again. */
+ | { kind: "hello"; cursor: string; resumed: boolean }
+ /** From a computer's companion, on a phone's own stream, when where the phone may connect changes. It has no seq. */
+ | ({ kind: "companion.endpoints" } & CompanionEndpointsSnapshot)
+ | { kind: "sections"; sections: string[] }
+ | { kind: "bot.queued"; queues: BotQueuedMessages }
+ | { kind: "message"; threadId: string; message: WireMessage }
+ | { kind: "message.patch"; threadId: string; message: WireMessage }
+ | { kind: "thread"; threadId: string; activeLeafId: string }
+ | { kind: "bot"; bot: WireBot }
+ | { kind: "group"; group: WireGroup }
+ | { kind: "notify"; notification: NotificationLogEntry }
+ | { kind: "notifications.read"; threadId: string; ids: string[] }
+ | { kind: "group.deleted"; groupId: string }
+ | { kind: "routine"; routine: Routine }
+ | { kind: "routine.deleted"; routineId: string }
+ | { kind: "routine.run"; run: RoutineRun }
+ | { kind: "webhook"; webhook: WebhookTrigger }
+ | { kind: "webhook.attempt"; attempt: WebhookAttempt }
+ | { kind: "webhook.deleted"; webhookId: string }
+ | { kind: "app-trigger"; botId: string; trigger: AppTrigger }
+ | { kind: "app-trigger.attempt"; botId: string; attempt: AppEventAttempt }
+ | { kind: "app-trigger.deleted"; triggerId: string }
+ | { kind: "app-trigger.service"; service: AppTriggerService }
+ | { kind: "runtime"; event: RuntimeEvent }
+ /** An MCP server was added, changed or removed: a list of them is stale. */
+ | { kind: "mcp.changed" }
+ /** `surface` names what the frame shows: the bot's desktop (`computer`) or its built-in browser. */
+ | { kind: "screen"; botId: string; threadId: string; png: string; mime?: string; surface?: "browser" | "computer" }
+ /** A bot's computer is being set up or woken for a turn; the chat shows
+ * one progress line until its first screen frame. `place` names a cloud
+ * computer (absent: a Local VM). */
+ | { kind: "computer"; botId: string; state: "provisioning" | "waking"; place?: "cloud" }
+ | { kind: "computer-control"; botId: string; held: boolean; helpReason: string | null; help?: ComputerHelpRef | null }
+ /** A bot's data sheet changed. Whole sheet each time. */
+ | DataBroadcast
+ | { kind: "bot.deleted"; botId: string }
+ /** The whole fleet (PUT /api/bots/order) or every room (PUT /api/groups/order) in its new order; a member is sent only the ones they see. */
+ | { kind: "bots.order"; botIds: string[] } | { kind: "groups.order"; groupIds: string[] } | WindowPrefFrame
+ | { kind: "live.call"; botId: string; threadId: string; call: LiveCallState | null }
+ /** A job is waiting for the phone whose registry key this is; it polls now. */
+ | { kind: "device.job"; phone: string; id: string }
+ /** Who is here on a Team Cloud (shared/team-presence.ts). */
+ | PresenceFrame
+ /** The config status object spread flat into the frame. */
+ | ({ kind: "config" } & Record<string, unknown>);
diff --git a/packages/phone-protocol/tsconfig.json b/packages/phone-protocol/tsconfig.json
new file mode 100644
index 0000000000..0e1163938c
--- /dev/null
+++ b/packages/phone-protocol/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "target": "ES2022",
+ "lib": ["ES2022"],
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "allowImportingTsExtensions": true,
+ "strict": true,
+ "noUnusedLocals": true,
+ "noUnusedParameters": true,
+ "noFallthroughCasesInSwitch": true,
+ "skipLibCheck": true,
+ "isolatedModules": true,
+ "erasableSyntaxOnly": true,
+ "noEmit": true,
+ "types": []
+ },
+ "include": ["src", "portable-globals.d.ts"],
+ "exclude": ["src/**/*.test.ts"]
+}
diff --git a/scripts/ci-scope.mjs b/scripts/ci-scope.mjs
index d7206127c9..714e545137 100644
--- a/scripts/ci-scope.mjs
+++ b/scripts/ci-scope.mjs
@@ -219,7 +219,7 @@ const AREAS = [
[/^src\/locales\/(?:(?!en\.json$)[^/]+\.json|[^/]+\.test\.ts)$/, "locales"],
[/^(?:src|public)\/|^[^/]+-preview\.html$/, "web"],
[/^companion\/src\/e2e\/vectors\//, "e2e-vectors"],
- [/^(?:server|shared|enterprise|companion|evals|skills|deploy|cloudflare\/composio-broker)\/|^(?:Dockerfile|\.dockerignore|compose\.yaml)$/, "server"],
+ [/^(?:server|shared|packages\/phone-protocol|enterprise|companion|evals|skills|deploy|cloudflare\/composio-broker)\/|^(?:Dockerfile|\.dockerignore|compose\.yaml)$/, "server"],
[/^electron\/(?:cua|cua-failure|cua-connection|capabilities|screen-status|shared-cua-connection|shared-computer-access|lent-screen-tools|lent-screen-failures|paced-typing)\.[cm]js$/, "windows-computer-control"],
[/^(?:electron|build)\/|^(?:electron-builder\.yml|index\.html|rail\.html)$/, "desktop"],
[/^cloudflare\/control-plane\//, "control-plane"],
diff --git a/scripts/ci-scope.test.ts b/scripts/ci-scope.test.ts
index 84c412b8b3..4353a46f7f 100644
--- a/scripts/ci-scope.test.ts
+++ b/scripts/ci-scope.test.ts
@@ -535,7 +535,7 @@ describe("the repository's import graph", () => {
const frameSmoke = readFileSync(join(ROOT, "scripts/smoke-app-frames.mjs"), "utf8");
expect(frameSmoke).toContain('resolveDir: join(ROOT, "src/components/app")');
expect(frameSmoke).toContain("from \\\"./app-frame-host.ts\\\"");
- const runtime = ["server", "shared", "electron", "companion", "enterprise", "evals", "cloudflare"]
+ const runtime = ["server", "shared", "packages", "electron", "companion", "enterprise", "evals", "cloudflare"]
.flatMap((directory) => codeFiles(join(ROOT, directory)))
.filter((file) => !TEST_FILE.test(relative(ROOT, file).split("\\").join("/")));
expect(runtime.length).toBeGreaterThan(500);
@@ -546,7 +546,7 @@ describe("the repository's import graph", () => {
});
it("runs every test outside the renderer that reads a translation other than English with the locale tests", () => {
- const files = ["server", "shared", "electron", "companion", "enterprise", "evals", "scripts", "cloudflare"]
+ const files = ["server", "shared", "packages", "electron", "companion", "enterprise", "evals", "scripts", "cloudflare"]
.flatMap((directory) => codeFiles(join(ROOT, directory)))
// The selection names the catalogs without reading them.
.filter((file) => !/[/\\]ci-scope\.(?:mjs|test\.ts)$/.test(file));
@@ -572,7 +572,7 @@ describe("the repository's import graph", () => {
expect(inStatic).toContain("scripts/testing/verification-docs.test.ts");
// A docs path a test reads from the repository root: join(ROOT, "docs", ...), new URL("docs/...", ROOT) or read("docs/...").
const DOCS_READ = /(?:(?:join|resolve)\(\s*ROOT\s*,\s*|new URL\(\s*|\bread\w*\(\s*)["'`]((?:apps\/docs|docs)\b[^"'`]*|[A-Z][A-Z_]+\.md)["'`]/g;
- const readers = ["server", "shared", "electron", "companion", "enterprise", "evals", "scripts", "src", "cloudflare"]
+ const readers = ["server", "shared", "packages", "electron", "companion", "enterprise", "evals", "scripts", "src", "cloudflare"]
.flatMap((directory) => codeFiles(join(ROOT, directory)))
.filter((file) => /\.(?:test|node-test)\.[cm]?[jt]sx?$/.test(file) && !file.endsWith("ci-scope.test.ts"))
.filter((file) => [...readFileSync(file, "utf8").replace(/(["'`])\s*,\s*(["'`])/g, "/").matchAll(DOCS_READ)]
@@ -583,7 +583,7 @@ describe("the repository's import graph", () => {
});
it("never loads a test file from other code, so a test under scripts/ affects only the jobs that run it", () => {
- const code = ["server", "shared", "electron", "companion", "enterprise", "evals", "scripts", "src", "cloudflare"]
+ const code = ["server", "shared", "packages", "electron", "companion", "enterprise", "evals", "scripts", "src", "cloudflare"]
.flatMap((directory) => codeFiles(join(ROOT, directory)));
const loaders = code.filter((file) => imports(file).some((target) => /\.test\.[cm]?[jt]sx?$/.test(target)));
expect(loaders.map((file) => relative(ROOT, file))).toEqual([]);
diff --git a/scripts/gen-carved-bodies.ts b/scripts/gen-carved-bodies.ts
index c98d67f074..b36eb0da13 100644
--- a/scripts/gen-carved-bodies.ts
+++ b/scripts/gen-carved-bodies.ts
@@ -1,5 +1,5 @@
/**
- * Bakes every festival pack into `shared/carved-bodies.ts`. Run with `pnpm gen:carved`.
+ * Bakes every festival pack into `packages/phone-protocol/src/carved-bodies.ts`. Run with `pnpm gen:carved`.
*
* Each pack's drawings live in `scripts/mascot-bodies/<pack>.ts`, in a 240-unit square
* centred on x = 120.
@@ -294,9 +294,9 @@ ${entries.join("\n")}
`
}
-const out = fileURLToPath(new URL("../shared/carved-bodies.ts", import.meta.url))
+const out = fileURLToPath(new URL("../packages/phone-protocol/src/carved-bodies.ts", import.meta.url))
writeFileSync(out, emitTs())
-console.log(`wrote ${BAKED.length} carved bodies to shared/carved-bodies.ts`)
+console.log(`wrote ${BAKED.length} carved bodies to packages/phone-protocol/src/carved-bodies.ts`)
for (const [flag, emitNative] of [["--swift", emitSwift], ["--kotlin", emitKotlin]] as const) {
const at = process.argv.indexOf(flag)
diff --git a/scripts/gen-mascot-bodies.ts b/scripts/gen-mascot-bodies.ts
index 5746d28490..1034894fc0 100644
--- a/scripts/gen-mascot-bodies.ts
+++ b/scripts/gen-mascot-bodies.ts
@@ -1,5 +1,5 @@
/**
- * Bakes the mascot body catalog into `shared/mascot-bodies.ts`. Run with `pnpm gen:bodies`.
+ * Bakes the mascot body catalog into `packages/phone-protocol/src/mascot-bodies.ts`. Run with `pnpm gen:bodies`.
*
* Fails with a non-zero exit if any expression would clip at any body's final anchor at
* any aim: fix the geometry, never the check.
@@ -497,7 +497,7 @@ function main(): void {
)
}
- const out = fileURLToPath(new URL("../shared/mascot-bodies.ts", import.meta.url))
+ const out = fileURLToPath(new URL("../packages/phone-protocol/src/mascot-bodies.ts", import.meta.url))
writeFileSync(out, emit(baked))
console.log(`wrote ${out}`)
diff --git a/scripts/mascot-bodies/carved-bodies.test.mjs b/scripts/mascot-bodies/carved-bodies.test.mjs
index 34c3b6369f..f0e20d1a4f 100644
--- a/scripts/mascot-bodies/carved-bodies.test.mjs
+++ b/scripts/mascot-bodies/carved-bodies.test.mjs
@@ -8,7 +8,7 @@ import { CARVED_BODIES, CARVED_BODY_IDS, DIWALI_BODY_IDS, HALLOWEEN_BODY_IDS } f
import { MASCOT_BODY_IDS } from "../../shared/mascot-bodies.ts";
const root = fileURLToPath(new URL("../../", import.meta.url));
-const CATALOG = new URL("../../shared/carved-bodies.ts", import.meta.url);
+const CATALOG = new URL("../../packages/phone-protocol/src/carved-bodies.ts", import.meta.url);
const read = () => readFileSync(CATALOG, "utf8").replace(/\r\n/g, "\n");
/** Even-odd point-in-path over the flattened outline. */
@@ -35,7 +35,7 @@ describe("carved catalog", () => {
}
const after = read();
writeFileSync(CATALOG, before);
- expect(after === before, "shared/carved-bodies.ts was hand-edited or the generator is non-deterministic").toBe(true);
+ expect(after === before, "packages/phone-protocol/src/carved-bodies.ts was hand-edited or the generator is non-deterministic").toBe(true);
}, 120_000);
it("uses ids that never collide with each other or the gradient catalog", () => {
diff --git a/scripts/mascot-bodies/generated.test.mjs b/scripts/mascot-bodies/generated.test.mjs
index 732ff4f34b..e61b43d743 100644
--- a/scripts/mascot-bodies/generated.test.mjs
+++ b/scripts/mascot-bodies/generated.test.mjs
@@ -16,7 +16,7 @@ const root = fileURLToPath(new URL("../../", import.meta.url));
// Guards the TypeScript catalog the desktop and web apps use. The generator writes
// the native catalogs only when given their paths (`--swift`, `--kotlin`).
-const TS_PATH = "../../shared/mascot-bodies.ts";
+const TS_PATH = "../../packages/phone-protocol/src/mascot-bodies.ts";
// Normalised to LF: a clone whose git config disagrees with .gitattributes must
// fail over generated content, not line endings.
@@ -57,7 +57,7 @@ describe("generated catalogs", () => {
throw new Error(
`Running \`pnpm gen:bodies\` failed while checking the catalogs for drift. ` +
`The working tree may now hold a partially-written or reverted file — run ` +
- `\`git status\` / \`git diff -- shared/mascot-bodies.ts\` ` +
+ `\`git status\` / \`git diff -- packages/phone-protocol/src/mascot-bodies.ts\` ` +
`before trusting either file. Original error:\n${err.stderr?.toString() ?? err.message}`
);
}
@@ -71,7 +71,7 @@ describe("generated catalogs", () => {
write(TS_PATH, before.ts);
const drifts = [
- describeDrift("shared/mascot-bodies.ts", before.ts, after.ts),
+ describeDrift("packages/phone-protocol/src/mascot-bodies.ts", before.ts, after.ts),
].filter(Boolean);
if (drifts.length > 0) {
diff --git a/scripts/testing/comment-history.test.ts b/scripts/testing/comment-history.test.ts
index 17e8afd5dd..8c95d1d9c9 100644
--- a/scripts/testing/comment-history.test.ts
+++ b/scripts/testing/comment-history.test.ts
@@ -8,7 +8,7 @@ const ROOT = new URL("../../", import.meta.url);
const OUR_REF = /(?<![\w./-])(?:(?:PR|issue|pull request)\s+)?#\d{3,5}\b/i;
function sourceFiles(): string[] {
- const out = execFileSync("git", ["ls-files", "server", "shared", "src", "scripts", "evals", "electron", "companion", "cloudflare"], { cwd: ROOT, encoding: "utf8" });
+ const out = execFileSync("git", ["ls-files", "server", "shared", "packages", "src", "scripts", "evals", "electron", "companion", "cloudflare"], { cwd: ROOT, encoding: "utf8" });
return out.split("\n").filter((file) => /\.(ts|tsx|mts|mjs|cjs|js)$/.test(file) && !file.startsWith("electron/vendor/") && !file.endsWith(".d.ts"));
}
diff --git a/scripts/testing/file-size-ratchet.test.ts b/scripts/testing/file-size-ratchet.test.ts
index d3053be942..63c3058c26 100644
--- a/scripts/testing/file-size-ratchet.test.ts
+++ b/scripts/testing/file-size-ratchet.test.ts
@@ -49,7 +49,7 @@ const LINES: Record<string, number> = {
};
function sourceFiles(): string[] {
- const out = execFileSync("git", ["ls-files", "server", "shared", "src", "scripts", "evals", "electron", "companion"], { cwd: ROOT, encoding: "utf8" });
+ const out = execFileSync("git", ["ls-files", "server", "shared", "packages", "src", "scripts", "evals", "electron", "companion"], { cwd: ROOT, encoding: "utf8" });
return out.split("\n").filter((file) => /\.(ts|tsx|mjs|cjs)$/.test(file))
.filter((file) => !file.includes(".test.") && !file.includes("/testing/") && !file.includes("goldens") && !file.startsWith("electron/vendor/"));
}
diff --git a/scripts/testing/lazy-server-modules.test.ts b/scripts/testing/lazy-server-modules.test.ts
index 86a0e1f3a8..333d6b4841 100644
--- a/scripts/testing/lazy-server-modules.test.ts
+++ b/scripts/testing/lazy-server-modules.test.ts
@@ -7,7 +7,7 @@ const ROOT = new URL("../../", import.meta.url);
const FIRST_USE_ONLY = /^\s*import\s+(?!type\b)[^;]*?from\s+["'](tar|undici|@hpke\/core)["']/m;
it("the server loads tar, undici and the phone-secret cipher at first use", () => {
- const files = execFileSync("git", ["ls-files", "server", "shared"], { cwd: ROOT, encoding: "utf8" }).split("\n")
+ const files = execFileSync("git", ["ls-files", "server", "shared", "packages"], { cwd: ROOT, encoding: "utf8" }).split("\n")
.filter((file) => file.endsWith(".ts") && !file.includes(".test.") && !file.includes("/testing/"));
expect(files.filter((file) => FIRST_USE_ONLY.test(readFileSync(new URL(file, ROOT), "utf8")))).toEqual([]);
});
diff --git a/scripts/testing/modelgo-links.test.ts b/scripts/testing/modelgo-links.test.ts
index 9d50d2030c..7bad6d9cbd 100644
--- a/scripts/testing/modelgo-links.test.ts
+++ b/scripts/testing/modelgo-links.test.ts
@@ -20,10 +20,10 @@ describe("links to ModelGo's site", () => {
expect(MODELGO_URL).toBe("https://modelgo.ai/?utm_source=openmausbot&utm_medium=sponsorship&utm_content=app&campaign_id=openmausbot&ad_group_id=app");
});
- it("is the only ModelGo address anywhere in src/ and shared/", () => {
- const found = files("src", "shared").flatMap((file) => mentions(file).map((mention) => [file, mention]));
+ it("is the only ModelGo address anywhere in src/, shared/ and the phone protocol", () => {
+ const found = files("src", "shared", "packages/phone-protocol/src").flatMap((file) => mentions(file).map((mention) => [file, mention]));
expect(found.filter(([, mention]) => mention !== MODELGO_URL)).toEqual([]);
- expect(found.map(([file]) => file)).toEqual(["shared/modelgo.ts"]);
+ expect(found.map(([file]) => file)).toEqual(["packages/phone-protocol/src/modelgo.ts"]);
});
it("is the only link the driver and the secret card offer; the server otherwise names only the API base", () => {
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index 6baf27718c..42cd5b2f75 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -62,7 +62,7 @@ const ROOT = new URL("../../", import.meta.url);
/** The `OMB_` names in the code the server runs, and in what starts it (the desktop app). */
function knownOmbNames(): string[] {
- const files = execFileSync("git", ["ls-files", "server", "shared", "enterprise/server", "electron"], { cwd: ROOT, encoding: "utf8" })
+ const files = execFileSync("git", ["ls-files", "server", "shared", "packages", "enterprise/server", "electron"], { cwd: ROOT, encoding: "utf8" })
.split("\n").filter((file) => /\.(?:ts|mts|mjs|cjs|js)$/.test(file) && !/\.test\.|\/testing\/|node-test/.test(file));
const names = new Set<string>();
for (const file of files) for (const match of readFileSync(new URL(file, ROOT), "utf8").matchAll(/\bOMB_[A-Z0-9_]+\b/g)) names.add(match[0]);
diff --git a/server/environment.ts b/server/environment.ts
index b6227020ae..058761d4a2 100644
--- a/server/environment.ts
+++ b/server/environment.ts
@@ -15,52 +15,10 @@ import { hostname } from "node:os";
import { dirname, join } from "node:path";
import { cliPrefix } from "./cli-invocation.ts";
+import type { EnvironmentDescriptor, ServerInstall } from "../packages/phone-protocol/src/environment.ts";
import { SERVER_ROOT } from "./proxy-paths.ts";
-export interface EnvironmentDescriptor {
- environmentId: string;
- label: string;
- platform: NodeJS.Platform;
- version: string;
- capabilities: {
- /** Pairing and sessions are available (this build). */
- remoteSessions: true;
- /** Only while the maintainer flag `features.sharedComputers` is on; otherwise absent, like a build without the feature. */
- sharedComputers?: true;
- lendingDetails?: true;
- /** A Cloud home with lending on: a lent computer may open the device link and lend its internet connection. */
- deviceLink?: true;
- /** A personal Cloud home with lending on: a lent computer may lend its Chrome to the bots here. Never a team Cloud. */
- myChromeLink?: true;
- /** The same: the app on the person's computer says how it is and hears what the bots here ask of it
- * (POST /api/shared-computers/asks). */
- computerAsks?: true;
- /** A lent computer may say it takes run_command's timeout_seconds; only then does this server send it. */
- commandTimeouts?: true;
- /** A lent computer may say it runs a command for up to 900 seconds; only then does this server ask it for more than 240. */
- longCommands?: true;
- /** A lent computer may say it takes edit_file, append_file and delete_file; only then does this server send them. */
- fileEdits?: true;
- /** A lent computer may say it runs the MCP servers saved here that run on it (mcp_tools, mcp_call). Never a team Cloud. */
- lentMcp?: true;
- /** A person's own OMB Cloud home. */
- cloudHome?: true;
- /** A team's Cloud home: `label` is the team's name. */
- cloudTeam?: true;
- /** A Cloud home, or a server one person owns, that takes the one-time move from that person's computer: by-row chats,
- * the manifest, the chats and credentials checks, and lines its owner wrote there stamped as the owner's. Whether a
- * session is that person, /api/auth/session says (`own`). */
- move?: 1;
- /** Who can update the server: the desktop app that runs it, or the operator. */
- selfUpdate: "desktop-managed" | "operator";
- /** For an operator's server: how it was installed, so a client offers the update command that fits it. */
- install?: ServerInstall;
- /** Whether /pair offers "sign in with your email" (an allow-list is set). */
- emailSignIn?: boolean;
- /** GET /api/threads/:id/job answers, long-polled (the headless CLI needs it). */
- jobs: true;
- };
-}
+export type { EnvironmentDescriptor, ServerInstall };
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
@@ -154,8 +112,6 @@ export function reportableServerVersion(version = serverVersion()): string | und
return RELEASE_VERSION.test(version) ? version : undefined;
}
-export type ServerInstall = "npx" | "global" | "docker" | "source";
-
/** How this server was started: the Docker image (OMB_CLI_PREFIX, or Docker's own /.dockerenv), a checkout, npx, or a
* global install. */
export function serverInstall(env: NodeJS.ProcessEnv = process.env, script = process.argv[1] ?? "", docker = () => existsSync("/.dockerenv")): ServerInstall {
diff --git a/server/index.ts b/server/index.ts
index 51aae5d10d..6f5d35afc4 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -107,7 +107,7 @@ import { createDataRoutes } from "./data/routes.ts";
import { DataSheetRegistry } from "./data/sheet.ts";
import { DataFailure } from "./data/types.ts";
import { TeamComputers, teamComputerOwner, type TeamComputerRecord } from "./team-computers.ts";
-import { isEffortLevel, type CardAnswerer, type ResolvedSender, type SignInRequestCardData, type WireBot, type WireGroup, type WireTask } from "../shared/wire.ts";
+import { isEffortLevel, type AuthPairResponse, type CardAnswerer, type PairResponse, type ResolvedSender, type ServerFrame, type SignInRequestCardData, type WireBot, type WireGroup, type WireTask } from "../shared/wire.ts";
import { isPersistentQuestionCard, shouldSettleRequestCard } from "../shared/ask-question.ts";
import { parseToolScope } from "../shared/tool-scope.ts";
import type { TeamComputersPayload } from "../shared/team-computer.ts";
@@ -12606,7 +12606,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
res.setHeader("set-cookie", serializeSessionCookie(SESSION_COOKIE, result.token, { secure, maxAgeSeconds: cookieMaxAgeSeconds(result.session) }));
return json(res, 200, { session: result.session, environment });
}
- return json(res, 200, { token: result.token, session: result.session, environment });
+ return json(res, 200, { token: result.token, session: result.session, environment } satisfies AuthPairResponse);
}
// The companion apps' pairing route: same window, lockout and single-use exchange as /api/auth/pair; redeeming the credential IS the sign-in.
if (method === "POST" && path === "/api/pair") {
@@ -12634,7 +12634,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
},
serverName: cfg.computerName || environmentDescriptor({ environmentId: ENVIRONMENT_ID, ...TEAM_LABEL, desktopManaged: DESKTOP_MANAGED }).label,
...phoneRelay?.pairedOver(req),
- });
+ } satisfies PairResponse);
}
const gate = resolveRequestAuth(req, {
sessions,
@@ -14669,7 +14669,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {
kind: "hello",
cursor: `${STREAM_ID}:${lastSeq}`,
resumed,
- })}\n\n`,
+ } satisfies ServerFrame)}\n\n`,
);
if (resumed) {
for (const buffered of replayBuffer) {
diff --git a/server/routes/threads.ts b/server/routes/threads.ts
index 2e6a6a9dd5..5603dfc398 100644
--- a/server/routes/threads.ts
+++ b/server/routes/threads.ts
@@ -1,7 +1,7 @@
import { userError } from "../user-errors.ts";
import { basename, join } from "node:path";
-import type { WireBot, WireGroup } from "../../shared/wire.ts";
+import type { BotsResponse, WireBot, WireGroup } from "../../shared/wire.ts";
import { NO_SUCH_BOT } from "../../shared/bot-read.ts";
import {
ATTACHMENTS_DIR, attachmentStorageUsage, clearAttachments, deleteAttachment, extensionForMime, FILE_MAX_BYTES, IMAGE_MAX_BYTES,
@@ -124,7 +124,7 @@ export function createThreadRoutes(deps: ThreadRouteDeps): RouteHandler {
return [bot.id, { held: snapshot.held, helpReason: snapshot.helpReason, ...(snapshot.help ? { help: snapshot.help } : {}) }];
}),
),
- });
+ } satisfies BotsResponse<MessagePage["messages"][number]>);
}
m = path.match(/^\/api\/bots\/([\w-]+)$/);
diff --git a/server/testing/limit-clock-hooks.mjs b/server/testing/limit-clock-hooks.mjs
index 3279083674..471065846d 100644
--- a/server/testing/limit-clock-hooks.mjs
+++ b/server/testing/limit-clock-hooks.mjs
@@ -8,7 +8,7 @@ if (!dataDir || dataDir !== process.env.HOME || process.env.OMB_TEST_LIMIT_CLOCK
throw new Error('The limit clock requires an explicitly isolated fixture');
}
const seams = new Map([
- [new URL('../../shared/limit-reset.ts', import.meta.url).href, ['export const AFTER_RESET_MS = 60_000;', 'export const AFTER_RESET_MS = 1_000;']],
+ [new URL('../../packages/phone-protocol/src/limit-reset.ts', import.meta.url).href, ['export const AFTER_RESET_MS = 60_000;', 'export const AFTER_RESET_MS = 1_000;']],
[new URL('../routines.ts', import.meta.url).href, ['startDueTimer({ run: () => this.tick(),', 'startDueTimer({ retryMs: 250, run: () => this.tick(),']],
]);
registerHooks({
diff --git a/shared/activity.ts b/shared/activity.ts
index 575d5b636a..1f62a7685a 100644
--- a/shared/activity.ts
+++ b/shared/activity.ts
@@ -1,40 +1 @@
-import type { ServerTextParams } from "./server-text.ts";
-// The shape of one line in a bot's activity log, shared by the harness reader
-// and the panel that renders it.
-
-export type ActivityOutcome =
- /** the tool finished and reported success */
- | "ran"
- /** the tool finished and reported failure */
- | "failed"
- /** started, no completion seen yet */
- | "running"
- /** approved, but no matching tool run was found in the thread's events */
- | "allowed"
- /** a person or reviewer said no; nothing ran */
- | "denied"
- /** a card is open and nobody has answered it */
- | "waiting";
-
-export interface ActivityRow {
- /** when it started (a tool) or was asked (a request) */
- at: string;
- threadId: string;
- turnId?: string;
- requestId?: string;
- tool: string;
- /** the connected app or surface it touched, when there is one */
- app: string | null;
- /** the action, in words */
- label: string;
- /** `label` as an `activity.tool.*` catalog key, for a client to say in its own language */
- labelKey?: string;
- /** `app` as an `activity.app.*` catalog key, only for the app's own surfaces (Team, Computer, Research) */
- appKey?: string;
- /** the arguments the decision log recorded, already redacted */
- summary?: string;
- /** Fixed summary words; the English remains authoritative. */
- summaryCode?: string;
- summaryParams?: ServerTextParams;
- outcome: ActivityOutcome;
-}
+export * from "../packages/phone-protocol/src/activity.ts";
diff --git a/shared/agents-tool-names.ts b/shared/agents-tool-names.ts
index 46de64ad2a..47284177d2 100644
--- a/shared/agents-tool-names.ts
+++ b/shared/agents-tool-names.ts
@@ -1,99 +1 @@
-// The agents tools that each do several things, and the name each of their calls goes by: its member name, the name
-// that call has as a tool of its own. A tool selection and the call path read a call by that name, so a selector or a
-// saved skill naming a member means exactly those calls. Security: an engine may remember "always allow" by a tool's
-// name, so a tool never does anything more destructive than each of its members did alone: deleting a trigger is a
-// tool of its own.
-type Args = Record<string, unknown>;
-
-const given = (args: Args, key: string) => args[key] !== undefined && args[key] !== null;
-
-function record(value: unknown): value is Args {
- return value !== null && typeof value === "object" && !Array.isArray(value);
-}
-
-export interface AgentsActionTool {
- /** Every member, the tool's own name first when its plain calls keep it. */
- members: readonly string[];
- member(args: Args): string;
-}
-
-export const AGENTS_ACTION_TOOLS: Readonly<Record<string, AgentsActionTool>> = {
- trigger_info: { members: ["list_triggers", "list_trigger_events"], member: (args) => args.action === "events" ? "list_trigger_events" : "list_triggers" },
- trigger: { members: ["create_trigger", "manage_trigger"], member: (args) => args.action === "create" ? "create_trigger" : "manage_trigger" },
- delete_trigger: { members: ["manage_trigger"], member: () => "manage_trigger" },
- manage_room: { members: ["manage_room", "create_room"], member: (args) => args.action === "create" ? "create_room" : "manage_room" },
- session_search: { members: ["session_search", "session_read"], member: (args) => given(args, "thread_id") || given(args, "message_id") ? "session_read" : "session_search" },
- show_widget: { members: ["show_widget", "update_widget"], member: (args) => given(args, "widget_id") ? "update_widget" : "show_widget" },
- show_html: { members: ["show_html", "update_html"], member: (args) => given(args, "app_id") ? "update_html" : "show_html" },
- x_search: {
- members: ["x_search", "x_user_posts", "x_post", "x_profile"],
- member: (args) => args.action === "user_posts" ? "x_user_posts" : args.action === "post" ? "x_post" : args.action === "profile" ? "x_profile" : "x_search",
- },
-};
-
-/** A member name that is not a listed tool, still answered as a call: an engine session that saw it, a saved skill or
- * memory, or an external runtime may use one. It runs as the call `resolve` gives, to one of `tools`. */
-export interface AgentsAlias {
- tools: readonly string[];
- resolve(args: Args): { name: string; arguments: Args };
-}
-
-const as = (name: string, args: Args) => ({ name, arguments: args });
-/** An id the call must carry to mean an update: empty when it was left out, so the tool refuses rather than creates. */
-const required = (args: Args, key: string): Args => ({ ...args, [key]: args[key] ?? "" });
-
-export const AGENTS_TOOL_ALIASES: Readonly<Record<string, AgentsAlias>> = {
- list_triggers: { tools: ["trigger_info"], resolve: (args) => as("trigger_info", { ...args, action: "list" }) },
- list_trigger_events: { tools: ["trigger_info"], resolve: (args) => as("trigger_info", { ...args, action: "events" }) },
- create_trigger: { tools: ["trigger"], resolve: (args) => as("trigger", { ...args, action: "create" }) },
- manage_trigger: {
- tools: ["trigger", "delete_trigger"],
- resolve: ({ changes, ...args }) => {
- const fields = record(changes) ? changes : {};
- if (args.action === "delete") {
- const { action: _delete, ...target } = args;
- return as("delete_trigger", { ...fields, ...target });
- }
- return as("trigger", { ...fields, ...args, action: args.action === "create" ? undefined : args.action });
- },
- },
- create_room: { tools: ["manage_room"], resolve: (args) => as("manage_room", { ...args, action: "create" }) },
- session_read: { tools: ["session_search"], resolve: (args) => as("session_search", required(required(args, "thread_id"), "message_id")) },
- update_widget: { tools: ["show_widget"], resolve: (args) => as("show_widget", required(args, "widget_id")) },
- update_html: { tools: ["show_html"], resolve: (args) => as("show_html", required(args, "app_id")) },
- x_user_posts: { tools: ["x_search"], resolve: (args) => as("x_search", { ...args, action: "user_posts" }) },
- x_post: { tools: ["x_search"], resolve: (args) => as("x_search", { ...args, action: "post" }) },
- x_profile: { tools: ["x_search"], resolve: (args) => as("x_search", { ...args, action: "profile" }) },
-};
-
-const aliasOf = (name: string) => Object.hasOwn(AGENTS_TOOL_ALIASES, name) ? AGENTS_TOOL_ALIASES[name] : undefined;
-const actionToolOf = (name: string) => Object.hasOwn(AGENTS_ACTION_TOOLS, name) ? AGENTS_ACTION_TOOLS[name] : undefined;
-
-/** The tool a call runs and its arguments: an alias as its action tool's call, any other name as it came. */
-export function resolveAgentsCall(name: string, args: Args): { name: string; arguments: Args } {
- return aliasOf(name)?.resolve(args) ?? { name, arguments: args };
-}
-
-/** The member name a call to `tool` with `args` goes by; the tool's own name when it does one thing. */
-export function agentsCallMember(tool: string, args: unknown): string {
- return actionToolOf(tool)?.member(record(args) ? args : {}) ?? tool;
-}
-
-/** A call's names in a selection: its member name, and its tool's name when that is not itself a member. */
-function named(tool: string, member: string): string[] {
- return actionToolOf(tool)?.members.includes(tool) ? [member] : [tool, member];
-}
-
-/** The names that identify an agents call in a tool selection. With no arguments (a tool being listed), one set per
- * call the name can make. */
-export function agentsCallIdentities(name: string, args?: unknown): string[][] {
- const alias = aliasOf(name);
- if (alias) {
- if (args === undefined) return alias.tools.map((tool) => named(tool, name));
- const call = alias.resolve(record(args) ? args : {});
- return [named(call.name, agentsCallMember(call.name, call.arguments))];
- }
- const tool = actionToolOf(name);
- if (!tool) return [[name]];
- return args === undefined ? tool.members.map((member) => named(name, member)) : [named(name, tool.member(record(args) ? args : {}))];
-}
+export * from "../packages/phone-protocol/src/agents-tool-names.ts";
diff --git a/shared/app-settings.ts b/shared/app-settings.ts
index 1287447a7b..1cc965457d 100644
--- a/shared/app-settings.ts
+++ b/shared/app-settings.ts
@@ -1,86 +1 @@
-// The app_settings tool's wire shapes: a setting's tier (the whole policy), the applied card a change rides on, and the
-// preferences that live in the window's localStorage, which the server reaches through an SSE frame.
-import { z } from "zod";
-
-export type SettingTier = "safe" | "secret" | "owner-only";
-
-/** On a card: display values only, never a key. */
-export interface AppSettingRequest {
- settingId: string;
- label: string;
- before?: string;
- after: string;
- tier: SettingTier;
-}
-export interface AppSettingCardField {
- /** A bot's change to one of the app's own settings, applied with Undo. */
- appSettingRequest?: AppSettingRequest;
-}
-
-export const SKIN_IDS = [
- "midnight",
- "atelier",
- "foundry",
- "lagoon",
- "graphite",
- "linen",
- "dusk",
- "daylight",
- "meadow",
- "pop",
- "halloween",
- "diwali",
- "aurora",
-] as const;
-export const FONT_IDS = ["skin", "system", "inter", "poppins", "serif"] as const;
-export const CHAT_WIDTH_IDS = ["standard", "wide", "full"] as const;
-/** The Enter-adds-a-line modes are for input methods that confirm a conversion with Enter (Japanese). */
-export const SEND_KEYS = ["enter", "shift-enter", "mod-enter"] as const;
-export const PLACE_SWATCHES = ["blue", "green", "amber", "rose", "violet", "slate"] as const;
-export const TALK_KEYS = ["ctrl-opt-space", "ctrl-shift-space", "opt-shift-space"] as const;
-const pinnedPage = z.object({ name: z.string().trim().min(1).max(40), url: z.string().trim().max(2048).regex(/^https?:\/\/\S+$/, "an http(s) address") }).strict();
-
-/** Preferences kept in the window or behind the desktop app's own bridge, by setting id; the renderer applies a frame with
- * the matching setter. */
-export const WINDOW_PREFS = {
- "appearance.skin": z.enum([...SKIN_IDS, "system"]),
- "appearance.advanced": z.boolean(),
- "appearance.font": z.enum(FONT_IDS),
- "appearance.chatWidth": z.enum(CHAT_WIDTH_IDS),
- "general.sendKey": z.enum(SEND_KEYS),
- "general.notificationSounds": z.boolean(),
- "appearance.userBubbles": z.boolean(),
- "appearance.runCard": z.boolean(),
- "appearance.showThreads": z.boolean(),
- "appearance.toolsLayout": z.enum(["rows", "toolbar"]),
- "appearance.pinnedCircles": z.boolean(),
- "appearance.universalPins": z.boolean(),
- "appearance.pinnedPages": z.array(pinnedPage).max(6),
- "appearance.showComputers": z.boolean(),
- "appearance.windowFrame": z.boolean(),
- "appearance.sidebarColor": z.enum([...PLACE_SWATCHES, "none"]),
- "general.followUp": z.enum(["steer", "queue"]),
- "general.finishedNotifications": z.boolean(),
- "general.notificationFeed": z.boolean(),
- "general.analytics": z.boolean(),
- "general.openAtLogin": z.boolean(),
- "general.talkShortcut": z.object({ enabled: z.boolean(), key: z.enum(TALK_KEYS) }).strict(),
- "account.productEmails": z.boolean(),
- "remote.wifi": z.boolean(),
- "remote.relay": z.boolean(),
- "remote.tailscale": z.boolean(),
- "remote.keepAwake": z.boolean(),
-} as const;
-export type WindowPrefId = keyof typeof WINDOW_PREFS;
-export type WindowPrefValue<I extends WindowPrefId> = z.infer<(typeof WINDOW_PREFS)[I]>;
-export const WINDOW_PREF_IDS = Object.keys(WINDOW_PREFS) as WindowPrefId[];
-export const isWindowPrefId = (id: string): id is WindowPrefId => Object.hasOwn(WINDOW_PREFS, id);
-
-export interface WindowPrefFrame {
- kind: "window-pref";
- id: WindowPrefId;
- value: unknown;
-}
-
-/** What the window reports as its current values (PUT /api/window-prefs). */
-export const windowPrefReportSchema = z.object({ values: z.record(z.string(), z.unknown()) }).strict();
+export * from "../packages/phone-protocol/src/app-settings.ts";
diff --git a/shared/app-triggers.ts b/shared/app-triggers.ts
index d4fe680177..d8d9049c24 100644
--- a/shared/app-triggers.ts
+++ b/shared/app-triggers.ts
@@ -1,187 +1 @@
-/** App-event automations: "when something happens in a connected app, a bot does something". Wire shapes for the
- * REST snapshot (`/api/app-triggers`), the `app-trigger*` live frames and the chat card a bot's change leaves. */
-import type { ConnectorToolGrant } from "./wire.ts";
-import type { RoutineRunOn } from "./routines.ts";
-
-/** Plain words a person or bot gives. Gmail turns them into its own search, so other mail never arrives at all; other
- * apps match them, case-insensitively, against the event's fields. */
-export interface AppTriggerFilter {
- from?: string;
- /** The subject (or title) contains this. */
- subject?: string;
- label?: string;
- /** Anywhere in the event. */
- text?: string;
-}
-
-/** "instant": the app pushes each event; "poll": Composio checks on its interval (15 minutes on managed sign-ins). */
-export type AppTriggerDelivery = "instant" | "poll";
-
-export type AppTriggerProblem =
- | { kind: "reconnect"; at: number }
- | { kind: "error"; text: string; at: number };
-
-/** Events Composio sent but the connected-apps service did not keep, today (UTC, as the service counts its limit). */
-export interface AppTriggerSkipped {
- day: string;
- dailyLimit: number;
- queueFull: number;
- expired: number;
- /** Kept back here because this automation already had its limit of waiting runs. */
- tooMany: number;
-}
-
-export interface AppTrigger {
- id: string;
- name: string;
- prompt: string;
- botId: string;
- runOn: RoutineRunOn;
- enabled: boolean;
- /** Composio toolkit slug, e.g. `gmail`. */
- app: string;
- appName: string;
- /** Composio trigger type slug, e.g. `GMAIL_NEW_GMAIL_MESSAGE`. */
- event: string;
- eventName: string;
- delivery: AppTriggerDelivery;
- accountId: string;
- accountLabel?: string;
- /** Composio trigger config, with a Gmail filter already folded into `query`. */
- config: Record<string, unknown>;
- filter?: AppTriggerFilter;
- /** The connected-apps service's copy. `pending` is retried on its own until it holds. */
- remote: { triggerId?: string; state: "active" | "pending" | "error"; error?: string; syncedAt?: number };
- problem?: AppTriggerProblem;
- sourceThreadId?: string;
- /** Each run continues this automation's previous run conversation instead of starting a new one. */
- sameConversation?: boolean;
- /** Events that started a run or joined one. */
- received: number;
- filtered: number;
- skipped?: AppTriggerSkipped;
- lastEventAt?: number;
- lastRunId?: string;
- createdAt: number;
- updatedAt: number;
-}
-
-export type AppEventOutcome = "started" | "joined" | "filtered" | "duplicate" | "skipped" | "rejected";
-
-export interface AppEventAttempt {
- id: string;
- triggerId: string;
- eventId: string;
- at: number;
- outcome: AppEventOutcome;
- reason?: string;
- runId?: string;
- /** One line: who it is from and what it is about, when the event says. */
- preview?: string;
-}
-
-export interface AppTriggerService {
- /** "self-hosted": this server uses its own Composio key, which app events do not support. "off": OMB_COMPOSIO_BROKER=off. */
- available: boolean;
- reason?: "self-hosted" | "unavailable" | "off";
- plan?: "desktop" | "cloud";
- eventsPerDay?: number;
- eventsToday?: number;
-}
-
-export interface AppTriggersSnapshot {
- triggers: AppTrigger[];
- attempts: AppEventAttempt[];
- service: AppTriggerService;
-}
-
-/** One event type a connected app offers, as the picker and `trigger_info` events show it. */
-export interface AppEventType {
- event: string;
- name: string;
- description: string;
- delivery: AppTriggerDelivery;
- configFields: Array<{ name: string; type: string; required: boolean; description?: string; default?: unknown }>;
- filterFields: string[];
-}
-
-export interface AppEventCatalog {
- apps: Array<{ app: string; name: string; accounts: Array<{ id: string; alias?: string }>; events: AppEventType[]; error?: string }>;
- /** Popular apps with events that are not connected yet. */
- notConnected: Array<{ app: string; name: string }>;
- unavailable?: string;
-}
-
-export interface AppTriggerDefinition {
- name: string;
- instructions: string;
- app: string;
- event: string;
- /** Connected account id or alias; needed only when the person has more than one for this app. */
- account?: string;
- filter?: AppTriggerFilter;
- config?: Record<string, unknown>;
- runOn?: RoutineRunOn;
- /** Each run continues the automation's previous run conversation. */
- sameConversation?: boolean;
-}
-
-export type AppTriggerChange = Partial<Pick<AppTriggerDefinition, "name" | "instructions" | "filter" | "config" | "runOn" | "sameConversation">>;
-
-export type AppTriggerRequestOperation =
- | { action: "create"; trigger: AppTriggerDefinition; forBot?: { botId: string; name: string } }
- | { action: "update"; triggerId: string; changes: AppTriggerChange; forBot?: { botId: string; name: string } }
- | { action: "pause" | "resume" | "run_now" | "delete"; triggerId: string; forBot?: { botId: string; name: string } };
-
-/** Durable payload of an app-event automation a bot made or changed from chat: a receipt with what Undo needs. */
-export interface AppTriggerRequestCardData {
- version: 1;
- requestId: string;
- botId: string;
- threadId: string;
- createdAt: number;
- operation: AppTriggerRequestOperation;
- resultId?: string;
- undo?: {
- name: string;
- /** The automation's revision right after the change; Undo refuses once it moved. */
- appliedUpdatedAt?: number;
- before?: { name: string; prompt: string; runOn: RoutineRunOn; enabled: boolean; filter?: AppTriggerFilter; config: Record<string, unknown>; sameConversation?: boolean };
- };
-}
-
-export const APP_FILTER_MAX = 200;
-export const GMAIL_APP = "gmail";
-export const GMAIL_NEW_MESSAGE = "GMAIL_NEW_GMAIL_MESSAGE";
-
-const quoted = (value: string) => {
- const clean = value.replace(/["\\]/g, " ").replace(/\s+/g, " ").trim();
- return /\s/.test(clean) ? `"${clean}"` : clean;
-};
-
-/** Gmail search syntax for a plain filter: from:, subject:, label: and free words, so filtering happens at the source. */
-export function gmailSearchQuery(filter: AppTriggerFilter | undefined): string {
- if (!filter) return "";
- return [
- filter.from && `from:${quoted(filter.from)}`,
- filter.subject && `subject:(${filter.subject.replace(/[()\\]/g, " ").replace(/\s+/g, " ").trim()})`,
- filter.label && `label:${quoted(filter.label).replace(/\s+/g, "-")}`,
- filter.text && quoted(filter.text),
- ].filter(Boolean).join(" ");
-}
-
-/** Whether Composio filters this app's events itself from the plain filter (its config), or OpenMausBot does on arrival. */
-export function filtersAtSource(app: string): boolean {
- return app === GMAIL_APP;
-}
-
-/** A bot may watch an app its connected-app settings let it use: the same grants and scopes its tool calls meet. */
-export function botMayWatchApp(
- bot: { composio?: boolean; connectorTools?: Record<string, ConnectorToolGrant>; connectorScopes?: { apps: Record<string, "read" | "write"> } },
- app: string,
-): boolean {
- if (bot.composio === false) return false;
- if (bot.connectorTools !== undefined && !Object.hasOwn(bot.connectorTools, app)) return false;
- if (bot.connectorScopes !== undefined && !Object.hasOwn(bot.connectorScopes.apps, app)) return false;
- return true;
-}
+export * from "../packages/phone-protocol/src/app-triggers.ts";
diff --git a/shared/app.ts b/shared/app.ts
index b16e4c0a5c..bec8086bbd 100644
--- a/shared/app.ts
+++ b/shared/app.ts
@@ -1,418 +1 @@
-// Chat apps: HTML in a sandboxed frame inside a chat row, speaking the MCP Apps bridge
-// (io.modelcontextprotocol/ui, SEP-1865). Bot HTML (show_html) and an MCP server's UI
-// (_meta.ui.resourceUri) share the one wire kind, `app`.
-
-export const APP_MIME = "text/html;profile=mcp-app";
-export const APP_PROTOCOL_VERSION = "2026-01-26";
-export const APP_EXTENSION_KEY = "io.modelcontextprotocol/ui";
-
-export const APP_LIMITS = {
- /** show_html `html` or `jsx`, UTF-8 bytes after trimming. */
- htmlBytes: 256 * 1024,
- title: 80,
- fallback: 1_500,
- fallbackExcerpt: 600,
- heightMin: 80,
- heightMax: 720,
- /** ui/message text, and the appMessage on the send route. */
- messageText: 4_000,
- /** ui/update-model-context text, stored per row. */
- contextText: 4_000,
- /** The result line of an app row's "Done" note. */
- doneText: 300,
- /** An MCP server's UI resource, decoded. */
- mcpHtmlBytes: 2 * 1024 * 1024,
- /** tools/call arguments on the rpc route. */
- rpcArgumentsBytes: 64 * 1024,
- /** resources/read through the rpc route. */
- rpcResourceBytes: 8 * 1024 * 1024,
- /** appMessage sends per app row per hour. */
- messagesPerHour: 20,
- /** rpc calls per app row per minute. */
- rpcPerMinute: 60,
-} as const;
-
-/** Versions of one bot page kept for stepping back, the current one included. */
-export const APP_PAGE_VERSIONS = 10;
-
-export type AppSource = "html" | "mcp";
-
-/** Origins a frame may reach, after the host's filter. `refused`: what a server asked for and the
- * filter dropped. */
-export interface AppNetwork {
- connect: string[];
- resources: string[];
- refused?: string[];
-}
-
-/** The latest ui/update-model-context of one app row, delivered with the person's next message in
- * its thread. */
-export interface AppContextState {
- text: string;
- at: number;
- delivered: boolean;
-}
-
-/** The last change an MCP app made from its own card: a tool the bot could call too, not read-only, that did
- * not fail. Shown under the card, so a reopened conversation does not look as if it was never sent. */
-export interface AppDoneState {
- /** the tool's title, else its name */
- tool: string;
- /** the result's plain text, one line */
- text?: string;
- /** an https link the result names (html_url, else url) */
- url?: string;
- at: number;
-}
-
-export interface AppMcpRef {
- /** the mount name in config.json mcpServers */
- server: string;
- /** initialize serverInfo.title ?? name */
- serverTitle?: string;
- tool: string;
- /** ui://... */
- resourceUri: string;
- isError?: boolean;
-}
-
-/** Never carries the HTML: a client fetches the AppDocument when it mounts the frame. */
-export interface AppPayload {
- v: 1;
- source: AppSource;
- /** Header title, one line, ≤ 80 chars. Bot HTML: the bot's title. MCP:
- * the tool's title, else its name. */
- title: string;
- /** Content id of the stored document; a new value means the frame must reload. Empty when nothing
- * could be stored (`blocked`): the row then shows only its text. */
- doc: string;
- /** 0, bumped each time show_html replaces the page. */
- rev: number;
- /** Content ids of the versions before `doc`, oldest first, at most APP_PAGE_VERSIONS - 1: the last one is
- * rev - 1. */
- history?: string[];
- /** Bot HTML whose document is a React component file (show_html `jsx`), wrapped in the page shell when served. */
- format?: "jsx";
- /** UTF-8 bytes of the HTML, for the info popover. */
- bytes: number;
- /** Initial height in px before the frame reports its own (show_html
- * `height`, clamped 80..720). */
- height?: number;
- /** Draw the host's border and background (MCP prefersBorder; bot HTML: true). */
- border: boolean;
- /** Origins the frame may reach, after the host's filter, for the info popover. */
- network: AppNetwork;
- mcp?: AppMcpRef;
- /** The latest ui/update-model-context, delivered with the person's next
- * message in this thread. */
- context?: AppContextState;
- done?: AppDoneState;
- /** Why the document could not be stored or read when the row was written
- * (`too-large`, or an MCP server that was signed out or unreachable). The
- * row is still written, with its text. */
- blocked?: AppBlockedReason;
- /** A page from a folder that reloads in place when a file in its folder changes (show_html `live`). */
- live?: true;
-}
-
-/** A user row an app's ui/message sent. */
-export interface AppFromRef {
- messageId: string;
- title: string;
-}
-
-/** One part of a bot's page the person pointed at, as its chip on their message reads. `label` is the page's own
- * words. */
-export interface AppPointedRef {
- appId: string;
- label: string;
-}
-
-/** Why an app's server calls are off, or why its document is missing. `unavailable`: the UI resource
- * could not be read when the row was written (offline, wrong mime type). */
-export type AppBlockedReason = "signed-out" | "server-removed" | "server-disabled" | "apps-off" | "too-large" | "unavailable";
-
-/** What the frame may do right now; hostCapabilities is built from this. */
-export interface AppCan {
- serverTools: boolean;
- serverResources: boolean;
- message: boolean;
- openLinks: boolean;
- modelContext: boolean;
-}
-
-export interface AppToolDefinition {
- name: string;
- title?: string;
- description?: string;
- inputSchema?: object;
- annotations?: object;
- _meta?: object;
-}
-
-export interface AppToolResult {
- content: unknown[];
- structuredContent?: unknown;
- _meta?: Record<string, unknown>;
- isError?: boolean;
-}
-
-/** What a client fetches to mount a frame (GET /api/threads/:threadId/messages/:messageId/app), never
- * part of a thread load. A document with `tool` is an MCP app; one without is bot HTML. */
-export interface AppDocument {
- v: 1;
- messageId: string;
- rev: number;
- /** Set verbatim as the iframe's srcdoc. Starts with
- * `<!DOCTYPE html><meta http-equiv="Content-Security-Policy" content="…">`. */
- srcdoc: string;
- /** The policy in that meta, repeated for phone network enforcement. */
- csp: string;
- network: { connect: string[]; resources: string[] };
- /** MCP only: hostContext.toolInfo.tool, and the two notifications. */
- tool?: AppToolDefinition;
- toolInput?: Record<string, unknown>;
- toolResult?: AppToolResult;
- can: AppCan;
- /** Why serverTools/serverResources are off: drawn as a strip under the frame. */
- blocked?: { reason: AppBlockedReason; text: string };
- /** Shown in a room, to everyone who can see it: view-only. `can` has message, modelContext, serverTools and
- * serverResources off, and a bot's page reads `mausbot.room === true`. */
- room?: true;
-}
-
-/** Why a room refuses what an app or a widget would do for the person: nobody in a room speaks for the others. */
-export const ROOM_VIEW_ONLY = "In a room, pages, apps and widgets are view-only: they cannot send messages or tell a bot what anyone sees.";
-
-/** Exactly one of `html` (wrapped when it was a fragment), `jsx` and `path` (a folder with index.html, or an .html
- * file, in the bot's own folders), none yet scrubbed of secrets. */
-export interface ShowHtmlInput {
- html?: string;
- jsx?: string;
- path?: string;
- title: string;
- height?: number;
- fallbackText?: string;
- /** Show the page without the card frame (still in its sandboxed frame). */
- frameless?: boolean;
- /** Reload the page in place whenever a file in its folder changes; only with `path`. */
- live?: boolean;
-}
-
-export interface UpdateHtmlInput {
- appId: string;
- html?: string;
- jsx?: string;
- path?: string;
- title?: string;
- /** Change whether the page has the card frame; kept as it was when omitted. */
- frameless?: boolean;
- /** Turn reloading on folder changes on (only with `path`) or off; kept as it was when omitted. */
- live?: boolean;
-}
-
-export type AppInputResult<T> = { ok: true; value: T } | { ok: false; error: string };
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
-}
-
-export function utf8Bytes(text: string): number {
- let bytes = 0;
- for (let index = 0; index < text.length; index += 1) {
- const code = text.charCodeAt(index);
- if (code < 0x80) bytes += 1;
- else if (code < 0x800) bytes += 2;
- else if (code >= 0xd800 && code <= 0xdbff && index + 1 < text.length) {
- const next = text.charCodeAt(index + 1);
- if (next >= 0xdc00 && next <= 0xdfff) { bytes += 4; index += 1; } else bytes += 3;
- } else bytes += 3;
- }
- return bytes;
-}
-
-export function oneLine(text: string): string {
- return text.replace(/\s+/g, " ").trim();
-}
-
-/** A fragment gets a minimal document, so the CSP meta can lead its head. */
-export function wrapHtmlFragment(html: string): string {
- if (/<(?:html|body)[\s>/]/i.test(html) || /<(?:html|body)$/i.test(html)) return html;
- return `<!DOCTYPE html><html><head><meta charset="utf-8"></head><body>${html}</body></html>`;
-}
-
-function checkHtml(value: unknown): AppInputResult<string> {
- if (typeof value !== "string") return { ok: false, error: "html: must be a string holding one HTML document." };
- const html = value.trim();
- if (!html) return { ok: false, error: "html: is empty; send one HTML document with inline style and script." };
- const bytes = utf8Bytes(html);
- if (bytes > APP_LIMITS.htmlBytes) {
- return { ok: false, error: `html: is ${bytes} bytes, over the ${APP_LIMITS.htmlBytes}-byte limit; load libraries from a CDN and embed less data.` };
- }
- return { ok: true, value: wrapHtmlFragment(html) };
-}
-
-function checkJsx(value: unknown): AppInputResult<string> {
- if (typeof value !== "string") return { ok: false, error: "jsx: must be a string holding one React component file." };
- const jsx = value.trim();
- if (!jsx) return { ok: false, error: "jsx: is empty; send one React component file with a default export." };
- const bytes = utf8Bytes(jsx);
- if (bytes > APP_LIMITS.htmlBytes) return { ok: false, error: `jsx: is ${bytes} bytes, over the ${APP_LIMITS.htmlBytes}-byte limit; embed less data.` };
- if (!/\bexport\s+default\b/.test(jsx)) return { ok: false, error: "jsx: needs `export default` of the page's component." };
- return { ok: true, value: jsx };
-}
-
-function checkPage(input: Record<string, unknown>): AppInputResult<{ html: string } | { jsx: string } | { path: string }> {
- const given = (value: unknown) => value !== undefined && value !== null;
- if ([input.html, input.jsx, input.path].filter(given).length > 1) return { ok: false, error: "Send one of html, jsx or path." };
- if (given(input.path)) {
- const path = typeof input.path === "string" ? input.path.trim() : "";
- if (!path || path.length > 4_096) return { ok: false, error: "path: the folder with index.html, or the .html file, in your working folder." };
- return { ok: true, value: { path } };
- }
- if (given(input.jsx)) {
- const jsx = checkJsx(input.jsx);
- return jsx.ok ? { ok: true, value: { jsx: jsx.value } } : jsx;
- }
- const html = checkHtml(input.html);
- return html.ok ? { ok: true, value: { html: html.value } } : html;
-}
-
-function checkTitle(value: unknown): AppInputResult<string> {
- if (typeof value !== "string") return { ok: false, error: "title: must be a string of 1 to 80 characters." };
- const title = oneLine(value);
- if (!title || title.length > APP_LIMITS.title) return { ok: false, error: "title: must be 1 to 80 characters on one line." };
- return { ok: true, value: title };
-}
-
-function checkFrameless(value: unknown): AppInputResult<boolean | undefined> {
- if (value === undefined || value === null) return { ok: true, value: undefined };
- if (typeof value !== "boolean") return { ok: false, error: "frameless: must be true or false." };
- return { ok: true, value };
-}
-
-function checkLive(value: unknown, path: string | undefined): AppInputResult<boolean | undefined> {
- if (value === undefined || value === null) return { ok: true, value: undefined };
- if (typeof value !== "boolean") return { ok: false, error: "live: must be true or false." };
- if (value && path === undefined) return { ok: false, error: "live: only a page from a folder (path) can be live." };
- return { ok: true, value };
-}
-
-export function parseShowHtmlInput(input: unknown): AppInputResult<ShowHtmlInput> {
- if (!isRecord(input)) return { ok: false, error: "show_html needs {html, jsx or path, title, height?, fallback_text?}." };
- const page = checkPage(input);
- if (!page.ok) return page;
- const title = checkTitle(input.title);
- if (!title.ok) return title;
- const out: ShowHtmlInput = { ...page.value, title: title.value };
- const frameless = checkFrameless(input.frameless);
- if (!frameless.ok) return frameless;
- if (frameless.value) out.frameless = true;
- const live = checkLive(input.live, out.path);
- if (!live.ok) return live;
- if (live.value) out.live = true;
- if (input.height !== undefined && input.height !== null) {
- if (typeof input.height !== "number" || !Number.isFinite(input.height)) return { ok: false, error: "height: must be a number of pixels, 80 to 720." };
- out.height = Math.round(Math.min(APP_LIMITS.heightMax, Math.max(APP_LIMITS.heightMin, input.height)));
- }
- if (input.fallback_text !== undefined && input.fallback_text !== null) {
- if (typeof input.fallback_text !== "string") return { ok: false, error: "fallback_text: must be a string." };
- const fallback = input.fallback_text.trim();
- if (fallback.length > APP_LIMITS.fallback) return { ok: false, error: `fallback_text: must be at most ${APP_LIMITS.fallback} characters.` };
- if (fallback) out.fallbackText = fallback;
- }
- return { ok: true, value: out };
-}
-
-export function parseUpdateHtmlInput(input: unknown): AppInputResult<UpdateHtmlInput> {
- if (!isRecord(input)) return { ok: false, error: "Replacing a page needs {app_id, html, jsx or path, title?}." };
- if (typeof input.app_id !== "string" || !/^[\w-]{1,128}$/.test(input.app_id.trim())) {
- return { ok: false, error: "app_id: is required, the id show_html returned." };
- }
- const page = checkPage(input);
- if (!page.ok) return page;
- const out: UpdateHtmlInput = { appId: input.app_id.trim(), ...page.value };
- const frameless = checkFrameless(input.frameless);
- if (!frameless.ok) return frameless;
- if (frameless.value !== undefined) out.frameless = frameless.value;
- const live = checkLive(input.live, out.path);
- if (!live.ok) return live;
- if (live.value !== undefined) out.live = live.value;
- if (input.title !== undefined && input.title !== null) {
- const title = checkTitle(input.title);
- if (!title.ok) return title;
- out.title = title.value;
- }
- return { ok: true, value: out };
-}
-
-const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: "\"", apos: "'", nbsp: " ", "#39": "'" };
-
-/** A preview, not a parser or a sanitizer: it only ever feeds the row's readable fallback. */
-export function htmlVisibleText(html: string): string {
- return html
- .replace(/<!--[\s\S]*?(?:-->|$)/g, " ")
- .replace(/<(script|style|template|noscript|title|head)\b[\s\S]*?(?:<\/\1\s*>|$)/gi, " ")
- .replace(/<[^>]*>?/g, " ")
- .replace(/&(#\d+|#x[\da-f]+|[a-z]+\d*);/gi, (whole, name: string) => {
- const lower = name.toLowerCase();
- if (ENTITIES[lower] !== undefined) return ENTITIES[lower]!;
- const code = lower.startsWith("#x") ? Number.parseInt(lower.slice(2), 16) : lower.startsWith("#") ? Number.parseInt(lower.slice(1), 10) : NaN;
- return Number.isFinite(code) && code > 0 && code <= 0x10ffff && (code < 0xd800 || code > 0xdfff) ? String.fromCodePoint(code) : whole;
- })
- .replace(/\s+/g, " ")
- .trim();
-}
-
-function clip(text: string, limit: number): string {
- return text.length <= limit ? text : `${text.slice(0, limit - 1).trimEnd()}…`;
-}
-
-export function htmlFallbackText(title: string, html: string, fallbackText?: string): string {
- const given = fallbackText?.trim();
- if (given) return clip(given, APP_LIMITS.fallback);
- const visible = clip(htmlVisibleText(html), APP_LIMITS.fallbackExcerpt);
- return clip(visible ? `[App] ${title}\n${visible}` : `[App] ${title}`, APP_LIMITS.fallback);
-}
-
-export function mcpAppFallbackText(serverTitle: string, toolTitle: string, result: { content?: unknown } | undefined): string {
- const texts = Array.isArray(result?.content)
- ? result.content.flatMap((block) => (isRecord(block) && block.type === "text" && typeof block.text === "string" ? [block.text] : []))
- : [];
- const excerpt = clip(oneLine(texts.join(" ")), APP_LIMITS.fallbackExcerpt);
- const head = `${oneLine(serverTitle)} · ${oneLine(toolTitle)}`;
- return clip(excerpt ? `${head}\n${excerpt}` : head, APP_LIMITS.fallback);
-}
-
-const httpsLink = (value: unknown): string | undefined =>
- typeof value === "string" && value.length <= 2_048 && /^https:\/\/[^\s"'<>]+$/.test(value) ? value : undefined;
-const namedLink = (value: unknown): string | undefined => (isRecord(value) ? httpsLink(value.html_url) ?? httpsLink(value.url) : undefined);
-
-/** A JSON text block gives only its link; plain text gives the note's line and, failing a named link, its first
- * https link. */
-export function appDoneOf(tool: string, result: { content?: unknown; structuredContent?: unknown }, at: number): AppDoneState {
- let url = namedLink(result.structuredContent);
- let text: string | undefined;
- for (const block of Array.isArray(result.content) ? result.content : []) {
- if (!isRecord(block) || block.type !== "text" || typeof block.text !== "string") continue;
- const raw = block.text.trim();
- let parsed: unknown;
- try { parsed = /^[{[]/.test(raw) ? JSON.parse(raw) : undefined; } catch { parsed = undefined; }
- if (parsed !== undefined) { url ??= namedLink(parsed); continue; }
- url ??= httpsLink(/https:\/\/[^\s"'<>)\]]+/.exec(raw)?.[0]);
- text ??= clip(oneLine(raw), APP_LIMITS.doneText) || undefined;
- }
- return { tool, ...(text ? { text } : {}), ...(url ? { url } : {}), at };
-}
-
-export function appBlockedText(reason: AppBlockedReason, server?: string): string {
- const name = server?.trim() || "This app's server";
- switch (reason) {
- case "signed-out": return `Sign in to ${name} again`;
- case "server-removed": return `${name} is no longer connected`;
- case "server-disabled": return `${name} is switched off in Settings`;
- case "apps-off": return `Apps from ${name} are switched off in Settings`;
- case "too-large": return "This app is too large to store";
- case "unavailable": return `${name} did not send this app's page`;
- }
-}
+export * from "../packages/phone-protocol/src/app.ts";
diff --git a/shared/approval-mode.ts b/shared/approval-mode.ts
index 029ad4e3c6..ebfeb34910 100644
--- a/shared/approval-mode.ts
+++ b/shared/approval-mode.ts
@@ -1,112 +1 @@
-/** The approval levels exposed by the app. Each one is a provider's own
- * permission mode, passed through: OpenMausBot never decides a permission
- * itself (Full access aside, which answers residual prompts because that is
- * what the person granted). The order is the order the selector shows. */
-export const APPROVAL_MODES = ["ask", "edits", "auto", "full", "custom"] as const;
-
-export type ApprovalMode = (typeof APPROVAL_MODES)[number];
-
-/** Whether work at `level` lets nothing through that `limit` would stop; "custom" is comparable only to itself. */
-export const levelWithin = (level: ApprovalMode, limit: ApprovalMode): boolean =>
- level === limit || (level !== "custom" && limit !== "custom" && APPROVAL_MODES.indexOf(level) < APPROVAL_MODES.indexOf(limit));
-
-/** Only providers with an implemented permission mapping may expose a level.
- * `edits` (auto-accept edits) exists where the engine has such a mode:
- * Claude and Grok `acceptEdits`, Antigravity `auto_edit`, Qwen `auto-edit`,
- * Gemini `auto_edit`. Codex's Ask already runs `workspace-write`, so an edits
- * level would change nothing there. Full access, the default level, runs on
- * every engine: in the engine's own most permissive mode, or, where it has
- * none, with the harness answering the permission requests it leaves (the
- * chat-completions family, ACP agents such as Kimi or Hermes, Pi's computer
- * confirms). */
-export function supportsApprovalMode(driverKind: string | undefined, mode: ApprovalMode): boolean {
- if (mode === "custom") return driverKind === "codex";
- if (mode === "edits") return ["claudeAgent", "grokAgent", "antigravityAgent", "qwenAgent", "geminiAgent"].includes(driverKind ?? "");
- return true;
-}
-
-/** Whether switching engines must first drop this level to Ask. A Custom
- * grant's rules belong to one provider's tool semantics, so it never crosses
- * engines; Full carries silently to any engine; Auto-accept edits stops at an
- * engine without it.
- * Adapted from tahodev's provider-switch guard. */
-export function modelSwitchNeedsAsk(
- mode: ApprovalMode,
- fromDriver: string | undefined,
- toDriver: string | undefined,
-): boolean {
- return !supportsApprovalMode(toDriver, mode) || (mode === "custom" && fromDriver !== toDriver);
-}
-
-export function hasNativeAutoReview(driverKind: string | undefined): boolean {
- // Qwen Code's `--approval-mode auto` is an LLM classifier that approves
- // safe actions and blocks risky ones — a reviewer, not a rubber stamp.
- return ["codex", "claudeAgent", "cursorAgent", "grokAgent", "qwenAgent"].includes(driverKind ?? "");
-}
-
-const APPROVAL_RANK: Record<ApprovalMode, number> = { ask: 0, edits: 1, auto: 2, full: 3, custom: 4 };
-
-export interface ApprovalFields {
- approvalMode?: ApprovalMode;
- autoApprove?: boolean;
- alwaysAllow?: string[];
-}
-
-export function threadApproval(thread: ApprovalFields, bot: ApprovalFields): ApprovalFields {
- return {
- approvalMode: thread.approvalMode ?? (thread.autoApprove === undefined ? bot.approvalMode : undefined),
- autoApprove: thread.autoApprove ?? bot.autoApprove,
- alwaysAllow: structuredClone(thread.alwaysAllow ?? bot.alwaysAllow),
- };
-}
-
-export function approvalModeWidens(from: ApprovalMode, to: ApprovalMode): boolean {
- return APPROVAL_RANK[to] > APPROVAL_RANK[from];
-}
-
-export function isApprovalMode(value: unknown): value is ApprovalMode {
- return typeof value === "string" && (APPROVAL_MODES as readonly string[]).includes(value);
-}
-
-/** The level a bot or conversation runs at until a person picks one: Full
- * access, as in t3code (its DEFAULT_RUNTIME_MODE). Each provider maps it to
- * its own most permissive mode; a real question or a missing credential
- * still reaches a person. */
-export const DEFAULT_APPROVAL_MODE: ApprovalMode = "full";
-
-let defaultApprovalMode: ApprovalMode = DEFAULT_APPROVAL_MODE;
-
-/** On a shared company workspace Full access comes only from the operator's
- * own policy, so its server makes Ask the default once, at startup. */
-export function setDefaultApprovalMode(mode: ApprovalMode): void {
- defaultApprovalMode = mode;
-}
-
-/** An unset level runs at the default, the pre-approvalMode Auto bit reads as
- * safe Auto, and an unknown persisted value fails closed to Ask. */
-export function approvalModeFor(bot: {
- approvalMode?: unknown;
- autoApprove?: unknown;
- /** Server-only two-phase grant marker. Until Electron confirms it, the
- * stored elevated selection is deliberately executable only as Ask. */
- approvalGrant?: unknown;
- threadId?: string;
-}): ApprovalMode {
- const grant = bot.approvalGrant;
- const otherThread = grant && typeof grant === "object" && "threadOnly" in grant && grant.threadOnly === true &&
- "threadId" in grant && typeof grant.threadId === "string" && typeof bot.threadId === "string" && grant.threadId !== bot.threadId;
- if (grant && !otherThread) return "ask";
- if (isApprovalMode(bot.approvalMode)) return bot.approvalMode;
- if (bot.autoApprove === true) return "auto";
- return bot.approvalMode === undefined ? defaultApprovalMode : "ask";
-}
-
-/** A private late-grant recovery may revoke an elevated mode even after a
- * turn began. It can only move to the fail-closed Ask mode, and it also stops
- * the running turn, which a native engine would otherwise finish elevated. */
-export function isEmergencyApprovalDowngrade(
- current: ApprovalMode,
- next: ApprovalMode,
-): boolean {
- return next === "ask" && (current === "full" || current === "custom");
-}
+export * from "../packages/phone-protocol/src/approval-mode.ts";
diff --git a/shared/ask-question.ts b/shared/ask-question.ts
index a767596187..76e80522e7 100644
--- a/shared/ask-question.ts
+++ b/shared/ask-question.ts
@@ -1,400 +1 @@
-/**
- * Structured questions from a provider's own "ask the human" tool, Claude
- * Code's `AskUserQuestion`. The CLI routes it through --permission-prompt-tool
- * like any tool use, so it is re-read here into the questions posed. The
- * payload is bot-authored: validated rather than cast, and capped.
- */
-
-export const ASK_USER_QUESTION_TOOL = "AskUserQuestion";
-export const QUESTION_DISMISS_MESSAGE = "The user closed this question without answering. Use your best judgment and continue.";
-
-/** Claude Code's own limits are 1-4 questions and 2-4 options; these leave
- * room for a provider that widens them. */
-export const MAX_QUESTIONS = 6;
-export const MAX_OPTIONS = 12;
-export const MAX_QUESTION_TEXT = 8_000;
-const MAX_LABEL = 120;
-const MAX_DESCRIPTION = 400;
-export const MAX_CUSTOM_ANSWER = 2000;
-
-export interface AskQuestionOption {
- label: string;
- description?: string;
-}
-
-export interface AskQuestion {
- question: string;
- /** Short tab label the model gives each question ("Schedule", "Model"). */
- header?: string;
- multiSelect?: boolean;
- options: AskQuestionOption[];
- /** false when the provider can only take an option back (an ACP
- * permission-style question answers with an option id): no free text. */
- custom?: false;
-}
-
-export interface QuestionRequestCardData {
- version: 1;
- questions: AskQuestion[];
- /** "tool" (or absent): a real tool call; "output": a block parsed from
- * model-authored output. Only drives the agent-composed badge. */
- origin?: "tool" | "output";
-}
-
-/** Excludes the other durable proposal card kinds that share requestId. */
-export function isPersistentQuestionCard(card?: {
- requestType?: "permission" | "question";
- questionRequest?: unknown;
- tool?: string;
- routineRequest?: unknown;
- skillRequest?: unknown;
- profileRequest?: unknown;
- modelRequest?: unknown;
- teamSetupRequest?: unknown;
-} | null): boolean {
- return Boolean(card && (
- card.requestType === "question" || card.questionRequest ||
- (!card.requestType && !card.tool && !card.routineRequest && !card.skillRequest && !card.profileRequest &&
- !card.modelRequest && !card.teamSetupRequest)
- ));
-}
-
-/** System/provider completion ends the live run, not the human's question. */
-export function shouldSettleRequestCard(card: Parameters<typeof isPersistentQuestionCard>[0], source: "user" | "auto" | "timeout" | "system" | "unavailable" | "peer"): boolean {
- return !isPersistentQuestionCard(card) || source === "user";
-}
-
-function text(value: unknown, limit: number): string | undefined {
- if (typeof value !== "string") return undefined;
- const trimmed = value.trim();
- return trimmed ? trimmed.slice(0, limit).trim() : undefined;
-}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return typeof value === "object" && value !== null && !Array.isArray(value);
-}
-
-function parseOption(value: unknown): AskQuestionOption | null {
- // Not the documented shape, but accepted.
- if (typeof value === "string") {
- const label = text(value, MAX_LABEL);
- return label ? { label } : null;
- }
- if (!isRecord(value)) return null;
- const label = text(value.label, MAX_LABEL);
- if (!label) return null;
- const description = text(value.description, MAX_DESCRIPTION);
- return description ? { label, description } : { label };
-}
-
-function parseQuestion(value: unknown): AskQuestion | null {
- if (!isRecord(value)) return null;
- const question = text(value.question, MAX_QUESTION_TEXT);
- if (!question) return null;
- const options: AskQuestionOption[] = [];
- const seen = new Set<string>();
- for (const raw of Array.isArray(value.options) ? value.options : []) {
- const option = parseOption(raw);
- // Duplicate labels: the answer text could not say which row was picked.
- if (!option || seen.has(option.label)) continue;
- seen.add(option.label);
- options.push(option);
- if (options.length === MAX_OPTIONS) break;
- }
- // An empty option list is kept: the card always offers free text.
- const header = text(value.header, MAX_LABEL);
- return {
- question,
- ...(header ? { header } : {}),
- ...(value.multiSelect === true ? { multiSelect: true } : {}),
- options,
- // only meaningful beside options: with none, free text is the only answer
- ...(value.custom === false && options.length ? { custom: false as const } : {}),
- };
-}
-
-/** null when the payload is not one; a malformed call gets the ordinary card. */
-export function parseAskQuestions(input: unknown): AskQuestion[] | null {
- if (!isRecord(input) || !Array.isArray(input.questions)) return null;
- const questions: AskQuestion[] = [];
- for (const raw of input.questions) {
- const question = parseQuestion(raw);
- if (!question) continue;
- questions.push(question);
- if (questions.length === MAX_QUESTIONS) break;
- }
- return questions.length ? questions : null;
-}
-
-/** Codex request_user_input_async's `{ title, options: string[] | null }` entries in the card's shape. Null unless one
- * offers an option: a bare question already reads in the message text. */
-export function parseAsyncQuestions(entries: unknown): AskQuestion[] | null {
- if (!Array.isArray(entries)) return null;
- const questions = parseAskQuestions({
- questions: entries.map((entry) => (isRecord(entry) ? { question: entry.title, options: entry.options } : null)),
- });
- return questions?.some((question) => question.options.length > 0) ? questions : null;
-}
-
-/** The one line the card subtitle and a spoken prompt show. */
-export function askQuestionSummary(questions: readonly AskQuestion[]): string {
- const first = questions[0]?.question ?? "";
- const rest = questions.length - 1;
- return rest > 0 ? `${first} (+${rest} more question${rest > 1 ? "s" : ""})` : first;
-}
-
-/** The tool advertises "2-5 suggested answers". */
-export const MAX_CHOICES = 5;
-
-/**
- * A model that has seen AskUserQuestion may hand over `{ label, description }`
- * rows instead of strings (MiniMax M3 does). Anything else is dropped: React
- * refuses a non-string child.
- */
-export function parseChoices(input: unknown, limit = MAX_CHOICES): string[] | undefined {
- if (!Array.isArray(input)) return undefined;
- const choices: string[] = [];
- const seen = new Set<string>();
- for (const raw of input) {
- const label = typeof raw === "string" ? text(raw, MAX_LABEL) : isRecord(raw) ? text(raw.label, MAX_LABEL) : undefined;
- if (!label || seen.has(label)) continue;
- seen.add(label);
- choices.push(label);
- if (choices.length === limit) break;
- }
- return choices.length ? choices : undefined;
-}
-
-/** For clients that only render a list of choices: only a single question can
- * be answered that way. */
-export function questionChoices(questions: readonly AskQuestion[]): string[] | undefined {
- if (questions.length !== 1) return undefined;
- const only = questions[0]!;
- if (only.multiSelect || only.options.length < 2) return undefined;
- return only.options.map((option) => option.label);
-}
-
-/** The chat runtime's ask tool. Named ask_user so the ASKS_A_PERSON backstop
- * covers it: no auto mode may answer a question. */
-export const ASK_USER_TOOL = "ask_user";
-
-/** Shaped for an OpenAI function-calling tool list. The parser enforces the caps
- * again: a model-authored argument is not a guarantee it followed the schema. */
-export const ASK_USER_TOOL_DEFINITION = {
- type: "function",
- function: {
- name: ASK_USER_TOOL,
- description:
- "Ask the person questions when the decision is theirs. Offer concrete options where they exist; they can always answer in their own words. Ask up to six questions in one call rather than one at a time.",
- parameters: {
- type: "object",
- properties: {
- questions: {
- type: "array",
- minItems: 1,
- maxItems: MAX_QUESTIONS,
- items: {
- type: "object",
- properties: {
- question: { type: "string", description: "The question to show the person." },
- header: { type: "string", description: "A short label for the question's tab." },
- multiSelect: { type: "boolean", description: "Whether several options may be picked." },
- options: {
- type: "array",
- maxItems: MAX_OPTIONS,
- description: "Suggested answers; the person may always write their own.",
- items: {
- type: "object",
- properties: {
- label: { type: "string" },
- description: { type: "string" },
- },
- required: ["label"],
- additionalProperties: false,
- },
- },
- },
- required: ["question"],
- additionalProperties: false,
- },
- },
- },
- required: ["questions"],
- additionalProperties: false,
- },
- },
-} as const;
-
-/** The answer is delivered on the deny channel, so it says what it is; the card
- * strips it back off for display. */
-export const ANSWER_PREAMBLE = "The user answered your questions.";
-const JSON_ANSWERS_PREFIX = `${ANSWER_PREAMBLE}\n\nAnswers (JSON):\n`;
-
-/** Arrives as the tool's result, so it names each question and what was picked. */
-export function formatQuestionAnswers(
- questions: readonly AskQuestion[],
- answers: readonly (readonly string[])[],
-): string {
- const pairs: [string, string][] = [];
- questions.forEach((question, index) => {
- const picked = (answers[index] ?? []).map((value) => value.trim()).filter(Boolean);
- if (!picked.length) return;
- pairs.push([question.question, picked.join(", ")]);
- });
- if (!pairs.length) return "";
- // Newlines can contain Q:/A: headers; JSON preserves them as answer text.
- if (pairs.some(pair => pair.some(value => /[\r\n]/.test(value)))) {
- return JSON_ANSWERS_PREFIX + JSON.stringify(pairs);
- }
- return `${ANSWER_PREAMBLE}\n\n${pairs.map(([question, answer]) => `Q: ${question}\nA: ${answer}`).join("\n\n")}`;
-}
-
-export function answerWithoutPreamble(answer: string): string {
- return answer.startsWith(`${ANSWER_PREAMBLE}\n\n`) ? answer.slice(ANSWER_PREAMBLE.length + 2) : answer;
-}
-
-/** Sized so a reply typed in a card is never cut; only a longer chat message echoed back as free text is. */
-export const MAX_ANSWER_ECHO = ANSWER_PREAMBLE.length + MAX_QUESTIONS
- * ("\n\nQ: \nA: ".length + MAX_QUESTION_TEXT + MAX_OPTIONS * (MAX_LABEL + ", ".length) + MAX_CUSTOM_ANSWER);
-
-/** Cut back to the last whole block, so no partial answer reads as one. */
-export function capAnswerEcho(answer: string, limit = MAX_ANSWER_ECHO): string {
- if (answer.length <= limit) return answer;
- const cut = answer.slice(0, limit);
- const boundary = cut.lastIndexOf("\n\nQ: ");
- const kept = boundary > 0 ? cut.slice(0, boundary) : cut;
- return kept + "\n\n[answer truncated]";
-}
-
-/**
- * The card sends one answer for the whole set; `formatQuestionAnswers` writes
- * each question's text beside its answer, so the map is recovered rather than
- * guessed. A message with no blocks is filed only when there is exactly one
- * question.
- */
-export function questionAnswersByQuestion(
- message: string,
- questions: readonly AskQuestion[],
-): Record<string, string> {
- return questionAnswersById(message, questions.map(question => ({ id: question.question, question })));
-}
-
-/**
- * One answer read back as picked option labels plus the person's own words, for a protocol that answers by option.
- * The card joins multi-select labels with ", " and a label may contain ", ": every reading is tried, a reading that
- * is labels end to end wins, and when the best readings disagree the whole answer is own words, never a guessed option.
- */
-export function pickedOptionLabels(answer: string, question: AskQuestion): { labels: string[]; other?: string } {
- const text = answer.trim();
- const labels = question.options.map((option) => option.label);
- if (!question.multiSelect) {
- if (labels.includes(text)) return { labels: [text] };
- return text ? { labels: [], other: text } : { labels: [] };
- }
- const whole: string[][] = [];
- const partial: Array<{ labels: string[]; other: string }> = [];
- const read = (rest: string, picked: string[]): void => {
- const next = labels.filter((label) => !picked.includes(label) && (rest === label || rest.startsWith(`${label}, `)));
- if (!next.length) {
- if (rest) partial.push({ labels: picked, other: rest });
- else whole.push(picked);
- return;
- }
- for (const label of next) read(rest.slice(label.length + 2), [...picked, label]);
- };
- read(text, []);
- const key = (reading: { labels: string[]; other?: string }) => JSON.stringify([[...reading.labels].sort(), reading.other ?? null]);
- const readings = whole.length ? whole.map((picked) => ({ labels: picked })) : partial;
- const first = readings[0]!;
- const agree = readings.every((reading) => key(reading) === key(first));
- return agree ? first : { labels: [], other: text };
-}
-
-/** Ids ride the reply, so they are capped like the rest. */
-const MAX_QUESTION_ID = 200;
-
-/** Ids live only in the protocol; the card never sees them. */
-export interface ProtocolAskQuestion {
- id: string;
- question: AskQuestion;
-}
-
-/** Entries carry their own string ids (codex's item/tool/requestUserInput). An
- * entry without a usable id and question is skipped; nothing answerable parses
- * to null. */
-export function parseProtocolAskQuestions(entries: unknown): ProtocolAskQuestion[] | null {
- if (!Array.isArray(entries)) return null;
- const parsed: ProtocolAskQuestion[] = [];
- const seenIds = new Set<string>();
- for (const raw of entries) {
- if (!isRecord(raw)) continue;
- const question = parseQuestion(raw);
- // Echoed back verbatim, so preserved exactly and an overlong id rejected
- // whole. A duplicate id fails the request: two questions cannot share one
- // answer slot.
- const id = raw.id;
- if (!question || typeof id !== "string" || !id.trim() || id.length > MAX_QUESTION_ID) continue;
- if (seenIds.has(id)) return null;
- seenIds.add(id);
- parsed.push({ id, question });
- if (parsed.length === MAX_QUESTIONS) break;
- }
- return parsed.length ? parsed : null;
-}
-
-/** A card reply answers by question text, so it cannot tell two questions with the same text apart. */
-export function repeatsQuestionText(questions: readonly ProtocolAskQuestion[]): boolean {
- return new Set(questions.map(({ question }) => question.question)).size !== questions.length;
-}
-
-/**
- * Answers by id (codex's requestUserInput). Only ids with a real block are
- * answered; without blocks, the whole message answers a lone question.
- */
-export function questionAnswersById(
- message: string,
- questions: readonly ProtocolAskQuestion[],
-): Record<string, string> {
- const answers: Record<string, string> = Object.create(null);
- const idByText = new Map<string, string>();
- const ambiguous = new Set<string>();
- for (const { id, question } of questions) {
- if (idByText.has(question.question)) {
- // Identical question text cannot be told apart in a block: neither is answered.
- ambiguous.add(question.question);
- continue;
- }
- idByText.set(question.question, id);
- }
- if (message.startsWith(JSON_ANSWERS_PREFIX)) {
- let pairs: unknown;
- try { pairs = JSON.parse(message.slice(JSON_ANSWERS_PREFIX.length)); }
- catch { return {}; }
- if (!Array.isArray(pairs) || !pairs.every(pair => Array.isArray(pair) && pair.length === 2 && pair.every(value => typeof value === "string"))) return {};
- for (const [asked, answer] of pairs as [string, string][]) {
- const id = idByText.get(asked);
- if (id && !ambiguous.has(asked) && answer.trim()) answers[id] = answer;
- }
- return answers;
- }
- // A block runs from one Q: header to the next; blank lines inside an answer
- // are the answer's.
- const blocks = message.matchAll(/(?:^|\n\n)Q: ([\s\S]+?)\nA: ([\s\S]*?)(?=\n\nQ: |$)/g);
- let sawBlock = false;
- for (const match of blocks) {
- sawBlock = true;
- const asked = match[1]!.trim();
- if (ambiguous.has(asked)) continue;
- const id = idByText.get(asked);
- const answer = match[2]!.trim();
- // A blank A: is no answer.
- if (id && answer) answers[id] = answer;
- }
- if (Object.keys(answers).length) return answers;
- // A reply that matched a block is authoritative even when it answered
- // nothing, or the literal Q:/A: text would be filed as the answer.
- if (sawBlock) return {};
- const only = questions.length === 1 ? questions[0] : undefined;
- const flat = message.trim();
- return only && flat ? { [only.id]: flat } : {};
-}
+export * from "../packages/phone-protocol/src/ask-question.ts";
diff --git a/shared/bot-access.ts b/shared/bot-access.ts
index cb90837ab7..20506ee682 100644
--- a/shared/bot-access.ts
+++ b/shared/bot-access.ts
@@ -1,72 +1 @@
-// Who may see, chat with and change a Team Cloud bot. Four levels, lowest first; a person's level is the highest of what
-// everyone in the team gets and what they were given. Admins and the bot's owner can always edit, so neither is listed.
-import type { BotVisibility } from "./wire.ts";
-
-export const BOT_ACCESS_LEVELS = ["none", "view", "chat", "edit"] as const;
-export type BotAccessLevel = (typeof BOT_ACCESS_LEVELS)[number];
-export type GrantedLevel = Exclude<BotAccessLevel, "none">;
-export const GRANTED_LEVELS: readonly GrantedLevel[] = ["view", "chat", "edit"];
-
-/** A Team Cloud bot's sharing. `everyone` is what every member of the team may do ("none": only the people added);
- * `people` gives each added person a level by lowercased address. An `@domain` entry, which only an older list carries,
- * covers that domain's addresses. */
-export interface BotAccess {
- everyone: BotAccessLevel;
- people: Record<string, GrantedLevel>;
-}
-
-export interface BotAccessFields {
- /** Team Cloud only, and only on the copy sent to someone who can edit the bot: who may see, chat with and change it. */
- access?: BotAccess;
- /** Team Cloud only: what the person this copy was sent to may do with the bot. */
- yourAccess?: BotAccessLevel;
- /** Team Cloud only, on everyone's copy: only the people added, whoever looks after the bot and the admins see it, so
- * its shared chats reach no further. */
- onlyPeopleAdded?: true;
-}
-
-export const levelRank = (level: BotAccessLevel | undefined): number => BOT_ACCESS_LEVELS.indexOf(level ?? "none");
-export const atLeast = (level: BotAccessLevel | undefined, wanted: BotAccessLevel): boolean => levelRank(level) >= levelRank(wanted);
-export const higherLevel = (a: BotAccessLevel, b: BotAccessLevel): BotAccessLevel => (atLeast(a, b) ? a : b);
-export const isAccessLevel = (value: unknown): value is BotAccessLevel => (BOT_ACCESS_LEVELS as readonly unknown[]).includes(value);
-
-/** A bot nobody set sharing for: what its older visibility setting meant. Everyone could chat with an everyone bot, the
- * listed people with a listed one, and only admins (who edit every bot) with an admins-only one. */
-export function accessFromVisibility(visibility: BotVisibility | undefined): BotAccess {
- if (visibility === undefined || visibility === "everyone") return { everyone: "chat", people: {} };
- if (visibility === "admins") return { everyone: "none", people: {} };
- return { everyone: "none", people: Object.fromEntries(visibility.people.map((entry) => [entry.trim().toLowerCase(), "chat" as const])) };
-}
-
-/** Who sees the bot at all: everyone when every member may at least view it, else its owner and the people added, else
- * admins only. */
-export function visibilityFromAccess(access: BotAccess, owner: string | null): BotVisibility {
- if (access.everyone !== "none") return "everyone";
- const people = [...new Set([...(owner ? [owner] : []), ...Object.keys(access.people)])];
- return people.length ? { people } : "admins";
-}
-
-export function entryMatches(entry: string, email: string): boolean {
- return entry.startsWith("@") ? email.endsWith(entry) && email.length > entry.length : entry === email;
-}
-
-/** What this address may do by the bot's sharing alone, before admins and the owner. */
-export function sharedLevel(access: BotAccess, email: string): BotAccessLevel {
- const address = email.trim().toLowerCase();
- let level = access.everyone;
- if (!address) return level;
- for (const [entry, granted] of Object.entries(access.people)) if (entryMatches(entry, address)) level = higherLevel(level, granted);
- return level;
-}
-
-export function sameAccess(a: BotAccess, b: BotAccess): boolean {
- const left = Object.entries(a.people), right = b.people;
- return a.everyone === b.everyone && left.length === Object.keys(right).length && left.every(([entry, level]) => right[entry] === level);
-}
-
-export interface AccessRequestCardField {
- /** Someone who can view a team bot asks the person this card is in front of to let them chat with it. */
- accessRequest?: { botId: string; botName: string; email: string; name: string };
-}
-
-export const ACCESS_REQUEST_OPTIONS = ["Allow", "Not now"] as const;
+export * from "../packages/phone-protocol/src/bot-access.ts";
diff --git a/shared/bot-avatar.ts b/shared/bot-avatar.ts
index e359281c73..5353b45aa7 100644
--- a/shared/bot-avatar.ts
+++ b/shared/bot-avatar.ts
@@ -1,86 +1 @@
-import { z } from "zod";
-
-export const MASCOT_FACE_COLORS = ["white", "black"] as const;
-export const mascotFaceColorSchema = z.enum(MASCOT_FACE_COLORS);
-export type MascotFaceColor = z.infer<typeof mascotFaceColorSchema>;
-
-export function mascotFaceInk(value: unknown): string | undefined {
- const color = mascotFaceColorSchema.safeParse(value).data;
- return color === "white" ? "#ffffff" : color === "black" ? "#000000" : undefined;
-}
-
-/**
- * `mascot` draws the animated mascot body, filled with the bot's colour
- * gradient. `circle`, `rounded`, and `square` crop the bot's own image
- * instead, shown as it is, with no mascot at all.
- */
-export const BOT_AVATAR_CROPS = ["mascot", "circle", "rounded", "square"] as const;
-export const botAvatarCropSchema = z.enum(BOT_AVATAR_CROPS);
-export type BotAvatarCrop = z.infer<typeof botAvatarCropSchema>;
-
-/** CSS radius for a profile crop. Mascot is drawn, not photo-cropped, so it is not clipped. */
-export function avatarCropRadius(crop: BotAvatarCrop): string {
- if (crop === "circle") return "50%";
- if (crop === "rounded") return "22%";
- return "0";
-}
-
-/** 1 shows the picture with object-fit cover. Larger values zoom in. */
-export const AVATAR_ZOOM_MIN = 1;
-export const AVATAR_ZOOM_MAX = 3;
-/** The point of the picture kept in the middle of the crop, from 0 to 1. */
-export const AVATAR_FOCUS_CENTER = 0.5;
-
-export function clampAvatarZoom(value: unknown): number {
- const parsed = typeof value === "number" ? value : Number.NaN;
- if (!Number.isFinite(parsed)) return AVATAR_ZOOM_MIN;
- const clamped = Math.min(AVATAR_ZOOM_MAX, Math.max(AVATAR_ZOOM_MIN, parsed));
- return Math.round(clamped * 100) / 100;
-}
-
-export function clampAvatarFocus(value: unknown): number {
- const parsed = typeof value === "number" ? value : Number.NaN;
- if (!Number.isFinite(parsed)) return AVATAR_FOCUS_CENTER;
- const clamped = Math.min(1, Math.max(0, parsed));
- return Math.round(clamped * 1000) / 1000;
-}
-
-/**
- * Custom avatars are deliberately limited to this app's attachment server.
- * Besides making persisted profiles portable across desktop/browser clients,
- * this prevents a bot profile from becoming an external tracking pixel or a
- * script-capable SVG.
- */
-export const botAvatarUrlSchema = z
- .string()
- .regex(
- /^\/api\/attachments\/[A-Za-z0-9-]+\.(?:png|jpg|gif|webp)$/,
- "must be a stored PNG, JPEG, GIF, or WebP attachment",
- );
-
-export function botAvatarUrlFromStoredPath(path: string): string | null {
- const name = path.replaceAll("\\", "/").split("/").pop();
- if (!name) return null;
- const url = `/api/attachments/${name}`;
- return botAvatarUrlSchema.safeParse(url).success ? url : null;
-}
-
-/** Runtime-safe defaults for untrusted persisted/SSE profile data. */
-export interface BotAvatarProfileInput {
- avatarUrl?: unknown;
- avatarCrop?: unknown;
-}
-
-export interface BotAvatarProfile {
- avatarUrl?: string;
- avatarCrop: BotAvatarCrop;
-}
-
-export function botAvatarProfile(value: BotAvatarProfileInput): BotAvatarProfile {
- const profile: BotAvatarProfile = {
- avatarCrop: botAvatarCropSchema.safeParse(value.avatarCrop).data ?? "mascot",
- };
- const url = botAvatarUrlSchema.safeParse(value.avatarUrl);
- if (url.success) profile.avatarUrl = url.data;
- return profile;
-}
+export * from "../packages/phone-protocol/src/bot-avatar.ts";
diff --git a/shared/bot-body.ts b/shared/bot-body.ts
index 5d3e076a79..b7a18f1bc5 100644
--- a/shared/bot-body.ts
+++ b/shared/bot-body.ts
@@ -1,63 +1 @@
-/** Every body a bot can wear: the gradient catalog plus the festival bodies. */
-
-import { z } from "zod";
-
-import { DEFAULT_MASCOT_BODY, MASCOT_BODY_IDS } from "./mascot-bodies.ts";
-import { CARVED_BODY_IDS, DIWALI_BODY_IDS, HALLOWEEN_BODY_IDS, type CarvedBodyId } from "./carved-bodies.ts";
-import type { MausColor } from "./wire.ts";
-
-export const BOT_BODY_IDS = [...MASCOT_BODY_IDS, ...CARVED_BODY_IDS] as const;
-
-export type BotBodyId = (typeof BOT_BODY_IDS)[number];
-
-export const botBodySchema = z.enum(BOT_BODY_IDS);
-
-/** Runtime-safe read of an untrusted persisted or streamed body id. */
-export function botBodyId(value: unknown): BotBodyId {
- return botBodySchema.safeParse(value).data ?? DEFAULT_MASCOT_BODY;
-}
-
-export function isCarvedBody(value: unknown): value is CarvedBodyId {
- return (CARVED_BODY_IDS as readonly unknown[]).includes(value);
-}
-
-export type CostumeColor = Exclude<MausColor, "silver" | "chrome">;
-
-/** A festival skin's own bodies, and the costume each bot colour wears while "Dress my bots up" is on with it. */
-const festival = <Id extends CarvedBodyId>(bodies: readonly Id[], costumes: Record<CostumeColor, NoInfer<Id>>) => ({ bodies, costumes });
-
-/** Keyed by the skin id that turns each festival on. */
-export const FESTIVALS = {
- halloween: festival(HALLOWEEN_BODY_IDS, {
- orange: "pumpkin",
- purple: "ghost",
- teal: "witch",
- red: "bat",
- blue: "cat",
- cyan: "skull",
- green: "monster",
- yellow: "mummy",
- coral: "vampire",
- pink: "spider",
- }),
- diwali: festival(DIWALI_BODY_IDS, {
- orange: "laddu",
- purple: "chakri",
- teal: "karanji",
- red: "rocket",
- blue: "bomb",
- cyan: "chakli",
- green: "anaar",
- yellow: "katli",
- coral: "jalebi",
- pink: "sparkler",
- }),
-};
-
-export type FestivalId = keyof typeof FESTIVALS;
-
-export const FESTIVAL_IDS = Object.keys(FESTIVALS) as FestivalId[];
-
-export function isFestival(value: unknown): value is FestivalId {
- return typeof value === "string" && Object.hasOwn(FESTIVALS, value);
-}
+export * from "../packages/phone-protocol/src/bot-body.ts";
diff --git a/shared/burst.ts b/shared/burst.ts
index 2f8d8a474e..fe9adcd56c 100644
--- a/shared/burst.ts
+++ b/shared/burst.ts
@@ -1,55 +1 @@
-/** One burst: one person's task split into many threads of the same bot, run in parallel, merged into one result. */
-export type BurstPhase = "preview" | "running" | "merging" | "done" | "cancelled";
-export type BurstChildStatus = "queued" | "running" | "done" | "failed" | "cancelled";
-export type BurstCounts = Record<BurstChildStatus, number>;
-
-/** The card in the parent chat: a preview until the person presses Run, then the one progress card, patched in place. It
- * carries counts only, and the rows come from GET /api/bursts/<id>, so a card stays one small row however large the burst. */
-export interface BurstCardData {
- version: 1;
- burstId: string;
- botId: string;
- task: string;
- phase: BurstPhase;
- /** Tasks that run. */
- total: number;
- /** Tasks the bot proposed: more than `total` when the plan's task limit cut the list. */
- requested: number;
- /** How many run at once here. */
- parallel: number;
- /** The plan's most tasks per burst, set when it cut this list. */
- taskLimit?: number;
- /** Set on a plan where a higher one runs more at once. */
- smallPlan?: true;
- modelName: string;
- /** A rough figure for the preview, in minutes. */
- estimateMinutes: number;
- counts: BurstCounts;
- /** The first few tasks, for the preview. */
- sample: string[];
- /** Parts that did not finish, named once the burst settles, with `failedMore` counting past the ones listed. */
- failed?: BurstFailure[];
- failedMore?: number;
-}
-
-export interface BurstFailure {
- title: string;
- reason: string;
-}
-
-/** One part of a burst, as GET /api/bursts/<id> lists it. `threadId` is absent until it starts. */
-export interface BurstChildRow {
- seq: number;
- title: string;
- status: BurstChildStatus;
- threadId?: string;
- error?: string;
-}
-
-export interface BurstView {
- burstId: string;
- phase: BurstPhase;
- instructions: string;
- items: string[];
- children: BurstChildRow[];
-}
+export * from "../packages/phone-protocol/src/burst.ts";
diff --git a/shared/carved-bodies.ts b/shared/carved-bodies.ts
index 4bbd5ab892..579f426ab9 100644
--- a/shared/carved-bodies.ts
+++ b/shared/carved-bodies.ts
@@ -1,321 +1 @@
-/**
- * The festival bodies a bot can wear, drawn flat with a carved face.
- *
- * GENERATED FILE — do not hand-edit. Run `pnpm gen:carved` to rebuild it from
- * `scripts/gen-carved-bodies.ts`.
- *
- * Drawn flat: the bot's own colour (or a pale or fixed stand-in), a few fixed-colour accents
- * and a carved face. Paths are in a 240-unit square centred on x = 120.
- */
-
-/** Every Halloween body id, in the order the picker shows them. */
-export const HALLOWEEN_BODY_IDS = ["pumpkin", "ghost", "witch", "bat", "cat", "skull", "monster", "mummy", "vampire", "spider"] as const;
-
-export type HalloweenBodyId = (typeof HALLOWEEN_BODY_IDS)[number];
-
-/** Every Diwali body id, in the order the picker shows them. */
-export const DIWALI_BODY_IDS = ["rocket", "anaar", "chakri", "sparkler", "bomb", "laddu", "chakli", "jalebi", "katli", "karanji"] as const;
-
-export type DiwaliBodyId = (typeof DIWALI_BODY_IDS)[number];
-
-export const CARVED_BODY_IDS = [...HALLOWEEN_BODY_IDS, ...DIWALI_BODY_IDS] as const;
-
-export type CarvedBodyId = (typeof CARVED_BODY_IDS)[number];
-
-export interface CarvedEyes {
- /** Rest position of the pair's centre. */
- cx: number;
- cy: number;
- /** Half the distance between the two eyes. */
- dx: number;
- /** Resting pill size. */
- w: number;
- h: number;
- /** Diameter when startled. */
- round: number;
- ink: string;
- /** False when the drawing carries its own mouth. */
- mouth: boolean;
- mouthInk: string;
- /** Where the smile sits when it can't hang under the eyes. */
- mouthY: number | null;
-}
-
-export interface CarvedBody {
- id: CarvedBodyId;
- /** Human-readable name, used for the picker and the accessible label. */
- name: string;
- /** "bot" fills with the bot's colour, "pale" with a near-white tint of it, "bone" with `bone`. */
- paint: "bot" | "pale" | "bone";
- bone: string | null;
- eyes: CarvedEyes;
- /** Where the eyes may show. */
- clip: string;
- /** Draw order, bottom first. "body" is the paint; "accent" is the bot's colour. */
- parts: ReadonlyArray<{ fill: string; d: string }>;
-}
-
-export const CARVED_BODIES: Record<CarvedBodyId, CarvedBody> = {
- pumpkin: {
- id: "pumpkin",
- name: "Pumpkin",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 152, dx: 35, w: 28, h: 56, round: 50, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M90.5 54.48 C77.98 56.31 67.02 63.37 58.51 72.5 C55.95 75.24 53.91 78.51 51.11 81 C47.33 84.36 42.38 85.53 38 87.83 C32.54 90.69 27.86 94.89 24 99.66 C0.95 128.17 1.01 181.52 24.97 209.5 C31.03 216.58 39.12 222.26 48.5 223.66 C53.49 224.41 58.74 223.08 63.5 225.16 C66.21 226.35 68.43 228.42 70.9 230 C78.54 234.9 87.38 237.89 96.5 238 C102.12 238.06 107.73 237.03 113 235.08 C114.66 234.46 118.98 231.87 120.5 232.13 C121.68 232.33 127.39 235.28 129.5 235.93 C135.79 237.88 142.47 238.48 149 237.59 C156.48 236.58 163.59 233.66 169.87 229.5 C172.18 227.96 174.28 226.04 176.89 225 C181.28 223.25 185.94 224.33 190.5 223.8 C198.11 222.91 205.1 219.14 210.69 214 C238.8 188.15 239.54 131.34 217.5 101.6 C212.81 95.28 206.78 89.78 199.5 86.63 C196.43 85.31 193.26 84.22 190.5 82.26 C185.59 78.78 182.01 72.7 177.5 68.51 C167.37 59.12 153.97 53.16 140 54.1 C134.84 54.45 129.76 55.71 125 57.71 C123.69 58.27 121.86 59.64 120.5 59.87 C119.38 60.06 111.9 56.48 110 55.92 C103.69 54.04 97.01 53.52 90.5 54.48 Z",
- parts: [
- { fill: "#3d3d3d", d: "M94.5 3.93 C90.73 5.44 88.5 9.55 89.93 13.5 C91.2 17 95.18 19.44 97.5 22.28 C101.77 27.51 104.88 33.56 106.89 40 C109.27 47.63 110.3 56.02 109.8 64 C109.52 68.57 107.41 72.89 108.74 77.5 C110.77 84.55 118.63 88.55 125.5 85.93 C135.23 82.22 133.7 73.67 132.84 65.5 C130.89 47.14 126.81 30.93 114.5 16.5 C110.8 12.16 100.82 1.39 94.5 3.93 Z" },
- { fill: "body", d: "M90.5 54.48 C77.98 56.31 67.02 63.37 58.51 72.5 C55.95 75.24 53.91 78.51 51.11 81 C47.33 84.36 42.38 85.53 38 87.83 C32.54 90.69 27.86 94.89 24 99.66 C0.95 128.17 1.01 181.52 24.97 209.5 C31.03 216.58 39.12 222.26 48.5 223.66 C53.49 224.41 58.74 223.08 63.5 225.16 C66.21 226.35 68.43 228.42 70.9 230 C78.54 234.9 87.38 237.89 96.5 238 C102.12 238.06 107.73 237.03 113 235.08 C114.66 234.46 118.98 231.87 120.5 232.13 C121.68 232.33 127.39 235.28 129.5 235.93 C135.79 237.88 142.47 238.48 149 237.59 C156.48 236.58 163.59 233.66 169.87 229.5 C172.18 227.96 174.28 226.04 176.89 225 C181.28 223.25 185.94 224.33 190.5 223.8 C198.11 222.91 205.1 219.14 210.69 214 C238.8 188.15 239.54 131.34 217.5 101.6 C212.81 95.28 206.78 89.78 199.5 86.63 C196.43 85.31 193.26 84.22 190.5 82.26 C185.59 78.78 182.01 72.7 177.5 68.51 C167.37 59.12 153.97 53.16 140 54.1 C134.84 54.45 129.76 55.71 125 57.71 C123.69 58.27 121.86 59.64 120.5 59.87 C119.38 60.06 111.9 56.48 110 55.92 C103.69 54.04 97.01 53.52 90.5 54.48 Z" },
- ],
- },
- ghost: {
- id: "ghost",
- name: "Ghost",
- paint: "pale",
- bone: null,
- eyes: {cx: 120, cy: 112, dx: 32, w: 26, h: 52, round: 44, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M111.5 18.45 C102.67 19.45 94.05 21.8 86 25.58 C79.38 28.69 73.19 32.71 67.66 37.5 C55.69 47.85 46.96 61.73 42.81 77 C41.15 83.07 41.21 88.17 40.02 93.5 C39.67 95.08 38.72 96.36 38.5 97.97 C37.5 105.16 38.47 113.18 38.11 120.5 C37.62 130.51 36.53 140.51 35.71 150.5 C34.9 160.48 34.46 170.57 33.23 180.5 C32.61 185.5 30.7 190.45 30.58 195.5 C30.54 197.24 31.38 198.4 31.89 200 C33.45 204.88 34.26 209.22 38 213.1 C45.27 220.62 57.05 222.23 65.9 216.5 C68.85 214.59 75.17 206.54 75.27 206.5 C75.82 206.31 76.48 206.39 77 206.65 C77.78 207.05 82.14 213.41 84 214.97 C91.11 220.92 101.63 221.6 109.5 216.75 C112.96 214.63 119.13 206.55 119.27 206.5 C121.64 205.67 124.14 210.98 125.45 212.5 C129.1 216.73 134.46 219.4 140 219.91 C146.43 220.5 153.1 218.15 157.61 213.5 C158.94 212.13 161.82 207.01 163.27 206.5 C165.61 205.68 168.9 212.06 170.5 213.61 C175.27 218.25 181.86 220.62 188.5 219.86 C196.53 218.94 203.54 213.52 206.49 206 C207.26 204.04 207.48 201.99 208.11 200 C208.44 198.97 209.07 198.05 209.32 197 C210.25 193.16 207.29 184.77 206.77 180.5 C205.35 169.08 204.85 157.47 203.92 146 C203.19 137.02 202.16 128.01 201.83 119 C201.57 112.11 202.45 104.83 201.5 98 C201.28 96.4 200.36 95.14 200 93.58 C199.55 91.62 199.57 89.5 199.31 87.5 C198.7 82.92 197.7 78.4 196.32 74 C190.52 55.58 178.01 39.62 161.5 29.61 C154.53 25.38 146.92 22.23 139 20.29 C130.06 18.1 120.66 17.42 111.5 18.45 Z",
- parts: [
- { fill: "body", d: "M111.5 18.45 C102.67 19.45 94.05 21.8 86 25.58 C79.38 28.69 73.19 32.71 67.66 37.5 C55.69 47.85 46.96 61.73 42.81 77 C41.15 83.07 41.21 88.17 40.02 93.5 C39.67 95.08 38.72 96.36 38.5 97.97 C37.5 105.16 38.47 113.18 38.11 120.5 C37.62 130.51 36.53 140.51 35.71 150.5 C34.9 160.48 34.46 170.57 33.23 180.5 C32.61 185.5 30.7 190.45 30.58 195.5 C30.54 197.24 31.38 198.4 31.89 200 C33.45 204.88 34.26 209.22 38 213.1 C45.27 220.62 57.05 222.23 65.9 216.5 C68.85 214.59 75.17 206.54 75.27 206.5 C75.82 206.31 76.48 206.39 77 206.65 C77.78 207.05 82.14 213.41 84 214.97 C91.11 220.92 101.63 221.6 109.5 216.75 C112.96 214.63 119.13 206.55 119.27 206.5 C121.64 205.67 124.14 210.98 125.45 212.5 C129.1 216.73 134.46 219.4 140 219.91 C146.43 220.5 153.1 218.15 157.61 213.5 C158.94 212.13 161.82 207.01 163.27 206.5 C165.61 205.68 168.9 212.06 170.5 213.61 C175.27 218.25 181.86 220.62 188.5 219.86 C196.53 218.94 203.54 213.52 206.49 206 C207.26 204.04 207.48 201.99 208.11 200 C208.44 198.97 209.07 198.05 209.32 197 C210.25 193.16 207.29 184.77 206.77 180.5 C205.35 169.08 204.85 157.47 203.92 146 C203.19 137.02 202.16 128.01 201.83 119 C201.57 112.11 202.45 104.83 201.5 98 C201.28 96.4 200.36 95.14 200 93.58 C199.55 91.62 199.57 89.5 199.31 87.5 C198.7 82.92 197.7 78.4 196.32 74 C190.52 55.58 178.01 39.62 161.5 29.61 C154.53 25.38 146.92 22.23 139 20.29 C130.06 18.1 120.66 17.42 111.5 18.45 Z" },
- ],
- },
- witch: {
- id: "witch",
- name: "Witch",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 174, dx: 30, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M70 115.37 C64.92 118.19 58.38 126.61 55.15 131.5 C39.04 155.88 40.93 187.85 59.5 210.37 C83.52 239.49 127.61 245.99 160 227.52 C193.86 208.21 206.9 166.06 185.5 132.5 C182.23 127.37 176.01 119.21 170.88 116 C168.88 114.75 156.18 116.17 153 116.31 C138.51 116.93 124 117.12 109.5 116.93 C100 116.81 90.49 116.52 81 116.03 C79.79 115.97 70.33 115.19 70 115.37 Z",
- parts: [
- { fill: "#3d3d3d", d: "M56 93.43 C43.48 96.13 40.36 109.2 37.78 120 C31.5 146.29 30.56 174.43 35.74 201 C37.12 208.09 38.78 215.1 40.92 222 C41.86 225.03 42.59 228.55 45.34 230.5 C50.73 234.32 58.38 230.12 57.98 223.5 C57.72 219 56.75 214.51 56.42 210 C55.7 200 56.02 189.96 57.07 180 C57.37 177.15 58.02 166.48 61 165.64 C63.18 165.03 66.49 167.44 68.5 168.11 C72.91 169.6 77.38 170 82 170 C105.5 170 129 170 152.5 170 C158.59 170 164.6 170.23 170.5 168.43 C172.53 167.82 177.65 164.86 179.5 165.82 C181.99 167.11 182.45 176.27 182.79 179 C184.42 191.91 184.37 205.09 182.77 218 C182.17 222.84 180.96 227.92 186 230.93 C187.77 231.99 190.01 232.27 192 231.75 C196.36 230.6 197.5 226.81 198.73 223 C201.11 215.63 202.91 208.12 204.32 200.5 C208.97 175.34 208.61 149 203.13 124 C201.42 116.16 199.23 104.47 193.5 98.63 C188.23 93.26 179.97 91.56 173 94.34 C168.24 96.23 164.9 99.79 159.5 100 C144.55 100.56 129.46 100 114.5 100 C103.07 100 91.41 100.67 80 99.98 C70.75 99.42 67.69 90.9 56 93.43 Z" },
- { fill: "body", d: "M111 98.49 C99.92 99.78 89.16 103.16 79.5 108.77 C71.23 113.57 63.85 119.91 58.01 127.5 C52.95 134.08 49.07 141.54 46.7 149.5 C31.29 201.28 80.43 243.45 130 237.39 C141.09 236.03 151.91 232.4 161.5 226.64 C169.36 221.92 176.39 215.78 181.99 208.5 C186.73 202.34 190.44 195.4 192.83 188 C209.5 136.52 160.9 92.7 111 98.49 Z" },
- { fill: "#3d3d3d", d: "M177 10.96 C138.98 13.21 103.23 27.45 85.12 63 C81.33 70.43 77.84 78.65 76.85 87 C76.55 89.52 76.75 91.99 76.61 94.5 C76.56 95.51 76.17 96.49 76.14 97.5 C76 101.4 77.46 105.9 78.82 109.5 C85.72 127.81 104.52 139.6 124 137.82 C143.59 136.03 160 120.88 163.36 101.5 C163.9 98.37 164.65 94.14 163.9 91 C162.95 87.07 162.41 82.91 161.16 79 C158.31 70.02 153.98 63.41 156.17 53.5 C158.71 41.94 167.43 31.98 176.22 24.5 C178.98 22.16 184.33 18.67 186.45 16.5 C187.23 15.7 187.64 14.61 187.46 13.5 C186.74 9 180.07 10.78 177 10.96 Z" },
- { fill: "accent", d: "M81 72.19 C79.92 73.17 77.55 82.62 77.22 84.5 C77.21 84.56 76.73 87.42 76.79 87.5 C77.5 88.43 80.51 88 81.5 88 C86.5 88 91.5 88 96.5 88 C113 88 129.5 88 146 88 C150 88 154 88 158 88 C158.41 88 162.39 88.09 162.5 88 C163.43 87.24 162.51 84.38 162.33 83.5 C161.84 81.07 159.9 72.86 157.5 72 C155.93 71.44 142.27 72 139.5 72 C126 72 112.5 72 99 72 C94.5 72 90 72 85.5 72 C84.65 72 81.67 71.58 81 72.19 Z" },
- { fill: "#3d3d3d", d: "M92.5 82.49 C70.51 83.29 48.05 84.51 26.5 89.19 C21.5 90.28 16.04 91.43 11.56 94 C9.93 94.93 7.19 96.67 8.22 99 C9.82 102.64 17.9 104.67 21.5 105.62 C34.2 108.96 47.45 110.39 60.5 111.56 C99.75 115.07 139.74 115.08 179 111.6 C192.04 110.44 217.43 108.32 228.44 102 C234.96 98.26 231.04 94.96 226 92.83 C217.57 89.26 208 87.94 199 86.66 C163.9 81.67 127.88 81.21 92.5 82.49 Z" },
- ],
- },
- bat: {
- id: "bat",
- name: "Bat",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 142, dx: 28, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M78.5 28.29 C74.93 30.19 75.47 37.8 75.15 41.5 C74.53 48.5 73.91 55.5 73.29 62.5 C72.9 66.96 72.85 71.64 71.75 76 C70.83 79.6 68.82 85.6 64.5 86.26 C59.64 87 48.75 76.45 44 74 C41.3 72.61 37.88 71.96 35 71 C27.5 68.5 20 66 12.5 63.5 C8.5 62.17 4.5 60.83 0.5 59.5 C-0.78 59.07 -2.92 57.58 -3.85 59.5 C-4.29 60.4 -3.66 61.5 -3.56 62.5 C-3.1 67.12 -0.34 68.8 2.57 72 C7.4 77.32 10.12 84.29 10 91.5 C9.9 96.81 8.27 102.08 5.32 106.5 C4.31 108.01 3.03 109.34 2.25 111 C1.43 112.74 1.01 118.51 2.5 119.97 C3.97 121.42 10.69 121.29 13 121.89 C18.65 123.35 23.67 126.57 27.45 131 C31.02 135.19 33.25 140.53 33.84 146 C34.08 148.27 33.22 153.18 34.21 155 C35.72 157.76 38.05 155.63 40 154.7 C43.58 153 47.39 152.47 50.08 156 C52.67 159.38 53.61 164.19 55.5 168 C58.57 174.19 62.54 179.93 67.25 185 C89.14 208.58 125.04 214.65 153.5 199.73 C165.15 193.62 175.01 184.28 181.77 173 C184.06 169.17 188.57 157.24 190.5 155.3 C193.16 152.64 196.34 153.04 199.5 154.47 C200.95 155.13 203.95 157.59 205.5 155.79 C206.74 154.34 205.93 148.54 206.11 146.5 C206.6 141.11 208.67 135.94 212 131.68 C215.97 126.61 221.72 123.03 228 121.65 C230.52 121.1 236.88 121.57 238.04 119 C238.13 118.81 238.37 116.21 238.39 116 C238.8 111.43 236.27 109.16 234.05 105.5 C231.32 101.01 229.91 95.75 230 90.5 C230.12 83.91 232.62 77.44 236.98 72.5 C239.99 69.1 243.08 67.35 243.56 62.5 C243.66 61.5 244.29 60.4 243.85 59.5 C242.92 57.58 240.78 59.07 239.5 59.5 C235.5 60.83 231.5 62.17 227.5 63.5 C220 66 212.5 68.5 205 71 C202.11 71.96 198.7 72.62 196 74 C191.23 76.44 180.37 87 175.5 86.26 C171.18 85.6 169.16 79.6 168.25 76 C167.15 71.64 167.1 66.96 166.71 62.5 C166.09 55.5 165.47 48.5 164.85 41.5 C164.54 37.89 165.2 28.63 160.5 28.03 C156.82 27.56 152.58 35.31 150.59 38 C146.75 43.2 137.29 57.47 133 60.83 C130.83 62.53 128.21 63.45 125.5 63.81 C123.5 64.08 121.51 63.99 119.5 64 C109.03 64.05 106.48 61.1 100.5 53.01 C97.5 48.95 94.5 44.89 91.5 40.83 C89.48 38.09 84.84 30.64 82.5 28.88 C81.44 28.09 79.75 27.63 78.5 28.29 Z",
- parts: [
- { fill: "body", d: "M78.5 28.29 C74.93 30.19 75.47 37.8 75.15 41.5 C74.53 48.5 73.91 55.5 73.29 62.5 C72.9 66.96 72.85 71.64 71.75 76 C70.83 79.6 68.82 85.6 64.5 86.26 C59.64 87 48.75 76.45 44 74 C41.3 72.61 37.88 71.96 35 71 C27.5 68.5 20 66 12.5 63.5 C8.5 62.17 4.5 60.83 0.5 59.5 C-0.78 59.07 -2.92 57.58 -3.85 59.5 C-4.29 60.4 -3.66 61.5 -3.56 62.5 C-3.1 67.12 -0.34 68.8 2.57 72 C7.4 77.32 10.12 84.29 10 91.5 C9.9 96.81 8.27 102.08 5.32 106.5 C4.31 108.01 3.03 109.34 2.25 111 C1.43 112.74 1.01 118.51 2.5 119.97 C3.97 121.42 10.69 121.29 13 121.89 C18.65 123.35 23.67 126.57 27.45 131 C31.02 135.19 33.25 140.53 33.84 146 C34.08 148.27 33.22 153.18 34.21 155 C35.72 157.76 38.05 155.63 40 154.7 C43.58 153 47.39 152.47 50.08 156 C52.67 159.38 53.61 164.19 55.5 168 C58.57 174.19 62.54 179.93 67.25 185 C89.14 208.58 125.04 214.65 153.5 199.73 C165.15 193.62 175.01 184.28 181.77 173 C184.06 169.17 188.57 157.24 190.5 155.3 C193.16 152.64 196.34 153.04 199.5 154.47 C200.95 155.13 203.95 157.59 205.5 155.79 C206.74 154.34 205.93 148.54 206.11 146.5 C206.6 141.11 208.67 135.94 212 131.68 C215.97 126.61 221.72 123.03 228 121.65 C230.52 121.1 236.88 121.57 238.04 119 C238.13 118.81 238.37 116.21 238.39 116 C238.8 111.43 236.27 109.16 234.05 105.5 C231.32 101.01 229.91 95.75 230 90.5 C230.12 83.91 232.62 77.44 236.98 72.5 C239.99 69.1 243.08 67.35 243.56 62.5 C243.66 61.5 244.29 60.4 243.85 59.5 C242.92 57.58 240.78 59.07 239.5 59.5 C235.5 60.83 231.5 62.17 227.5 63.5 C220 66 212.5 68.5 205 71 C202.11 71.96 198.7 72.62 196 74 C191.23 76.44 180.37 87 175.5 86.26 C171.18 85.6 169.16 79.6 168.25 76 C167.15 71.64 167.1 66.96 166.71 62.5 C166.09 55.5 165.47 48.5 164.85 41.5 C164.54 37.89 165.2 28.63 160.5 28.03 C156.82 27.56 152.58 35.31 150.59 38 C146.75 43.2 137.29 57.47 133 60.83 C130.83 62.53 128.21 63.45 125.5 63.81 C123.5 64.08 121.51 63.99 119.5 64 C109.03 64.05 106.48 61.1 100.5 53.01 C97.5 48.95 94.5 44.89 91.5 40.83 C89.48 38.09 84.84 30.64 82.5 28.88 C81.44 28.09 79.75 27.63 78.5 28.29 Z" },
- ],
- },
- cat: {
- id: "cat",
- name: "Cat",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 156, dx: 36, w: 27, h: 52, round: 46, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M48 25.42 C46.77 26.16 46.14 26.51 45.5 27.83 C44.09 30.74 43.01 40.74 42.34 44.5 C39.14 62.5 35.94 80.5 32.74 98.5 C31.46 105.73 28.94 112.44 27.09 119.5 C26.44 121.96 26.44 124.52 25.93 127 C25.3 130.04 24.17 132.96 23.51 136 C21.02 147.42 21.66 159.39 25.27 170.5 C29.81 184.46 38.78 196.64 50 205.99 C85.42 235.47 140.72 237.75 179.5 213.57 C186.45 209.23 192.84 204.02 198.4 198 C210.43 184.96 218 167.87 218 150 C218 141.88 215.96 135.26 214.18 127.5 C213.61 125.03 213.61 122.47 213.04 120 C211.96 115.44 210.13 111.04 208.95 106.5 C206.39 96.7 205.12 86.47 203.35 76.5 C201.03 63.5 198.72 50.5 196.41 37.5 C195.71 33.57 195.94 26.16 191 25.1 C187.51 24.35 184.88 27.92 182.63 30 C176.13 36 169.63 42 163.13 48 C157.65 53.05 146.41 64.8 140.5 67.87 C138.17 69.08 135.61 69.79 133 70.1 C130.41 70.4 108.36 70.34 106 69.96 C98.34 68.74 93.44 63.3 88 58.27 C79.78 50.68 71.55 43.09 63.33 35.5 C60.5 32.89 52.07 22.98 48 25.42 Z",
- parts: [
- { fill: "body", d: "M48 25.42 C46.77 26.16 46.14 26.51 45.5 27.83 C44.09 30.74 43.01 40.74 42.34 44.5 C39.14 62.5 35.94 80.5 32.74 98.5 C31.46 105.73 28.94 112.44 27.09 119.5 C26.44 121.96 26.44 124.52 25.93 127 C25.3 130.04 24.17 132.96 23.51 136 C21.02 147.42 21.66 159.39 25.27 170.5 C29.81 184.46 38.78 196.64 50 205.99 C85.42 235.47 140.72 237.75 179.5 213.57 C186.45 209.23 192.84 204.02 198.4 198 C210.43 184.96 218 167.87 218 150 C218 141.88 215.96 135.26 214.18 127.5 C213.61 125.03 213.61 122.47 213.04 120 C211.96 115.44 210.13 111.04 208.95 106.5 C206.39 96.7 205.12 86.47 203.35 76.5 C201.03 63.5 198.72 50.5 196.41 37.5 C195.71 33.57 195.94 26.16 191 25.1 C187.51 24.35 184.88 27.92 182.63 30 C176.13 36 169.63 42 163.13 48 C157.65 53.05 146.41 64.8 140.5 67.87 C138.17 69.08 135.61 69.79 133 70.1 C130.41 70.4 108.36 70.34 106 69.96 C98.34 68.74 93.44 63.3 88 58.27 C79.78 50.68 71.55 43.09 63.33 35.5 C60.5 32.89 52.07 22.98 48 25.42 Z" },
- ],
- },
- skull: {
- id: "skull",
- name: "Skull",
- paint: "bone",
- bone: "#f1ede6",
- eyes: {cx: 120, cy: 112, dx: 34, w: 42, h: 44, round: 50, ink: "#0d0a10", mouth: false, mouthInk: "#0d0a10", mouthY: null},
- clip: "M111 16.48 C60.53 22.23 26.1 71.09 38.54 120.5 C40.96 130.13 45.1 139.31 50.72 147.5 C55.37 154.28 61.54 159.58 64.33 167.5 C66.25 172.92 65.77 178.38 66.35 184 C66.91 189.5 67.86 194.95 67.98 200.5 C68.17 209.19 66.13 215.91 73.45 222.5 C80.55 228.89 89.65 228 98.5 228 C111 228 123.5 228 136 228 C141.94 228 148.08 228.45 154 227.91 C161.84 227.19 170.56 221.74 171.93 213.5 C172.59 209.54 171.97 205.49 172 201.5 C172.05 195.44 173.12 189.51 173.7 183.5 C174.04 180.01 173.78 176.47 174.27 173 C174.64 170.41 175.44 167.92 176.42 165.5 C179.29 158.45 185.28 153.4 189.5 147.18 C196.53 136.81 201.2 124.89 203.06 112.5 C211.17 58.67 165.37 10.29 111 16.48 Z",
- parts: [
- { fill: "body", d: "M111 16.48 C60.53 22.23 26.1 71.09 38.54 120.5 C40.96 130.13 45.1 139.31 50.72 147.5 C55.37 154.28 61.54 159.58 64.33 167.5 C66.25 172.92 65.77 178.38 66.35 184 C66.91 189.5 67.86 194.95 67.98 200.5 C68.17 209.19 66.13 215.91 73.45 222.5 C80.55 228.89 89.65 228 98.5 228 C111 228 123.5 228 136 228 C141.94 228 148.08 228.45 154 227.91 C161.84 227.19 170.56 221.74 171.93 213.5 C172.59 209.54 171.97 205.49 172 201.5 C172.05 195.44 173.12 189.51 173.7 183.5 C174.04 180.01 173.78 176.47 174.27 173 C174.64 170.41 175.44 167.92 176.42 165.5 C179.29 158.45 185.28 153.4 189.5 147.18 C196.53 136.81 201.2 124.89 203.06 112.5 C211.17 58.67 165.37 10.29 111 16.48 Z" },
- { fill: "#0d0a10", d: "M108.5 149.4 C107.57 150.05 107 150.82 107 152 C107 154.18 114.28 164.52 115.84 167 C116.89 168.68 118.36 171.98 121 170.83 C123.26 169.84 129.3 158.78 131 156.06 C132.04 154.39 134.17 151.94 132.23 150 C130.51 148.28 117.13 149 114 149 C112.48 149 109.83 148.48 108.5 149.4 Z" },
- { fill: "#0d0a10", d: "M94.5 187.86 C90.92 189.52 93.89 198.41 92.8 199.5 C91.51 200.79 82.21 198.69 80.5 200.4 C80.09 200.81 79.82 201.42 79.8 202 C79.71 204.75 83.35 204.2 85 204.2 C85.71 204.2 92.43 204.13 92.5 204.2 C94.27 205.97 90.74 214.92 94.5 216.14 C99.5 217.76 95.66 205.52 98 204.2 C98.87 203.71 100 204.2 101 204.2 C102.15 204.2 104.56 203.68 105.3 205 C106.51 207.15 103.11 216.05 107.5 216.2 C112.34 216.36 107.39 205.23 111 204.2 C111.96 203.93 113 204.2 114 204.2 C115 204.2 116.13 203.71 117 204.2 C118.31 204.94 117.8 210.08 117.8 211.5 C117.8 213.04 117.59 217.08 120.5 216.14 C124.04 215 121.14 205.56 122.2 204.5 C122.63 204.07 123.39 204.26 124 204.2 C124.45 204.16 129.99 204.19 130 204.2 C131.77 205.97 128.24 214.92 132 216.14 C134.91 217.08 134.7 213.04 134.7 211.5 C134.7 210.08 134.19 204.94 135.5 204.2 C136.37 203.71 137.5 204.2 138.5 204.2 C139.5 204.2 140.54 203.93 141.5 204.2 C141.99 204.34 142.55 204.56 142.8 205 C143.36 206 142.47 212.32 142.8 214 C143.12 215.64 144.94 217.16 146.5 215.6 C148.29 213.81 146.31 206.57 147.2 205 C148.42 202.83 156.88 205.32 159 203.96 C159.52 203.62 159.95 203.09 160.14 202.5 C161.24 199.11 155.62 199.8 154 199.8 C153.08 199.8 148.56 200.12 148 199.8 C145.66 198.48 149.5 186.24 144.5 187.86 C140.96 189 143.86 198.44 142.8 199.5 C142.42 199.88 140.04 199.8 139.5 199.8 C139.14 199.8 135.05 199.85 135 199.8 C133.92 198.72 136.59 184.88 131.5 188.04 C128.44 189.94 132 198.39 129.5 199.8 C128.63 200.29 127.5 199.8 126.5 199.8 C125.35 199.8 122.94 200.32 122.2 199 C120.99 196.85 124.39 187.95 120 187.8 C115.16 187.64 120.11 198.77 116.5 199.8 C115.54 200.07 114.5 199.8 113.5 199.8 C112.5 199.8 111.37 200.29 110.5 199.8 C108.57 198.71 110.45 191.48 109.64 189.5 C108.87 187.61 106.74 187.14 105.54 189 C104.68 190.34 105.78 199.02 105.3 199.5 C104.92 199.88 102.54 199.8 102 199.8 C101.64 199.8 97.55 199.85 97.5 199.8 C96.32 198.62 99.05 185.75 94.5 187.86 Z" },
- ],
- },
- monster: {
- id: "monster",
- name: "Monster",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 156, dx: 36, w: 27, h: 52, round: 46, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M62.5 85.83 C62.35 85.86 59.77 89.26 59.5 89.6 C57.48 92.13 51.44 101.28 48.5 101.5 C45.58 101.72 39.42 92.42 37.5 90.01 C36.59 88.88 34.53 86.24 34.5 86.25 C33.82 86.47 34 93.06 34 94 C34 102 34 110 34 118 C34 142 34 166 34 190 C34 201.71 32.25 214.47 41 223.75 C50.98 234.33 65.82 232 79 232 C103 232 127 232 151 232 C159.5 232 179.87 233.04 187 231.04 C196.89 228.27 204.38 219.67 205.76 209.5 C206.8 201.92 206 189.13 206 181 C206 162 206 143 206 124 C206 114.5 206 105 206 95.5 C206 92.69 206.04 86.51 206 86.5 C205.02 86.17 202.97 89.42 202.51 90 C200.52 92.51 195.5 100.01 193 101.23 C192.11 101.67 190.85 101.54 190 101.08 C188.02 99.98 182.32 91.88 180.5 89.6 C180.27 89.3 177.53 85.83 177.5 85.83 C176.98 85.81 174.43 89.26 174 89.8 C171.93 92.41 166.13 101.35 163 101.5 C160.25 101.63 153.88 92.16 152 89.8 C151.76 89.5 149.08 86.05 149 86.04 C147.81 85.89 146.09 88.85 145.5 89.6 C143.48 92.13 137.44 101.28 134.5 101.5 C130.72 101.78 122.19 86.67 120.5 86.25 C119.09 85.89 117.64 88.58 117 89.39 C115.13 91.74 108.86 100.75 106.5 101.4 C101.99 102.65 94.55 87.55 92.04 86.5 C90.19 85.73 88.38 89.32 87.5 90.43 C85.52 92.92 79.68 101.98 76.5 101.46 C73.7 101.01 67.54 91.73 65.5 89.18 C65.15 88.73 62.92 85.74 62.5 85.83 Z",
- parts: [
- { fill: "#8d8d8d", d: "M14.5 180.29 C13.19 180.99 12.59 181.55 12.13 183 C11.71 184.32 11.73 193.65 12.13 195 C12.45 196.1 13.06 196.94 14.07 197.5 C16.14 198.66 31.56 198 35 198 C37.29 198 40.56 198.62 42.5 197.12 C44.75 195.37 44.74 182.84 42.64 181 C40.99 179.55 38.5 180 36.5 180 C33.26 180 16.22 179.38 14.5 180.29 Z M198.5 180.29 C197.19 180.99 196.59 181.55 196.13 183 C195.71 184.32 195.73 193.65 196.13 195 C196.45 196.1 197.06 196.94 198.07 197.5 C200.14 198.66 215.56 198 219 198 C221.29 198 224.56 198.62 226.5 197.12 C228.75 195.37 228.74 182.84 226.64 181 C224.99 179.55 222.5 180 220.5 180 C217.26 180 200.22 179.38 198.5 180.29 Z" },
- { fill: "#6f6f6f", d: "M6 174.34 C2.94 176.55 4 181.14 4 184.5 C4 188.39 3.35 197.74 4.04 201 C4.3 202.25 4.84 203.05 6 203.66 C7.59 204.49 10.27 204 12 204 C13.45 204 15.23 204.3 16.5 203.37 C18.94 201.57 18 197.12 18 194.5 C18 191.27 18.73 176.79 17 175.05 C15.47 173.52 12.94 174 11 174 C9.71 174 7.11 173.53 6 174.34 Z M224 174.34 C220.94 176.55 222 181.14 222 184.5 C222 188.39 221.35 197.74 222.04 201 C222.3 202.25 222.84 203.05 224 203.66 C225.59 204.49 228.27 204 230 204 C231.45 204 233.23 204.3 234.5 203.37 C236.94 201.57 236 197.12 236 194.5 C236 191.27 236.73 176.79 235 175.05 C233.47 173.52 230.94 174 229 174 C227.71 174 225.11 173.53 224 174.34 Z" },
- { fill: "body", d: "M55 22.49 C44.2 24.71 35.73 33.52 34.24 44.5 C33.64 48.92 34 53.55 34 58 C34 96 34 134 34 172 C34 180 34 188 34 196 C34 200.93 33.53 206.14 34.49 211 C35.1 214.13 36.29 217.16 38 219.86 C46.73 233.59 60.38 232 74.5 232 C99 232 123.5 232 148 232 C156.48 232 178.53 232.92 185.5 231.41 C196.07 229.12 204.3 220.22 205.76 209.5 C206.43 204.6 206 199.44 206 194.5 C206 157 206 119.5 206 82 C206 74 206 66 206 58 C206 53.07 206.47 47.86 205.51 43 C204.9 39.87 203.71 36.84 202 34.14 C193.01 20 178.47 22 164 22 C140 22 116 22 92 22 C83.69 22 61.8 21.08 55 22.49 Z" },
- { fill: "#3d3d3d", d: "M55 18.42 C42.19 20.59 32 31.13 30.27 44 C29.41 50.36 30 57.09 30 63.5 C30 68 30 72.5 30 77 C30 77.97 29.55 80.79 30.5 81.5 C31.3 82.1 32.64 81.26 33.5 81.78 C34.97 82.67 36.42 85.45 37.5 86.8 C38.91 88.58 46.34 98.67 47.5 99.24 C49.39 100.17 50.54 97.63 51.45 96.5 C54.13 93.13 56.82 89.76 59.5 86.38 C59.73 86.1 62.49 82.62 62.5 82.62 C62.95 82.64 64.72 84.99 65 85.34 C67.67 88.69 70.33 92.04 73 95.38 C73.82 96.42 75.75 100.08 77.5 99.41 C78.97 98.85 86.46 88.53 88 86.59 C88.24 86.3 90.94 82.83 91 82.83 C92.18 82.73 93.9 85.63 94.5 86.38 C97.17 89.73 99.83 93.08 102.5 96.43 C103.26 97.39 104.41 99.72 106 99.46 C106.95 99.31 115.23 88.4 116.5 86.8 C116.79 86.44 119.31 83.08 119.5 83.04 C120.91 82.68 122.36 85.37 123 86.18 C125.67 89.52 128.33 92.87 131 96.22 C131.72 97.12 133.05 99.61 134.5 99.49 C135.82 99.38 137.28 96.71 138 95.8 C139.12 94.4 147.45 83.47 148 83.25 C149.78 82.5 151.66 86.16 152.5 87.22 C153.82 88.88 161.68 99.49 163 99.5 C164.27 99.51 172.2 88.86 173.5 87.22 C174.35 86.16 176.2 82.54 178 83.25 C178.45 83.42 186.93 94.46 188 95.8 C188.74 96.74 190.2 99.31 191.5 99.49 C192.89 99.69 194.33 97.06 195 96.22 C197.98 92.48 200.96 88.74 203.94 85 C204.62 84.14 205.16 83.13 206 82.41 C207.66 80.98 209.21 82.38 210 80 C210.52 78.45 210 67.49 210 65 C210 50.51 211.96 36.41 200 25.64 C188.98 15.71 173.68 18 160 18 C137 18 114 18 91 18 C82.08 18 62.75 17.11 55 18.42 Z" },
- ],
- },
- mummy: {
- id: "mummy",
- name: "Mummy",
- paint: "bone",
- bone: "#efe5cf",
- eyes: {cx: 120, cy: 119, dx: 30, w: 24, h: 24, round: 30, ink: "#f4efe4", mouthInk: "#0d0a10", mouthY: 170, mouth: true},
- clip: "M201.5 97.49 C164.5 98.63 127.5 99.77 90.5 100.91 C78 101.29 65.5 101.68 53 102.06 C48.3 102.21 42.56 101.73 38 102.52 C37.48 102.61 36.82 102.58 36.5 103 C36.25 103.33 36.5 109.62 36.5 110.5 C36.5 118 36.5 125.5 36.5 133 C36.5 133.71 36.42 140.42 36.5 140.5 C36.65 140.65 44.6 140.32 45.5 140.29 C55 140 64.5 139.71 74 139.42 C105.5 138.45 137 137.48 168.5 136.51 C177 136.25 185.5 135.98 194 135.72 C195.18 135.69 202.47 135.84 203 135.45 C203.86 134.81 203.5 127.83 203.5 126.5 C203.5 119 203.5 111.5 203.5 104 C203.5 103.31 203.7 98.26 203.5 98 C203.04 97.39 202.15 97.47 201.5 97.49 Z",
- parts: [
- { fill: "body", d: "M111 14.48 C76.78 18.38 47.65 43.09 38.8 76.5 C34.8 91.61 36 107.52 36 123 C36 140.11 34.75 157.49 40.13 174 C52.39 211.67 90.69 236.12 130 231.4 C163.8 227.35 192.49 202.41 201.2 169.5 C205.2 154.39 204 138.48 204 123 C204 105.89 205.25 88.51 199.87 72 C187.78 34.85 149.95 10.05 111 14.48 Z" },
- { fill: "#d8ccb2", d: "M174.5 35.45 C146.5 38.81 118.5 42.17 90.5 45.53 C79.5 46.85 68.5 48.17 57.5 49.49 C53.73 49.94 51.23 49.33 49.07 53 C48.78 53.49 47.97 54.03 48.28 54.5 C48.38 54.65 55.19 53.79 56 53.69 C63.5 52.79 71 51.89 78.5 50.99 C101.5 48.23 124.5 45.47 147.5 42.71 C155.5 41.75 163.5 40.79 171.5 39.83 C173.36 39.61 178.97 38.95 179 38.88 C179.56 37.71 175.8 35.29 174.5 35.45 Z M43 64.46 C42.99 64.47 41.71 67.42 41.73 67.5 C42.08 68.71 45.14 68.52 46 68.61 C49.5 68.96 53 69.31 56.5 69.66 C72 71.21 87.5 72.76 103 74.31 C128.5 76.86 154 79.41 179.5 81.96 C185.5 82.56 191.5 83.16 197.5 83.76 C199.48 83.96 202.33 85.3 202.56 82.5 C202.66 81.24 202.17 80.54 201 80.09 C198.79 79.24 189.02 78.89 186 78.59 C168.5 76.84 151 75.09 133.5 73.34 C110.5 71.04 87.5 68.74 64.5 66.44 C59 65.89 53.5 65.34 48 64.79 C47.4 64.73 43.12 64.28 43 64.46 Z M36.5 145.97 C33.26 150.75 40.97 150.53 43.5 150.83 C52.5 151.91 61.5 152.99 70.5 154.07 C100 157.61 129.5 161.15 159 164.69 C170 166.01 181 167.33 192 168.65 C192.91 168.76 200.81 169.85 201 169.71 C201.48 169.35 201.42 168.58 201.58 168 C201.73 167.51 202.15 166.97 201.94 166.5 C201.4 165.34 195.79 165.08 194.5 164.93 C186.5 163.97 178.5 163.01 170.5 162.05 C137.5 158.09 104.5 154.13 71.5 150.17 C62.5 149.09 53.5 148.01 44.5 146.93 C42 146.63 39.5 146.33 37 146.03 C36.83 146.01 36.59 145.83 36.5 145.97 Z M195 178.49 C158 182.19 121 185.89 84 189.59 C75 190.49 66 191.39 57 192.29 C56.12 192.38 49.54 193 49.5 193.15 C49.31 193.81 50.04 194.41 50.38 195 C51.95 197.75 54.8 196.53 57.5 196.26 C66.5 195.36 75.5 194.46 84.5 193.56 C110.5 190.96 136.5 188.36 162.5 185.76 C167.23 185.29 193.16 183.27 195.5 182.46 C197.22 181.86 197.03 181.54 197.67 180 C198.87 177.08 197.1 178.28 195 178.49 Z M63 209.43 C63 209.92 66.26 212.65 66.79 213 C69.51 214.78 78.4 214.68 82 214.97 C102.5 216.61 123 218.25 143.5 219.89 C146.75 220.15 159.21 221.83 161.5 221.03 C161.84 220.92 166 218.31 166 218.29 C166 217.49 163.3 217.46 163 217.43 C159.5 217.15 156 216.87 152.5 216.59 C138 215.43 123.5 214.27 109 213.11 C99 212.31 89 211.51 79 210.71 C75.5 210.43 72 210.15 68.5 209.87 C67 209.75 65.5 209.63 64 209.51 C63.67 209.49 63 209.1 63 209.43 Z" },
- { fill: "#0d0a10", d: "M201.5 97.49 C164.5 98.63 127.5 99.77 90.5 100.91 C78 101.29 65.5 101.68 53 102.06 C48.3 102.21 42.56 101.73 38 102.52 C37.48 102.61 36.82 102.58 36.5 103 C36.25 103.33 36.5 109.62 36.5 110.5 C36.5 118 36.5 125.5 36.5 133 C36.5 133.71 36.42 140.42 36.5 140.5 C36.65 140.65 44.6 140.32 45.5 140.29 C55 140 64.5 139.71 74 139.42 C105.5 138.45 137 137.48 168.5 136.51 C177 136.25 185.5 135.98 194 135.72 C195.18 135.69 202.47 135.84 203 135.45 C203.86 134.81 203.5 127.83 203.5 126.5 C203.5 119 203.5 111.5 203.5 104 C203.5 103.31 203.7 98.26 203.5 98 C203.04 97.39 202.15 97.47 201.5 97.49 Z" },
- ],
- },
- vampire: {
- id: "vampire",
- name: "Vampire",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 150, dx: 28, w: 22, h: 42, round: 38, ink: "#7a0f24", mouth: true, mouthInk: "#7a0f24", mouthY: null},
- clip: "M90.5 74.47 C84.48 75.44 78.4 77.7 72.5 79.27 C70.54 79.79 64.93 80.75 63.5 81.67 C61.68 82.85 59.36 87.13 58.03 89 C49.89 100.39 47.02 115.7 46.19 129.5 C44.07 165.18 60.28 205.2 94.5 220.49 C105.75 225.51 118.34 227.21 130.5 225.09 C176.27 217.11 198.13 165.57 193.28 123.5 C192.29 114.91 189.54 100.92 185.19 93.5 C183.7 90.97 181.7 88.63 180 86.24 C179.11 85 178.17 83 177 82.04 C175.59 80.88 159.05 77.02 156 76.2 C154.71 75.86 149.54 74.05 148.5 74.47 C147.76 74.76 145.18 78.26 144.5 79.04 C140.5 83.61 136.5 88.18 132.5 92.75 C129.5 96.18 126.5 99.61 123.5 103.04 C122.66 103.99 121.5 106 120 106 C118.37 106 114.64 100.91 113.5 99.61 C108.17 93.51 102.83 87.42 97.5 81.32 C96.28 79.93 92.06 74.22 90.5 74.47 Z",
- parts: [
- { fill: "#3d3d3d", d: "M23 108.27 C21.28 109.28 22.11 112.42 22.18 114 C22.41 119 22.63 124 22.86 129 C23.63 146 24.41 163 25.18 180 C25.33 183.4 25.18 197.44 26.68 199.5 C28.01 201.33 30.32 202.94 31.97 204.5 C37.79 210 43.62 215.5 49.44 221 C52.16 223.57 60.5 232.29 63 233.73 C64.91 234.82 77.88 237.02 81 237.69 C90.5 239.72 100 241.76 109.5 243.8 C112.77 244.5 116.66 246 120 246 C123.19 246 143.69 240.97 148.5 239.94 C152.57 239.07 175.06 234.84 177 233.73 C179.54 232.27 183.95 227.24 186.32 225 C192.55 219.12 198.77 213.24 205 207.36 C207.09 205.39 213.34 200.67 214 198.02 C214.74 195.06 214.65 183.83 214.82 180 C215.39 167.5 215.96 155 216.52 142.5 C216.91 134 217.3 125.5 217.68 117 C217.77 115.16 218.7 109.27 217 108.27 C214.68 106.91 211.26 112.91 210.04 114.5 C203.36 123.24 196.68 131.97 190 140.71 C183.68 148.97 177.36 157.24 171.04 165.5 C169.44 167.59 164.63 174.77 163.01 176 C161.21 177.37 157.66 177.66 155.5 178.25 C149 180.02 142.5 181.79 136 183.56 C132.6 184.49 122.37 188.05 119.5 187.79 C117.06 187.57 114.37 186.39 112 185.75 C105 183.84 98 181.93 91 180.02 C88.54 179.35 79.05 177.31 77.5 176.34 C75.46 175.05 71.68 169.06 70 166.86 C64 159.02 58 151.17 52 143.32 C45 134.17 38 125.02 31 115.86 C29.7 114.17 25.29 106.92 23 108.27 Z" },
- { fill: "accent", d: "M31 129.08 C30.83 129.18 31.08 133.51 31.1 134 C31.3 138.5 31.51 143 31.71 147.5 C32.23 159 32.76 170.5 33.28 182 C33.38 184.26 33.26 194.09 34.09 195.5 C35.17 197.32 41.21 202.22 43.09 204 C48.73 209.32 54.36 214.65 60 219.97 C62.03 221.89 64.08 224.44 66.39 226 C68.95 227.74 86.26 230.63 90.5 231.54 C96.75 232.88 105.4 235.43 111.5 236 C115.59 236.38 125.58 236.47 129.5 235.83 C137.54 234.51 145.53 232.39 153.5 230.69 C156.99 229.94 170.79 227.62 173 226.51 C175.03 225.49 180.56 219.44 182.5 217.61 C187.67 212.73 192.83 207.85 198 202.97 C199.86 201.22 204.77 197.42 205.91 195.5 C206.62 194.3 206.5 186.83 206.58 185 C207.02 175.5 207.45 166 207.88 156.5 C208.2 149.5 208.52 142.5 208.83 135.5 C208.92 133.72 209.19 129.54 209.11 129.5 C208.57 129.27 203.65 136.03 202.52 137.5 C195.52 146.66 188.51 155.83 181.5 164.99 C178.96 168.31 169.94 181.38 167.31 183 C164.18 184.92 155.89 186.43 152 187.49 C144.5 189.54 137 191.58 129.5 193.63 C126.63 194.41 123.47 195.74 120.5 195.98 C117.18 196.25 111.81 193.99 108.5 193.08 C100.5 190.9 92.5 188.72 84.5 186.54 C81.26 185.65 75.08 184.81 72.5 182.87 C69.62 180.71 59.01 165.66 56 161.72 C49.67 153.44 43.33 145.16 37 136.88 C34.7 133.87 31.03 129.05 31 129.08 Z" },
- { fill: "#f2eef4", d: "M112.5 46.46 C98.93 48.14 86.29 54.43 76.15 63.5 C44.86 91.51 38.25 141.01 54.77 178.5 C67.45 207.29 95.18 229.81 128 225.47 C141.63 223.67 154.29 217.22 164.4 208 C195.36 179.76 201.71 130.34 185.01 93 C172.31 64.61 144.93 42.44 112.5 46.46 Z" },
- { fill: "#3d3d3d", d: "M112 42.49 C89.7 45.35 70.68 59.42 58.6 78 C55.5 82.75 52.85 87.79 50.63 93 C50.47 93.36 48.79 97.47 48.83 97.5 C49.49 97.91 52.03 93.96 52.36 93.5 C54.54 90.45 59.14 82.93 61.5 80.7 C63.5 78.81 80.21 75.14 84 74.13 C85.49 73.74 90.24 71.93 91.5 72.13 C93.06 72.39 96.82 77.5 98 78.86 C103.33 84.95 108.67 91.05 114 97.14 C115.67 99.05 117.33 100.95 119 102.86 C119.33 103.24 119.49 104 120 104 C120.51 104 120.67 103.24 121 102.86 C123 100.57 125 98.29 127 96 C132 90.29 137 84.57 142 78.86 C142.67 78.09 147.64 72.11 148 72 C148.73 71.78 154.39 73.71 155.5 74 C158.39 74.77 176.92 79.22 178 80 C179.49 81.07 186.35 91.69 188 94 C188.99 95.38 190.99 98.2 191 98.2 C191.69 97.94 188.7 91.44 188.27 90.5 C184.89 83.14 180.63 76.18 175.5 69.92 C160.15 51.18 136.5 39.36 112 42.49 Z" },
- ],
- },
- spider: {
- id: "spider",
- name: "Spider",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 142, dx: 28, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M111.5 64.49 C100.9 65.75 90.63 69.24 81.5 74.8 C73.1 79.92 65.76 86.72 60 94.69 C29.57 136.79 51.51 197.11 102 209.78 C110.8 211.98 120 212.55 129 211.45 C139.53 210.16 149.8 206.59 158.82 201 C202.82 173.75 205.99 110.29 164.67 79 C157.16 73.32 148.58 69.1 139.5 66.62 C130.43 64.14 120.84 63.38 111.5 64.49 Z",
- parts: [
- { fill: "#8d8d8d", d: "M119.5 -1.2 C118.33 -0.73 118.7 8.01 118.7 9.5 C118.7 20 118.7 30.5 118.7 41 C118.7 48 118.7 55 118.7 62 C118.7 62.99 117.97 68.21 120.5 67.2 C121.67 66.73 121.3 57.99 121.3 56.5 C121.3 46 121.3 35.5 121.3 25 C121.3 18 121.3 11 121.3 4 C121.3 3.01 122.03 -2.21 119.5 -1.2 Z" },
- { fill: "#3d3d3d", d: "M26 56.34 C22.33 58.06 6.97 75.56 3 79.77 C0.83 82.08 -2.54 85.01 -0.33 88.5 C0.9 90.45 3.25 91.52 5.5 90.77 C8.52 89.76 18.53 79.17 21.5 76.37 C22.78 75.17 26.71 70.42 28.5 71.33 C29.8 71.99 35.57 78.91 37.05 80.5 C43.27 87.17 49.49 93.83 55.71 100.5 C59.14 104.17 63.66 111.14 69.46 107.5 C76.32 103.2 70.53 97.33 67 93.69 C57.67 84.04 48.33 74.39 39 64.74 C36.15 61.79 30.77 54.11 26 56.34 Z M210 56.34 C206.02 58.21 200.28 65.48 197 68.88 C190.51 75.58 184.02 82.29 177.53 89 C174.72 91.91 171.28 94.74 168.88 98 C165.76 102.22 168.57 108.5 174 108.5 C178.19 108.5 180.94 104.08 183.5 101.35 C190.5 93.84 197.5 86.34 204.5 78.83 C205.33 77.95 211.72 70.85 212 70.8 C212.81 70.63 216.85 74.82 217.5 75.43 C221.83 79.51 226.17 83.6 230.5 87.68 C232.57 89.63 234.89 92.04 238 90.58 C240.63 89.35 241.87 86.06 240.33 83.5 C238.37 80.24 222.75 64.66 219 60.68 C216.77 58.32 213.77 54.57 210 56.34 Z M10 100.34 C6.57 101.78 5.82 105.35 4.59 108.5 C2.09 114.91 -3.16 126.5 -4.77 132.5 C-5.53 135.33 -3.96 138.26 -1 138.9 C0.61 139.25 2.32 138.71 3.5 137.57 C5.71 135.43 10 124.43 11.6 121 C12.42 119.26 13.6 114.34 16 114.47 C17.05 114.52 22.23 117.36 23.5 117.95 C30 120.96 36.5 123.98 43 126.99 C46.52 128.62 51.06 131.92 55 129.77 C59.03 127.57 59.76 121.75 56 118.88 C52.96 116.56 27.09 106.04 21.5 103.6 C18.36 102.23 13.53 98.87 10 100.34 Z M226 100.34 C219.38 102.72 212.95 106.02 206.5 108.84 C199.54 111.87 192.26 114.55 185.5 118 C180.19 120.71 180.18 128.78 186.5 130.32 C190.04 131.19 193.9 128.43 196.98 127 C203.45 124 209.92 121 216.39 118 C218.23 117.14 222.07 114.72 223.93 114.5 C226.17 114.23 227.56 119.21 228.4 121 C229.98 124.38 234.35 135.35 236.43 137.5 C237.58 138.69 239.38 139.25 241 138.9 C243.96 138.26 245.53 135.33 244.77 132.5 C243.68 128.44 241.63 124.42 240.1 120.5 C237.96 115.03 236.1 109.34 233.66 104 C232.3 101.03 229.26 99.18 226 100.34 Z M44 145.99 C35 146.55 26 147.11 17 147.68 C13.65 147.89 9.05 147.35 7 150.69 C5.17 153.67 4.75 159.49 4.03 163 C2.4 170.92 0.13 178.98 -0.9 187 C-1.28 189.93 0.44 192.59 3.5 192.97 C6.77 193.39 8.45 190.72 9.17 188 C11.04 181 12.89 174 14.75 167 C15.25 165.14 15.54 160.73 17.5 159.8 C18.46 159.34 24.99 159.52 26.5 159.46 C31.8 159.26 49.63 159.28 53.5 158.32 C58.63 157.06 60.29 150.15 56 146.88 C52.8 144.44 47.71 145.76 44 145.99 Z M186 145.82 C179.25 148.05 180.72 157.67 187.5 158.48 C195.76 159.46 206 159.18 214.5 159.5 C216.14 159.56 222.53 159.3 223.5 160.42 C224.25 161.29 225.14 166.61 225.51 168 C227.36 174.96 228.87 182.15 231.09 189 C232.47 193.22 237.75 194.57 240.33 190.5 C242.19 187.56 238.67 176.18 237.92 172.5 C237.05 168.24 234.71 152.61 232.5 150.03 C230.09 147.23 225.33 147.82 222 147.61 C214 147.11 206 146.61 198 146.11 C194.69 145.91 189.07 144.8 186 145.82 Z M62 171.82 C59.08 172.78 56.4 175.64 54 177.5 C47.94 182.16 41.87 186.83 35.81 191.5 C33.36 193.38 28.56 196.15 27 198.69 C25.09 201.8 24.02 214.22 23.36 218.5 C22.82 221.95 20.49 232.18 21.1 235 C21.37 236.25 21.99 237.19 23 238 C27 241.21 30.4 237.25 31.23 233.5 C32.65 227.01 34.08 220.52 35.5 214.03 C36.06 211.47 36.18 207.04 38 205.05 C39.42 203.49 41.79 202.27 43.5 201.03 C49.44 196.69 55.39 192.34 61.33 188 C63.95 186.09 67.63 184.22 69.48 181.5 C72.84 176.54 67.56 169.97 62 171.82 Z M174 171.82 C168.53 173.63 168.37 180.28 172.5 183.49 C179.62 189.04 187.12 194.17 194.41 199.5 C196.09 200.73 201.55 204.03 202.5 205.41 C203.45 206.81 203.88 211.21 204.27 213 C205.7 219.5 207.13 226 208.55 232.5 C209.34 236.06 211.26 240.8 216 238.58 C217.67 237.8 218.74 236.33 218.97 234.5 C219.36 231.5 217.12 221.59 216.56 218 C215.98 214.28 214.65 200.87 212.87 198.5 C210.6 195.47 194.7 184.19 190.55 181 C186.69 178.02 179.05 170.14 174 171.82 Z" },
- { fill: "body", d: "M111.5 64.49 C100.9 65.75 90.63 69.24 81.5 74.8 C73.1 79.92 65.76 86.72 60 94.69 C29.57 136.79 51.51 197.11 102 209.78 C110.8 211.98 120 212.55 129 211.45 C139.53 210.16 149.8 206.59 158.82 201 C202.82 173.75 205.99 110.29 164.67 79 C157.16 73.32 148.58 69.1 139.5 66.62 C130.43 64.14 120.84 63.38 111.5 64.49 Z" },
- ],
- },
- rocket: {
- id: "rocket",
- name: "Rocket",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 136, dx: 24, w: 20, h: 38, round: 34, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M84.5 92.44 C73.32 95.79 74 105.01 74 114.5 C74 134 74 153.5 74 173 C74 179.43 72.79 193.18 75.6 198.5 C79.55 205.97 86.14 206 93.5 206 C107.5 206 121.5 206 135.5 206 C141.06 206 151.57 206.94 156.5 205.26 C166.84 201.72 166 192.32 166 183.5 C166 163.5 166 143.5 166 123.5 C166 116.39 167.52 103.86 163.5 98.02 C159.05 91.55 151.95 92 145 92 C131.5 92 118 92 104.5 92 C99.62 92 88.68 91.19 84.5 92.44 Z",
- parts: [
- { fill: "#8d8d8d", d: "M118 195.42 C113.86 197.91 115.06 202.85 115.15 207 C115.38 218 115.6 229 115.83 240 C115.91 243.49 114.51 251.33 119.5 251.97 C125.29 252.7 124.07 244.44 124.15 241 C124.41 228.5 124.67 216 124.93 203.5 C124.96 202.08 125.21 200.4 124.9 199 C124.29 196.26 120.75 193.77 118 195.42 Z" },
- { fill: "#ffc93c", d: "M84 213.4 C82.94 213.74 81.82 222.52 80.78 224 C79.27 226.14 70.96 226.4 70.5 227.28 C69.33 229.53 78.59 230.23 80 231.22 C82.14 232.73 82.4 241.04 83.28 241.5 C85.53 242.67 86.23 233.41 87.22 232 C88.73 229.86 97.04 229.6 97.5 228.72 C98.81 226.21 88.45 226.3 87 223.63 C85.53 220.92 85.89 217.33 84.72 214.5 C84.55 214.1 84.42 213.27 84 213.4 Z M158 223.4 C156.36 224.56 156.92 229.31 155.55 231 C154.23 232.63 148.14 232.93 148 233.4 C147.47 235.25 153.92 235.58 155 236.45 C156.63 237.77 156.93 243.86 157.4 244 C159.25 244.53 159.58 238.08 160.45 237 C161.77 235.37 167.86 235.07 168 234.6 C168.53 232.75 162.08 232.42 161 231.55 C158.88 229.83 159.6 226.27 158.6 224 C158.49 223.74 158.23 223.24 158 223.4 Z" },
- { fill: "body", d: "M84.5 92.44 C73.32 95.79 74 105.01 74 114.5 C74 134 74 153.5 74 173 C74 179.43 72.79 193.18 75.6 198.5 C79.55 205.97 86.14 206 93.5 206 C107.5 206 121.5 206 135.5 206 C141.06 206 151.57 206.94 156.5 205.26 C166.84 201.72 166 192.32 166 183.5 C166 163.5 166 143.5 166 123.5 C166 116.39 167.52 103.86 163.5 98.02 C159.05 91.55 151.95 92 145 92 C131.5 92 118 92 104.5 92 C99.62 92 88.68 91.19 84.5 92.44 Z" },
- { fill: "#fff3dc", d: "M74.5 178 C74.01 178.37 73.72 191.13 74 191.5 C74.32 191.92 74.98 191.91 75.5 192 C79.35 192.64 93.12 192 98 192 C113.5 192 129 192 144.5 192 C150 192 155.5 192 161 192 C162.97 192 165.59 192.94 166 190.5 C166.16 189.56 166.17 178.73 166 178.5 C165.39 177.69 161.04 178 160 178 C155 178 150 178 145 178 C127.5 178 110 178 92.5 178 C88 178 83.5 178 79 178 C78.56 178 74.65 177.88 74.5 178 Z" },
- { fill: "#3d3d3d", d: "M118 14.34 C114.29 15.71 108.91 27.66 106.79 31.5 C97.95 47.5 89.11 63.5 80.26 79.5 C78.24 83.17 73.15 90.9 72.19 94.5 C71.8 95.98 72.01 97.69 72.81 99 C73.75 100.55 75.21 101.59 77 101.92 C81.22 102.68 90.27 102 95 102 C111 102 127 102 143 102 C147.08 102 161.03 102.75 164 101.66 C172.74 98.43 164.27 87.7 161.67 83 C152 65.5 142.33 48 132.66 30.5 C130.72 27 126.58 17.88 124 15.53 C122.41 14.08 120.02 13.6 118 14.34 Z" },
- ],
- },
- anaar: {
- id: "anaar",
- name: "Anaar",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 170, dx: 26, w: 22, h: 40, round: 36, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M85.5 97.46 C83.8 98.28 82.55 99.28 81.68 101 C79.47 105.36 75.47 119.45 73.62 125 C64.95 151 56.29 177 47.62 203 C45.29 210 42.95 217 40.62 224 C39.47 227.46 37.89 231.06 40.5 234.33 C43.03 237.5 46.89 237 50.5 237 C59 237 67.5 237 76 237 C105 237 134 237 163 237 C171 237 179 237 187 237 C190.24 237 194.59 237.78 197.5 236.06 C203.71 232.4 199.73 225.07 198.05 220 C193.05 205 188.05 190 183.05 175 C176.71 156 170.38 137 164.05 118 C162.7 113.98 159.82 102.92 157.74 100 C157 98.96 156.14 98.24 155 97.68 C151.84 96.12 145.11 97 141.5 97 C132 97 122.5 97 113 97 C106.5 97 100 97 93.5 97 C91.12 97 87.71 96.39 85.5 97.46 Z",
- parts: [
- { fill: "#ffc93c", d: "M119 5.71 C116.56 7.31 117.27 11.92 117.13 14.5 C116.63 23 116.14 31.5 115.65 40 C115.58 41.37 115.32 49.98 114.55 50.5 C112.6 51.82 110.67 45.61 110.21 44.5 C107.69 38.5 105.18 32.5 102.67 26.5 C101.93 24.72 100.92 19.95 98 20.92 C94.8 21.99 96.74 25.86 97.31 28 C99.04 34.49 100.77 40.98 102.5 47.47 C102.75 48.42 104.49 54.52 103.71 55 C102.24 55.9 98.4 50.91 97.5 49.89 C92.84 44.59 88.17 39.3 83.51 34 C81.99 32.28 79.13 28.39 77.05 32 C76.18 33.51 77.75 35.16 78.5 36.29 C81.17 40.29 83.83 44.29 86.5 48.3 C91.5 55.81 96.5 63.31 101.5 70.82 C104.14 74.79 107.27 78.72 109.39 83 C110.59 85.4 110.6 88.16 111.97 90.5 C114.3 94.45 119.21 96.31 123.5 94.51 C129.49 91.99 129.75 84.46 132.76 79.5 C139.59 68.24 147.4 57.46 154.7 46.5 C156.1 44.39 163.2 34.78 163.17 33 C163.16 32.47 163 31.9 162.65 31.5 C159.85 28.35 156.6 33.88 155 35.7 C150.67 40.61 146.33 45.53 142 50.45 C141.38 51.16 138.17 55 137.51 55 C134.61 55 137.38 47.94 137.76 46.5 C139.36 40.5 140.96 34.5 142.56 28.5 C143.13 26.36 145.07 22.67 142.5 21.12 C139.53 19.32 138.26 24.27 137.54 26 C135.03 32 132.51 38 130 44 C129.58 45.01 127.2 51.27 126.08 51 C124.62 50.65 124.54 43.36 124.46 42 C123.94 33 123.42 24 122.9 15 C122.81 13.36 123.24 2.93 119 5.71 Z" },
- { fill: "#fff3c4", d: "M118.5 36.36 C114.78 38.21 113.38 43.83 112.53 47.5 C110.82 54.8 110.6 62.56 111.44 70 C111.72 72.5 112.49 75 112.62 77.5 C112.77 80.03 111.72 82.46 112.06 85 C112.75 90.08 118.2 93.41 123 91.42 C130.09 88.47 127.07 82.94 127.38 77.5 C127.51 75 128.28 72.5 128.56 70 C129.4 62.56 129.18 54.8 127.47 47.5 C126.7 44.21 123.66 33.8 118.5 36.36 Z" },
- { fill: "#ffc93c", d: "M120 -3.6 C118.09 -2.25 119.38 2.17 117 3.91 C115.7 4.86 111.13 4.95 111 5.4 C110.48 7.21 116.67 7.3 117.91 9 C118.86 10.3 118.95 14.87 119.4 15 C121.23 15.53 121.36 10.39 121.84 9.5 C123.09 7.14 128.92 6.87 129 6.6 C129.52 4.79 123.33 4.7 122.09 3 C120.9 1.37 121.38 -1.21 120.6 -3 C120.49 -3.26 120.23 -3.76 120 -3.6 Z M56 22.4 C53.85 23.91 55.2 29.53 52.54 31.5 C50.93 32.7 45.18 32.78 45 33.4 C44.45 35.34 52.08 35.53 53.5 37.46 C54.7 39.07 54.78 44.82 55.4 45 C57.3 45.54 57.67 39.05 58.23 38 C59.66 35.35 66.89 35 67 34.6 C67.55 32.66 59.92 32.47 58.5 30.54 C57.02 28.54 57.59 25.22 56.6 23 C56.48 22.74 56.23 22.24 56 22.4 Z M184 22.4 C181.85 23.91 183.2 29.53 180.54 31.5 C178.93 32.7 173.18 32.78 173 33.4 C172.45 35.34 180.08 35.53 181.5 37.46 C182.7 39.07 182.78 44.82 183.4 45 C185.3 45.54 185.67 39.05 186.23 38 C187.66 35.35 194.89 35 195 34.6 C195.55 32.66 187.92 32.47 186.5 30.54 C185.02 28.54 185.59 25.22 184.6 23 C184.48 22.74 184.23 22.24 184 22.4 Z" },
- { fill: "body", d: "M85.5 97.46 C83.8 98.28 82.55 99.28 81.68 101 C79.47 105.36 75.47 119.45 73.62 125 C64.95 151 56.29 177 47.62 203 C45.29 210 42.95 217 40.62 224 C39.47 227.46 37.89 231.06 40.5 234.33 C43.03 237.5 46.89 237 50.5 237 C59 237 67.5 237 76 237 C105 237 134 237 163 237 C171 237 179 237 187 237 C190.24 237 194.59 237.78 197.5 236.06 C203.71 232.4 199.73 225.07 198.05 220 C193.05 205 188.05 190 183.05 175 C176.71 156 170.38 137 164.05 118 C162.7 113.98 159.82 102.92 157.74 100 C157 98.96 156.14 98.24 155 97.68 C151.84 96.12 145.11 97 141.5 97 C132 97 122.5 97 113 97 C106.5 97 100 97 93.5 97 C91.12 97 87.71 96.39 85.5 97.46 Z" },
- { fill: "#fff3dc", d: "M76 118 C75.28 118.7 72.97 126.95 72.45 128.5 C72.12 129.5 70.97 130.57 71.45 131.5 C71.94 132.43 75.2 132 76 132 C80.5 132 85 132 89.5 132 C108.5 132 127.5 132 146.5 132 C152 132 157.5 132 163 132 C164.65 132 168.04 132.94 168.21 130.5 C168.25 130.02 164.42 118.69 164.21 118.5 C163.17 117.56 149.79 118 147.5 118 C131.5 118 115.5 118 99.5 118 C93.5 118 87.5 118 81.5 118 C80.99 118 76.06 117.94 76 118 Z" },
- { fill: "#3d3d3d", d: "M102.5 86.46 C98.27 88.32 98 91.95 98 96 C98 99.72 98.12 103.49 102 105.32 C104.64 106.57 108.16 106 111 106 C115.81 106 134.81 106.83 138 105.32 C143.72 102.62 143.72 89.38 138 86.68 C134.81 85.17 115.81 86 111 86 C108.41 86 104.93 85.4 102.5 86.46 Z" },
- ],
- },
- chakri: {
- id: "chakri",
- name: "Chakri",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 126, dx: 24, w: 20, h: 38, round: 34, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M111 46.47 C98.86 47.75 87.03 51.64 76.5 57.81 C66.82 63.49 58.28 71.06 51.5 80 C14.9 128.24 38.89 199.11 97.48 215 C107.72 217.78 118.45 218.64 129 217.53 C141.14 216.25 152.97 212.36 163.5 206.19 C173.18 200.51 181.72 192.94 188.5 184 C225.1 135.76 201.11 64.89 142.52 49 C132.28 46.22 121.55 45.36 111 46.47 Z",
- parts: [
- { fill: "#ffc93c", d: "M74 30.45 C70.49 31.64 64.72 37 62 39.72 C51.88 49.87 45.59 62.85 43.61 77 C42.81 82.68 41.74 95.72 48 98.45 C52.15 100.26 56.99 97.42 57.65 93 C58.04 90.36 55.7 83.04 55.4 79.5 C54.75 71.87 56.06 64.16 58.69 57 C61.05 50.58 64.6 44.67 69 39.44 C70.84 37.26 73.16 35.52 75 33.38 C76.08 32.13 76.14 29.72 74 30.45 Z M150.5 33.46 C138.12 34.29 126.42 38.39 116.5 45.91 C111.03 50.06 112.32 59 120 59 C124.16 59 126.63 55.04 129.5 52.61 C134.19 48.64 139.68 45.6 145.5 43.64 C153.7 40.86 162.4 40.01 171 40.99 C172.62 41.18 184.35 43.93 184.5 43.85 C188.58 41.74 178.17 38.02 177 37.57 C168.7 34.37 159.39 32.87 150.5 33.46 Z M187 85.38 C181.77 87.68 180.52 94.47 185.5 97.89 C188.08 99.66 192.92 100.18 195.99 101.5 C202.87 104.47 208.94 108.98 213.99 114.5 C218.86 119.84 222.71 126.24 225.24 133 C225.71 134.24 228.08 143.29 228.31 143.5 C228.74 143.9 229.44 144.2 229.99 144 C231.59 143.4 230.9 140.64 230.84 139.5 C230.55 134.43 229.53 129.32 227.91 124.5 C223.32 110.78 214.55 99.06 202.5 91.03 C199.18 88.81 191.04 83.6 187 85.38 Z M10.5 119.91 C8.34 120.32 9.07 122.57 9.14 124 C9.38 129.07 10.36 134.17 11.91 139 C16.47 153.16 25.72 165.52 38.3 173.5 C42.52 176.18 50.17 181.49 55 177.54 C58.29 174.85 58.61 170.04 55.61 167 C53.12 164.47 48.22 164.22 45 162.93 C38.4 160.29 32.46 156.11 27.5 151.05 C21.93 145.35 17.55 138.46 14.76 131 C14.14 129.35 12.19 121.12 11.69 120.5 C11.42 120.15 10.94 119.83 10.5 119.91 Z M187 165.38 C184.27 166.58 182.27 168.88 182.28 172 C182.3 175.45 184 179.03 184.4 182.5 C185.35 190.59 184.28 198.82 181.5 206.47 C179.01 213.3 175.31 219.7 170.5 225.16 C169.45 226.36 164.6 230.52 164.21 231.5 C163.69 232.82 164.75 233.69 166 233.55 C168.2 233.31 176.11 226.18 178 224.28 C188.58 213.68 195.87 199.08 196.67 184 C196.96 178.59 197.96 168.15 192 165.55 C190.54 164.91 188.5 164.72 187 165.38 Z M117.5 205.46 C114.7 206.69 109.27 212.67 105.65 215 C98.01 219.9 89.04 222.68 80 223.3 C74.5 223.67 68.88 223.28 63.5 222.08 C62.07 221.76 57.07 219.8 56 220.03 C54.77 220.29 54.13 221.41 54.95 222.5 C56.54 224.63 67.12 227.84 70 228.61 C85.91 232.86 103.96 230.48 118 221.84 C120.3 220.42 122.96 218.92 124.9 217 C130 211.92 124.39 202.44 117.5 205.46 Z" },
- { fill: "body", d: "M111 46.47 C98.86 47.75 87.03 51.64 76.5 57.81 C66.82 63.49 58.28 71.06 51.5 80 C14.9 128.24 38.89 199.11 97.48 215 C107.72 217.78 118.45 218.64 129 217.53 C141.14 216.25 152.97 212.36 163.5 206.19 C173.18 200.51 181.72 192.94 188.5 184 C225.1 135.76 201.11 64.89 142.52 49 C132.28 46.22 121.55 45.36 111 46.47 Z" },
- { fill: "#3d3d3d", d: "M151.5 53.91 C149.68 54.3 148.66 56.44 149.83 58 C150.98 59.53 155.66 61.23 157.5 62.31 C161.79 64.82 165.84 67.73 169.58 71 C182.08 81.92 190.92 96.78 194.43 113 C203.28 153.79 177.05 195.2 135.5 202.65 C84.6 211.77 39.51 164.21 55.93 114 C58.35 106.59 62.08 99.6 66.93 93.5 C72.41 86.61 79.25 80.84 87 76.67 C116.65 60.68 154.62 70.66 171.14 100.5 C177.43 111.85 179.88 125.17 177.92 138 C177.3 142.1 176.23 146.13 174.75 150 C174.19 151.45 173.19 153.01 172.81 154.5 C172.19 156.98 174.88 159.06 177 157.29 C180.8 154.11 183.66 135.74 183.77 130.5 C184.39 100.13 162.81 73.06 133.5 65.81 C124.69 63.62 115.46 63.25 106.5 64.67 C97.48 66.1 88.78 69.34 81 74.13 C74.14 78.36 68.02 83.8 63 90.1 C31.87 129.13 49.92 186.89 96 204.13 C156.15 226.64 214.37 169.92 198.83 109 C194.01 90.12 182.41 73.32 166.57 62 C164.36 60.42 153.86 53.41 151.5 53.91 Z" },
- ],
- },
- sparkler: {
- id: "sparkler",
- name: "Sparkler",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 104, dx: 24, w: 21, h: 40, round: 36, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M112.5 46.46 C104.13 47.48 95.94 50.21 88.67 54.5 C41.85 82.12 50.89 153.23 103.5 167.76 C111.29 169.91 119.48 170.52 127.5 169.54 C135.87 168.52 144.06 165.79 151.33 161.5 C198.15 133.88 189.11 62.77 136.5 48.24 C128.71 46.09 120.52 45.48 112.5 46.46 Z",
- parts: [
- { fill: "#8d8d8d", d: "M118 155.97 C116.82 156.76 116.29 157.12 115.76 158.5 C114.81 160.99 115.57 171.69 115.59 175 C115.69 193 115.8 211 115.9 229 C115.92 232.52 115.37 244.42 116.13 247 C116.59 248.57 117.85 249.76 119.5 249.97 C121.12 250.17 122.71 249.35 123.5 247.93 C124.83 245.56 124.07 233.41 124.09 230 C124.21 210.5 124.32 191 124.43 171.5 C124.46 167.4 126.07 157.51 121.5 155.76 C120.5 155.38 118.93 155.35 118 155.97 Z" },
- { fill: "#ffc93c", d: "M147.5 0 C146.05 0.87 144.26 7.21 143.57 9 C140.94 15.9 136.25 26.33 134.42 33 C133.53 36.24 135.58 39.61 139 40.05 C142.95 40.55 144.77 37.34 145.31 34 C146.75 25 148.2 16 149.64 7 C149.95 5.1 151.62 0.75 149 -0.18 C148.53 -0.35 147.93 -0.26 147.5 0 Z M94.5 13.38 C92.16 14.23 93.48 18.71 93.64 20.5 C93.94 23.84 94.18 34.58 95.39 37 C96.66 39.55 99.86 40.85 102.5 39.64 C104.51 38.73 105.89 36.74 105.83 34.5 C105.76 31.79 100.69 22.52 99.29 19.5 C98.53 17.87 97.1 12.44 94.5 13.38 Z M41.5 28.35 C40.38 28.74 39.99 29.99 40.38 31 C41.12 32.94 46.85 39.07 48.5 41.09 C51.67 44.99 59.38 55.53 62.5 58.27 C64.68 60.19 67.81 60.25 70 58.29 C72.05 56.45 72.31 53.19 70.69 51 C68.79 48.44 54.22 37.41 50.64 34.5 C49.04 33.21 43.34 27.71 41.5 28.35 Z M187 38.33 C184.94 39.36 171.17 48.97 169.73 50.5 C167.74 52.61 167.81 55.87 169.71 58 C171.53 60.03 174.83 60.34 177 58.69 C179.44 56.83 183.98 49.1 186 46.23 C187.07 44.7 189.49 42.34 189.84 40.5 C190.15 38.9 188.41 37.61 187 38.33 Z M223.5 77.96 C214 79.48 204.5 81.01 195 82.53 C191.31 83.13 186.95 84.74 188.04 89.5 C188.69 92.38 191.59 94.32 194.5 93.72 C198.75 92.85 213.38 86.57 218.5 84.62 C220.15 83.99 226.55 82.04 227.5 81.09 C227.91 80.67 228.24 80.09 228.25 79.5 C228.28 76.78 224.99 77.72 223.5 77.96 Z M26.5 81.31 C24.17 82.43 25.59 84.32 27 85.2 C29.32 86.65 44.47 93.77 46.5 93.83 C48.74 93.89 50.73 92.5 51.64 90.5 C52.78 88.01 51.68 84.74 49.21 83.5 C46.33 82.05 37.59 82.09 34 81.77 C32.52 81.64 27.68 80.74 26.5 81.31 Z M45 122.42 C42.46 123.12 39.96 124.34 37.5 125.28 C31.5 127.57 25.5 129.86 19.5 132.15 C17.81 132.79 10.94 134.51 11.82 137 C12.81 139.78 18.45 137.73 20.5 137.4 C24.9 136.69 46.6 133.83 49 132.61 C54.91 129.6 51.29 120.7 45 122.42 Z M192 122.35 C187.44 123.62 186.34 130.26 190.79 132.5 C193.45 133.84 203.95 134.05 207.5 134.36 C209 134.49 212.11 135.36 213.5 134.69 C215.83 133.57 214.41 131.68 213 130.8 C210.51 129.24 197.79 123.33 195 122.43 C194.01 122.12 193.01 122.08 192 122.35 Z M65 156.39 C61.08 157.74 54.77 168.67 52.09 172.5 C51.16 173.81 48.32 177.47 52 177.88 C53.42 178.04 55.47 175.94 56.5 175.21 C59.62 173.02 70.36 166.61 71.47 163.5 C72.79 159.79 69.07 154.98 65 156.39 Z M172.5 156.38 C168.57 157.72 166.8 162.16 169.73 165.5 C172.49 168.64 185.23 178.14 189.36 181.5 C190.96 182.79 196.66 188.29 198.5 187.65 C202.13 186.38 196.6 181.18 195.5 179.82 C190.5 173.68 185.5 167.53 180.5 161.38 C178.6 159.04 176.17 155.13 172.5 156.38 Z M99.5 175.97 C95.51 176.61 94.98 180.2 94.45 183.5 C93.25 191 92.04 198.5 90.84 206 C90.49 208.17 88.38 215.25 91 216.18 C93.52 217.07 95.2 210.22 95.85 208.5 C98.14 202.5 100.43 196.5 102.72 190.5 C103.66 188.04 104.88 185.54 105.58 183 C106.62 179.22 103.52 175.33 99.5 175.97 Z M139 175.95 C136.26 176.26 134.1 178.75 134.17 181.5 C134.25 184.35 139.9 194.76 141.41 198 C142.1 199.48 143.1 203.49 145.5 202.62 C147.84 201.77 146.52 197.29 146.36 195.5 C146.06 192.16 145.82 181.42 144.61 179 C143.57 176.9 141.32 175.69 139 175.95 Z" },
- { fill: "#ffc93c", d: "M28 21.4 C26.98 21.73 26.13 29.17 25.16 30.5 C23.82 32.35 16.86 32.6 16.5 33.28 C15.35 35.45 23.22 35.91 24.5 36.84 C26.35 38.18 26.6 45.14 27.28 45.5 C29.45 46.65 29.91 38.78 30.84 37.5 C32.18 35.65 39.14 35.4 39.5 34.72 C40.75 32.35 31.89 32.57 30.54 30 C29.05 27.18 29.25 21 28 21.4 Z M214 47.4 C212.36 48.56 212.92 53.31 211.55 55 C210.23 56.63 204.14 56.93 204 57.4 C203.47 59.25 209.92 59.58 211 60.45 C212.63 61.77 212.93 67.86 213.4 68 C215.25 68.53 215.58 62.08 216.45 61 C217.77 59.37 223.86 59.07 224 58.6 C224.53 56.75 218.08 56.42 217 55.55 C214.88 53.83 215.6 50.27 214.6 48 C214.49 47.74 214.23 47.24 214 47.4 Z M36 160.4 C34.09 161.75 35.38 166.17 33 167.91 C31.7 168.86 27.13 168.95 27 169.4 C26.48 171.21 32.67 171.3 33.91 173 C34.86 174.3 34.95 178.87 35.4 179 C37.23 179.53 37.36 174.39 37.84 173.5 C39.09 171.14 44.92 170.87 45 170.6 C45.52 168.79 39.33 168.7 38.09 167 C36.9 165.37 37.38 162.79 36.6 161 C36.49 160.74 36.23 160.24 36 160.4 Z" },
- { fill: "body", d: "M112.5 46.46 C104.13 47.48 95.94 50.21 88.67 54.5 C41.85 82.12 50.89 153.23 103.5 167.76 C111.29 169.91 119.48 170.52 127.5 169.54 C135.87 168.52 144.06 165.79 151.33 161.5 C198.15 133.88 189.11 62.77 136.5 48.24 C128.71 46.09 120.52 45.48 112.5 46.46 Z" },
- ],
- },
- bomb: {
- id: "bomb",
- name: "Bomb",
- paint: "bot",
- bone: null,
- eyes: {cx: 120, cy: 150, dx: 34, w: 26, h: 50, round: 44, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M111 62.47 C98.86 63.75 87.03 67.64 76.5 73.81 C66.82 79.49 58.28 87.06 51.5 96 C14.9 144.24 38.89 215.11 97.48 231 C107.72 233.78 118.45 234.64 129 233.53 C141.14 232.25 152.97 228.36 163.5 222.19 C173.18 216.51 181.72 208.94 188.5 200 C225.1 151.76 201.11 80.89 142.52 65 C132.28 62.22 121.55 61.36 111 62.47 Z",
- parts: [
- { fill: "#b08a5a", d: "M190.5 14.84 C188.2 16.26 186.69 22.31 182.29 25.5 C171.79 33.11 159.94 29.76 151.1 43.5 C149.19 46.48 145.5 52.25 149 55.35 C154.69 60.39 156.89 50.92 158.67 48 C159.93 45.93 161.56 44.17 163.5 42.73 C171.81 36.57 182.48 36.65 189.94 28.5 C192.23 26 195.04 21.96 195.46 18.5 C195.77 16.02 192.92 13.34 190.5 14.84 Z" },
- { fill: "#3d3d3d", d: "M132.5 40.29 C129.8 41.52 123.5 56.05 121.78 59.5 C120.88 61.29 119.34 63.4 120.29 65.5 C121.29 67.69 124.01 68.48 126 69.47 C131 71.97 136 74.47 141 76.97 C144.05 78.5 154.65 85 157.5 83.71 C160.2 82.48 166.5 67.95 168.22 64.5 C169.12 62.71 170.66 60.6 169.71 58.5 C168.71 56.31 165.99 55.52 164 54.53 C159 52.03 154 49.53 149 47.03 C145.95 45.5 135.35 39 132.5 40.29 Z" },
- { fill: "body", d: "M111 62.47 C98.86 63.75 87.03 67.64 76.5 73.81 C66.82 79.49 58.28 87.06 51.5 96 C14.9 144.24 38.89 215.11 97.48 231 C107.72 233.78 118.45 234.64 129 233.53 C141.14 232.25 152.97 228.36 163.5 222.19 C173.18 216.51 181.72 208.94 188.5 200 C225.1 151.76 201.11 80.89 142.52 65 C132.28 62.22 121.55 61.36 111 62.47 Z" },
- { fill: "#ffc93c", d: "M196 -6.6 C194.72 -6.19 193.32 5.23 192 7 C190.4 9.13 184.13 9.89 181.5 10.54 C180.5 10.78 178.97 10.36 178.5 11.28 C177.22 13.76 189.33 14.75 191 16 C193.13 17.6 193.89 23.87 194.54 26.5 C194.78 27.5 194.36 29.03 195.28 29.5 C197.76 30.78 198.75 18.67 200 17 C201.6 14.87 207.87 14.11 210.5 13.46 C211.5 13.22 213.03 13.64 213.5 12.72 C214.49 10.8 210.78 10.61 210 10.41 C207 9.67 201.4 9.44 199.75 6.5 C198.53 4.35 197.74 -1.36 197.09 -4 C196.82 -5.13 196.52 -6.76 196 -6.6 Z" },
- { fill: "#fff3c4", d: "M194 6.34 C185.67 9.82 192 21.46 199 17.19 C204.97 13.56 200.6 3.59 194 6.34 Z" },
- ],
- },
- laddu: {
- id: "laddu",
- name: "Laddu",
- paint: "bone",
- bone: "#f6a420",
- eyes: {cx: 120, cy: 138, dx: 34, w: 26, h: 50, round: 44, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M118 44.82 C114.73 46.19 114.06 49.72 112 50.32 C109.4 51.07 107.36 44.78 102 46.23 C97.16 47.54 98.12 52.8 95 53.5 C92.77 54 90.49 49.4 86 50.78 C80.4 52.5 82.43 58.49 79.68 59.5 C77.1 60.45 74.63 56.47 70.5 58.39 C64.71 61.09 68.32 65.69 66 67.95 C63.86 70.04 59.56 65.76 55.58 69.5 C51.81 73.05 55.55 78.07 53 79.77 C50.36 81.53 46.21 77.52 43.14 83.5 C41.36 86.98 44.7 90.79 43.54 92.5 C41.61 95.36 34.86 92.17 33.88 99.5 C33.47 102.66 36.59 104.71 36.2 107 C35.76 109.56 30.29 109.18 28.5 112.92 C25.79 118.57 31.55 119.99 31.56 123 C31.57 125.72 25.92 126.11 25.01 130.5 C23.79 136.37 29.98 136.93 29.99 140 C30.01 142.91 24.23 143.49 24.93 149 C25.6 154.32 29.84 153.19 31.35 156 C32.58 158.3 26.85 161.35 28.11 166 C29.6 171.53 34.04 169.54 35.78 172 C37.53 174.47 32.16 177.91 34.48 182.5 C36.96 187.41 42.48 184.84 43.75 188 C44.38 189.58 41.85 192.6 42.75 195.5 C45.02 202.81 51.48 198.16 53.5 200.68 C54.97 202.51 52.93 205.91 54.14 208.5 C57.26 215.16 62.61 210.56 65 211.44 C68.44 212.71 64.59 219.43 71 221.8 C74.53 223.11 78.1 219.43 80 220.65 C82.91 222.51 80.14 227.96 86.5 229.35 C90.35 230.19 93.62 225.72 95.5 226.62 C98.57 228.09 97.03 232.87 102.5 233.88 C107.85 234.87 107.96 230.39 111 229.66 C114.12 228.92 115.05 236.9 121.5 235.32 C125 234.47 126.5 229.11 129 229.66 C131.94 230.32 132.17 234.87 137.5 233.88 C142.95 232.88 142.19 226.21 145.5 226.49 C148.56 226.74 149.49 231.07 154.5 229.05 C159.76 226.93 157.34 223.11 159.5 221.01 C161.48 219.1 165.4 222.8 168.5 221.96 C175.59 220.04 171.5 213.57 174.5 211.67 C177.08 210.03 180.79 214.73 184.89 210 C187.99 206.42 184.79 203.31 186.25 201 C187.8 198.53 192.98 201.74 196.25 197.5 C199.37 193.45 194.8 188.99 196.84 187 C199.21 184.68 202.93 187.6 205.5 182.54 C207.85 177.91 202.48 174.47 204.22 172 C206.03 169.44 211.41 171.42 212.07 165 C212.47 161.15 207.52 158.17 208.65 156 C210.12 153.18 215.81 153.89 215.08 147.5 C214.63 143.5 210.02 142.44 210.01 140 C210 137.61 214.63 136.47 215.08 132.5 C215.81 126.12 210.18 126.85 208.65 124 C207.42 121.7 213.15 118.65 211.89 114 C210.4 108.47 205.96 110.46 204.22 108 C202.47 105.53 207.84 102.09 205.52 97.5 C203.04 92.59 197.52 95.16 196.25 92 C195.26 89.53 200.17 86.01 195.5 81.66 C192.49 78.85 187.92 81.1 186.5 79.32 C184.77 77.17 187.83 73.6 185 70.13 C181 65.24 175.66 70.47 173.63 67.5 C171.98 65.09 175.31 60.53 169 58.2 C165.47 56.89 161.9 60.57 160 59.35 C157.95 58.04 158.79 54.22 156.5 52.18 C150.9 47.2 147.12 54.63 144.5 53.38 C142.27 52.31 142.37 49.11 140.5 47.51 C134.76 42.58 131.49 49.75 129 50.34 C125.88 51.08 124.32 42.16 118 44.82 Z",
- parts: [
- { fill: "body", d: "M118 44.82 C114.73 46.19 114.06 49.72 112 50.32 C109.4 51.07 107.36 44.78 102 46.23 C97.16 47.54 98.12 52.8 95 53.5 C92.77 54 90.49 49.4 86 50.78 C80.4 52.5 82.43 58.49 79.68 59.5 C77.1 60.45 74.63 56.47 70.5 58.39 C64.71 61.09 68.32 65.69 66 67.95 C63.86 70.04 59.56 65.76 55.58 69.5 C51.81 73.05 55.55 78.07 53 79.77 C50.36 81.53 46.21 77.52 43.14 83.5 C41.36 86.98 44.7 90.79 43.54 92.5 C41.61 95.36 34.86 92.17 33.88 99.5 C33.47 102.66 36.59 104.71 36.2 107 C35.76 109.56 30.29 109.18 28.5 112.92 C25.79 118.57 31.55 119.99 31.56 123 C31.57 125.72 25.92 126.11 25.01 130.5 C23.79 136.37 29.98 136.93 29.99 140 C30.01 142.91 24.23 143.49 24.93 149 C25.6 154.32 29.84 153.19 31.35 156 C32.58 158.3 26.85 161.35 28.11 166 C29.6 171.53 34.04 169.54 35.78 172 C37.53 174.47 32.16 177.91 34.48 182.5 C36.96 187.41 42.48 184.84 43.75 188 C44.38 189.58 41.85 192.6 42.75 195.5 C45.02 202.81 51.48 198.16 53.5 200.68 C54.97 202.51 52.93 205.91 54.14 208.5 C57.26 215.16 62.61 210.56 65 211.44 C68.44 212.71 64.59 219.43 71 221.8 C74.53 223.11 78.1 219.43 80 220.65 C82.91 222.51 80.14 227.96 86.5 229.35 C90.35 230.19 93.62 225.72 95.5 226.62 C98.57 228.09 97.03 232.87 102.5 233.88 C107.85 234.87 107.96 230.39 111 229.66 C114.12 228.92 115.05 236.9 121.5 235.32 C125 234.47 126.5 229.11 129 229.66 C131.94 230.32 132.17 234.87 137.5 233.88 C142.95 232.88 142.19 226.21 145.5 226.49 C148.56 226.74 149.49 231.07 154.5 229.05 C159.76 226.93 157.34 223.11 159.5 221.01 C161.48 219.1 165.4 222.8 168.5 221.96 C175.59 220.04 171.5 213.57 174.5 211.67 C177.08 210.03 180.79 214.73 184.89 210 C187.99 206.42 184.79 203.31 186.25 201 C187.8 198.53 192.98 201.74 196.25 197.5 C199.37 193.45 194.8 188.99 196.84 187 C199.21 184.68 202.93 187.6 205.5 182.54 C207.85 177.91 202.48 174.47 204.22 172 C206.03 169.44 211.41 171.42 212.07 165 C212.47 161.15 207.52 158.17 208.65 156 C210.12 153.18 215.81 153.89 215.08 147.5 C214.63 143.5 210.02 142.44 210.01 140 C210 137.61 214.63 136.47 215.08 132.5 C215.81 126.12 210.18 126.85 208.65 124 C207.42 121.7 213.15 118.65 211.89 114 C210.4 108.47 205.96 110.46 204.22 108 C202.47 105.53 207.84 102.09 205.52 97.5 C203.04 92.59 197.52 95.16 196.25 92 C195.26 89.53 200.17 86.01 195.5 81.66 C192.49 78.85 187.92 81.1 186.5 79.32 C184.77 77.17 187.83 73.6 185 70.13 C181 65.24 175.66 70.47 173.63 67.5 C171.98 65.09 175.31 60.53 169 58.2 C165.47 56.89 161.9 60.57 160 59.35 C157.95 58.04 158.79 54.22 156.5 52.18 C150.9 47.2 147.12 54.63 144.5 53.38 C142.27 52.31 142.37 49.11 140.5 47.51 C134.76 42.58 131.49 49.75 129 50.34 C125.88 51.08 124.32 42.16 118 44.82 Z" },
- { fill: "#ffc560", d: "M105.5 58.92 C100.23 60.32 102.29 68.46 107.5 67.08 C112.77 65.68 110.71 57.54 105.5 58.92 Z M125.5 58.92 C120.23 60.32 122.29 68.46 127.5 67.08 C132.77 65.68 130.71 57.54 125.5 58.92 Z M79 71.92 C73.73 73.32 75.79 81.46 81 80.08 C86.27 78.68 84.21 70.54 79 71.92 Z M99 71.92 C93.73 73.32 95.79 81.46 101 80.08 C106.27 78.68 104.21 70.54 99 71.92 Z M114 71.92 C108.73 73.32 110.79 81.46 116 80.08 C121.27 78.68 119.21 70.54 114 71.92 Z M134 71.92 C128.73 73.32 130.79 81.46 136 80.08 C141.27 78.68 139.21 70.54 134 71.92 Z M149 71.92 C143.73 73.32 145.79 81.46 151 80.08 C156.27 78.68 154.21 70.54 149 71.92 Z M54.5 84.92 C49.23 86.32 51.29 94.46 56.5 93.08 C61.77 91.68 59.71 83.54 54.5 84.92 Z M74.5 84.92 C69.23 86.32 71.29 94.46 76.5 93.08 C81.77 91.68 79.71 83.54 74.5 84.92 Z M89.5 84.92 C84.23 86.32 86.29 94.46 91.5 93.08 C96.77 91.68 94.71 83.54 89.5 84.92 Z M104.5 84.92 C99.23 86.32 101.29 94.46 106.5 93.08 C111.77 91.68 109.71 83.54 104.5 84.92 Z M124.5 84.92 C119.23 86.32 121.29 94.46 126.5 93.08 C131.77 91.68 129.71 83.54 124.5 84.92 Z M139.5 84.92 C134.23 86.32 136.29 94.46 141.5 93.08 C146.77 91.68 144.71 83.54 139.5 84.92 Z M159.5 89.92 C154.23 91.32 156.29 99.46 161.5 98.08 C166.77 96.68 164.71 88.54 159.5 89.92 Z M174.5 89.92 C169.23 91.32 171.29 99.46 176.5 98.08 C181.77 96.68 179.71 88.54 174.5 89.92 Z M48 102.92 C42.73 104.32 44.79 112.46 50 111.08 C55.27 109.68 53.21 101.54 48 102.92 Z M63 102.92 C57.73 104.32 59.79 112.46 65 111.08 C70.27 109.68 68.21 101.54 63 102.92 Z M83 102.92 C77.73 104.32 79.79 112.46 85 111.08 C90.27 109.68 88.21 101.54 83 102.92 Z M98 102.92 C92.73 104.32 94.79 112.46 100 111.08 C105.27 109.68 103.21 101.54 98 102.92 Z M113 102.92 C107.73 104.32 109.79 112.46 115 111.08 C120.27 109.68 118.21 101.54 113 102.92 Z M133 102.92 C127.73 104.32 129.79 112.46 135 111.08 C140.27 109.68 138.21 101.54 133 102.92 Z M148 107.92 C142.73 109.32 144.79 117.46 150 116.08 C155.27 114.68 153.21 106.54 148 107.92 Z M168 107.92 C162.73 109.32 164.79 117.46 170 116.08 C175.27 114.68 173.21 106.54 168 107.92 Z M183 107.92 C177.73 109.32 179.79 117.46 185 116.08 C190.27 114.68 188.21 106.54 183 107.92 Z M38.5 115.92 C33.23 117.32 35.29 125.46 40.5 124.08 C45.77 122.68 43.71 114.54 38.5 115.92 Z M53.5 115.92 C48.23 117.32 50.29 125.46 55.5 124.08 C60.77 122.68 58.71 114.54 53.5 115.92 Z M73.5 115.92 C68.23 117.32 70.29 125.46 75.5 124.08 C80.77 122.68 78.71 114.54 73.5 115.92 Z M88.5 115.92 C83.23 117.32 85.29 125.46 90.5 124.08 C95.77 122.68 93.71 114.54 88.5 115.92 Z M108.5 115.92 C103.23 117.32 105.29 125.46 110.5 124.08 C115.77 122.68 113.71 114.54 108.5 115.92 Z M123.5 115.92 C118.23 117.32 120.29 125.46 125.5 124.08 C130.77 122.68 128.71 114.54 123.5 115.92 Z M138.5 120.92 C133.23 122.32 135.29 130.46 140.5 129.08 C145.77 127.68 143.71 119.54 138.5 120.92 Z M158.5 120.92 C153.23 122.32 155.29 130.46 160.5 129.08 C165.77 127.68 163.71 119.54 158.5 120.92 Z M178.5 120.92 C173.23 122.32 175.29 130.46 180.5 129.08 C185.77 127.68 183.71 119.54 178.5 120.92 Z M193.5 120.92 C188.23 122.32 190.29 130.46 195.5 129.08 C200.77 127.68 198.71 119.54 193.5 120.92 Z M47 133.92 C41.73 135.32 43.79 143.46 49 142.08 C54.27 140.68 52.21 132.54 47 133.92 Z M62 133.92 C56.73 135.32 58.79 143.46 64 142.08 C69.27 140.68 67.21 132.54 62 133.92 Z M82 133.92 C76.73 135.32 78.79 143.46 84 142.08 C89.27 140.68 87.21 132.54 82 133.92 Z M97 133.92 C91.73 135.32 93.79 143.46 99 142.08 C104.27 140.68 102.21 132.54 97 133.92 Z M117 133.92 C111.73 135.32 113.79 143.46 119 142.08 C124.27 140.68 122.21 132.54 117 133.92 Z M137 133.92 C131.73 135.32 133.79 143.46 139 142.08 C144.27 140.68 142.21 132.54 137 133.92 Z M152 133.92 C146.73 135.32 148.79 143.46 154 142.08 C159.27 140.68 157.21 132.54 152 133.92 Z M172 133.92 C166.73 135.32 168.79 143.46 174 142.08 C179.27 140.68 177.21 132.54 172 133.92 Z M187 133.92 C181.73 135.32 183.79 143.46 189 142.08 C194.27 140.68 192.21 132.54 187 133.92 Z M37.5 146.92 C32.23 148.32 34.29 156.46 39.5 155.08 C44.77 153.68 42.71 145.54 37.5 146.92 Z M57.5 146.92 C52.23 148.32 54.29 156.46 59.5 155.08 C64.77 153.68 62.71 145.54 57.5 146.92 Z M72.5 146.92 C67.23 148.32 69.29 156.46 74.5 155.08 C79.77 153.68 77.71 145.54 72.5 146.92 Z M92.5 146.92 C87.23 148.32 89.29 156.46 94.5 155.08 C99.77 153.68 97.71 145.54 92.5 146.92 Z M112.5 146.92 C107.23 148.32 109.29 156.46 114.5 155.08 C119.77 153.68 117.71 145.54 112.5 146.92 Z M127.5 151.92 C122.23 153.32 124.29 161.46 129.5 160.08 C134.77 158.68 132.71 150.54 127.5 151.92 Z M142.5 151.92 C137.23 153.32 139.29 161.46 144.5 160.08 C149.77 158.68 147.71 150.54 142.5 151.92 Z M162.5 151.92 C157.23 153.32 159.29 161.46 164.5 160.08 C169.77 158.68 167.71 150.54 162.5 151.92 Z M177.5 151.92 C172.23 153.32 174.29 161.46 179.5 160.08 C184.77 158.68 182.71 150.54 177.5 151.92 Z M197.5 151.92 C192.23 153.32 194.29 161.46 199.5 160.08 C204.77 158.68 202.71 150.54 197.5 151.92 Z M51 159.92 C45.73 161.32 47.79 169.46 53 168.08 C58.27 166.68 56.21 158.54 51 159.92 Z M66 159.92 C60.73 161.32 62.79 169.46 68 168.08 C73.27 166.68 71.21 158.54 66 159.92 Z M86 159.92 C80.73 161.32 82.79 169.46 88 168.08 C93.27 166.68 91.21 158.54 86 159.92 Z M101 164.92 C95.73 166.32 97.79 174.46 103 173.08 C108.27 171.68 106.21 163.54 101 164.92 Z M121 164.92 C115.73 166.32 117.79 174.46 123 173.08 C128.27 171.68 126.21 163.54 121 164.92 Z M136 164.92 C130.73 166.32 132.79 174.46 138 173.08 C143.27 171.68 141.21 163.54 136 164.92 Z M151 164.92 C145.73 166.32 147.79 174.46 153 173.08 C158.27 171.68 156.21 163.54 151 164.92 Z M171 164.92 C165.73 166.32 167.79 174.46 173 173.08 C178.27 171.68 176.21 163.54 171 164.92 Z M186 164.92 C180.73 166.32 182.79 174.46 188 173.08 C193.27 171.68 191.21 163.54 186 164.92 Z M61.5 177.92 C56.23 179.32 58.29 187.46 63.5 186.08 C68.77 184.68 66.71 176.54 61.5 177.92 Z M76.5 177.92 C71.23 179.32 73.29 187.46 78.5 186.08 C83.77 184.68 81.71 176.54 76.5 177.92 Z M91.5 177.92 C86.23 179.32 88.29 187.46 93.5 186.08 C98.77 184.68 96.71 176.54 91.5 177.92 Z M111.5 182.92 C106.23 184.32 108.29 192.46 113.5 191.08 C118.77 189.68 116.71 181.54 111.5 182.92 Z M126.5 182.92 C121.23 184.32 123.29 192.46 128.5 191.08 C133.77 189.68 131.71 181.54 126.5 182.92 Z M146.5 182.92 C141.23 184.32 143.29 192.46 148.5 191.08 C153.77 189.68 151.71 181.54 146.5 182.92 Z M161.5 182.92 C156.23 184.32 158.29 192.46 163.5 191.08 C168.77 189.68 166.71 181.54 161.5 182.92 Z M176.5 182.92 C171.23 184.32 173.29 192.46 178.5 191.08 C183.77 189.68 181.71 181.54 176.5 182.92 Z M85 195.92 C79.73 197.32 81.79 205.46 87 204.08 C92.27 202.68 90.21 194.54 85 195.92 Z M100 195.92 C94.73 197.32 96.79 205.46 102 204.08 C107.27 202.68 105.21 194.54 100 195.92 Z M120 195.92 C114.73 197.32 116.79 205.46 122 204.08 C127.27 202.68 125.21 194.54 120 195.92 Z M135 195.92 C129.73 197.32 131.79 205.46 137 204.08 C142.27 202.68 140.21 194.54 135 195.92 Z M155 195.92 C149.73 197.32 151.79 205.46 157 204.08 C162.27 202.68 160.21 194.54 155 195.92 Z M110.5 208.92 C105.23 210.32 107.29 218.46 112.5 217.08 C117.77 215.68 115.71 207.54 110.5 208.92 Z M125.5 208.92 C120.23 210.32 122.29 218.46 127.5 217.08 C132.77 215.68 130.71 207.54 125.5 208.92 Z" },
- ],
- },
- chakli: {
- id: "chakli",
- name: "Chakli",
- paint: "bone",
- bone: "#cf8f45",
- eyes: {cx: 120, cy: 128, dx: 30, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M110.5 42.49 C108.7 42.68 106.15 42.62 104.53 43.5 C101.84 44.96 101.77 47.78 98 48.22 C92.47 48.87 93.76 44.31 84.5 49.13 C81.79 50.53 81.81 53.93 79.12 55.5 C76.05 57.29 72.97 55.04 70 56.77 C60.87 62.1 65.76 62.65 62.04 67 C59.43 70.05 55.7 68.43 53 70.95 C51.59 72.27 49.26 74.49 48.5 76.31 C47.41 78.9 49 81.48 47 83.95 C43.57 88.21 42.2 84.22 38.41 91.5 C38.26 91.77 37.02 94.19 36.93 94.5 C35.97 97.64 38.9 100.01 36.84 103.5 C35.29 106.11 32.27 106.46 31.32 109.5 C30.68 111.55 29.38 114.86 30.04 117 C30.73 119.2 32.36 120.49 32.18 123 C31.95 126.21 29 127.23 28.15 130 C28.03 130.42 28.01 132.57 28.01 133 C27.9 142.82 31.77 139.38 32.18 145 C32.39 147.92 29.75 149.72 29.89 152.5 C30 154.55 30.77 158.25 31.86 160 C33.44 162.54 36.54 162.71 37.45 166 C38.08 168.27 36.85 169.84 36.73 172 C36.6 174.3 38.75 177.58 40 179.43 C42.04 182.46 46.2 181.67 47.83 185.5 C50.04 190.69 45.57 190.06 52.96 197 C55.65 199.53 59.41 197.93 62 200.95 C65.3 204.81 61.28 205.3 68 209.89 C68.36 210.14 70.57 211.64 71 211.81 C73.45 212.78 75.93 211.03 78.5 212.18 C81.46 213.51 81.28 216.49 83.5 218.31 C85.11 219.64 88.94 220.99 91 221.27 C93.66 221.63 95.68 219.29 98.5 219.86 C102.43 220.64 102.82 224.47 107 225.08 C108.79 225.34 111.2 225.98 113 225.65 C115.87 225.11 117.22 222.26 120.5 222.52 C124.44 222.83 124.8 226 129.5 225.51 C131.3 225.32 133.85 225.38 135.47 224.5 C138.16 223.04 138.23 220.22 142 219.78 C147.53 219.13 146.24 223.69 155.5 218.87 C158.21 217.47 158.19 214.07 160.88 212.5 C163.95 210.71 167.03 212.96 170 211.23 C179.13 205.9 174.24 205.35 177.96 201 C180.57 197.95 184.3 199.57 187 197.05 C188.41 195.73 190.74 193.51 191.5 191.69 C192.59 189.1 191 186.52 193 184.05 C196.43 179.79 197.8 183.78 201.59 176.5 C201.74 176.23 202.98 173.81 203.07 173.5 C204.03 170.36 201.1 167.99 203.16 164.5 C204.71 161.89 207.73 161.54 208.68 158.5 C209.32 156.45 210.62 153.14 209.96 151 C209.27 148.8 207.64 147.51 207.82 145 C208.05 141.79 211 140.77 211.85 138 C211.97 137.58 211.99 135.43 211.99 135 C212.1 125.18 208.23 128.62 207.82 123 C207.61 120.08 210.25 118.28 210.11 115.5 C210 113.45 209.23 109.75 208.14 108 C206.56 105.46 203.46 105.29 202.55 102 C201.92 99.73 203.15 98.16 203.27 96 C203.4 93.7 201.25 90.42 200 88.57 C197.96 85.54 193.8 86.33 192.17 82.5 C189.96 77.31 194.43 77.94 187.04 71 C184.35 68.47 180.59 70.07 178 67.05 C174.7 63.19 178.72 62.7 172 58.11 C171.64 57.86 169.43 56.36 169 56.19 C166.55 55.22 164.07 56.97 161.5 55.82 C158.54 54.49 158.72 51.51 156.5 49.69 C154.89 48.36 151.06 47.01 149 46.73 C146.34 46.37 144.32 48.71 141.5 48.14 C137.57 47.36 137.18 43.53 133 42.92 C131.21 42.66 128.8 42.02 127 42.35 C124.13 42.89 122.78 45.74 119.5 45.48 C115.56 45.17 115.2 42 110.5 42.49 Z",
- parts: [
- { fill: "body", d: "M110.5 42.49 C108.7 42.68 106.15 42.62 104.53 43.5 C101.84 44.96 101.77 47.78 98 48.22 C92.47 48.87 93.76 44.31 84.5 49.13 C81.79 50.53 81.81 53.93 79.12 55.5 C76.05 57.29 72.97 55.04 70 56.77 C60.87 62.1 65.76 62.65 62.04 67 C59.43 70.05 55.7 68.43 53 70.95 C51.59 72.27 49.26 74.49 48.5 76.31 C47.41 78.9 49 81.48 47 83.95 C43.57 88.21 42.2 84.22 38.41 91.5 C38.26 91.77 37.02 94.19 36.93 94.5 C35.97 97.64 38.9 100.01 36.84 103.5 C35.29 106.11 32.27 106.46 31.32 109.5 C30.68 111.55 29.38 114.86 30.04 117 C30.73 119.2 32.36 120.49 32.18 123 C31.95 126.21 29 127.23 28.15 130 C28.03 130.42 28.01 132.57 28.01 133 C27.9 142.82 31.77 139.38 32.18 145 C32.39 147.92 29.75 149.72 29.89 152.5 C30 154.55 30.77 158.25 31.86 160 C33.44 162.54 36.54 162.71 37.45 166 C38.08 168.27 36.85 169.84 36.73 172 C36.6 174.3 38.75 177.58 40 179.43 C42.04 182.46 46.2 181.67 47.83 185.5 C50.04 190.69 45.57 190.06 52.96 197 C55.65 199.53 59.41 197.93 62 200.95 C65.3 204.81 61.28 205.3 68 209.89 C68.36 210.14 70.57 211.64 71 211.81 C73.45 212.78 75.93 211.03 78.5 212.18 C81.46 213.51 81.28 216.49 83.5 218.31 C85.11 219.64 88.94 220.99 91 221.27 C93.66 221.63 95.68 219.29 98.5 219.86 C102.43 220.64 102.82 224.47 107 225.08 C108.79 225.34 111.2 225.98 113 225.65 C115.87 225.11 117.22 222.26 120.5 222.52 C124.44 222.83 124.8 226 129.5 225.51 C131.3 225.32 133.85 225.38 135.47 224.5 C138.16 223.04 138.23 220.22 142 219.78 C147.53 219.13 146.24 223.69 155.5 218.87 C158.21 217.47 158.19 214.07 160.88 212.5 C163.95 210.71 167.03 212.96 170 211.23 C179.13 205.9 174.24 205.35 177.96 201 C180.57 197.95 184.3 199.57 187 197.05 C188.41 195.73 190.74 193.51 191.5 191.69 C192.59 189.1 191 186.52 193 184.05 C196.43 179.79 197.8 183.78 201.59 176.5 C201.74 176.23 202.98 173.81 203.07 173.5 C204.03 170.36 201.1 167.99 203.16 164.5 C204.71 161.89 207.73 161.54 208.68 158.5 C209.32 156.45 210.62 153.14 209.96 151 C209.27 148.8 207.64 147.51 207.82 145 C208.05 141.79 211 140.77 211.85 138 C211.97 137.58 211.99 135.43 211.99 135 C212.1 125.18 208.23 128.62 207.82 123 C207.61 120.08 210.25 118.28 210.11 115.5 C210 113.45 209.23 109.75 208.14 108 C206.56 105.46 203.46 105.29 202.55 102 C201.92 99.73 203.15 98.16 203.27 96 C203.4 93.7 201.25 90.42 200 88.57 C197.96 85.54 193.8 86.33 192.17 82.5 C189.96 77.31 194.43 77.94 187.04 71 C184.35 68.47 180.59 70.07 178 67.05 C174.7 63.19 178.72 62.7 172 58.11 C171.64 57.86 169.43 56.36 169 56.19 C166.55 55.22 164.07 56.97 161.5 55.82 C158.54 54.49 158.72 51.51 156.5 49.69 C154.89 48.36 151.06 47.01 149 46.73 C146.34 46.37 144.32 48.71 141.5 48.14 C137.57 47.36 137.18 43.53 133 42.92 C131.21 42.66 128.8 42.02 127 42.35 C124.13 42.89 122.78 45.74 119.5 45.48 C115.56 45.17 115.2 42 110.5 42.49 Z" },
- { fill: "#a8692b", d: "M93.5 50.95 C84.2 53.05 69.54 63.76 62.74 70.5 C23.83 109.08 31.36 176.49 81.5 201.68 C89.47 205.68 98.14 208.3 107 209.35 C116.52 210.48 126.24 209.8 135.5 207.31 C164.66 199.48 186.95 173.78 189.33 143.5 C192.65 101.31 156.21 64.42 113.5 71.68 C89.04 75.83 68.66 94.93 64.09 119.5 C57.81 153.24 83.71 186.58 119 184.46 C137.57 183.34 154.61 171.52 161.28 154 C170.67 129.3 156.23 100 129 96.42 C115.86 94.69 102.28 100.11 94.53 111 C83.78 126.11 87.67 149.25 105.5 157.09 C114.39 161.01 125.16 159.7 132.37 153 C134.18 151.32 138.65 146.12 137.56 143.5 C136.65 141.3 133.76 140.62 132.14 142.5 C131.4 143.36 131.16 144.55 130.55 145.5 C128.35 148.89 124.87 151.28 121 152.36 C111.69 154.96 102.03 149.75 97.57 141.5 C84.73 117.74 114.27 92.24 140 106.69 C161.3 118.65 163.21 148.04 146.98 165 C134.8 177.72 115.78 181.45 99.5 175.02 C69.42 163.16 61.11 125.79 79 100.23 C92.04 81.59 116.14 73.41 138 78.91 C177.03 88.72 194.13 133.84 175.5 168.34 C162.44 192.53 135.17 206.16 108 203.03 C64.27 198 36.31 154.58 46.2 112.5 C50.42 94.56 61.17 78.46 76 67.54 C80.23 64.43 84.75 61.74 89.5 59.51 C91.39 58.62 93.64 58.05 95.43 57 C98.47 55.23 97.28 50.09 93.5 50.95 Z" },
- ],
- },
- jalebi: {
- id: "jalebi",
- name: "Jalebi",
- paint: "bone",
- bone: "#f7941d",
- eyes: {cx: 120, cy: 128, dx: 30, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M111 46.46 C98.31 47.8 85.98 51.84 75 58.38 C65.1 64.27 56.39 72.11 49.5 81.33 C12.72 130.58 37.1 202.34 96.5 218.8 C107.2 221.77 118.46 222.69 129.5 221.49 C141.62 220.17 153.44 216.31 164 210.21 C174.31 204.26 183.38 196.21 190.5 186.67 C227.67 136.89 202.32 64.37 142 48.79 C131.92 46.19 121.35 45.37 111 46.46 Z",
- parts: [
- { fill: "#c9650c", d: "M111 46.46 C66.5 51.29 30.86 89.67 32.01 135 C32.21 143.1 34.35 151.44 37.15 159 C50.23 194.25 86.34 217.76 124 213.29 C148.37 210.41 170.75 195.84 182.5 174.16 C185.85 167.99 188.33 161.37 189.81 154.5 C190.24 152.52 190.58 150.51 190.84 148.5 C190.9 148 190.6 147.28 191.02 147 C192.04 146.31 194.35 149.04 195 149.49 C196.48 150.54 203.77 154.07 205.5 152.99 C205.97 152.7 206.06 152.03 206.24 151.5 C208.89 143.83 208.18 128.07 206.88 120 C199.53 74.41 157.06 41.46 111 46.46 Z" },
- { fill: "body", d: "M119.5 41.47 C77.13 44.17 41.16 76.39 36.27 119 C30.32 170.89 74.59 217.91 127.5 208.75 C152.93 204.35 174.95 186.47 183.56 162 C196.52 125.13 175.17 82.72 135.5 75.85 C94.49 68.75 56.62 107.47 73.08 147.5 C75.45 153.28 78.95 158.56 83.35 163 C103.34 183.2 140.39 180.27 151.45 152 C156.14 140.01 153.75 126.23 145 116.71 C141.79 113.22 137.87 110.41 133.5 108.54 C132.27 108.01 125.29 106.81 128.5 105.3 C129.48 104.84 133.43 105.92 134.5 106.24 C140.62 108.09 145.99 112.04 149.96 117 C161.5 131.44 159.3 152.82 147 166.04 C126.62 187.95 91.64 182.67 75.11 159 C63.75 142.73 62.76 121.09 71.68 103.5 C92.18 63.1 146.85 61.52 174.92 94.5 C181.77 102.55 186.64 112.25 189.16 122.5 C190.47 127.79 190.36 136.13 192.48 140.5 C197.19 150.21 210.56 151.8 217.5 143.63 C219.32 141.48 220.49 138.78 220.87 136 C222.08 127.05 217.16 109.9 213.73 101.5 C198.41 64 160.17 38.89 119.5 41.47 Z" },
- { fill: "#ffc566", d: "M119.5 50.48 C92.13 52.57 66.86 68.13 53.81 92.5 C50.53 98.63 48.07 105.21 46.55 112 C46.33 112.98 45.16 117.31 46 118 C46.77 118.64 48 118 49 118 C50.72 118 55.05 118.53 56.5 118 C57 117.82 57.46 117.45 57.74 117 C58.27 116.12 59.91 108.43 60.62 106.5 C62.97 100.1 66.32 94.09 70.5 88.71 C83.88 71.48 105.28 61.77 127 62.26 C149.28 62.77 170.44 73.85 184 91.46 C188.13 96.83 191.55 102.74 194.15 109 C194.7 110.31 196.78 117.5 197.5 118 C198.06 118.39 205.3 118 206.5 118 C207.5 118 208.86 118.77 209.5 118 C209.74 117.71 207.76 111.33 207.5 110.54 C205.03 103.12 201.6 96.03 197.3 89.5 C180.44 63.92 150.26 48.13 119.5 50.48 Z M123 83.99 C108.29 84.83 94.43 91.98 86 104.22 C85.03 105.63 79.16 116.42 79.83 117.5 C80.07 117.9 91.51 118.33 92 118 C92.08 117.94 93.38 115.09 93.42 115 C94.65 112.52 96.18 110.17 98 108.09 C104.68 100.45 114.38 96.07 124.5 95.86 C135.27 95.62 145.87 100.05 153.5 107.63 C155.56 109.67 160.86 117.41 160.97 117.5 C161.46 117.92 172.53 118.31 173 118 C174.73 116.85 172.93 114.66 172.34 113.5 C170.23 109.33 167.6 105.41 164.5 101.91 C154.16 90.26 138.7 83.09 123 83.99 Z M122 117.47 C122 118.17 124.83 118 125 118 C126 118 128 119 128 118 C128 116.6 122 117.41 122 117.47 Z" },
- ],
- },
- katli: {
- id: "katli",
- name: "Kaju katli",
- paint: "bone",
- bone: "#f2e4c6",
- eyes: {cx: 120, cy: 122, dx: 30, w: 24, h: 46, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M117.5 18.4 C113.87 19.89 111.22 23.46 108.5 26.19 C103.06 31.62 97.62 37.06 92.19 42.5 C73.46 61.23 54.73 79.96 36 98.69 C30.17 104.52 24.33 110.35 18.5 116.19 C15.74 118.94 13.14 121.77 14.25 126 C15.13 129.33 18.35 131.67 20.69 134 C26.12 139.44 31.56 144.88 37 150.31 C56.56 169.88 76.12 189.44 95.69 209 C101.12 214.44 106.56 219.88 112 225.31 C115.17 228.48 118.8 231.55 123.5 229.19 C126.94 227.47 143.48 209.83 147.5 205.81 C165.83 187.48 184.17 169.15 202.5 150.81 C208.33 144.98 214.17 139.15 220 133.31 C222.79 130.52 226.26 127.87 225.98 123.5 C225.75 119.83 222.91 117.6 220.5 115.19 C215.5 110.19 210.5 105.19 205.5 100.19 C185.1 79.79 164.71 59.4 144.31 39 C138.48 33.17 132.65 27.33 126.81 21.5 C124.39 19.08 121.08 16.94 117.5 18.4 Z",
- parts: [
- { fill: "#d9c39a", d: "M117.5 32.4 C113.87 33.89 111.22 37.46 108.5 40.19 C103.06 45.62 97.62 51.06 92.19 56.5 C73.46 75.23 54.73 93.96 36 112.69 C30.17 118.52 24.33 124.35 18.5 130.19 C15.74 132.94 13.14 135.77 14.25 140 C15.13 143.33 18.35 145.67 20.69 148 C26.12 153.44 31.56 158.88 37 164.31 C56.56 183.88 76.12 203.44 95.69 223 C101.12 228.44 106.56 233.88 112 239.31 C115.17 242.48 118.8 245.55 123.5 243.19 C126.94 241.47 143.48 223.83 147.5 219.81 C165.83 201.48 184.17 183.15 202.5 164.81 C208.33 158.98 214.17 153.15 220 147.31 C222.79 144.52 226.26 141.87 225.98 137.5 C225.75 133.83 222.91 131.6 220.5 129.19 C215.5 124.19 210.5 119.19 205.5 114.19 C185.1 93.79 164.71 73.4 144.31 53 C138.48 47.17 132.65 41.33 126.81 35.5 C124.39 33.08 121.08 30.94 117.5 32.4 Z" },
- { fill: "body", d: "M117.5 18.4 C113.87 19.89 111.22 23.46 108.5 26.19 C103.06 31.62 97.62 37.06 92.19 42.5 C73.46 61.23 54.73 79.96 36 98.69 C30.17 104.52 24.33 110.35 18.5 116.19 C15.74 118.94 13.14 121.77 14.25 126 C15.13 129.33 18.35 131.67 20.69 134 C26.12 139.44 31.56 144.88 37 150.31 C56.56 169.88 76.12 189.44 95.69 209 C101.12 214.44 106.56 219.88 112 225.31 C115.17 228.48 118.8 231.55 123.5 229.19 C126.94 227.47 143.48 209.83 147.5 205.81 C165.83 187.48 184.17 169.15 202.5 150.81 C208.33 144.98 214.17 139.15 220 133.31 C222.79 130.52 226.26 127.87 225.98 123.5 C225.75 119.83 222.91 117.6 220.5 115.19 C215.5 110.19 210.5 105.19 205.5 100.19 C185.1 79.79 164.71 59.4 144.31 39 C138.48 33.17 132.65 27.33 126.81 21.5 C124.39 19.08 121.08 16.94 117.5 18.4 Z" },
- { fill: "#cdd3db", d: "M116.5 50.48 C109.63 51.83 98.39 57.9 106.97 65.5 C112.3 70.23 121.35 70.74 128 69.43 C135.21 68.01 145.85 61 136.4 54 C131.01 50.01 122.93 49.21 116.5 50.48 Z M64 104.45 C56.72 105.58 41.53 112.42 50.5 121.56 C56.71 127.88 67.69 128.83 76 127.55 C83.28 126.42 98.47 119.58 89.5 110.44 C83.29 104.12 72.31 103.17 64 104.45 Z M164.5 121.42 C156.96 122.61 143.48 129.58 153.24 138 C159 142.97 168.3 143.71 175.5 142.58 C183.04 141.39 196.52 134.42 186.76 126 C181 121.03 171.7 120.29 164.5 121.42 Z M119 187.45 C112.47 188.8 102.49 195.04 111.34 201.5 C116.33 205.15 123.62 205.67 129.5 204.45 C135.47 203.22 144.64 197.57 137.5 191.17 C132.84 187 124.9 186.23 119 187.45 Z" },
- ],
- },
- karanji: {
- id: "karanji",
- name: "Karanji",
- paint: "bone",
- bone: "#ecb460",
- eyes: {cx: 120, cy: 150, dx: 30, w: 24, h: 44, round: 40, ink: "#0d0a10", mouth: true, mouthInk: "#0d0a10", mouthY: null},
- clip: "M110.5 72.46 C61.45 77.23 24.93 117.01 12.78 163 C10.06 173.28 8.5 183.87 8.1 194.5 C8.05 195.91 7.65 204.26 8.09 205 C9.05 206.66 17.9 206 20 206 C32.5 206 45 206 57.5 206 C100.5 206 143.5 206 186.5 206 C197.5 206 208.5 206 219.5 206 C220.94 206 230.97 206.41 231.5 206 C232.39 205.31 231.94 195.58 231.88 194 C231.31 180.23 228.8 166.54 224.35 153.5 C207.85 105.16 163.52 67.3 110.5 72.46 Z",
- parts: [
- { fill: "body", d: "M117.5 65.91 C114.31 66.95 111.01 71.93 109.5 71.82 C106.46 71.59 104.87 65.82 98 67.92 C92.99 69.45 91.87 75.89 89.5 76.07 C86.62 76.28 83.82 70.96 77.5 74.5 C72.94 77.06 73.27 83.27 71 84.25 C69.72 84.8 67.69 83.51 66.5 83.21 C63.2 82.38 59.78 83.49 57.5 86 C54.74 89.05 56.04 95.08 53.5 96.25 C50.74 97.52 46.49 93.39 41.63 99 C38.01 103.19 40.95 109.28 39.13 111 C36.36 113.61 30.21 109.49 26.73 117 C24.62 121.54 28.47 126.92 26.51 129 C23.87 131.81 18.58 128.74 15.58 136 C13.31 141.49 18.38 145.09 17.5 148 C16.61 150.95 10.42 151 8.07 155.5 C4.29 162.75 12.23 166.45 11.03 170 C10.05 172.93 5.04 173.58 3.26 177.5 C0 184.68 5.89 186.57 7.8 190.5 C8.64 192.21 8.09 194.67 8.04 196.5 C8.02 197.45 7.85 205.24 8.1 205.5 C9.11 206.54 19.98 206 22 206 C35 206 48 206 61 206 C100.5 206 140 206 179.5 206 C191.5 206 203.5 206 215.5 206 C217.91 206 229.05 206.5 230.5 206 C231.05 205.81 231.62 205.5 231.91 205 C232.75 203.56 231.37 193.92 231.89 191.5 C232.84 187.02 239.51 186.13 237.11 178.5 C235.56 173.55 229.32 172.61 228.87 169.5 C228.54 167.17 231.05 165.36 231.99 163.5 C233.98 159.55 232.57 154.34 228.79 152 C226.86 150.81 223.84 150.71 222.67 148.5 C221.61 146.5 223.73 144.2 224.4 142.5 C225.57 139.55 225.05 135.99 223 133.55 C220.13 130.13 213.96 130.6 212.88 128 C211.69 125.12 216.15 121.28 212.73 116 C208.96 110.18 201.78 113.22 200.26 110 C198.78 106.87 202.98 102.98 197.5 98.12 C193.3 94.4 187.1 97.34 185.5 95.63 C183.08 93.03 186.94 86.9 179 83.55 C175.34 82 169.93 84.96 168.5 84.02 C165.62 82.12 168 75.76 160.5 73.69 C155.81 72.4 151.93 76.49 150 75.98 C147.68 75.37 147.13 69.17 141.5 67.78 C135.68 66.35 131.71 72.41 129.5 71.68 C127 70.85 125.09 63.45 117.5 65.91 Z" },
- { fill: "#cf923d", d: "M111 87.49 C72.98 91.74 43.35 121.08 30.67 156 C27.67 164.25 25.55 172.81 24.31 181.5 C24.17 182.46 23.1 190.18 23.34 190.5 C24 191.36 32.51 191 34 191 C45.5 191 57 191 68.5 191 C103 191 137.5 191 172 191 C182 191 192 191 202 191 C204.21 191 214.14 191.52 215.5 191 C215.97 190.82 216.43 190.46 216.62 190 C217.01 189.03 215.63 181.02 215.39 179.5 C213.32 166.47 209.26 153.75 203.23 142 C185.79 108.01 150.26 83.1 111 87.49 Z M120 91.5 C158.05 91.62 189.39 118.96 203.36 153 C206.72 161.2 209.16 169.77 210.66 178.5 C210.79 179.25 211.87 185.81 211.73 186 C211.06 186.85 202.49 186.5 201 186.5 C191 186.5 181 186.5 171 186.5 C135.5 186.5 100 186.5 64.5 186.5 C55.5 186.5 46.5 186.5 37.5 186.5 C36.6 186.5 28.65 186.64 28.5 186.5 C27.99 186.02 29.32 178.58 29.51 177.5 C31.09 168.76 33.61 160.19 37.06 152 C51.13 118.58 82.4 91.38 120 91.5 Z" },
- ],
- },
-};
+export * from "../packages/phone-protocol/src/carved-bodies.ts";
diff --git a/shared/command-allowlist.ts b/shared/command-allowlist.ts
index 8430ab5990..3b7e3edd28 100644
--- a/shared/command-allowlist.ts
+++ b/shared/command-allowlist.ts
@@ -1,18 +1 @@
-/** An exact command in one engine instance and working directory. */
-export interface CommandAllowlistCandidate {
- command: string;
- cwd: string;
- providerInstanceId: string;
-}
-
-export interface CommandAllowlistRule extends CommandAllowlistCandidate {
- id: string;
-}
-
-export type CommandAllowRule = CommandAllowlistRule;
-
-export interface CommandAllowlistResponse {
- rules: CommandAllowlistRule[];
- context: { providerInstanceId: string; cwd: string | null };
- supported: boolean;
-}
+export * from "../packages/phone-protocol/src/command-allowlist.ts";
diff --git a/shared/computer-ask.ts b/shared/computer-ask.ts
index 6cdf51dc8e..fc87289847 100644
--- a/shared/computer-ask.ts
+++ b/shared/computer-ask.ts
@@ -1,129 +1 @@
-// A bot on the person's own Cloud that needs their computer (its apps and screen, its files, or its terminal) when it
-// isn't available asks once with a card: what it wants and why, why it isn't available, and the one-tap fix. The English
-// mirrors src/locales/en.json `computerAsk.*` exactly (a test holds them together): the server has no i18n.
-
-/** The card's tool name: no engine has a tool by this name, and "Always allow" is never offered for it. */
-export const COMPUTER_ASK_TOOL = "turn_on_your_computer";
-/** The bots' tool that raises the card. */
-export const ASK_FOR_COMPUTER_TOOL = "ask_for_computer";
-export const DESKTOP_DOWNLOAD_URL = "https://www.openmausbot.com/download";
-
-export const COMPUTER_NEEDS = ["screen", "folders", "terminal"] as const;
-export type ComputerNeed = (typeof COMPUTER_NEEDS)[number];
-
-/**
- * Why the computer can't give what's needed now. From the app on that computer: "paused" (the person paused it from its
- * icon), and for apps and screen "starting", "permissions" (macOS hasn't allowed it), "blocked" (its helper is missing
- * or stopped, as Windows Security does), "off" (Linux control is off), "not-running" and "unsupported"; "terminal-off"
- * (running commands isn't turned on). Without the app there: "closed" (it was used before), "never", and "update" (an
- * app too old to answer the card).
- */
-export const COMPUTER_ASK_REASONS = [
- "paused", "starting", "permissions", "blocked", "off", "not-running", "unsupported", "terminal-off", "closed", "never", "update",
-] as const;
-export type ComputerAskReason = (typeof COMPUTER_ASK_REASONS)[number];
-
-/** "asking" until an answer; "turning-on" once Turn on was tapped; "on" once it lends what was needed; "failed" when the
- * app there couldn't turn it on (Turn on again tries again); "declined" for Not now; "ended" when the conversation
- * was stopped or deleted. */
-export type ComputerAskState = "asking" | "turning-on" | "on" | "failed" | "declined" | "ended";
-
-export type ComputerDevice = "PC" | "Mac" | "computer";
-
-export interface ComputerAskCard {
- need: ComputerNeed;
- reason: ComputerAskReason;
- device: ComputerDevice;
- state: ComputerAskState;
- /** What the bot wants to do and why, in its own words, cleaned. */
- why?: string;
-}
-
-export interface ComputerAskField {
- /** A bot on the person's own Cloud asks to turn on what it needs from their computer. */
- computerAsk?: ComputerAskCard;
-}
-
-/** A tap on Turn on can fix this from wherever the card is: the app on that computer does it. */
-export function turnsOnFromHere(reason: ComputerAskReason): boolean {
- return reason === "paused" || reason === "permissions" || reason === "blocked" || reason === "off" || reason === "not-running" || reason === "terminal-off";
-}
-
-/** The fix is getting the app there: install it, open it, or update it. */
-export function needsTheApp(reason: ComputerAskReason): boolean {
- return reason === "closed" || reason === "never" || reason === "update";
-}
-
-export const COMPUTER_ASK_WORDS = {
- "computerAsk.want.screen": "{name} wants to use your {device}'s apps and screen",
- "computerAsk.want.folders": "{name} wants to use the files on your {device}",
- "computerAsk.want.terminal": "{name} wants to run commands on your {device}",
- "computerAsk.reason.paused": "Using your {device} is paused.",
- "computerAsk.reason.starting": "Screen control is still starting on your {device}.",
- "computerAsk.reason.permissions": "macOS hasn't allowed {app} to see and use the screen yet.",
- "computerAsk.reason.blocked": "Screen control is blocked on your {device}.",
- "computerAsk.reason.blockedPc": "Screen control is blocked on your PC: Windows Security may have stopped it.",
- "computerAsk.reason.off": "Screen control is off on your {device}.",
- "computerAsk.reason.notRunning": "Screen control isn't running on your {device}.",
- "computerAsk.reason.unsupported": "Screen control can't work on your {device} right now.",
- "computerAsk.reason.terminalOff": "Running commands isn't turned on for your {device}.",
- "computerAsk.reason.closed": "{app} isn't open on your {device}. Open it there and {name} carries on.",
- "computerAsk.reason.never": "{app} isn't on your computer yet. Install it, sign in to MausBot Cloud there, and {name} carries on.",
- "computerAsk.reason.update": "{app} on your {device} needs an update first. Update it, and {name} carries on.",
- "computerAsk.action.turnOn": "Turn on",
- "computerAsk.action.tryAgain": "Try again",
- "computerAsk.action.notNow": "Not now",
- "computerAsk.action.getApp": "Get {app}",
- "computerAsk.state.turningOn": "Turning on…",
- "computerAsk.state.on": "Turned on. {name} is carrying on.",
- "computerAsk.state.failed": "It didn't turn on.",
- "computerAsk.state.declined": "Not now",
- "computerAsk.state.ended": "No longer needed",
-} as const;
-
-export type ComputerAskKey = keyof typeof COMPUTER_ASK_WORDS;
-
-/** The product's name as the person reads it, as the app fills `{app}`. */
-export const COMPUTER_ASK_APP = "MausBot";
-
-export function computerAskText(key: ComputerAskKey, params: Record<string, string>): string {
- return COMPUTER_ASK_WORDS[key].replace(/\{(\w+)\}/g, (whole, name: string) => (name === "app" ? params.app ?? COMPUTER_ASK_APP : params[name] ?? whole));
-}
-
-const WANT_KEY: Record<ComputerNeed, ComputerAskKey> = {
- screen: "computerAsk.want.screen",
- folders: "computerAsk.want.folders",
- terminal: "computerAsk.want.terminal",
-};
-
-/** The card's headline: who wants what, from which computer. */
-export function computerAskHeadline(card: Pick<ComputerAskCard, "need" | "device">): { key: ComputerAskKey; params: Record<string, string> } {
- return { key: WANT_KEY[card.need], params: { device: card.device } };
-}
-
-/** Why it isn't available, as a catalog key and its values. */
-export function computerAskReasonLine(card: Pick<ComputerAskCard, "reason" | "device">, name: string): { key: ComputerAskKey; params: Record<string, string> } {
- const params = { device: card.device, name };
- switch (card.reason) {
- case "paused": return { key: "computerAsk.reason.paused", params };
- case "starting": return { key: "computerAsk.reason.starting", params };
- case "permissions": return { key: "computerAsk.reason.permissions", params };
- case "blocked": return { key: card.device === "PC" ? "computerAsk.reason.blockedPc" : "computerAsk.reason.blocked", params };
- case "off": return { key: "computerAsk.reason.off", params };
- case "unsupported": return { key: "computerAsk.reason.unsupported", params };
- case "terminal-off": return { key: "computerAsk.reason.terminalOff", params };
- case "closed": return { key: "computerAsk.reason.closed", params };
- case "never": return { key: "computerAsk.reason.never", params };
- case "update": return { key: "computerAsk.reason.update", params };
- default: return { key: "computerAsk.reason.notRunning", params };
- }
-}
-
-/** What a bot wrote as its reason, made safe for one line on the card: no control or direction characters, at most 200. */
-export function cleanAskWhy(value: unknown): string | undefined {
- if (typeof value !== "string") return undefined;
- // eslint-disable-next-line no-control-regex
- const line = value.replace(/[\u0000-\u001f\u007f‪-‮⁦-⁩]+/g, " ").replace(/\s+/g, " ").trim();
- if (!line) return undefined;
- return line.length > 200 ? `${line.slice(0, 199).trimEnd()}…` : line;
-}
+export * from "../packages/phone-protocol/src/computer-ask.ts";
diff --git a/shared/connector-card.ts b/shared/connector-card.ts
index f3a52f57c3..9d68d4f334 100644
--- a/shared/connector-card.ts
+++ b/shared/connector-card.ts
@@ -1,21 +1 @@
-export interface ConnectorCardData {
- /** What the card connects: a Composio app (absent or "composio"), or a sign-in to an MCP server ("mcp"). */
- source?: "composio" | "mcp";
- /** Composio toolkit slug, or the MCP server's name. It is validated server-side before every action. */
- slug: string;
- label: string;
- description: string;
- status: "required" | "authorizing" | "connected" | "failed";
- /** Cards created by one agent request resume together after all connect. */
- resumeKey: string;
- /** Account alias supplied by the agent when adding a second account. */
- alias?: string;
- error?: string;
- dismissed?: boolean;
- /** A newer card for the same request replaced this one: it is hidden as `dismissed` is, and nothing waits on it. */
- superseded?: boolean;
- resumed?: boolean;
- /** Stop ended the turn this card paused: it offers no action, and a
- * connection made afterwards is kept but continues nothing. */
- stopped?: boolean;
-}
+export * from "../packages/phone-protocol/src/connector-card.ts";
diff --git a/shared/connector-scopes.ts b/shared/connector-scopes.ts
index e7a64f3f19..2f8384f26f 100644
--- a/shared/connector-scopes.ts
+++ b/shared/connector-scopes.ts
@@ -1,101 +1 @@
-// Per-bot connection scopes: which connected apps a bot may use, and whether
-// only to read. Absent means every connected app, read and write; present, an
-// app not listed is off and "read" refuses anything that is not a read. The
-// harness enforces it at the connector relay; the app shows the control.
-import { KNOWN_READ_SLUGS } from "./outbound.ts";
-
-const READ_VERBS = new Set(["GET", "LIST", "FETCH", "SEARCH", "READ", "FIND", "RETRIEVE", "LOOKUP", "DOWNLOAD", "VIEW", "CHECK", "COUNT"]);
-
-interface ScopedCall {
- slug: string;
-}
-
-export type ConnectorScope = "read" | "write";
-
-export interface ConnectorScopes {
- /** toolkit slug (lower case, Composio's) → what this bot may do with it */
- apps: Record<string, ConnectorScope>;
-}
-
-const TOOLKIT_SLUG = /^[a-z0-9][a-z0-9_-]{0,63}$/;
-
-/** The toolkit a Composio slug belongs to: the part before the first
- * underscore, lower-cased. A workbench API proxy belongs to no app. */
-export function toolkitOf(slug: string): string {
- const cut = slug.indexOf("_");
- return (cut > 0 ? slug.slice(0, cut) : slug).toLowerCase();
-}
-
-/** Toolkits whose actions name a one-word resource before the verb
- * (HIGHLEVEL_MCP_CONTACTS_GET_CONTACTS lists contacts). Anything else there,
- * such as a longer resource name, stays a write. */
-const RESOURCE_FIRST_TOOLKITS = ["highlevel_mcp"];
-
-/** A read verb first means the tool reads. Creating a draft writes to the
- * account even though it sends nothing, so it is a write here. */
-export function isReadOnlyAction(slug: string, toolkit?: string): boolean {
- if (slug === "COMPOSIO_PROXY_EXECUTE") return false;
- if (KNOWN_READ_SLUGS.has(slug)) return true;
- const resourceFirst = RESOURCE_FIRST_TOOLKITS.find((candidate) => (toolkit ?? candidate) === candidate && slug.startsWith(candidate.toUpperCase() + "_"));
- const cut = resourceFirst ? resourceFirst.length : toolkit ? toolkit.length : slug.indexOf("_");
- const action = cut > 0 ? slug.slice(cut + 1) : "";
- const verb = action.toUpperCase().split(/[^A-Z0-9]+/).filter(Boolean)[resourceFirst ? 1 : 0];
- return verb !== undefined && READ_VERBS.has(verb);
-}
-
-/** The stored shape, or null when the value is not one. */
-export function normalizeConnectorScopes(value: unknown): ConnectorScopes | null {
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
- const raw = (value as { apps?: unknown }).apps;
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return null;
- const apps: Record<string, ConnectorScope> = Object.create(null);
- for (const [key, scope] of Object.entries(raw as Record<string, unknown>)) {
- const slug = key.trim().toLowerCase();
- if (!TOOLKIT_SLUG.test(slug)) return null;
- if (scope !== "read" && scope !== "write") return null;
- apps[slug] = scope;
- }
- return { apps };
-}
-
-export type ConnectorAccess =
- | { ok: true }
- | { ok: false; slug: string; toolkit: string; reason: "app" | "write" };
-
-/** May this bot run these calls? The first refusal wins, so a batch that
- * mixes an allowed read with a forbidden write is refused whole rather
- * than half-run. */
-export function connectorAccessDecision(scopes: ConnectorScopes | undefined, calls: ScopedCall[], toolkits: readonly string[] = []): ConnectorAccess {
- if (!scopes) return { ok: true };
- for (const call of calls) {
- const toolkit = toolkits.filter(candidate => call.slug.startsWith(candidate.toUpperCase() + "_"))
- .sort((a, b) => b.length - a.length)[0] ?? toolkitOf(call.slug);
- const scope = call.slug === "COMPOSIO_PROXY_EXECUTE" || !Object.hasOwn(scopes.apps, toolkit) ? undefined : scopes.apps[toolkit];
- if (!scope) return { ok: false, slug: call.slug, toolkit, reason: "app" };
- if (scope === "read" && !isReadOnlyAction(call.slug, toolkit)) return { ok: false, slug: call.slug, toolkit, reason: "write" };
- }
- return { ok: true };
-}
-
-/** A bot whose scopes switch an app on gets that app's tools: every one, unless its tool list already names some. A tool
- * list that leaves out an app its scopes turn on would give that app no tool on any engine. True when `bot` changed. */
-export function grantScopedApps(bot: { connectorScopes?: ConnectorScopes; connectorTools?: Record<string, { tools: "*" | string[] }> }): boolean {
- const tools = bot.connectorTools, scopes = bot.connectorScopes;
- if (!scopes || !tools || typeof tools !== "object" || Array.isArray(tools)) return false;
- const missing = Object.keys(scopes.apps).filter((slug) => !Object.hasOwn(tools, slug));
- if (!missing.length) return false;
- bot.connectorTools = { ...tools, ...Object.fromEntries(missing.map((slug) => [slug, { tools: "*" as const }])) };
- return true;
-}
-
-/** One sentence for the bot's prompt, so it does not spend a turn finding
- * out. Empty when the bot is unscoped. */
-export function describeConnectorScopes(scopes: ConnectorScopes | undefined): string {
- if (!scopes) return "";
- const entries = Object.entries(scopes.apps);
- if (entries.length === 0) return " This bot has been given no connected apps; do not try to use any.";
- const listed = entries
- .map(([slug, scope]) => `${slug} (${scope === "read" ? "read only" : "read and write"})`)
- .join(", ");
- return ` This bot may use only these connected apps: ${listed}. Do not try others, and do not write to a read-only one.`;
-}
+export * from "../packages/phone-protocol/src/connector-scopes.ts";
diff --git a/shared/credential-request.ts b/shared/credential-request.ts
index f55e45d75b..b76c9d8f99 100644
--- a/shared/credential-request.ts
+++ b/shared/credential-request.ts
@@ -1,324 +1 @@
-import { MODELGO_URL } from "./modelgo.ts";
-/**
- * Credentials an agent may ask the person to provide through an inline
- * card. The id is the entire authority surface: agents never choose a
- * config path, label, URL, or arbitrary field name.
- */
-export const CREDENTIAL_TARGETS = {
- xaiApiKey: {
- label: "xAI API key",
- description: "Used by the built-in Grok provider.",
- placeholder: "xai-…",
- helpUrl: "https://console.x.ai/",
- },
- boxToken: {
- label: "Boat API key",
- description: "Gives bots an isolated cloud computer when Boat is selected.",
- placeholder: "Paste your Boat API key",
- helpUrl: "https://docs.boat.dev/api-keys",
- },
- opencodeGoApiKey: {
- label: "OpenCode API key",
- description: "Used for OpenCode Zen and Go.",
- placeholder: "Paste your OpenCode API key",
- helpUrl: "https://opencode.ai/docs/providers/",
- },
- ttsKey: {
- label: "ElevenLabs API key",
- description: "Enables text-to-speech voices in calls.",
- placeholder: "Paste your ElevenLabs API key",
- helpUrl: "https://elevenlabs.io/app/settings/api-keys",
- },
- geminiTtsKey: {
- label: "Gemini speech API key",
- description: "Generates spoken replies, voice notes and call speech with Gemini.",
- placeholder: "Paste your Google AI Studio API key",
- helpUrl: "https://aistudio.google.com/api-keys",
- },
- fishAudioKey: {
- label: "Fish Audio API key",
- description: "Enables Fish Audio voices in calls.",
- placeholder: "Paste your Fish Audio API key",
- helpUrl: "https://fish.audio/app/api-keys/",
- },
- openaiImageApiKey: {
- label: "OpenAI API key",
- description: "Used to generate images in chats and bot avatars when OpenAI is the image provider.",
- placeholder: "sk-…",
- helpUrl: "https://platform.openai.com/api-keys",
- },
- onePasswordToken: {
- label: "1Password service account token",
- description: "Lets bots sign in with the website logins in the 1Password vault this token can read, the way Settings → Logins does.",
- placeholder: "ops_…",
- helpUrl: "https://developer.1password.com/docs/service-accounts/get-started/",
- },
- composioApiKey: {
- label: "Composio API key",
- description: "Connects apps such as Gmail, Slack and GitHub through your own Composio project.",
- placeholder: "ak_…",
- helpUrl: "https://dashboard.composio.dev/~/project/settings/api-keys",
- },
- openaiApiKey: {
- label: "OpenAI API key",
- description: "Runs OpenAI models with your own key.",
- placeholder: "sk-…",
- helpUrl: "https://platform.openai.com/api-keys",
- },
- anthropicApiKey: {
- label: "Anthropic API key",
- description: "Runs Claude models with your own key. Bots signed in to Claude keep using their sign-in.",
- placeholder: "sk-ant-…",
- helpUrl: "https://console.anthropic.com/settings/keys",
- },
- openrouterApiKey: {
- label: "OpenRouter API key",
- description: "Runs models from many providers through OpenRouter.",
- placeholder: "sk-or-v1-…",
- helpUrl: "https://openrouter.ai/keys",
- },
- mistralApiKey: {
- label: "Mistral API key",
- description: "Runs Mistral models with your own key.",
- placeholder: "Paste your Mistral API key",
- helpUrl: "https://console.mistral.ai/api-keys",
- },
- cerebrasApiKey: {
- label: "Cerebras API key",
- description: "Runs Cerebras models with your own key.",
- placeholder: "csk-…",
- helpUrl: "https://cloud.cerebras.ai/",
- },
- groqApiKey: {
- label: "Groq API key",
- description: "Runs Groq models with your own key.",
- placeholder: "gsk_…",
- helpUrl: "https://console.groq.com/keys",
- },
- greenferenceApiKey: {
- label: "Greenference API key",
- description: "Runs Greenference models with your own key.",
- placeholder: "Paste your Greenference API key",
- helpUrl: "https://greenference.com/dashboard/tokens",
- },
- modelgoApiKey: {
- label: "ModelGo API key",
- description: "Runs ModelGo models with your own key.",
- placeholder: "Paste your ModelGo API key",
- helpUrl: MODELGO_URL,
- },
- metaApiKey: {
- label: "Meta API key",
- description: "Runs Meta's models with your own key.",
- placeholder: "LLM|…",
- helpUrl: "https://dev.meta.ai/docs/authentication",
- },
- deepseekApiKey: {
- label: "DeepSeek API key",
- description: "Runs DeepSeek models with your own key.",
- placeholder: "sk-…",
- helpUrl: "https://platform.deepseek.com/api_keys",
- },
-} as const;
-
-export type CredentialTargetId = keyof typeof CREDENTIAL_TARGETS;
-/** Saved in the sealed login store, not the settings file. */
-export type LoginCredentialTargetId = "onePasswordToken";
-export type ConfigCredentialTargetId = Exclude<CredentialTargetId, LoginCredentialTargetId>;
-/** AI provider keys: refused where Admin manages the models, and typed only in the computer's own app or a desktop paired to it, never on a phone. */
-export const PROVIDER_CREDENTIAL_TARGETS = [
- "openaiApiKey", "anthropicApiKey", "openrouterApiKey", "mistralApiKey", "cerebrasApiKey", "groqApiKey", "greenferenceApiKey", "modelgoApiKey", "metaApiKey", "deepseekApiKey",
-] as const satisfies readonly ConfigCredentialTargetId[];
-export type DesktopCredentialSlot = ConfigCredentialTargetId;
-export type CredentialConfig = {
- xai?: { key?: string };
- box?: { token?: string };
- opencodeGo?: { apiKey?: string };
- tts?: { key?: string; fishKey?: string; geminiKey?: string };
- imageGen?: { key?: string };
- composio?: { apiKey?: string };
- openai?: { key?: string };
- anthropic?: { key?: string; everyClaudeBot?: boolean };
- openrouter?: { key?: string };
- mistral?: { key?: string };
- cerebras?: { key?: string };
- groq?: { key?: string };
- greenference?: { key?: string };
- modelgo?: { key?: string };
- meta?: { key?: string };
- deepseek?: { key?: string };
- /** Not in the settings file: the server fills it from its login store. */
- onePassword?: { connected?: boolean };
-};
-
-/** A secret OpenMausBot does not keep itself: the bot names it, and gets a one-use reference or a private file. */
-export const CUSTOM_SECRET_TARGET = "customSecret";
-export type SecretDelivery = "ref" | "file";
-export const SECRET_DELIVERIES: readonly SecretDelivery[] = ["ref", "file"];
-export const CUSTOM_SECRET_LABEL_MAX = 80;
-export const CUSTOM_SECRET_REASON_MAX = 240;
-
-export function isCredentialTargetId(value: unknown): value is CredentialTargetId {
- return typeof value === "string" && Object.prototype.hasOwnProperty.call(CREDENTIAL_TARGETS, value);
-}
-
-export function isConfigCredentialTarget(id: CredentialTargetId): id is ConfigCredentialTargetId {
- return id !== "onePasswordToken";
-}
-
-export function isProviderCredentialTarget(id: CredentialTargetId): boolean {
- return (PROVIDER_CREDENTIAL_TARGETS as readonly string[]).includes(id);
-}
-
-/** The desktop's encrypted-store slot that holds this key, where Settings saves it; null for the 1Password token, which Logins keeps. */
-export function desktopCredentialSlot(id: CredentialTargetId): DesktopCredentialSlot | null {
- return isConfigCredentialTarget(id) ? id : null;
-}
-
-/** Where a card saves what the person typed: the 1Password token goes to Logins, which checks it reaches 1Password. */
-export function credentialSaveRequest(id: CredentialTargetId, value: string): { path: string; method: "PUT" | "POST"; body: object } {
- return isConfigCredentialTarget(id)
- ? { path: "/api/config", method: "PUT", body: credentialConfigPatch(id, value) }
- : { path: "/api/logins/1password", method: "POST", body: { token: value } };
-}
-
-export function credentialConfigPatch(id: ConfigCredentialTargetId, value: string): CredentialConfig {
- switch (id) {
- case "xaiApiKey":
- return { xai: { key: value } };
- case "boxToken":
- return { box: { token: value } };
- case "opencodeGoApiKey":
- return { opencodeGo: { apiKey: value } };
- case "ttsKey":
- return { tts: { key: value } };
- case "geminiTtsKey":
- return { tts: { geminiKey: value } };
- case "fishAudioKey":
- return { tts: { fishKey: value } };
- case "openaiImageApiKey":
- return { imageGen: { key: value } };
- case "composioApiKey":
- return { composio: { apiKey: value } };
- case "openaiApiKey":
- return { openai: { key: value } };
- // Settings' first Anthropic key leaves every bot signed in to Claude on its sign-in; a card appears only while none is set.
- case "anthropicApiKey":
- return { anthropic: { key: value, everyClaudeBot: false } };
- case "openrouterApiKey":
- return { openrouter: { key: value } };
- case "mistralApiKey":
- return { mistral: { key: value } };
- case "cerebrasApiKey":
- return { cerebras: { key: value } };
- case "groqApiKey":
- return { groq: { key: value } };
- case "greenferenceApiKey":
- return { greenference: { key: value } };
- case "modelgoApiKey":
- return { modelgo: { key: value } };
- case "metaApiKey":
- return { meta: { key: value } };
- case "deepseekApiKey":
- return { deepseek: { key: value } };
- }
-}
-
-export function credentialIsConfigured(config: CredentialConfig, id: CredentialTargetId): boolean {
- switch (id) {
- case "xaiApiKey":
- return Boolean(config.xai?.key);
- case "boxToken":
- return Boolean(config.box?.token);
- case "opencodeGoApiKey":
- return Boolean(config.opencodeGo?.apiKey);
- case "ttsKey":
- return Boolean(config.tts?.key);
- case "geminiTtsKey":
- return Boolean(config.tts?.geminiKey);
- case "fishAudioKey":
- return Boolean(config.tts?.fishKey);
- case "openaiImageApiKey":
- return Boolean(config.imageGen?.key);
- case "onePasswordToken":
- return Boolean(config.onePassword?.connected);
- case "composioApiKey":
- return Boolean(config.composio?.apiKey);
- case "openaiApiKey":
- return Boolean(config.openai?.key);
- case "anthropicApiKey":
- return Boolean(config.anthropic?.key);
- case "openrouterApiKey":
- return Boolean(config.openrouter?.key);
- case "mistralApiKey":
- return Boolean(config.mistral?.key);
- case "cerebrasApiKey":
- return Boolean(config.cerebras?.key);
- case "groqApiKey":
- return Boolean(config.groq?.key);
- case "greenferenceApiKey":
- return Boolean(config.greenference?.key);
- case "modelgoApiKey":
- return Boolean(config.modelgo?.key);
- case "metaApiKey":
- return Boolean(config.meta?.key);
- case "deepseekApiKey":
- return Boolean(config.deepseek?.key);
- }
-}
-
-/** A still-pending credential card for this target — the set a newer
- * request supersedes. Provided, dismissed, and already-superseded cards
- * keep their settled state untouched. */
-export function isPendingCredentialRequest(
- message: {
- kind?: unknown;
- secret?: { target?: unknown; provided?: unknown; dismissed?: unknown; superseded?: unknown };
- from?: { botId?: unknown };
- },
- target: CredentialTargetId,
- requestingBotId: string,
- roomThread: boolean,
-): boolean {
- return (
- message.kind === "secret" &&
- message.secret?.target === target &&
- message.secret.provided !== true &&
- message.secret.dismissed !== true &&
- message.secret.superseded !== true &&
- (!roomThread || message.from?.botId === requestingBotId)
- );
-}
-
-/** A still-pending card from this bot for a custom secret with the same name, which a newer request supersedes. */
-export function isPendingCustomSecretRequest(
- message: {
- kind?: unknown;
- secret?: { target?: unknown; label?: unknown; provided?: unknown; dismissed?: unknown; superseded?: unknown };
- from?: { botId?: unknown };
- },
- label: string,
- requestingBotId: string,
- roomThread: boolean,
-): boolean {
- return (
- message.kind === "secret" &&
- message.secret?.target === CUSTOM_SECRET_TARGET &&
- typeof message.secret.label === "string" &&
- message.secret.label.toLowerCase() === label.toLowerCase() &&
- message.secret.provided !== true &&
- message.secret.dismissed !== true &&
- message.secret.superseded !== true &&
- (!roomThread || message.from?.botId === requestingBotId)
- );
-}
-
-export function credentialResumeOutcome(state: {
- provided?: unknown;
- dismissed?: unknown;
-}): "provided" | "dismissed" | null {
- const provided = state.provided === true;
- const dismissed = state.dismissed === true;
- if (provided === dismissed) return null;
- return provided ? "provided" : "dismissed";
-}
+export * from "../packages/phone-protocol/src/credential-request.ts";
diff --git a/shared/data-surface.ts b/shared/data-surface.ts
index c776ebf974..953e73ae63 100644
--- a/shared/data-surface.ts
+++ b/shared/data-surface.ts
@@ -1,254 +1 @@
-// The Data surface: what the server, the bots' tools and the panel agree on.
-// DuckDB runs in the OMB server, one database per bot.
-
-/** The five tools a bot gets, in the order the catalog lists them. */
-export const DATA_TOOL_NAMES = ["data_load", "data_describe", "data_sql", "data_show", "data_export"] as const;
-export type DataToolName = (typeof DATA_TOOL_NAMES)[number];
-
-/** Bounds. Every result is capped by rows AND bytes; the gate's own trimming
- * is the backstop, never the plan. */
-export const DATA_LIMITS = {
- /** `data_sql` rows returned to the model by default, and at most. */
- sqlRowsDefault: 50,
- sqlRowsMax: 500,
- /** Bytes of rows `data_sql` returns to the model. */
- sqlBytesMax: 32 * 1024,
- /** `data_describe` result bytes; beyond `describeColumnsMax` columns, types only. */
- describeBytesMax: 16 * 1024,
- describeColumnsMax: 50,
- /** Sample values per column, each at most `sampleChars` characters. */
- sampleValues: 3,
- sampleChars: 40,
- /** Rows per page the panel's grid asks for (Tad's proven size). */
- pageSize: 1024,
- /** Marks a chart may render after its SQL reduction. */
- chartMaxMarks: 10_000,
- /** Rows `data_show kind:"table"` keeps for the panel; the grid pages them. */
- showTableRowsMax: 1_000_000,
- /** One statement's wall clock before `interrupt()`. */
- sqlTimeoutMs: 60_000,
- /** Cards a sheet holds; the oldest unpinned card goes first. */
- sheetCardsMax: 200,
-} as const;
-
-/** Where materialised results live inside a bot's database. DuckDB temp tables
- * are per connection; a real schema is visible to both and survives a restart. */
-export const DATA_RESULTS_SCHEMA = "omb_results";
-
-export type DataErrorCode =
- | "invalid_input"
- | "source_not_found"
- | "source_unsupported"
- | "sql_error"
- | "write_refused"
- | "table_not_found"
- | "spec_invalid"
- | "card_not_found"
- | "output_too_large"
- | "timeout"
- | "cancelled"
- | "engine_unavailable";
-
-/** The structured failure every tool and route returns. `line` is DuckDB's
- * own 1-based line in `sql`; `message` is DuckDB's text, never reworded. */
-export interface DataError {
- code: DataErrorCode;
- message: string;
- sql?: string;
- line?: number;
- hint?: string;
- retryable?: boolean;
- /** For `table_not_found`: close names the bot can use instead. */
- candidates?: string[];
-}
-
-export interface DataColumn {
- name: string;
- /** DuckDB's type name as `DESCRIBE` prints it (BIGINT, VARCHAR, DECIMAL(10,2), …). */
- type: string;
- nullPct?: number;
- approxUnique?: number;
- min?: string | null;
- max?: string | null;
- /** Up to DATA_LIMITS.sampleValues distinct values, as text. */
- sample?: string[];
-}
-
-/** One entry of the bot's table catalog, as GET /data reports it from DuckDB. */
-export interface DataTable {
- name: string;
- /** A quoted identifier ready to paste into SQL; `name` remains the identity. */
- sqlName?: string;
- rowCount: number;
- columns: DataColumn[];
-}
-
-/** A table the bot loaded, as the Sources strip and `data_load` report it. */
-export interface DataSource {
- name: string;
- /** A quoted identifier ready to paste into SQL; name remains the source identity. */
- sqlName?: string;
- kind: "csv" | "parquet" | "json" | "xlsx" | "folder" | "url" | "postgres" | "mysql" | "sqlite" | "gsheet" | "connector" | "sql";
- /** The path, URL or connection the table came from, with credentials removed. */
- source: string;
- options?: Record<string, string | number | boolean>;
- rowCount: number;
- columns: DataColumn[];
- loadedAt: string;
-}
-
-/** What a bot says when it wants a chart. Small on purpose: the server
- * compiles it to SQL (with the reduction) and to Vega-Lite, so the model
- * never writes a chart grammar. */
-export interface OmbChartSpec {
- type: "bar" | "line" | "area" | "scatter" | "histogram" | "pie" | "heatmap";
- /** Column for the x axis (the category, the time, or the value to bin). */
- x: string;
- /** Column for the y axis. Absent means count. */
- y?: string;
- /** Column to colour by (series, stack segments, heatmap cells). */
- color?: string;
- /** How y is aggregated per x (and colour). Default: sum when y is set, else count. */
- agg?: "count" | "sum" | "avg" | "min" | "max" | "median";
- /** Order of categories. Default: by x. */
- sort?: "x" | "-x" | "y" | "-y";
- /** Categories to keep (the rest fold into "other"). Default 20 for categorical x. */
- limit?: number;
- stack?: boolean;
- /** Bucket a date or timestamp x. Default: chosen from the x range. */
- timeUnit?: "hour" | "day" | "week" | "month" | "quarter" | "year";
- /** Histogram bins. Default 30. */
- bins?: number;
- /** Column for mark size (scatter). */
- size?: string;
-}
-
-/** How the compiler shrank the data before charting, shown on the card. */
-export interface DataReduction {
- method: "group" | "bins" | "topN" | "timeBucket" | "m4" | "sample" | "none";
- inputRows: number;
- outputRows: number;
- note?: string;
-}
-
-export type DataCardKind = "table" | "chart" | "text";
-
-/** One card on the sheet. The SQL is always kept so Refresh re-runs it; the
- * result table is `${DATA_RESULTS_SCHEMA}.${result}` while it exists. */
-export interface DataCard {
- id: string;
- kind: DataCardKind;
- title: string;
- /** The SQL whose result this card shows (table and chart cards). */
- sql?: string;
- /** The materialised result table in DATA_RESULTS_SCHEMA, or null while running or failed. */
- result?: string | null;
- columns?: DataColumn[];
- rowCount?: number;
- truncated?: boolean;
- /** Chart cards: the bot's spec, the compiled Vega-Lite (data-free; the
- * panel binds the reduced rows as the dataset named "table"), the reduction. */
- chart?: OmbChartSpec;
- vegaLite?: Record<string, unknown>;
- reduction?: DataReduction;
- /** Text cards: Markdown. */
- text?: string;
- status: "running" | "ready" | "failed";
- error?: DataError;
- /** Who made or last changed it: the bot (tool) or the person (panel). */
- by: "bot" | "person";
- pinned?: boolean;
- createdAt: string;
- updatedAt: string;
- elapsedMs?: number;
-}
-
-/** The sheet: what the Data tab shows and what `sheet.json` stores. */
-export interface DataSheet {
- version: 1;
- botId: string;
- cards: DataCard[];
- sources: DataSource[];
- updatedAt: string;
-}
-
-/** Server → client. One message carries the whole sheet (sheets hold no rows).
- * The database's catalog is not on it: GET /api/bots/:id/data reads it fresh. */
-export interface DataBroadcast {
- kind: "data";
- botId: string;
- sheet: DataSheet;
-}
-
-/** Panel routes, all under `/api/bots/:botId/data`. The person's own
- * actions take the same paths as the bot's tools inside the server. */
-export interface DataPageRequest {
- /** A source table name, or a card id (its result table). Exactly one. */
- table?: string;
- cardId?: string;
- offset: number;
- limit: number;
- sort?: { column: string; direction: "asc" | "desc" };
- /** Case-insensitive literal text matching, across all columns unless filterColumn is set. */
- filter?: string;
- /** Exact column name to search; values are cast to text. */
- filterColumn?: string;
-}
-
-export interface DataPage {
- columns: DataColumn[];
- /** Cells as JSON: DuckDB bigints and decimals arrive as strings. */
- rows: Array<Array<string | number | boolean | null>>;
- rowCount: number;
- offset: number;
-}
-
-export interface DataRunRequest {
- sql: string;
- /** Update this card instead of adding one. */
- cardId?: string;
- title?: string;
- /** Chart the result instead of tabling it. */
- chart?: OmbChartSpec;
- vegaLite?: Record<string, unknown>;
- /** Replace an existing result only after a successful, current live edit. */
- live?: boolean;
-}
-
-export interface DataColumnStats {
- table: string;
- rowCount: number;
- columns: DataColumn[];
-}
-
-export interface DataHistogram {
- table: string;
- column: string;
- /** Numeric and date columns: equal-width bins; text: top values. */
- bins: Array<{ label: string; count: number }>;
-}
-
-export type DataExportFormat = "csv" | "parquet" | "xlsx" | "png" | "svg";
-
-export interface DataExportRequest {
- cardId?: string;
- table?: string;
- format: DataExportFormat;
-}
-
-export const DATA_ROUTES = {
- sheet: (botId: string) => `/api/bots/${encodeURIComponent(botId)}/data`,
- page: (botId: string) => `/api/bots/${encodeURIComponent(botId)}/data/page`,
- run: (botId: string) => `/api/bots/${encodeURIComponent(botId)}/data/run`,
- cancel: (botId: string) => `/api/bots/${encodeURIComponent(botId)}/data/cancel`,
- card: (botId: string, cardId: string) => `/api/bots/${encodeURIComponent(botId)}/data/cards/${encodeURIComponent(cardId)}`,
- stats: (botId: string, table: string) => `/api/bots/${encodeURIComponent(botId)}/data/tables/${encodeURIComponent(table)}/stats`,
- histogram: (botId: string, table: string, column: string) =>
- `/api/bots/${encodeURIComponent(botId)}/data/tables/${encodeURIComponent(table)}/histogram?column=${encodeURIComponent(column)}`,
- export: (botId: string) => `/api/bots/${encodeURIComponent(botId)}/data/export`,
- /** Server-rendered chart image for phones, Slack and email. */
- image: (botId: string, cardId: string) => `/api/bots/${encodeURIComponent(botId)}/data/cards/${encodeURIComponent(cardId)}/image`,
-} as const;
-
-/** The tab's id in the Computer panel and the storage key suffix. */
-export const DATA_PANEL_VIEW = "data" as const;
+export * from "../packages/phone-protocol/src/data-surface.ts";
diff --git a/shared/default-bot.ts b/shared/default-bot.ts
index 52bc8930a4..acc4bebee7 100644
--- a/shared/default-bot.ts
+++ b/shared/default-bot.ts
@@ -1,48 +1 @@
-import type { HelperFollowupField } from "./helper-followup.ts";
-import type { MausColor } from "./wire.ts";
-
-/** MausBot: every person's built-in helper. A new install's first bot (its Chief of Staff too); an existing place or
- * person without one is given one once. It can be renamed and recoloured, hidden from the sidebar, never deleted. */
-export const DEFAULT_BOT_NAME = "MausBot";
-export const DEFAULT_BOT_COLOR: MausColor = "chrome";
-
-export interface DefaultBotMark {
- /** Team Cloud only: the lowercased email of the member this MausBot belongs to. Absent: the place's own. */
- person?: string;
-}
-
-export interface DefaultBotFields {
- /** This bot is its place's (or, on a Team Cloud, its member's) MausBot. Never deleted or archived. */
- defaultBot?: DefaultBotMark;
- /** Settings → General "Show MausBot in the sidebar" is off: the bot keeps working, only its sidebar row is gone. */
- sidebarHidden?: boolean;
- /** Its person has seen MausBot's first-launch welcome here and chose Add or Not now. */
- welcomed?: boolean;
-}
-
-export interface HelperIntroField extends HelperFollowupField {
- /** MausBot's introduction. Clients that know it say it in the viewer's language with example asks; `text` is the
- * English fallback the model and older clients read. */
- helperIntro?: true;
-}
-
-export const defaultBotPerson = (bot: DefaultBotFields): string => bot.defaultBot?.person?.trim().toLowerCase() ?? "";
-
-/** The MausBot a viewer sees as theirs: their own on a Team Cloud (by email), else the place's. */
-export function viewersDefaultBot<T extends DefaultBotFields>(bots: readonly T[], email?: string | null): T | undefined {
- const person = email?.trim().toLowerCase() ?? "";
- return (person ? bots.find((bot) => bot.defaultBot && defaultBotPerson(bot) === person) : undefined)
- ?? bots.find((bot) => bot.defaultBot && !defaultBotPerson(bot));
-}
-
-/** A MausBot hidden from the sidebar comes back when it is renamed or moved to another department, unless the same
- * change says whether to show it. Returns the patch to save. */
-export function reshowWhenMoved<P extends { name?: string; section?: string; sidebarHidden?: boolean }>(
- bot: DefaultBotFields & { name: string; section?: string },
- patch: P,
-): P {
- if (!bot.defaultBot || !bot.sidebarHidden || Object.hasOwn(patch, "sidebarHidden")) return patch;
- const renamed = patch.name !== undefined && patch.name.trim() !== bot.name.trim();
- const moved = Object.hasOwn(patch, "section") && (patch.section?.trim() ?? "") !== (bot.section?.trim() ?? "");
- return renamed || moved ? { ...patch, sidebarHidden: false } : patch;
-}
+export * from "../packages/phone-protocol/src/default-bot.ts";
diff --git a/shared/devs-report-status.ts b/shared/devs-report-status.ts
index 147444b1f8..0e28f2ef37 100644
--- a/shared/devs-report-status.ts
+++ b/shared/devs-report-status.ts
@@ -1,33 +1 @@
-// A @devs bug report's status, as the MausBot team last said it (server/host/devs-reports.ts asks about it hourly and at each
-// start). The server writes it on the person's message that sent the report, and on the one line that tells them its fix
-// runs here; clients say it in their own words (src/components/BugReportNote.tsx), so it follows the app's language.
-
-export interface BugReportStatus {
- /** The MausBot team's id for the report (the "Sent to the MausBot team (report …)" line names it). */
- id: string;
- /** `received`: we have it and are looking; `fixed`: the team fixed it. */
- status: "received" | "fixed";
- /** The release the fix ships in, once the team knows it. */
- fixedIn?: string;
- /** This app runs that release (or a later one): the fix is here. */
- running?: true;
-}
-
-export interface BugReportField {
- /** On a person's message that tagged @devs: its report's status. On the one notice that tells them the fix runs here: the same, `running` set. */
- bugReport?: BugReportStatus;
-}
-
-const VERSION = /^v?(\d{1,6})\.(\d{1,6})\.(\d{1,6})(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;
-
-/** Whether this app's version (`running`) is the release `fixedIn` or a later one. Anything that doesn't read as a version is
- * never at least it, and neither is a pre-release of that very release: the fix is said to be here only when it surely is. */
-export function versionAtLeast(running: string, fixedIn: string): boolean {
- const have = VERSION.exec(running.trim()), want = VERSION.exec(fixedIn.trim());
- if (!have || !want || want[4] !== undefined) return false;
- for (const part of [1, 2, 3]) {
- const a = Number(have[part]), b = Number(want[part]);
- if (a !== b) return a > b;
- }
- return have[4] === undefined;
-}
+export * from "../packages/phone-protocol/src/devs-report-status.ts";
diff --git a/shared/digest.ts b/shared/digest.ts
index 940ef13b45..358c360dd1 100644
--- a/shared/digest.ts
+++ b/shared/digest.ts
@@ -1,38 +1 @@
-// Observed per-turn evidence, shared by server and companion renderers.
-export type HookCoverage = "full" | "preview" | "none";
-
-export interface DigestFiles {
- changed: string[];
- added: string[];
- deleted: string[];
- /** How many paths were cut from the lists above to stay within bounds. */
- truncated?: number;
-}
-
-export interface DigestTool {
- name: string;
- count: number;
- failed: number;
- /** One redacted one-line sample of the tool's input (the existing chip summary). */
- sample?: string;
-}
-
-export interface TurnDigest {
- turnId: string;
- botId: string;
- threadId: string;
- at: number;
- durationMs: number;
- tools: DigestTool[];
- /** Total observed calls, including tool names omitted from the list. */
- toolCalls?: number;
- /** Tools beyond the busiest MAX_TOOLS, dropped from `tools`. */
- toolsDropped?: number;
- files?: DigestFiles;
- memory: Array<{ path: string; kind: "created" | "updated" | "deleted" }>;
- memoryDropped?: number;
- /** First sentence of the terminal assistant text, at most REPLY_CHARS. */
- reply: string;
- usage?: { input: number; output: number; cachedInput?: number; costUsd?: number | null };
- hookCoverage: HookCoverage;
-}
+export * from "../packages/phone-protocol/src/digest.ts";
diff --git a/shared/email.ts b/shared/email.ts
index fe140fe73c..d9afafe94b 100644
--- a/shared/email.ts
+++ b/shared/email.ts
@@ -1,92 +1 @@
-// The Email connector's fixed names, shared by the server (tools, per-bot checks) and the app (bot settings, the card).
-// Tool names are upper-snake with the EMAIL_ prefix so the connector grant and scope rules apply unchanged.
-
-/** The connector slug in a bot's connectorScopes.apps and connectorTools. */
-export const EMAIL_SLUG = "email";
-/** The MCP server name bots see (tools arrive as mcp__email__EMAIL_<ACTION>). */
-export const EMAIL_MCP_SERVER = "email";
-/** What a bot passes as request_credential's credential_id for the mailbox card. */
-export const EMAIL_CREDENTIAL = "email";
-
-export const EMAIL_READ_TOOL_NAMES = ["EMAIL_LIST_MAILBOXES", "EMAIL_LIST_MESSAGES", "EMAIL_SEARCH_MESSAGES", "EMAIL_READ_MESSAGE"] as const;
-export const EMAIL_TOOL_NAMES = [...EMAIL_READ_TOOL_NAMES, "EMAIL_SEND_MESSAGE"] as const;
-export type EmailToolName = (typeof EMAIL_TOOL_NAMES)[number];
-
-/** How a mail server speaks TLS: from the first byte, or upgraded with STARTTLS. Never in the clear. */
-export type EmailSecurity = "tls" | "starttls";
-
-/** Where a mailbox's outgoing server is, when the person types it, and its own sign-in when that isn't the incoming
- * server's. A password left out is the mailbox's own. */
-export interface EmailOutgoingFields {
- smtpHost?: string;
- smtpPort?: number;
- smtpSecurity?: EmailSecurity;
- smtpUsername?: string;
- smtpPassword?: string;
-}
-
-/** Where a mailbox's mail servers are, when the person types them. */
-export interface EmailServerFields extends EmailOutgoingFields {
- imapHost?: string;
- imapPort?: number;
- username?: string;
-}
-
-export interface EmailConnectRequest extends EmailServerFields {
- address: string;
- password: string;
-}
-
-export interface EmailAccountView {
- address: string;
- imapHost: string;
- /** The server that sends, once one took the password. */
- smtpHost?: string;
- smtpPort?: number;
- smtpSecurity?: EmailSecurity;
- /** The outgoing server's own user name, when it has one. */
- smtpUsername?: string;
- /** While sending doesn't work: the outgoing server the reason is about, to start the form with. */
- smtpTried?: Pick<EmailOutgoingFields, "smtpHost" | "smtpPort" | "smtpSecurity">;
- connectedAt: string;
- /** Why it needs the person, in one plain sentence. */
- problem?: string;
- /** Why sending doesn't work, in one plain sentence naming the server; none while it works. */
- sendingProblem?: string;
-}
-
-/** What an outgoing form starts with: the server a mailbox sends through, or the one its sending problem is about; never a
- * password. */
-export function outgoingFieldsOf(account: EmailAccountView): EmailOutgoingFields {
- const server = account.smtpHost ? { smtpHost: account.smtpHost, smtpPort: account.smtpPort, smtpSecurity: account.smtpSecurity } : account.smtpTried ?? {};
- return Object.fromEntries(Object.entries({ ...server, smtpUsername: account.smtpUsername }).filter(([, value]) => value !== undefined)) as EmailOutgoingFields;
-}
-
-/** What POST /api/email/accounts/:address/outgoing answers: it checked sending again, at the server typed there (an
- * EmailOutgoingFields body) or the ones found for the address, without signing in to read again. */
-export type EmailOutgoingAnswer = { ok: true; account: EmailAccountView } | { ok: false; error: string; account?: EmailAccountView };
-
-/** A provider whose own sign-in fits better than a mailbox password: its app in Connected apps (`app`, its slug there),
- * or an app password made at `appPasswordUrl`. */
-export interface EmailSignInHint {
- provider: string;
- app?: "gmail" | "outlook";
- appPasswordUrl?: string;
-}
-
-/** POST /api/email/accounts/:address/test: a message from the mailbox to itself. */
-export type EmailTestAnswer = { ok: true } | { ok: false; error: string };
-
-/** GET /api/email. */
-export interface EmailStatus {
- state: "unavailable" | "signed-out" | "connected";
- accounts: EmailAccountView[];
- /** Why it is unavailable here. */
- reason?: string;
-}
-
-/** What POST /api/email/accounts answers: read a real header, or why not. `needsServer`: nothing was found, so the person
- * types where their mail server is. */
-export type EmailConnectAnswer =
- | { ok: true; account: EmailAccountView; inbox: { messages: number; newest?: { from: string; subject: string } }; sending: { ok: boolean; problem?: string; signIn?: EmailSignInHint } }
- | { ok: false; error: string; needsServer?: true; signIn?: EmailSignInHint };
+export * from "../packages/phone-protocol/src/email.ts";
diff --git a/shared/first-reply-rescue.ts b/shared/first-reply-rescue.ts
index c65b94e0ab..8a32a1a52d 100644
--- a/shared/first-reply-rescue.ts
+++ b/shared/first-reply-rescue.ts
@@ -1,38 +1 @@
-// A chat whose AI has said nothing yet, some seconds into the turn, gets one
-// notice row with what the person can do about it. The row's tool name is a
-// whole plain sentence, so a client that only prints tool names (the phones)
-// still reads it; this payload is what lets the desktop draw its buttons.
-
-export interface FirstReplyRescue {
- /** The bot whose turn is waiting: its AI is what "Switch AI" changes. */
- botId: string;
- threadId: string;
- /** The turn this row is about: its buttons never reach another one. */
- turnId: string;
- /** The person's message that turn answers, to send again on another AI. */
- requestMessageId?: string;
- /** The AI the turn waits on, as its instance id and the name a person knows it by. */
- instanceId: string;
- ai: string;
- /** A room turn: the room it is running in. */
- groupId?: string;
- /** The AI has started answering: the row no longer asks anything of the person. */
- settled?: true;
- /** Its turn ended (or gave way to the next) without an answer: the row is history, with no live buttons. */
- over?: true;
-}
-
-/** The waiting row's words, for clients that print the tool name. */
-export function firstReplyWaitingName(botName: string, ai: string): string {
- return `notice: ${botName} hasn't heard back from ${ai} yet.`;
-}
-
-/** The same row once its turn ended without an answer: history, true as it stands. */
-export function firstReplyOverName(botName: string, ai: string): string {
- return `notice: ${botName} didn't hear back from ${ai}.`;
-}
-
-/** The same row once the AI's first output arrived. */
-export function firstReplySettledName(ai: string): string {
- return `notice: ${ai} answered after a slow start.`;
-}
+export * from "../packages/phone-protocol/src/first-reply-rescue.ts";
diff --git a/shared/group-goal-run.ts b/shared/group-goal-run.ts
index 37ad398ac2..607b3e6e2c 100644
--- a/shared/group-goal-run.ts
+++ b/shared/group-goal-run.ts
@@ -1,28 +1 @@
-import type { ServerTextParams } from "./server-text.ts";
-/** Durable progress receipt for one goal-driven channel run. */
-export type GroupGoalRunStatus =
- | "working"
- | "completed"
- | "needs-input"
- | "blocked"
- | "limit-reached"
- /** The operator (or a guard) parked the run. */
- | "paused"
- | "stopped"
- | "failed";
-
-export interface GroupGoalRunCardData {
- runId: string;
- goal: string;
- status: GroupGoalRunStatus;
- coordinatorBotId: string;
- coordinatorName: string;
- turnCount: number;
- maxTurns: number;
- detail?: string;
- /** Fixed detail words, used only while they reconstruct the stored English. */
- detailCode?: string;
- detailParams?: ServerTextParams;
- startedAt: number;
- finishedAt?: number;
-}
+export * from "../packages/phone-protocol/src/group-goal-run.ts";
diff --git a/shared/helper-followup.ts b/shared/helper-followup.ts
index af9ebf75e2..d11948a58e 100644
--- a/shared/helper-followup.ts
+++ b/shared/helper-followup.ts
@@ -1,79 +1 @@
-// MausBot's follow-up after its first look around, under its intro (HelperIntro). The server writes it once, in English,
-// as a real message the model and the sidebar's preview read; clients say it in the viewer's language from its facts.
-// ENGLISH mirrors src/locales/en.json helperIntro.followup.*. It never names the AI it thinks with.
-
-export interface HelperFollowupFacts {
- /** "own": an AI of the person's own answers; "backup": only the free backup model works; "none": no AI yet. */
- ai: "own" | "backup" | "none";
- /** The apps every bot here can use, by name. */
- apps: string[];
- /** The person's other bots, and the routines running here, when it looked. */
- bots: number;
- routines: number;
- /** On a team, for someone who can't connect an AI: the name of the person who does; empty until the team's owner has
- * opened the team. */
- connects?: string;
-}
-
-export interface HelperFollowupField {
- helperFollowup?: HelperFollowupFacts;
-}
-
-/** At most this many app names; the rest are counted. */
-export const FOLLOWUP_APP_NAMES = 3;
-
-export const FOLLOWUP_ENGLISH = {
- "helperIntro.followup.found": "I looked around and nothing's waiting on you yet.",
- "helperIntro.followup.empty": "There's no unfinished work, no other bots or routines, and no apps are connected so far.",
- "helperIntro.followup.counts": "You have {bots} and {routines}, and no apps are connected so far.",
- "helperIntro.followup.botsNone": "no other bots",
- "helperIntro.followup.botOne": "1 other bot",
- "helperIntro.followup.bots": "{count} other bots",
- "helperIntro.followup.routinesNone": "no routines",
- "helperIntro.followup.routineOne": "1 routine",
- "helperIntro.followup.routines": "{count} routines",
- "helperIntro.followup.offer": "If you'd like me to keep an eye on your day, I can connect your email and calendar so I can flag what matters each morning. Just say the word, or hand me whatever's on your plate today.",
- "helperIntro.followup.apps": "I can already use {apps}. Hand me whatever's on your plate today, or ask me to set up a bot for something you do every week.",
- "helperIntro.followup.more": "{count} more",
- "helperIntro.followup.noAi": "I looked around. Before I can do real work, I need an AI to think with. Sign in with an account you already have, like Claude or ChatGPT, and I'll take it from there.",
- "helperIntro.followup.backup": "I looked around. For now I'm thinking with a free backup model. Sign in with an account you already have, like Claude or ChatGPT, and I'll take it from there.",
- "helperIntro.followup.noAiOwner": "I looked around. Before I can do real work, I need an AI to think with. {name} connects that for the team, and I'll take it from there.",
- "helperIntro.followup.noAiTeamOwner": "I looked around. Before I can do real work, I need an AI to think with. The team's owner connects that, and I'll take it from there.",
- "helperIntro.followup.backupOwner": "I looked around. For now I'm thinking with a free backup model. {name} can connect a better one for the team.",
- "helperIntro.followup.backupTeamOwner": "I looked around. For now I'm thinking with a free backup model. The team's owner can connect a better one.",
-} as const;
-
-export type FollowupKey = keyof typeof FOLLOWUP_ENGLISH;
-type Say = (key: FollowupKey, params?: Record<string, string | number>) => string;
-
-function counted(say: Say, count: number, none: FollowupKey, one: FollowupKey, many: FollowupKey): string {
- return count <= 0 ? say(none) : count === 1 ? say(one) : say(many, { count });
-}
-
-/** The follow-up in `say`'s language; `list` joins app names as that language does. */
-export function followupText(facts: HelperFollowupFacts, say: Say, list: (items: string[]) => string): string {
- if (facts.ai !== "own") {
- const none = facts.ai === "none", connects = facts.connects;
- if (connects === undefined) return say(none ? "helperIntro.followup.noAi" : "helperIntro.followup.backup");
- if (connects) return say(none ? "helperIntro.followup.noAiOwner" : "helperIntro.followup.backupOwner", { name: connects });
- return say(none ? "helperIntro.followup.noAiTeamOwner" : "helperIntro.followup.backupTeamOwner");
- }
- const found = say("helperIntro.followup.found");
- if (facts.apps.length) {
- const shown = facts.apps.slice(0, FOLLOWUP_APP_NAMES);
- const rest = facts.apps.length - shown.length;
- return `${found} ${say("helperIntro.followup.apps", { apps: list(rest > 0 ? [...shown, say("helperIntro.followup.more", { count: rest })] : shown) })}`;
- }
- const middle = facts.bots <= 0 && facts.routines <= 0 ? say("helperIntro.followup.empty") : say("helperIntro.followup.counts", {
- bots: counted(say, facts.bots, "helperIntro.followup.botsNone", "helperIntro.followup.botOne", "helperIntro.followup.bots"),
- routines: counted(say, facts.routines, "helperIntro.followup.routinesNone", "helperIntro.followup.routineOne", "helperIntro.followup.routines"),
- });
- return `${found} ${middle} ${say("helperIntro.followup.offer")}`;
-}
-
-/** The English the server stores, which the model reads. */
-export function englishFollowup(facts: HelperFollowupFacts): string {
- const fill = (key: FollowupKey, params?: Record<string, string | number>) =>
- FOLLOWUP_ENGLISH[key].replace(/\{(\w+)\}/g, (match, name: string) => (params && name in params ? String(params[name]) : match));
- return followupText(facts, fill, (items) => new Intl.ListFormat("en", { style: "long", type: "conjunction" }).format(items));
-}
+export * from "../packages/phone-protocol/src/helper-followup.ts";
diff --git a/shared/inbox.ts b/shared/inbox.ts
index 58f5e46c75..b4b3854f0b 100644
--- a/shared/inbox.ts
+++ b/shared/inbox.ts
@@ -1,78 +1 @@
-import type { ConnectorCardData } from "./connector-card.ts";
-import type { OptionCardData, SecretRequestCardData, SignInRequestCardData } from "./wire.ts";
-
-/** On a Team Cloud, a line in a person's inbox: their own conversation with their own Chief of Staff (their own MausBot
- * when they crowned none), where everything addressed to them arrives. It says who it is from and where it came from,
- * so clients can label it and open that conversation. Replying to the line answers it: the answer goes back where it
- * came from. */
-export interface InboxItem {
- /** "message": a teammate's or a bot's message, or an @mention; "ask": a question or approval card, copied here
- * and answered here as there; "result": a routine's report; "notice": a failure or a sign-in it needs. */
- kind: "message" | "ask" | "result" | "notice";
- /** Who it is from: a teammate (their address) or a bot (its id). */
- from: { name: string; email?: string; botId?: string };
- /** The bot that passed a teammate's message on. */
- via?: { botId: string; name: string };
- /** The conversation it came from, when the person may open it. */
- origin?: { botId: string; threadId: string; title: string; groupId?: string; messageId?: string };
- /** It waits on the person's answer. */
- replies?: true;
- /** The sender's assistant wrote it for them, from what they share with the team. */
- assistant?: true;
- /** How it was answered: the person's own words, or their assistant's, which answers facts only. */
- answers?: Array<{ by: "person" | "assistant"; text: string; at: number }>;
-}
-
-/** A task's fields on a team's server when it is a person's inbox, sent to that person alone. */
-export interface InboxTask {
- /** This person's inbox, the conversation with their Chief where everything for them arrives. */
- inbox?: true;
- /** The asks waiting on them there (questions, approvals, work handed on), each open where it was asked; absent when
- * none. */
- openAsks?: number;
- /** When what the inbox lists last changed; a client that shows the list reads it again when this moves. */
- inboxChangedAt?: number;
-}
-
-/** Where a line of the inbox is listed: "needs-you" while it waits on the person (an ask whose card is open where it was
- * asked), "info" for news until they answer it or mark it done, "done" once it is settled or marked done. */
-export type InboxTab = "needs-you" | "info" | "done";
-
-/** One line of a person's inbox as their inbox lists it, newest first. `kind` names its source; a new source adds a kind
- * of its own with what its row needs. */
-export interface InboxRow {
- /** The line's id in the inbox conversation. */
- id: string;
- kind: InboxItem["kind"];
- tab: InboxTab;
- from: InboxItem["from"];
- via?: InboxItem["via"];
- /** The bot that handed this work to the bot it is from. */
- workingFor?: { botId: string; name: string };
- /** On someone's Cloud: a guest's conversation asks this, not its owner's; `name` is empty when it isn't known. */
- askedBy?: { name: string };
- origin?: InboxItem["origin"];
- text: string;
- at: number;
- unread: boolean;
- replies?: true;
- answers?: InboxItem["answers"];
- /** An ask's card as the inbox holds it: answering it answers the card where it was asked. */
- card?: OptionCardData;
- /** A password the bot asked for, answered with the chat's own card for it. */
- secret?: SecretRequestCardData;
- /** A sign-in the bot asked the person to do, answered with the chat's own card for it. */
- signIn?: SignInRequestCardData;
- /** An app the bot asked the person to connect, answered with the chat's own card for it. */
- connector?: ConnectorCardData;
-}
-
-/** A person's inbox: where its lines live (none yet before the first arrives), and the line the inbox's card in that
- * conversation sits under (the newest that needed them, else the newest). Off a team `botId` and `threadId` are null: its
- * lines stay in the conversations they came from, each answered through its `origin`. */
-export interface InboxView {
- botId: string | null;
- threadId: string | null;
- rows: InboxRow[];
- anchor: string | null;
-}
+export * from "../packages/phone-protocol/src/inbox.ts";
diff --git a/shared/json.ts b/shared/json.ts
index 95c075ce39..e352ed930a 100644
--- a/shared/json.ts
+++ b/shared/json.ts
@@ -1,8 +1 @@
-/** Plain JSON values: the vocabulary every cross-layer payload that is "just
- * JSON" shares. */
-export type JsonPrimitive = string | number | boolean | null;
-export interface JsonObject {
- [key: string]: JsonValue;
-}
-export type JsonValue = JsonPrimitive | JsonObject | JsonValue[];
-
+export * from "../packages/phone-protocol/src/json.ts";
diff --git a/shared/limit-reset.ts b/shared/limit-reset.ts
index 715de71dba..ecdb35d05c 100644
--- a/shared/limit-reset.ts
+++ b/shared/limit-reset.ts
@@ -1,73 +1 @@
-/** Wire shapes for automations that run when an engine's usage limit resets, and for the engines' limit state
- * the Automations page, the chat and the calendar show. */
-
-export type LimitResetRepeat = "once" | "every_reset";
-
-/** A routine schedule that runs when an engine's usage limit resets. */
-export interface LimitResetSchedule {
- type: "limit_reset";
- /** The engine instance id whose limit it waits for, e.g. "claude" or "codex". */
- engine: string;
- repeat: LimitResetRepeat;
- /** Derived by the server, never taken from input: the reset plus a short buffer, or null while the time is not known. */
- at: number | null;
-}
-
-/** As a request or an edit sends it: the server derives `at`. */
-export type LimitResetScheduleInput = Omit<LimitResetSchedule, "at" | "repeat"> & { repeat?: LimitResetRepeat; at?: number | null };
-
-/** How long after a reset the run starts, so the provider has rolled its window over. */
-export const AFTER_RESET_MS = 60_000;
-
-/** From this share of a window used, an engine is shown as near its limit. */
-export const NEAR_LIMIT_PERCENT = 90;
-
-export type LimitWindowName = "5-hour" | "weekly" | "other";
-
-/** One usage window as the engine reported it. */
-export interface LimitWindowUsage {
- window: LimitWindowName;
- /** 0–100. */
- usedPercent: number;
- /** Epoch ms when it resets; null when not known. */
- resetsAt: number | null;
-}
-
-/** One engine's usage limit as OpenMausBot knows it now. */
-export interface EngineLimit {
- /** Engine instance id. */
- engine: string;
- /** The engine's display name ("Claude", "Codex", or the instance's own name). */
- name: string;
- driver: "claude" | "codex" | "grok" | "opencode";
- /** The window that decides the reset: the fullest, or the one refusing work. */
- window: LimitWindowName | null;
- /** 0–100, or null when the engine reported no window. */
- usedPercent: number | null;
- /** Epoch ms when that window resets; null when not known. */
- resetsAt: number | null;
- /** The engine refuses work until resetsAt. */
- blocked: boolean;
- /** Blocked only by a refusal's hold, which "Try again now" can end; absent when a window at its limit blocks it. */
- held?: boolean;
- /** Every window the engine reported, in the engine's order. A server that predates it sends only the deciding window above. */
- windows?: LimitWindowUsage[];
-}
-
-export interface EngineLimitsReport {
- checkedAt: number;
- engines: EngineLimit[];
-}
-
-export function isLimitResetSchedule(schedule: { type: string } | null | undefined): schedule is LimitResetSchedule {
- return schedule?.type === "limit_reset";
-}
-
-/** A one-time automation: a fixed time, or the next reset only. */
-export function runsOnce(schedule: { type: string; repeat?: unknown }): boolean {
- return schedule.type === "once" || (schedule.type === "limit_reset" && schedule.repeat !== "every_reset");
-}
-
-export function nearLimit(limit: Pick<EngineLimit, "usedPercent" | "blocked">): boolean {
- return limit.blocked || (limit.usedPercent ?? 0) >= NEAR_LIMIT_PERCENT;
-}
+export * from "../packages/phone-protocol/src/limit-reset.ts";
diff --git a/shared/live-approval.ts b/shared/live-approval.ts
index 0187312b03..d15afa73e7 100644
--- a/shared/live-approval.ts
+++ b/shared/live-approval.ts
@@ -1,145 +1 @@
-// What the harness tells GPT-Live about the bot's cards during a Live call.
-// English only (the voice speaks the user's language on its own), mirroring
-// src/locales/en.json approval.voice.* and approval.tool.*.
-import type { OptionCardData } from "./wire.ts";
-
-export type LiveCardKind = "approval" | "review" | "question";
-
-/** "approval": a provider or peer ask the voice may decide with a strict yes/no.
- * "review": a harness-native proposal (skill, routine, profile, default
- * model, team setup, an MCP server change, a quota-switch offer) that must be
- * reviewed on screen.
- * "question": a provider question. An expired proposal is settled: nothing
- * can answer it any more. */
-export function liveCardKind(card: OptionCardData | undefined): LiveCardKind | null {
- if (!card?.requestId || card.answered || card.dismissed || card.expired) return null;
- if (card.skillRequest || card.routineRequest || card.profileRequest || card.modelRequest || card.teamSetupRequest || card.mcpRequest || card.quotaSwitch || card.lendingLift) {
- return "review";
- }
- return card.tool ? "approval" : "question";
-}
-
-/** Why a decision made on a Live call must not reach this card, or null to
- * deliver it. A card settled a moment earlier (answered or dismissed on
- * screen) is refused before anything runs: delivering to it would add a
- * false "the action was not run" line after the tap did run it. A card that
- * is not on the thread is left to the normal answer path. */
-export function liveDecisionRefusal(card: OptionCardData | undefined): string | null {
- if (!card) return null;
- const kind = liveCardKind(card);
- if (kind === "review") return "This request is reviewed on screen.";
- return kind ? null : "The request is no longer open.";
-}
-
-const TOOL_PHRASES: Record<string, string> = {
- Bash: "run a command",
- Read: "read a file",
- Write: "write a file",
- Edit: "edit a file",
- WebFetch: "fetch a web page",
- WebSearch: "search the web",
- schedule_routine: "schedule a routine",
- manage_routine: "change a routine",
- stage_skill: "enable a learned skill",
- update_skill: "update a learned skill",
- update_profile: "update its profile",
- shell: "run a command",
- edit: "edit a file",
- read: "read a file",
- fetch: "fetch a web page",
- delete: "delete a file",
- think: "think",
- other: "take an action",
- tool: "use a tool",
-};
-
-export function toolPhrase(tool?: string): string {
- if (!tool) return "take an action";
- return TOOL_PHRASES[tool] ?? tool.replace(/^mcp__[^_]+__/, "").replace(/_/g, " ");
-}
-
-const DETAIL_LIMIT = 400;
-
-function duration(ms: number): string {
- const seconds = Math.max(0, Math.round(ms / 1_000));
- if (seconds < 60) return `${seconds} second${seconds === 1 ? "" : "s"}`;
- const minutes = Math.round(seconds / 60);
- return `${minutes} minute${minutes === 1 ? "" : "s"}`;
-}
-
-/** A bot's step as the voice may name it: the tool's own spoken label, or
- * the tool's name ("team notes: query database") — never its arguments,
- * which can hold paths, queries or private text. */
-export function liveStepLabel(tool: { name: string; spoken?: string }): string {
- if (tool.spoken?.trim()) return brief(tool.spoken, 80);
- const parts = tool.name.split("__");
- if (parts[0] === "mcp" && parts.length >= 3) {
- const server = parts[1].replace(/[-_]+/g, " ").trim();
- const action = parts.slice(2).join(" ").replace(/_+/g, " ").trim();
- return brief(`${server}: ${action}`, 80);
- }
- return toolPhrase(tool.name);
-}
-
-function brief(text: string, limit = DETAIL_LIMIT): string {
- const flat = text.replace(/\s+/g, " ").trim().replace(/[.!?]+$/, "");
- return flat.length <= limit ? flat : `${flat.slice(0, limit).replace(/\s+\S*$/, "")}…`;
-}
-
-// The voice IS the bot to the person on the call: say everything as the bot
-// ("I …") or to the voice as "you", never naming the bot in the third person.
-
-export function spokenApprovalPrompt(card: OptionCardData): string {
- const detail = brief(card.subtitle);
- return `I want to ${toolPhrase(card.tool)}.${detail ? ` ${detail}.` : ""} May I?`;
-}
-
-export function spokenReviewPrompt(card: OptionCardData): string {
- const title = brief(card.title || "a proposal", 200);
- return `Tell the user, in your own words, that you need their decision in the chat: ${title}. They review it on screen and choose there; it cannot be decided by voice.`;
-}
-
-/** The bot waits for an app to be connected in the chat (a connector card). */
-export function spokenConnectorPrompt(label: string): string {
- return `Tell the user, in your own words, that you need them to connect ${brief(label || "an app", 80)} in the chat before you can go on. It cannot be done by voice.`;
-}
-
-/** The bot waits for a credential entered on screen (a secret card). It must
- * never travel through the call, so the voice never asks for it aloud. */
-export function spokenSecretPrompt(label: string): string {
- return `Tell the user, in your own words, that you need ${brief(label || "a credential", 80)} entered in the chat on screen before you can go on. Never ask them to say it aloud.`;
-}
-
-/** The bot waits for the person to sign in to a site themselves (a sign-in
- * card). The password goes into the page only, never through the call. */
-export function spokenSignInPrompt(site: string): string {
- return `Tell the user, in your own words, that you need them to sign in to ${brief(site || "a website", 80)} themselves on screen, then press Done in the chat, before you can go on. Never ask them to say a password or code aloud.`;
-}
-
-export function spokenQuestionPrompt(card: OptionCardData): string {
- const detail = brief(card.subtitle || card.title);
- const choices = card.options.length ? ` The options are ${card.options.join(", ")}.` : "";
- return `Ask the user, in your own words: ${detail}${detail.endsWith("?") ? "" : "?"}${choices} Then delegate their answer.`;
-}
-
-export const LIVE_COPY = {
- notHeard: "The request was not heard clearly. Ask the user to say it again.",
- notClear: "That was not a clear yes or no. Ask the user again for a clear yes or no.",
- deniedMessage: "Denied by the user, on a live call.",
- answeredInChat: "The user answered that request in the chat. Do not ask about it again.",
- working: "You are working on the request now. Nothing is done until the result comes back; do not guess it.",
- answerPassed: "You are using the user's answer now. Wait for the result.",
- granted: "Thanks, I'll go ahead.",
- denied: "Okay, I won't do it.",
- saveFailed: (detail: string) => `The decision could not be saved${detail ? `: ${detail}` : "."} Ask the user to try again.`,
- noAnswer: "I'm done. The result, or what went wrong, is in the chat.",
- typedAnswerLead: (typed: string) => `About what you typed in the chat ("${brief(typed, 200)}"):`,
- progress: (spoken: string) => `Progress: ${brief(spoken, 200)}`,
- status: (workedMs: number, steps: number, lastStep: string | null, lastStepAgoMs: number) =>
- `Status note, do not announce it: you are still working on it (${duration(workedMs)} so far, ${steps} step${steps === 1 ? "" : "s"}${
- lastStep ? `; last step: ${lastStep}, ${duration(lastStepAgoMs)} ago` : ""}).`,
- signedOut: "The call has ended because the sign-in that started it has ended. Sign in again to start a new call.",
- unpaired: "The call has ended because the phone that started it was unpaired from this computer.",
- goodbye: "The user asked to end the call. Say a short goodbye in one sentence and nothing else; the call ends right after.",
- permissionRequest: (prompt: string) => `You need the user's permission. Say it in your own words: ${prompt} Ask for a clear yes or no, then delegate their answer.`,
-};
+export * from "../packages/phone-protocol/src/live-approval.ts";
diff --git a/shared/live-call-wire.ts b/shared/live-call-wire.ts
index 512843acb7..be954bc6e9 100644
--- a/shared/live-call-wire.ts
+++ b/shared/live-call-wire.ts
@@ -1,104 +1 @@
-/** A Live call as the wire carries it: its state, the record a finished call
- * leaves, and the non-secret Live settings. Types only; `wire.ts` re-exports them. */
-
-/** Which app holds the microphone of a Live call: the desktop app (its own
- * page or a server's page in it), a web browser, or a phone. Self-declared;
- * for display and logs only. The phone apps show a value they do not know as
- * "another device". */
-export type LiveClient = "desktop" | "web" | "ios" | "android";
-export type LiveCallStatus = "connecting" | "live" | "ending" | "ended";
-/** Why a call ended. "signed-out": the sign-in or paired phone that started
- * it was signed out, revoked or unpaired. A client that does not know a
- * reason shows the call's `error` text, or plain "Call ended.". */
-export type LiveEndReason =
- | "hung-up" | "idle" | "expired" | "content" | "remote-hangup" | "connection-lost"
- | "sideband-lost" | "deleted" | "shutdown" | "signed-out" | "error";
-
-/** The one Live call a harness runs. Never carries the key or any speech. */
-export interface LiveCallState {
- callId: string;
- botId: string;
- threadId: string;
- client: LiveClient;
- voice: string;
- /** epoch ms when the session was created */
- startedAt: number;
- status: LiveCallStatus;
- endReason?: LiveEndReason;
- /** short, user-facing; present when the call ended on a problem */
- error?: string;
-}
-
-/** One finished Live call, written once when a call that went live ends. Never carries speech. */
-export interface LiveCallRecord {
- callId: string;
- botId: string;
- client: LiveClient;
- /** epoch ms, = LiveCallState.startedAt */
- startedAt: number;
- /** epoch ms when the call ended */
- endedAt: number;
- /** whole seconds: OpenAI usage seconds when given, else wall clock */
- seconds: number;
- endReason: LiveEndReason;
- /** only when LLM thread titles are on and the engine can generateText */
- title?: string;
-}
-
-/** Who runs a Live call's voice session: OpenAI itself, a GPT-Live deployment on the user's own Azure OpenAI / Foundry
- * resource, or a Fish Audio Live 3 agent the harness sets up on the person's Fish Audio account, whose session the client joins with Fish's SDK. */
-export type LiveProvider = "openai" | "azure" | "fish";
-
-/** `live`: the key saved for Live calls only; `openai`: the OpenAI API key from Settings → API keys, used when there is no `live` key;
- * `fishAudio`: the Fish Audio key from Settings → API keys, the only key a Fish Audio call uses. */
-export type LiveKeySource = "live" | "openai" | "fishAudio";
-
-/** Non-secret Live settings, as GET /api/config and PATCH /api/live/settings report them. */
-export interface LiveSettings {
- /** A Live call has everything it needs: a key (`keySource` says which; never the key itself), and for Azure a valid endpoint and deployment. */
- configured: boolean;
- keySource?: LiveKeySource;
- /** Absent means "openai". With "azure" only the `live` key is used and with "fish" only the Fish Audio key, never the OpenAI API key. */
- provider?: LiveProvider;
- /** The Azure resource endpoint as saved, e.g. `https://my-resource.openai.azure.com`. Not a secret. */
- azureEndpoint?: string;
- /** The Azure deployment of gpt-live-1; empty means "gpt-live-1". */
- azureDeployment?: string;
- voice: string;
- readTypedReplies: boolean;
- idleMinutes: number;
-}
-
-/** The single-use token Fish Audio returns for one agent session (Fish API v1 `LiveKitSessionToken`), passed verbatim to
- * `AgentSession.start({ sessionToken })` of `@fishaudio/agent-client` 1.x. Holds no API key. */
-export interface LiveFishSessionToken {
- transport: "livekit";
- session_id: string;
- /** ISO time by which the client must join */
- expires_at: string;
- max_duration_seconds: number;
- livekit_url: string;
- token: string;
-}
-
-/** A "fish" call's transport, answered only to the client that started the call: Fish's session token, and the token
- * that client presents on POST /api/live/relay, the call's only route for what it heard and for the bot's replies. */
-export interface LiveFishTransport {
- type: "fish";
- session: LiveFishSessionToken;
- relayToken: string;
-}
-
-/** What the client of a "fish" call reports on POST /api/live/relay. Times are ms since the client joined the session. */
-export type LiveFishRelayEvent =
- | { type: "connected" }
- | { type: "heard"; text: string; startMs: number; endMs: number }
- | { type: "spoke"; startMs: number; endMs: number }
- | { type: "delegate"; id: string; atMs: number }
- | { type: "ended"; reason: string }
- | { type: "error"; code: string };
-
-/** What the harness hands the client of a "fish" call: words for the agent to speak or know (`kind` as on GPT-Live), or the end of the call. */
-export type LiveFishRelayCommand =
- | { type: "append"; kind: "instructions" | "thinking" | "commentary"; content: string; delegationId: string | null }
- | { type: "close" };
+export * from "../packages/phone-protocol/src/live-call-wire.ts";
diff --git a/shared/mascot-bodies.ts b/shared/mascot-bodies.ts
index 8c11bf2c4b..c28b21fc57 100644
--- a/shared/mascot-bodies.ts
+++ b/shared/mascot-bodies.ts
@@ -1,129 +1 @@
-/**
- * The mascot bodies a bot can wear.
- *
- * GENERATED FILE — do not hand-edit. Run `pnpm gen:bodies` to rebuild it from
- * `scripts/gen-mascot-bodies.ts`, which solves each face placement against the real
- * expression geometry and verifies that nothing clips.
- *
- * Every body carries the same face at the same size: the generator clamps the whole
- * catalog to the smallest face any one body can hold, so the mascot reads as one
- * character in different bodies rather than ten different mascots. Roomier bodies simply
- * end up with more margin around the face.
- *
- * The fields match `CursorSilhouette` exactly, so a body can be handed to the renderer
- * with no adapter in between.
- */
-
-import { z } from "zod";
-
-/** Every selectable body id, in the order the picker shows them. */
-export const MASCOT_BODY_IDS = ["cursor", "blob", "circle", "squircle", "capsule", "drop", "shield", "hexagon", "diamond", "star"] as const;
-
-export type MascotBodyId = (typeof MASCOT_BODY_IDS)[number];
-
-export const mascotBodySchema = z.enum(MASCOT_BODY_IDS);
-
-export interface MascotBody {
- id: MascotBodyId;
- /** Human-readable name, used for the picker and the accessible label. */
- name: string;
- /** Transform mapping the outline into the face box. */
- fit: string;
- /** Body markup. `{{GRADIENT}}` is replaced with the bot's own gradient. */
- body: string;
- /** The same outline without a fill, used as the clip region. */
- clip: string;
- /** Where the face sits inside the body, in face-space units. */
- anchor: { x: number; y: number; scale: number };
-}
-
-/** The shipped mascot, and the fallback for any unrecognised value. */
-export const DEFAULT_MASCOT_BODY: MascotBodyId = "cursor";
-
-export const MASCOT_BODIES: Record<MascotBodyId, MascotBody> = {
- cursor: {
- id: "cursor",
- name: "Cursor",
- fit: "translate(68.1612 9.8302) scale(0.593918)",
- body: "<path fill=\"{{GRADIENT}}\" d=\"M0 0 C1.12815992 0.94880479 2.25705591 1.89673511 3.38671875 2.84375 C5.57657936 4.68528228 7.75793952 6.53624249 9.93359375 8.39453125 C13.5602214 11.48647103 17.25022962 14.49819427 20.9453125 17.5078125 C25.41301487 21.15281776 29.86103386 24.8215994 34.31054688 28.48876953 C38.00933931 31.5370903 41.70951059 34.58367973 45.4140625 37.625 C52.50037463 43.44570076 59.55669812 49.29508834 66.54003906 55.23901367 C70.43289872 58.54377434 74.40406577 61.73568847 78.40625 64.90625 C82.05401433 67.85083084 85.6145398 70.89451533 89.18359375 73.93359375 C92.41424312 76.67774533 95.67698054 79.36747809 99 82 C103.47931906 85.54855146 107.83340036 89.22936876 112.18359375 92.93359375 C115.41424312 95.67774533 118.67698054 98.36747809 122 101 C125.9014198 104.09073517 129.71091352 107.27378506 133.5 110.5 C137.99002543 114.32092614 142.53350963 118.0537239 147.15234375 121.71875 C156.74255328 129.40144186 166.1812645 137.27326897 175.53833008 145.23754883 C179.4317456 148.54281661 183.40347641 151.73522157 187.40625 154.90625 C191.05401433 157.85083084 194.6145398 160.89451533 198.18359375 163.93359375 C201.41424312 166.67774533 204.67698054 169.36747809 208 172 C236.43637507 194.63776677 236.43637507 194.63776677 238.27050781 209.13867188 C239.19944445 221.27193361 237.57124038 231.13444436 230 241 C223.66050278 247.82715086 215.75482398 254.47140646 206.04764748 255.13307858 C205.3615811 255.13693349 204.67551472 255.1407884 203.96865845 255.14476013 C203.17563324 255.15165863 202.38260803 255.15855713 201.56555176 255.16566467 C200.27360901 255.16958473 200.27360901 255.16958473 198.95556641 255.17358398 C198.04112762 255.180271 197.12668884 255.18695801 196.18453979 255.19384766 C194.19843498 255.20789156 192.21231409 255.21978771 190.22618484 255.22979546 C187.07149762 255.24625057 183.91692738 255.26949556 180.76229858 255.29469299 C171.79227585 255.36530712 162.82220292 255.42526708 153.85205078 255.47680664 C148.36195434 255.5088283 142.87198905 255.55017011 137.38199997 255.59700203 C135.30028042 255.61289593 133.21853066 255.62527474 131.13676834 255.63390923 C104.46972494 255.74602279 80.75351522 259.19455182 60.52978516 278.41845703 C55.75259196 283.35727885 51.81217213 289.04473423 47.77441406 294.5859375 C44.62107661 298.87600364 41.36381878 303.08685058 38.125 307.3125 C32.82026548 314.26649347 27.55386673 321.24815866 22.3125 328.25 C21.07690581 329.89589556 19.84122979 331.5417297 18.60546875 333.1875 C16.22002164 336.36552908 13.84996009 339.55428087 11.48828125 342.75 C3.0450311 354.10095576 -5.25712203 365.22607871 -20 368 C-33.42903027 368.85957067 -44.2929604 367.90032788 -55 358.9140625 C-63.51513963 350.76480778 -67.79688328 340.99527428 -68.37686157 329.29350281 C-68.43541887 328.1487851 -68.49397617 327.00406738 -68.55430794 325.82466125 C-68.61453573 324.57243271 -68.67476353 323.32020416 -68.73681641 322.0300293 C-68.80423726 320.68369989 -68.87198477 319.33738681 -68.94003105 317.99108887 C-69.12569162 314.29881586 -69.30666938 310.60632592 -69.48688698 306.91378379 C-69.68142908 302.94481208 -69.88036562 298.97606035 -70.07873535 295.00727844 C-70.55465828 285.46711948 -71.02377004 275.92663022 -71.49235249 266.3861084 C-71.71278092 261.90166682 -71.93398876 257.41726373 -72.1552124 252.93286133 C-72.22122149 251.59460763 -72.22122149 251.59460763 -72.28856409 250.2293185 C-72.37783973 248.41936974 -72.46711776 246.6094211 -72.55639815 244.79947257 C-72.7821203 240.22326204 -73.00777832 235.64704836 -73.23336792 231.0708313 C-73.2783997 230.15734865 -73.32343148 229.24386601 -73.36982787 228.30270207 C-73.64581049 222.70253299 -73.92113412 217.10233189 -74.19602597 211.50210917 C-75.35713101 187.85146938 -76.54638525 164.20245932 -77.76320994 140.55462319 C-78.3174362 129.77404232 -78.86176258 118.9929594 -79.40472984 108.2118063 C-79.83986282 99.58021501 -80.28322749 90.94912395 -80.73695588 82.31848997 C-81.04621068 76.42094211 -81.34513355 70.52292566 -81.63612723 64.62444884 C-81.8031421 61.24551841 -81.97612174 57.86718776 -82.15861511 54.48903847 C-84.29931862 14.73242483 -84.29931862 14.73242483 -72.03125 -1.625 C-50.89854752 -24.96559677 -21.34867451 -18.24899383 0 0 Z \"/>",
- clip: "<path d=\"M0 0 C1.12815992 0.94880479 2.25705591 1.89673511 3.38671875 2.84375 C5.57657936 4.68528228 7.75793952 6.53624249 9.93359375 8.39453125 C13.5602214 11.48647103 17.25022962 14.49819427 20.9453125 17.5078125 C25.41301487 21.15281776 29.86103386 24.8215994 34.31054688 28.48876953 C38.00933931 31.5370903 41.70951059 34.58367973 45.4140625 37.625 C52.50037463 43.44570076 59.55669812 49.29508834 66.54003906 55.23901367 C70.43289872 58.54377434 74.40406577 61.73568847 78.40625 64.90625 C82.05401433 67.85083084 85.6145398 70.89451533 89.18359375 73.93359375 C92.41424312 76.67774533 95.67698054 79.36747809 99 82 C103.47931906 85.54855146 107.83340036 89.22936876 112.18359375 92.93359375 C115.41424312 95.67774533 118.67698054 98.36747809 122 101 C125.9014198 104.09073517 129.71091352 107.27378506 133.5 110.5 C137.99002543 114.32092614 142.53350963 118.0537239 147.15234375 121.71875 C156.74255328 129.40144186 166.1812645 137.27326897 175.53833008 145.23754883 C179.4317456 148.54281661 183.40347641 151.73522157 187.40625 154.90625 C191.05401433 157.85083084 194.6145398 160.89451533 198.18359375 163.93359375 C201.41424312 166.67774533 204.67698054 169.36747809 208 172 C236.43637507 194.63776677 236.43637507 194.63776677 238.27050781 209.13867188 C239.19944445 221.27193361 237.57124038 231.13444436 230 241 C223.66050278 247.82715086 215.75482398 254.47140646 206.04764748 255.13307858 C205.3615811 255.13693349 204.67551472 255.1407884 203.96865845 255.14476013 C203.17563324 255.15165863 202.38260803 255.15855713 201.56555176 255.16566467 C200.27360901 255.16958473 200.27360901 255.16958473 198.95556641 255.17358398 C198.04112762 255.180271 197.12668884 255.18695801 196.18453979 255.19384766 C194.19843498 255.20789156 192.21231409 255.21978771 190.22618484 255.22979546 C187.07149762 255.24625057 183.91692738 255.26949556 180.76229858 255.29469299 C171.79227585 255.36530712 162.82220292 255.42526708 153.85205078 255.47680664 C148.36195434 255.5088283 142.87198905 255.55017011 137.38199997 255.59700203 C135.30028042 255.61289593 133.21853066 255.62527474 131.13676834 255.63390923 C104.46972494 255.74602279 80.75351522 259.19455182 60.52978516 278.41845703 C55.75259196 283.35727885 51.81217213 289.04473423 47.77441406 294.5859375 C44.62107661 298.87600364 41.36381878 303.08685058 38.125 307.3125 C32.82026548 314.26649347 27.55386673 321.24815866 22.3125 328.25 C21.07690581 329.89589556 19.84122979 331.5417297 18.60546875 333.1875 C16.22002164 336.36552908 13.84996009 339.55428087 11.48828125 342.75 C3.0450311 354.10095576 -5.25712203 365.22607871 -20 368 C-33.42903027 368.85957067 -44.2929604 367.90032788 -55 358.9140625 C-63.51513963 350.76480778 -67.79688328 340.99527428 -68.37686157 329.29350281 C-68.43541887 328.1487851 -68.49397617 327.00406738 -68.55430794 325.82466125 C-68.61453573 324.57243271 -68.67476353 323.32020416 -68.73681641 322.0300293 C-68.80423726 320.68369989 -68.87198477 319.33738681 -68.94003105 317.99108887 C-69.12569162 314.29881586 -69.30666938 310.60632592 -69.48688698 306.91378379 C-69.68142908 302.94481208 -69.88036562 298.97606035 -70.07873535 295.00727844 C-70.55465828 285.46711948 -71.02377004 275.92663022 -71.49235249 266.3861084 C-71.71278092 261.90166682 -71.93398876 257.41726373 -72.1552124 252.93286133 C-72.22122149 251.59460763 -72.22122149 251.59460763 -72.28856409 250.2293185 C-72.37783973 248.41936974 -72.46711776 246.6094211 -72.55639815 244.79947257 C-72.7821203 240.22326204 -73.00777832 235.64704836 -73.23336792 231.0708313 C-73.2783997 230.15734865 -73.32343148 229.24386601 -73.36982787 228.30270207 C-73.64581049 222.70253299 -73.92113412 217.10233189 -74.19602597 211.50210917 C-75.35713101 187.85146938 -76.54638525 164.20245932 -77.76320994 140.55462319 C-78.3174362 129.77404232 -78.86176258 118.9929594 -79.40472984 108.2118063 C-79.83986282 99.58021501 -80.28322749 90.94912395 -80.73695588 82.31848997 C-81.04621068 76.42094211 -81.34513355 70.52292566 -81.63612723 64.62444884 C-81.8031421 61.24551841 -81.97612174 57.86718776 -82.15861511 54.48903847 C-84.29931862 14.73242483 -84.29931862 14.73242483 -72.03125 -1.625 C-50.89854752 -24.96559677 -21.34867451 -18.24899383 0 0 Z \"/>",
- anchor: { x: 85.54, y: 106.35, scale: 0.791 },
- },
- blob: {
- id: "blob",
- name: "Blob",
- fit: "translate(-0.7217 2.9555) scale(1.134706)",
- body: "<path fill=\"{{GRADIENT}}\" d=\"M198.91052 113.12915C198.30169 121.88191 196.37668 130.37605 193.1355 138.61157C189.89431 146.84709 185.49332 154.4026 179.93252 161.27809C174.37172 168.15358 167.99976 174.1053 160.81663 179.13325C153.6335 184.1612 145.98678 188.22176 137.87645 191.31491C129.76613 194.40806 121.42581 196.55178 112.85548 197.74609C104.28516 198.94039 95.66469 199.12755 86.99407 198.30758C78.32344 197.4876 69.86713 195.54477 61.62513 192.47909C53.38313 189.41341 45.74309 185.20915 38.70501 179.86633C31.66693 174.52351 25.60941 168.25632 20.53243 161.06476C15.45546 153.87319 11.54067 146.15559 8.78808 137.91195C6.03549 129.66831 4.37316 121.28874 3.80109 112.77325C3.22902 104.25775 3.5616 95.83136 4.79882 87.49409C6.03604 79.15682 8.08364 70.99969 10.94163 63.0227C13.79962 55.04571 17.53174 47.38891 22.13799 40.0523C26.74425 32.71568 32.30193 26.0276 38.81103 19.98806C45.32014 13.94852 52.65266 9.00619 60.80862 5.16109C68.96458 1.31599 77.53546 -1.10241 86.52128 -2.09412C95.50709 -3.08583 104.37427 -2.64309 113.12282 -0.76589C121.87137 1.11131 130.09712 4.12751 137.80007 8.28271C145.50302 12.43791 152.53652 17.35515 158.90058 23.03443C165.26463 28.7137 170.969 34.91856 176.01368 41.649C181.05836 48.37944 185.3953 55.56843 189.02451 63.21597C192.65372 70.86352 195.3609 78.90607 197.14605 87.34364C198.93119 95.78121 199.51935 104.37638 198.91052 113.12915Z\"/>",
- clip: "<path d=\"M198.91052 113.12915C198.30169 121.88191 196.37668 130.37605 193.1355 138.61157C189.89431 146.84709 185.49332 154.4026 179.93252 161.27809C174.37172 168.15358 167.99976 174.1053 160.81663 179.13325C153.6335 184.1612 145.98678 188.22176 137.87645 191.31491C129.76613 194.40806 121.42581 196.55178 112.85548 197.74609C104.28516 198.94039 95.66469 199.12755 86.99407 198.30758C78.32344 197.4876 69.86713 195.54477 61.62513 192.47909C53.38313 189.41341 45.74309 185.20915 38.70501 179.86633C31.66693 174.52351 25.60941 168.25632 20.53243 161.06476C15.45546 153.87319 11.54067 146.15559 8.78808 137.91195C6.03549 129.66831 4.37316 121.28874 3.80109 112.77325C3.22902 104.25775 3.5616 95.83136 4.79882 87.49409C6.03604 79.15682 8.08364 70.99969 10.94163 63.0227C13.79962 55.04571 17.53174 47.38891 22.13799 40.0523C26.74425 32.71568 32.30193 26.0276 38.81103 19.98806C45.32014 13.94852 52.65266 9.00619 60.80862 5.16109C68.96458 1.31599 77.53546 -1.10241 86.52128 -2.09412C95.50709 -3.08583 104.37427 -2.64309 113.12282 -0.76589C121.87137 1.11131 130.09712 4.12751 137.80007 8.28271C145.50302 12.43791 152.53652 17.35515 158.90058 23.03443C165.26463 28.7137 170.969 34.91856 176.01368 41.649C181.05836 48.37944 185.3953 55.56843 189.02451 63.21597C192.65372 70.86352 195.3609 78.90607 197.14605 87.34364C198.93119 95.78121 199.51935 104.37638 198.91052 113.12915Z\"/>",
- anchor: { x: 111.22, y: 116.58, scale: 0.791 },
- },
- circle: {
- id: "circle",
- name: "Circle",
- fit: "translate(0 0) scale(1.142705)",
- body: "<path fill=\"{{GRADIENT}}\" d=\"M200 100C200 155.22847 155.22847 200 100 200C44.77153 200 0 155.22847 0 100C0 44.77153 44.77153 0 100 0C155.22847 0 200 44.77153 200 100Z\"/>",
- clip: "<path d=\"M200 100C200 155.22847 155.22847 200 100 200C44.77153 200 0 155.22847 0 100C0 44.77153 44.77153 0 100 0C155.22847 0 200 44.77153 200 100Z\"/>",
- anchor: { x: 113.82, y: 110.27, scale: 0.791 },
- },
- squircle: {
- id: "squircle",
- name: "Squircle",
- fit: "translate(0 0) scale(1.142705)",
- body: "<path fill=\"{{GRADIENT}}\" d=\"M50 0C83.33333 0 116.66667 0 150 0C177.61424 0 200 22.38576 200 50C200 83.33333 200 116.66667 200 150C200 177.61424 177.61424 200 150 200C116.66667 200 83.33333 200 50 200C22.38576 200 0 177.61424 0 150C0 116.66667 0 83.33333 0 50C0 22.38576 22.38576 0 50 0Z\"/>",
- clip: "<path d=\"M50 0C83.33333 0 116.66667 0 150 0C177.61424 0 200 22.38576 200 50C200 83.33333 200 116.66667 200 150C200 177.61424 177.61424 200 150 200C116.66667 200 83.33333 200 50 200C22.38576 200 0 177.61424 0 150C0 116.66667 0 83.33333 0 50C0 22.38576 22.38576 0 50 0Z\"/>",
- anchor: { x: 111.78, y: 111.79, scale: 0.791 },
- },
- capsule: {
- id: "capsule",
- name: "Capsule",
- fit: "translate(0 0) scale(1.142705)",
- body: "<path fill=\"{{GRADIENT}}\" d=\"M100 0C141.42136 0 175 33.57864 175 75C175 91.66667 175 108.33333 175 125C175 166.42136 141.42136 200 100 200C58.57864 200 25 166.42136 25 125C25 108.33333 25 91.66667 25 75C25 33.57864 58.57864 0 100 0Z\"/>",
- clip: "<path d=\"M100 0C141.42136 0 175 33.57864 175 75C175 91.66667 175 108.33333 175 125C175 166.42136 141.42136 200 100 200C58.57864 200 25 166.42136 25 125C25 108.33333 25 91.66667 25 75C25 33.57864 58.57864 0 100 0Z\"/>",
- anchor: { x: 113.82, y: 131.68, scale: 0.791 },
- },
- drop: {
- id: "drop",
- name: "Drop",
- fit: "translate(-3.5341 -3.5341) scale(1.178046)",
- body: "<path fill=\"{{GRADIENT}}\" d=\"M100 3C160.84 78.2235 178 103.298 178 119C178 162.07821 143.07821 197 100 197C56.92179 197 22 162.07821 22 119C22 103.298 39.16 78.2235 100 3Z\"/>",
- clip: "<path d=\"M100 3C160.84 78.2235 178 103.298 178 119C178 162.07821 143.07821 197 100 197C56.92179 197 22 162.07821 22 119C22 103.298 39.16 78.2235 100 3Z\"/>",
- anchor: { x: 112.47, y: 138.8, scale: 0.791 },
- },
- shield: {
- id: "shield",
- name: "Shield",
- fit: "translate(-12.1611 -24.3222) scale(1.264316)",
- body: "<path fill=\"{{GRADIENT}}\" d=\"M57.25 38.475C85.75 12.825 114.25 12.825 142.75 38.475C153.89667 76.64167 165.04333 114.80833 176.19 152.975C188.73 184.325 179.325 200 147.975 200C115.99167 200 84.00833 200 52.025 200C20.675 200 11.27 184.325 23.81 152.975C34.95667 114.80833 46.10333 76.64167 57.25 38.475Z\"/>",
- clip: "<path d=\"M57.25 38.475C85.75 12.825 114.25 12.825 142.75 38.475C153.89667 76.64167 165.04333 114.80833 176.19 152.975C188.73 184.325 179.325 200 147.975 200C115.99167 200 84.00833 200 52.025 200C20.675 200 11.27 184.325 23.81 152.975C34.95667 114.80833 46.10333 76.64167 57.25 38.475Z\"/>",
- anchor: { x: 112.38, y: 170.61, scale: 0.791 },
- },
- hexagon: {
- id: "hexagon",
- name: "Hexagon",
- fit: "translate(-4.1077 -4.1077) scale(1.183782)",
- body: "<path fill=\"{{GRADIENT}}\" d=\"M94.90777 4.94C98.30259 2.98 101.69741 2.98 105.09223 4.94C129.98757 19.31333 154.88292 33.68667 179.77826 48.06C183.17308 50.02 184.87049 52.96 184.87049 56.88C184.87049 85.62667 184.87049 114.37333 184.87049 143.12C184.87049 147.04 183.17308 149.98 179.77826 151.94C154.88292 166.31333 129.98757 180.68667 105.09223 195.06C101.69741 197.02 98.30259 197.02 94.90777 195.06C70.01243 180.68667 45.11708 166.31333 20.22174 151.94C16.82692 149.98 15.12951 147.04 15.12951 143.12C15.12951 114.37333 15.12951 85.62667 15.12951 56.88C15.12951 52.96 16.82692 50.02 20.22174 48.06C45.11708 33.68667 70.01243 19.31333 94.90777 4.94Z\"/>",
- clip: "<path d=\"M94.90777 4.94C98.30259 2.98 101.69741 2.98 105.09223 4.94C129.98757 19.31333 154.88292 33.68667 179.77826 48.06C183.17308 50.02 184.87049 52.96 184.87049 56.88C184.87049 85.62667 184.87049 114.37333 184.87049 143.12C184.87049 147.04 183.17308 149.98 179.77826 151.94C154.88292 166.31333 129.98757 180.68667 105.09223 195.06C101.69741 197.02 98.30259 197.02 94.90777 195.06C70.01243 180.68667 45.11708 166.31333 20.22174 151.94C16.82692 149.98 15.12951 147.04 15.12951 143.12C15.12951 114.37333 15.12951 85.62667 15.12951 56.88C15.12951 52.96 16.82692 50.02 20.22174 48.06C45.11708 33.68667 70.01243 19.31333 94.90777 4.94Z\"/>",
- anchor: { x: 112.26, y: 110.7, scale: 0.791 },
- },
- diamond: {
- id: "diamond",
- name: "Diamond",
- fit: "translate(-5.9383 -5.9383) scale(1.202088)",
- body: "<path fill=\"{{GRADIENT}}\" d=\"M94.12 7.88C98.04 3.96 101.96 3.96 105.88 7.88C134.62667 36.62667 163.37333 65.37333 192.12 94.12C196.04 98.04 196.04 101.96 192.12 105.88C163.37333 134.62667 134.62667 163.37333 105.88 192.12C101.96 196.04 98.04 196.04 94.12 192.12C65.37333 163.37333 36.62667 134.62667 7.88 105.88C3.96 101.96 3.96 98.04 7.88 94.12C36.62667 65.37333 65.37333 36.62667 94.12 7.88Z\"/>",
- clip: "<path d=\"M94.12 7.88C98.04 3.96 101.96 3.96 105.88 7.88C134.62667 36.62667 163.37333 65.37333 192.12 94.12C196.04 98.04 196.04 101.96 192.12 105.88C163.37333 134.62667 134.62667 163.37333 105.88 192.12C101.96 196.04 98.04 196.04 94.12 192.12C65.37333 163.37333 36.62667 134.62667 7.88 105.88C3.96 101.96 3.96 98.04 7.88 94.12C36.62667 65.37333 65.37333 36.62667 94.12 7.88Z\"/>",
- anchor: { x: 112.53, y: 109.95, scale: 0.791 },
- },
- star: {
- id: "star",
- name: "Star",
- fit: "translate(-8.3327 3.1407) scale(1.226032)",
- body: "<path fill=\"{{GRADIENT}}\" d=\"M100 2C110.56054 20.13133 121.12108 38.26266 131.68163 56.39398C152.18893 60.83477 172.69623 65.27555 193.20354 69.71633C179.22301 85.3629 165.24248 101.00946 151.26195 116.65602C153.37562 137.5319 155.48929 158.40778 157.60295 179.28367C138.40197 170.82244 119.20098 162.36122 100 153.9C80.79902 162.36122 61.59803 170.82244 42.39705 179.28367C44.51071 158.40778 46.62438 137.5319 48.73805 116.65602C34.75752 101.00946 20.77699 85.3629 6.79646 69.71633C27.30377 65.27555 47.81107 60.83477 68.31837 56.39398C78.87892 38.26266 89.43946 20.13133 100 2Z\"/>",
- clip: "<path d=\"M100 2C110.56054 20.13133 121.12108 38.26266 131.68163 56.39398C152.18893 60.83477 172.69623 65.27555 193.20354 69.71633C179.22301 85.3629 165.24248 101.00946 151.26195 116.65602C153.37562 137.5319 155.48929 158.40778 157.60295 179.28367C138.40197 170.82244 119.20098 162.36122 100 153.9C80.79902 162.36122 61.59803 170.82244 42.39705 179.28367C44.51071 158.40778 46.62438 137.5319 48.73805 116.65602C34.75752 101.00946 20.77699 85.3629 6.79646 69.71633C27.30377 65.27555 47.81107 60.83477 68.31837 56.39398C78.87892 38.26266 89.43946 20.13133 100 2Z\"/>",
- anchor: { x: 113.82, y: 125.43, scale: 0.791 },
- },
-};
-
-/** Runtime-safe read of an untrusted persisted or streamed body id. */
-export function botMascotBody(value: unknown): MascotBodyId {
- return mascotBodySchema.safeParse(value).data ?? DEFAULT_MASCOT_BODY;
-}
+export * from "../packages/phone-protocol/src/mascot-bodies.ts";
diff --git a/shared/mcp-request.ts b/shared/mcp-request.ts
index 045591ebc7..2dbb5e8a2d 100644
--- a/shared/mcp-request.ts
+++ b/shared/mcp-request.ts
@@ -1,18 +1 @@
-/** Security: display data only. An update's change (the bot's fields, its secretRefs) stays in the server's memory until
- * the person answers and never reaches the wire or messages.json, so after a restart a Change card can only expire. A
- * Turn on or Remove card holds no fields, so it still applies after a restart. */
-export interface McpChangeRequest {
- requestId: string;
- botId: string;
- threadId: string;
- action: "enable" | "update" | "remove";
- name: string;
- /** sha256 hex of the server's display target (the masked address, or the command line with secrets hidden), the string
- * the card and the bot show. An answer applies only while the server still reaches there. Security: the card is stored,
- * synced to phones and visible to teammates, so the hash must never cover a raw secret a reader could guess offline;
- * a change confined to a masked part is not detected. */
- targetHash: string;
- result?: { state: "applied" | "denied" | "expired" | "failed"; text: string };
- /** The bot's parked turn took the result. */
- resumed?: boolean;
-}
+export * from "../packages/phone-protocol/src/mcp-request.ts";
diff --git a/shared/model-request.ts b/shared/model-request.ts
index b115a2e28c..77e51c396b 100644
--- a/shared/model-request.ts
+++ b/shared/model-request.ts
@@ -1,22 +1 @@
-/**
- * Durable payload carried by a default-model confirmation card (propose_model).
- * "before" is the exact selection the user was shown; a confirmation fails
- * closed if the target's default moved since.
- */
-import type { ModelSelection } from "./wire.ts";
-
-export interface ModelRequestCardData {
- version: 1;
- requestId: string;
- /** The proposing conversation; authority is fixed here. */
- botId: string;
- threadId: string;
- /** Whose default model changes: the proposer, or a section peer named by a Chief. */
- targetBotId: string;
- targetName: string;
- createdAt: number;
- reason: string;
- selection: ModelSelection;
- before: ModelSelection;
- appliedAt?: number;
-}
+export * from "../packages/phone-protocol/src/model-request.ts";
diff --git a/shared/modelgo.ts b/shared/modelgo.ts
index 09c5cbf048..c2b7c947ca 100644
--- a/shared/modelgo.ts
+++ b/shared/modelgo.ts
@@ -1,2 +1 @@
-/** The sponsor asked for this exact address, every parameter included, on every in-app link to its site. */
-export const MODELGO_URL = "https://modelgo.ai/?utm_source=openmausbot&utm_medium=sponsorship&utm_content=app&campaign_id=openmausbot&ad_group_id=app";
+export * from "../packages/phone-protocol/src/modelgo.ts";
diff --git a/shared/notification.ts b/shared/notification.ts
index 026701fb51..afa08c5e58 100644
--- a/shared/notification.ts
+++ b/shared/notification.ts
@@ -1,63 +1 @@
-/** The notification wire shape: what the harness decides is worth
- * interrupting someone for, emitted as the `notify` live frame. */
-export type NotifyKind =
- | "approval"
- | "question"
- | "done"
- | "routine-failed"
- | "routine-deferred"
- | "turn-failed"
- /** A run failed, stalled or could not start and no Chief of Staff was
- * there to take it: the person is the one who has to look. */
- | "incident"
- /** A bot asked the person to sign in to a website themselves
- * (request_sign_in): it waits on their hands, at the place it works. */
- | "sign-in"
- /** A bot asked the person for a password or key on a secure card (request_credential): its work rests on them until
- * they save it or say no. */
- | "secret"
- /** A delegated request settled and the coordinator auto-resumed the person's
- * own conversation with the results; both are internal, so without this it
- * sits silent until the resume's first token. A teammate's own step in a
- * longer chain sends none: nothing there waits on the person. */
- | "delegation-settled"
- /** A bot's settled room reply tagged the person (`@you` or their profile name). Rooms only. On a Team Cloud also
- * a teammate tagged by name, or a message a bot passed on to them, with `forPerson`. */
- | "mention"
- /** The workspace crossed its monthly spend warning or reached its cap.
- * Sent to admins only, at most once per month for each. */
- | "spend"
- /** The main agent's brief has something new that needs the person, or a
- * meeting prep or reminder it posted with no AI turn. Personal installs only. */
- | "brief"
- /** A wait a bot set up (wait_until) fired: what it was waiting for happened. */
- | "wait"
- /** Something OpenMausBot changed on its own that the person hears about
- * once: a tool turned off for the bots it doesn't start for. */
- | "notice";
-
-export interface Notification {
- kind: NotifyKind;
- botId: string;
- botName: string;
- threadId: string;
- title: string;
- body: string;
- /** The bot's stored profile image, when it has one; clients show it as
- * the OS notification's icon so every banner carries its bot's face. */
- avatarUrl?: string;
- /** The room this came out of, when the bot was speaking in one. Routing
- * already works off `threadId` alone; this is what lets a client say which
- * room, and stack a room's banners together instead of under the bot. */
- groupId?: string;
- /** On a Team Cloud, the one person this is for (their person key): a teammate tagged by name, or the person a bot
- * passed a message to. It reaches nobody else, an admin included. */
- forPerson?: string;
-}
-
-/** A `Notification` as the feed stores it: the live `notify` frame and `GET /api/notifications` carry the same entry. */
-export interface NotificationLogEntry extends Notification {
- id: string;
- at: number;
- read: boolean;
-}
+export * from "../packages/phone-protocol/src/notification.ts";
diff --git a/shared/options-card.ts b/shared/options-card.ts
index 5ed342ab32..d61fd99da5 100644
--- a/shared/options-card.ts
+++ b/shared/options-card.ts
@@ -1,58 +1 @@
-/** The one bot allowed to create passive choice cards for the Watcher flow. */
-export const WATCHER_OPTIONS_CARD_BOT_ID = "f08dd8e3-f942-4eb4-8783-df32b26b88a4";
-
-/** Keep agent-authored cards small enough to remain useful on desktop and mobile. */
-export const OPTIONS_CARD_LIMITS = {
- title: 120,
- subtitle: 1_000,
- option: 120,
- minOptions: 2,
- maxOptions: 6,
-} as const;
-
-export interface OptionsCardInput {
- title: string;
- subtitle: string;
- options: string[];
-}
-
-export type ParsedOptionsCardInput =
- | { ok: true; value: OptionsCardInput }
- | { ok: false; error: string };
-
-function record(value: unknown): value is Record<string, unknown> {
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
-}
-
-function boundedText(value: unknown, field: string, maximum: number): string | { error: string } {
- if (typeof value !== "string") return { error: `${field} must be a string.` };
- const text = value.trim();
- if (!text) return { error: `${field} must not be blank.` };
- if (text.length > maximum) return { error: `${field} must be at most ${maximum} characters.` };
- return text;
-}
-
-/** Normalize untrusted model input before it is persisted into a native card. */
-export function parseOptionsCardInput(value: unknown): ParsedOptionsCardInput {
- if (!record(value)) return { ok: false, error: "create_options_card needs an object." };
-
- const title = boundedText(value.title, "title", OPTIONS_CARD_LIMITS.title);
- if (typeof title !== "string") return { ok: false, error: title.error };
- const subtitle = boundedText(value.subtitle, "subtitle", OPTIONS_CARD_LIMITS.subtitle);
- if (typeof subtitle !== "string") return { ok: false, error: subtitle.error };
- if (!Array.isArray(value.options)) return { ok: false, error: "options must be an array of strings." };
- if (value.options.length < OPTIONS_CARD_LIMITS.minOptions || value.options.length > OPTIONS_CARD_LIMITS.maxOptions) {
- return { ok: false, error: `options must contain ${OPTIONS_CARD_LIMITS.minOptions}-${OPTIONS_CARD_LIMITS.maxOptions} items.` };
- }
-
- const options: string[] = [];
- const seen = new Set<string>();
- for (let index = 0; index < value.options.length; index += 1) {
- const option = boundedText(value.options[index], `options[${index}]`, OPTIONS_CARD_LIMITS.option);
- if (typeof option !== "string") return { ok: false, error: option.error };
- if (seen.has(option)) return { ok: false, error: `options must be unique; "${option}" is repeated.` };
- seen.add(option);
- options.push(option);
- }
- return { ok: true, value: { title, subtitle, options } };
-}
+export * from "../packages/phone-protocol/src/options-card.ts";
diff --git a/shared/outbound.ts b/shared/outbound.ts
index 3aace15a2d..8d21f948e4 100644
--- a/shared/outbound.ts
+++ b/shared/outbound.ts
@@ -1,167 +1 @@
-// Outbound actions: calls that reach a person outside the app or move money.
-// Below Full access they get their own confirmation unless the bot's rule sends
-// without asking; at Full access they run unless the bot has a rule of its own.
-// A read-and-draft routine run never reaches them: the relay refuses every send
-// there. Shared by the harness (which enforces it) and the app.
-import { isConnectedAppsServer } from "./own-apps.ts";
-
-export type OutboundPolicy = {
- /** ask: every outbound call waits for a tap. allow: outbound calls go out without asking. */
- policy: "ask" | "allow";
-};
-
-/** Tools whose action is one of these words send something somewhere. */
-const SEND_VERBS = new Set([
- "SEND",
- "SENDS",
- "REPLY",
- "RESPOND",
- "FORWARD",
- "POST",
- "PUBLISH",
- "TWEET",
- "RETWEET",
- "BROADCAST",
- "INVITE",
- "SHARE",
- "REFUND",
- "CHARGE",
- "PAY",
- "PAYOUT",
- "TRANSFER",
- "BUY",
- "PURCHASE",
- "DIAL",
-]);
-
-/** Creating one of these is sending it: a created comment is a comment
- * someone reads, a created invoice is one someone receives, a created call rings someone. */
-const CREATE_VERBS = new Set(["CREATE", "CREATION", "ADD", "NEW", "MAKE"]);
-const SENT_NOUNS = new Set(["MESSAGE", "COMMENT", "POST", "EMAIL", "MAIL", "INVOICE", "PAYMENT", "REFUND", "REPLY", "TWEET", "DM", "CALL"]);
-
-/** Telnyx's hosted server reaches its whole API through one tool, so any call of it may ring, text or buy. */
-const RAW_API_ACTION = /^mcp__.+__invoke_api_endpoint$/;
-
-/** A read verb first means the rest of the name is what is being read:
- * REDDIT_GET_POST fetches a post, it does not post. */
-const READ_VERBS = new Set(["GET", "LIST", "FETCH", "SEARCH", "READ", "FIND", "RETRIEVE", "LOOKUP", "DOWNLOAD", "VIEW", "CHECK", "COUNT"]);
-
-/** Composio reads known by slug, since some put the noun first (GOOGLECALENDAR_EVENTS_LIST lists events). */
-export const KNOWN_READ_SLUGS: ReadonlySet<string> = new Set([
- "GMAIL_FETCH_EMAILS",
- "GMAIL_GET_PROFILE",
- "GMAIL_FETCH_MESSAGE_BY_MESSAGE_ID",
- "GMAIL_FETCH_MESSAGE_BY_THREAD_ID",
- "GOOGLECALENDAR_EVENTS_LIST",
- "GOOGLECALENDAR_EVENTS_GET",
- "GOOGLECALENDAR_FIND_EVENT",
- "GOOGLECALENDAR_LIST_CALENDARS",
-]);
-
-/** The action part of a tool name, as upper-case word tokens. Composio's
- * TOOLKIT_ACTION drops its toolkit; an MCP server's mcp__server__action
- * drops its server; a bare built-in like Bash stays as it is. */
-function actionTokens(name: string): string[] {
- let action = name;
- if (name.startsWith("mcp__")) {
- const [, server = "", ...rest] = name.split("__");
- action = rest.join("_");
- if (isConnectedAppsServer(server)) return actionTokens(action);
- } else if (/^[A-Z][A-Z0-9]*_[A-Z0-9_]+$/.test(name)) {
- action = name.slice(name.indexOf("_") + 1);
- }
- return action
- .replace(/([a-z0-9])([A-Z])/g, "$1_$2")
- .toUpperCase()
- .split(/[^A-Z0-9]+/)
- .filter(Boolean);
-}
-
-/** Does the tool name describe a read-only action? This is deliberately
- * narrower than "not outbound": updates, deletes and other writes do not
- * become reads merely because they send nothing to another person. */
-export function isReadOnlyTool(name: string): boolean {
- if (KNOWN_READ_SLUGS.has(name.replace(/^mcp__(?:composio|own_apps)__/, ""))) return true;
- const tokens = actionTokens(name);
- return tokens.length > 0 && READ_VERBS.has(tokens[0]);
-}
-
-/** The built-in agents server's X research tools only read X: x_post reads a post, it does not post one. */
-const AGENTS_X_READS = /^(?:mcp__agents__|agents__|agents_)?x_(?:search|user_posts|post|profile)$/;
-
-/** Does this tool send something to someone, or move money? */
-export function isOutboundTool(name: string): boolean {
- // A raw API call from the workbench can do anything an app tool can, and
- // nothing here can read which; it is treated as a send.
- if (name === "COMPOSIO_PROXY_EXECUTE" || RAW_API_ACTION.test(name)) return true;
- if (AGENTS_X_READS.test(name)) return false;
- const tokens = actionTokens(name);
- if (tokens.length === 0) return false;
- if (isReadOnlyTool(name)) return false;
- if (tokens.some((token) => SEND_VERBS.has(token))) return true;
- if (tokens.includes("DRAFT")) return false;
- return tokens.some((token) => CREATE_VERBS.has(token)) && tokens.some((token) => SENT_NOUNS.has(token));
-}
-
-/** The stored shape, or null when the value is not one. Fields other than `policy` are dropped. */
-export function normalizeOutboundPolicy(value: unknown): OutboundPolicy | null {
- if (!value || typeof value !== "object" || Array.isArray(value)) return null;
- const { policy } = value as { policy?: unknown };
- return policy === "ask" || policy === "allow" ? { policy } : null;
-}
-
-/** What a bot without a stored policy does: ask, every time. */
-export const DEFAULT_OUTBOUND_POLICY: OutboundPolicy = { policy: "ask" };
-
-/** Drops from a stored bot's rule what `normalizeOutboundPolicy` drops, so every copy of one rule reads the same; true
- * when it changed. A rule that is not one is left as it is, and asks. */
-export function trimOutboundPolicy(bot: { outbound?: OutboundPolicy }): boolean {
- const kept = bot.outbound && normalizeOutboundPolicy(bot.outbound);
- if (!kept || Object.keys(bot.outbound!).length === Object.keys(kept).length) return false;
- bot.outbound = kept;
- return true;
-}
-
-/** One app tool a connector request would run, with its arguments when the
- * request carries them. */
-export interface ConnectorCall {
- slug: string;
- arguments?: unknown;
-}
-
-const isRecord = (value: unknown): value is Record<string, unknown> =>
- Boolean(value) && typeof value === "object" && !Array.isArray(value);
-
-/** Composio's session exposes a handful of meta tools and runs the app
- * tools inside them: a multi-execute call carries a list of slugs with
- * arguments. Arbitrary workbench/bash code is opaque: it requires an
- * explicit unrestricted approval, never an inferred app or send count.
- * Search, schema lookup, and connection management run no app tools. */
-export function connectorCallsIn(name: string, args: unknown): ConnectorCall[] {
- if (name === "COMPOSIO_MULTI_EXECUTE_TOOL") {
- const tools = isRecord(args) && Array.isArray(args.tools) ? args.tools
- : isRecord(args) && typeof args.tool_slug === "string" ? [args] : [];
- if (!tools.length) return [{ slug: "COMPOSIO_PROXY_EXECUTE", arguments: args }];
- const calls: ConnectorCall[] = [];
- for (const item of tools) {
- if (!isRecord(item)) return [{ slug: "COMPOSIO_PROXY_EXECUTE", arguments: args }];
- const slug = [item.tool_slug, item.slug, item.name, item.tool].find((value) => typeof value === "string" && value);
- if (typeof slug !== "string") return [{ slug: "COMPOSIO_PROXY_EXECUTE", arguments: args }];
- calls.push({ slug, ...(item.arguments !== undefined ? { arguments: item.arguments } : {}) });
- }
- return calls;
- }
- if (name === "COMPOSIO_REMOTE_WORKBENCH" || name === "COMPOSIO_REMOTE_BASH_TOOL") {
- // Arbitrary code can compute tool names and repeat calls. Its app and
- // outbound count cannot be inferred from literals in the source.
- return [{ slug: "COMPOSIO_PROXY_EXECUTE", arguments: args }];
- }
- if (["COMPOSIO_SEARCH_TOOLS", "COMPOSIO_GET_TOOL_SCHEMAS", "COMPOSIO_MANAGE_CONNECTIONS", "COMPOSIO_WAIT_FOR_CONNECTIONS"].includes(name)) return [];
- if (name.startsWith("COMPOSIO_")) return [{ slug: "COMPOSIO_PROXY_EXECUTE", arguments: args }];
- return [{ slug: name, ...(args !== undefined ? { arguments: args } : {}) }];
-}
-
-/** The subset of a request's app tools that would send something. */
-export function outboundCallsIn(name: string, args: unknown): ConnectorCall[] {
- return connectorCallsIn(name, args).filter((call) => isOutboundTool(call.slug));
-}
+export * from "../packages/phone-protocol/src/outbound.ts";
diff --git a/shared/outside-write.ts b/shared/outside-write.ts
index a74d55dbeb..4678c400f6 100644
--- a/shared/outside-write.ts
+++ b/shared/outside-write.ts
@@ -1,4 +1 @@
-export interface OutsideWriteCardField {
- /** What work from outside asked to write where later turns read it; nothing is written until a person says yes. */
- outsideWrite?: { kind: "room-bulletin"; roomId: string; bulletin: string } | { kind: "memory"; action: string; text?: string; oldText?: string; until?: string };
-}
+export * from "../packages/phone-protocol/src/outside-write.ts";
diff --git a/shared/own-apps.ts b/shared/own-apps.ts
index 538a10226f..e2b89b96a2 100644
--- a/shared/own-apps.ts
+++ b/shared/own-apps.ts
@@ -1,6 +1 @@
-// A Team Cloud member's own connected apps: mounted beside the team's `composio` server, only in that member's own turns in
-// their private chat. Everything that reads a `composio` tool as an app tool reads this one the same way.
-export const OWN_APPS_SERVER = "own_apps";
-
-/** The two servers whose tools are connected-app (Composio) tools. */
-export const isConnectedAppsServer = (server: string): boolean => server === "composio" || server === OWN_APPS_SERVER;
+export * from "../packages/phone-protocol/src/own-apps.ts";
diff --git a/shared/pairing-code.ts b/shared/pairing-code.ts
index 9b5078061f..b4be7605eb 100644
--- a/shared/pairing-code.ts
+++ b/shared/pairing-code.ts
@@ -1,79 +1 @@
-/** The one kind of secret a device joins with: 12 symbols from this alphabet, shown as `7KQ2-M9XD-H4TP`. Dashes,
- * spaces and case never matter. A link or QR carries the same code with an address. */
-export const PAIRING_CODE_ALPHABET = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ";
-export const PAIRING_CODE_LENGTH = 12;
-/** The high-entropy credential a QR carries instead of the code; accepted wherever a code is, never shown. */
-export const PAIRING_CREDENTIAL_PREFIX = "omb_pair_";
-const PAIRING_CREDENTIAL = /^omb_pair_[A-Za-z0-9_-]{43}$/;
-
-export function normalizePairingCode(input: string): string {
- return input
- .toUpperCase()
- .replace(/[^A-Z0-9]/g, "")
- .replace(/0/g, "O")
- .replace(/1/g, "I");
-}
-
-export function formatPairingCode(code: string): string {
- return normalizePairingCode(code).match(/.{1,4}/g)?.join("-") ?? code;
-}
-
-/** What someone typed or pasted where a pairing code goes, and the sentence that explains anything else. */
-export type PairingInput =
- | { kind: "code"; code: string }
- | { kind: "credential"; credential: string }
- | { kind: "wrong"; problem: PairingInputProblem }
- | { kind: "empty" };
-
-export type PairingInputProblem = "emailCode" | "oldCode" | "scriptKey" | "notACode";
-
-/** English for each problem; src/locales/en.json carries the same sentences under the same keys. */
-export const PAIRING_INPUT_PROBLEM_TEXT = {
- "serverError.pair.emailCode": "That's a sign-in code from an email. Pairing needs a 12-character code like 7KQ2-M9XD-H4TP.",
- "serverError.pair.oldCode": "That's a code from an older MausBot. Make a new one on the other computer: Phone & devices → Pair a device.",
- "serverError.pair.scriptKey": "That's a script key. Pairing needs a pairing code.",
- "serverError.pair.notACode": "That isn't a pairing code. Pairing needs a 12-character code like 7KQ2-M9XD-H4TP.",
-} as const;
-
-/** `serverError.*` catalog keys, so the server, the CLI and every screen word a wrong kind of code the same way. */
-export const PAIRING_INPUT_PROBLEM_KEY: Record<PairingInputProblem, keyof typeof PAIRING_INPUT_PROBLEM_TEXT> = {
- emailCode: "serverError.pair.emailCode",
- oldCode: "serverError.pair.oldCode",
- scriptKey: "serverError.pair.scriptKey",
- notACode: "serverError.pair.notACode",
-};
-
-function fromLink(raw: string): string | null {
- let url: URL;
- try {
- url = new URL(raw);
- } catch {
- return null;
- }
- const hash = new URLSearchParams(url.hash.replace(/^#/, ""));
- return url.searchParams.get("token") ?? url.searchParams.get("code") ?? hash.get("code");
-}
-
-/** Reads a typed code, an `omb_pair_` credential, or a link that carries either (`openmausbot://pair?…`,
- * `…/pair#code=…`, `?code=…`). */
-export function readPairingInput(raw: string): PairingInput {
- let value = raw.trim();
- if (!value) return { kind: "empty" };
- if (/^[a-z][a-z0-9+.-]*:\/\//i.test(value)) {
- const carried = fromLink(value);
- if (!carried) return { kind: "wrong", problem: "notACode" };
- value = carried.trim();
- }
- if (value.startsWith("omb_sess_")) return { kind: "wrong", problem: "scriptKey" };
- if (value.startsWith(PAIRING_CREDENTIAL_PREFIX)) {
- return PAIRING_CREDENTIAL.test(value) ? { kind: "credential", credential: value } : { kind: "wrong", problem: "notACode" };
- }
- const digits = value.replace(/[\s-]/g, "");
- if (/^\d{8}$/.test(digits)) return { kind: "wrong", problem: "emailCode" };
- if (/^\d{6}$/.test(digits)) return { kind: "wrong", problem: "oldCode" };
- const code = normalizePairingCode(value);
- if (code.length !== PAIRING_CODE_LENGTH || [...code].some((symbol) => !PAIRING_CODE_ALPHABET.includes(symbol))) {
- return { kind: "wrong", problem: "notACode" };
- }
- return { kind: "code", code };
-}
+export * from "../packages/phone-protocol/src/pairing-code.ts";
diff --git a/shared/pairing-link.ts b/shared/pairing-link.ts
index 4c9c822868..5a0402cb69 100644
--- a/shared/pairing-link.ts
+++ b/shared/pairing-link.ts
@@ -1,198 +1 @@
-// The one `openmausbot://pair` link builder, read by the Android and iOS
-// scanners (`PairingInvite.parse`). Every value is written with
-// encodeURIComponent, so a space is `%20`.
-
-export type CompanionEndpointKind = "hosted" | "tailnet" | "lan" | "bonjour";
-
-export interface CompanionEndpoint {
- url: string;
- kind: CompanionEndpointKind;
- priority: number;
-}
-
-export interface PairingE2EDescriptor {
- v: 1;
- k: string;
- h?: string;
- r?: string[];
-}
-
-const B64U_FIELD = /^[A-Za-z0-9_-]+$/;
-const RELAY_HOST = /^relay[1-9][0-9]?\.openmausbot\.com$/;
-
-/** The QR's `e2e` value, or null for anything a phone would refuse: then the link goes out without it, as from a
- * computer without the encrypted connection. A QR never says "local": a restriction is set per phone, later. */
-export function encodePairingE2E(descriptor: PairingE2EDescriptor | null | undefined): string | null {
- if (!descriptor || descriptor.v !== 1 || typeof descriptor.k !== "string" || descriptor.k.length !== 87 || !B64U_FIELD.test(descriptor.k)) return null;
- const relay = typeof descriptor.h === "string" && Array.isArray(descriptor.r) && descriptor.r.length >= 1 && descriptor.r.length <= 4
- && descriptor.h.length === 22 && B64U_FIELD.test(descriptor.h) && descriptor.r.every((node) => RELAY_HOST.test(node))
- ? { h: descriptor.h, r: descriptor.r }
- : {};
- const json = JSON.stringify({ v: 1, k: descriptor.k, ...relay });
- const encoded = btoa(json).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
- return encoded.length <= 1024 ? encoded : null;
-}
-
-export interface PhonePairingLinkOptions {
- /** Where the phone dials first: a host or IP literal together with `port`
- * (the desktop companion), or a complete http(s) origin (a server). */
- address: string;
- port?: number;
- /** The high-entropy one-time credential the scanner redeems. */
- token: string;
- /** The six digits the desktop shows; servers have none. */
- code?: string;
- name?: string;
- /** Every host the phone could dial later, best first. */
- hosts?: string[];
- /** Complete base URLs, encoded apart from `address`/`hosts` so HTTPS and
- * port 443 stay unambiguous. */
- endpoints?: CompanionEndpoint[];
- /** The end-to-end descriptor `{v, k, h?, r?}`: the computer's transport key, pinned by the scan, and its relay
- * identity. Sent as `e2e=<base64url JSON>`; a phone that can't parse it refuses the whole link. */
- e2e?: PairingE2EDescriptor | null;
- /** P-256 HPKE recipient key pinned by the camera scan. Its private half
- * remains in the desktop's OS-encrypted credential store. */
- secretPublicKey?: string;
-}
-
-/** How many fallback routes a link will carry. The list is tiny in practice;
- * the cap only keeps a pathological interface table from bloating the QR. */
-export const MAX_PAIRING_HOSTS = 8;
-
-const ENDPOINT_KINDS = new Set<CompanionEndpointKind>(["hosted", "tailnet", "lan", "bonjour"]);
-
-/** Strict even for our own sidecar's input: a public URL with credentials or a
- * path is not a companion base URL. Sorted by priority, deduplicated by origin,
- * capped. */
-export function qrEndpoints(endpoints: CompanionEndpoint[] | undefined): CompanionEndpoint[] {
- const seen = new Set<string>();
- const valid: CompanionEndpoint[] = [];
-
- for (const endpoint of endpoints ?? []) {
- if (
- !endpoint ||
- !ENDPOINT_KINDS.has(endpoint.kind) ||
- !Number.isInteger(endpoint.priority) ||
- endpoint.priority < 0 ||
- endpoint.priority > 1_000_000
- ) {
- continue;
- }
-
- try {
- const parsed = new URL(endpoint.url);
- const expectedProtocol = endpoint.kind === "hosted" ? "https:" : "http:";
- const explicitPort = parsed.port ? Number(parsed.port) : null;
- const hostname = parsed.hostname.toLowerCase().replace(/\.$/, "");
- if (
- parsed.protocol !== expectedProtocol ||
- // No empty DNS label (".ts.net", "mac..local"): the phones refuse
- // one, and one endpoint they refuse makes them refuse the whole QR.
- hostname.split(".").includes("") ||
- (endpoint.kind === "tailnet" && !hostname.endsWith(".ts.net")) ||
- (explicitPort !== null && (!Number.isInteger(explicitPort) || explicitPort < 1 || explicitPort > 65_535)) ||
- parsed.username ||
- parsed.password ||
- parsed.pathname !== "/" ||
- parsed.search ||
- parsed.hash ||
- seen.has(parsed.origin)
- ) {
- continue;
- }
- seen.add(parsed.origin);
- valid.push({ url: parsed.origin, kind: endpoint.kind, priority: endpoint.priority });
- } catch {
- }
- }
-
- return valid.sort((left, right) => left.priority - right.priority).slice(0, MAX_PAIRING_HOSTS);
-}
-
-/** URL-safe, unpadded base64 keeps the structured JSON smaller than query
- * escaping every quote and slash while remaining straightforward to decode
- * with Foundation on iOS. */
-function encodeEndpoints(endpoints: CompanionEndpoint[]): string {
- const bytes = new TextEncoder().encode(JSON.stringify(endpoints));
- let binary = "";
- for (const byte of bytes) binary += String.fromCharCode(byte);
- return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "");
-}
-
-function validSecretPublicKey(value: string | undefined): string | null {
- if (!value || !/^[A-Za-z0-9_-]{87}$/.test(value)) return null;
- try {
- const base64 = value.replaceAll("-", "+").replaceAll("_", "/") + "=";
- const decoded = atob(base64);
- if (decoded.length !== 65 || decoded.charCodeAt(0) !== 4) return null;
- let binary = "";
- for (let index = 0; index < decoded.length; index += 1) binary += decoded[index];
- return btoa(binary).replaceAll("+", "-").replaceAll("/", "_").replace(/=+$/, "") === value
- ? value
- : null;
- } catch {
- return null;
- }
-}
-
-/** The `address` value: `host:port` (IPv6 bracketed) or a bare http(s)
- * origin, or null when it is neither. Both phones refuse an address with
- * credentials, a path, a query or a fragment, as `qrEndpoints` does. */
-function linkAddress(address: string, port: number | undefined): string | null {
- const value = address.trim();
- if (!value) return null;
- if (/^https?:\/\//i.test(value)) {
- try {
- const parsed = new URL(value);
- if (parsed.username || parsed.password || parsed.pathname !== "/" || parsed.search || parsed.hash) return null;
- return parsed.origin;
- } catch {
- return null;
- }
- }
- if (port === undefined || !Number.isInteger(port) || port < 1 || port > 65_535) return null;
- const authority = value.includes(":") && !value.startsWith("[") ? `[${value}]` : value;
- return `${authority}:${port}`;
-}
-
-/**
- * A short-lived handoff from a trusted pairing screen to the mobile app. The
- * credential still has to be redeemed; putting it in the link does not
- * create or expose the long-lived device token. Null when any required part
- * is malformed, so a caller never prints a link a phone would refuse.
- */
-export function phonePairingLink({
- address,
- port,
- token,
- code,
- name,
- hosts,
- endpoints,
- secretPublicKey,
- e2e,
-}: PhonePairingLinkOptions): string | null {
- const dial = linkAddress(address, port);
- if (!dial || !/^omb_pair_[A-Za-z0-9_-]{43}$/.test(token)) return null;
- if (code !== undefined && !/^\d{6}$/.test(code)) return null;
-
- const fields: Array<[string, string]> = [["address", dial], ["token", token]];
- if (code !== undefined) fields.push(["code", code]);
- if (name?.trim()) fields.push(["name", name.trim()]);
- // Comma-joined, which no hostname or IP literal can contain. A bad candidate
- // is filtered, not fatal: it costs the phone one failed dial.
- const candidates = (hosts ?? [])
- .map((candidate) => candidate.trim())
- .filter((candidate) => candidate && !/[\s/?#,[\]]/.test(candidate))
- .slice(0, MAX_PAIRING_HOSTS);
- if (candidates.length) fields.push(["hosts", candidates.join(",")]);
- const routes = qrEndpoints(endpoints);
- if (routes.length) fields.push(["endpoints", encodeEndpoints(routes)]);
- const secretKey = validSecretPublicKey(secretPublicKey);
- if (secretKey) fields.push(["secretKey", secretKey]);
- const descriptor = encodePairingE2E(e2e);
- if (descriptor) fields.push(["e2e", descriptor]);
-
- return `openmausbot://pair?${fields.map(([key, value]) => `${key}=${encodeURIComponent(value)}`).join("&")}`;
-}
+export * from "../packages/phone-protocol/src/pairing-link.ts";
diff --git a/shared/phone-apps.ts b/shared/phone-apps.ts
index 476afac134..6536c7db71 100644
--- a/shared/phone-apps.ts
+++ b/shared/phone-apps.ts
@@ -1,66 +1 @@
-// Vocabulary for "phone apps as bot tools": the apps a paired phone may allow,
-// per-bot grants, and the PHONE_* tool names served by the `device` MCP server.
-import { isReadOnlyAction } from "./connector-scopes.ts";
-
-export const PHONE_CAPABILITIES = ["calendar", "reminders", "contacts", "location", "home", "messages"] as const;
-export type PhoneCapability = (typeof PHONE_CAPABILITIES)[number];
-export type PhoneGrant = "read" | "write";
-/** Per-bot grant; an absent key is off. */
-export type PhoneApps = Partial<Record<PhoneCapability, PhoneGrant>>;
-
-export const PHONE_SLUG = "phone";
-export const PHONE_MCP_SERVER = "device";
-export const PHONE_PLATFORMS = ["ios", "android"] as const;
-export type PhonePlatform = (typeof PHONE_PLATFORMS)[number];
-
-export const PHONE_TOOL_NAMES = [
- "PHONE_LIST_EVENTS", "PHONE_GET_EVENT", "PHONE_FIND_FREE_TIME", "PHONE_CREATE_EVENT", "PHONE_UPDATE_EVENT", "PHONE_DELETE_EVENT", "PHONE_RESPOND_TO_INVITE",
- "PHONE_LIST_REMINDERS", "PHONE_CREATE_REMINDER", "PHONE_UPDATE_REMINDER", "PHONE_COMPLETE_REMINDER", "PHONE_DELETE_REMINDER",
- "PHONE_SEARCH_CONTACTS", "PHONE_GET_CONTACT", "PHONE_CREATE_CONTACT", "PHONE_UPDATE_CONTACT",
- "PHONE_GET_LOCATION", "PHONE_FIND_PLACES_NEARBY",
- "PHONE_LIST_HOME", "PHONE_SET_ACCESSORY", "PHONE_RUN_SCENE",
- "PHONE_SEND_MESSAGE", "PHONE_SEND_WHATSAPP",
-] as const;
-export type PhoneToolName = (typeof PHONE_TOOL_NAMES)[number];
-
-const TOOL_CAPABILITY: Record<PhoneToolName, PhoneCapability> = {
- PHONE_LIST_EVENTS: "calendar", PHONE_GET_EVENT: "calendar", PHONE_FIND_FREE_TIME: "calendar", PHONE_CREATE_EVENT: "calendar",
- PHONE_UPDATE_EVENT: "calendar", PHONE_DELETE_EVENT: "calendar", PHONE_RESPOND_TO_INVITE: "calendar",
- PHONE_LIST_REMINDERS: "reminders", PHONE_CREATE_REMINDER: "reminders", PHONE_UPDATE_REMINDER: "reminders",
- PHONE_COMPLETE_REMINDER: "reminders", PHONE_DELETE_REMINDER: "reminders",
- PHONE_SEARCH_CONTACTS: "contacts", PHONE_GET_CONTACT: "contacts", PHONE_CREATE_CONTACT: "contacts", PHONE_UPDATE_CONTACT: "contacts",
- PHONE_GET_LOCATION: "location", PHONE_FIND_PLACES_NEARBY: "location",
- PHONE_LIST_HOME: "home", PHONE_SET_ACCESSORY: "home", PHONE_RUN_SCENE: "home",
- PHONE_SEND_MESSAGE: "messages", PHONE_SEND_WHATSAPP: "messages",
-};
-
-export function isPhoneToolName(name: unknown): name is PhoneToolName {
- return typeof name === "string" && Object.hasOwn(TOOL_CAPABILITY, name);
-}
-
-export function phoneToolCapability(name: PhoneToolName): PhoneCapability {
- return TOOL_CAPABILITY[name];
-}
-
-/** GET/LIST/SEARCH/FIND read; everything else writes (isReadOnlyAction(name, "phone")). */
-export function isPhoneWrite(name: string): boolean {
- return !isReadOnlyAction(name, PHONE_SLUG);
-}
-
-export function phoneToolSends(name: string): boolean {
- return name.startsWith("PHONE_SEND_");
-}
-
-/** Unknown key or value → null; `{}` is valid (everything off). */
-export function normalizePhoneApps(value: unknown): PhoneApps | null {
- if (typeof value !== "object" || value === null || Array.isArray(value)) return null;
- const out: PhoneApps = {};
- for (const [key, grant] of Object.entries(value)) {
- if (!(PHONE_CAPABILITIES as readonly string[]).includes(key)) return null;
- if (grant !== "read" && grant !== "write") return null;
- out[key as PhoneCapability] = grant;
- }
- return out;
-}
-
-export const ALL_PHONE_APPS: PhoneApps = Object.fromEntries(PHONE_CAPABILITIES.map((c) => [c, "write"])) as PhoneApps;
+export * from "../packages/phone-protocol/src/phone-apps.ts";
diff --git a/shared/phone-steps.ts b/shared/phone-steps.ts
index eee319f557..4c99a8c232 100644
--- a/shared/phone-steps.ts
+++ b/shared/phone-steps.ts
@@ -1,4 +1 @@
-/** The phone tools a step of the phone server's batch tool can run; a batch may run only where all of them may. */
-export const PHONE_STEP_TOOLS = ["open_app", "tap_text", "tap", "swipe", "type_text", "press", "read_screen"] as const;
-
-export type PhoneStepTool = (typeof PHONE_STEP_TOOLS)[number];
+export * from "../packages/phone-protocol/src/phone-steps.ts";
diff --git a/shared/place-view.ts b/shared/place-view.ts
index 0aa6a8a0d6..5df7d82345 100644
--- a/shared/place-view.ts
+++ b/shared/place-view.ts
@@ -1,592 +1 @@
-// Where a bot works, said once: one plain line and at most one next action for
-// every state a place can be in. The server words a failed turn's row from it
-// in English; the app renders the same state in the person's language. The
-// English mirrors src/locales/en.json `place.*` exactly (a test holds them
-// together): the server has no i18n.
-
-export type Place = "cloud" | "vm" | "local" | "browser";
-
-/** Every state a place can be in. cc-* is the cloud computer. */
-export const PLACE_STATES = [
- "auto", "auto-team",
- "cc-cannot", "cc-tools-off", "cc-sign-in", "cc-new", "cc-starting", "cc-waking", "cc-on", "cc-asleep",
- "cc-no-hours", "cc-at-once", "cc-unavailable", "cc-ended", "cc-no-start", "cc-clearing", "cc-provider",
- "cc-on-my-cloud", "cc-needs-key", "vps",
- "browser", "browser-off", "browser-cannot",
- "local", "local-unavailable", "vm", "vm-cannot", "place-failed",
- "off",
-] as const;
-export type PlaceState = (typeof PLACE_STATES)[number];
-
-/** Where a failed place came from: the one control a person changes when it
- * can't be used. A routine and a room member are their own sources; Auto and
- * a team's shared computer name no place, so they never fail as one. */
-export type PlaceSource = "works-on" | "pin" | "auto-pin" | "routine" | "room";
-
-/** The next actions a place offers. Each is one button in the app and, on a
- * stored row, one sentence a phone can read. */
-export const PLACE_ACTIONS = [
- "choose-model", "open-tools", "sign-in", "start", "wake", "watch", "see-plan", "manage-computers",
- "try-again", "open-my-cloud", "add-boat-key", "turn-on-browser", "open-team-map", "open-vm-settings",
- "clear-pin", "change-routine", "open-computer-panel",
-] as const;
-export type PlaceActionId = (typeof PLACE_ACTIONS)[number];
-
-/** What a failed-turn row stores about its place, beside its English words,
- * so the app can word it again in the reader's language. */
-export interface PlaceRow {
- state: PlaceState;
- params: PlaceParams;
- source: PlaceSource;
-}
-
-export interface PlaceParams {
- bot?: string;
- engine?: string;
- model?: string;
- computer?: string;
- hours?: number;
- month?: string;
- plan?: string;
- max?: number;
- holders?: string[];
- words?: string;
- reason?: string;
- cause?: string;
- /** The cloud desktop's limit is a free trial's. */
- trial?: boolean;
-}
-
-export interface PlaceAction {
- id: PlaceActionId;
- label: string;
-}
-
-export interface PlaceView {
- state: PlaceState;
- params: PlaceParams;
- /** A few words for a card, a grid tile or a chip row. */
- short: string;
- /** The one plain message. */
- line: string;
- action: PlaceAction | null;
-}
-
-/** Where this server runs, as the Auto line describes it. */
-export type ServerKind = "my-cloud" | "mac" | "pc" | "linux" | "remote";
-
-/** The facts a place's state is read from. */
-export interface PlaceFacts {
- /** The place to describe: Auto, Off, or one of the four places. */
- place: Place | "auto" | "off";
- server: ServerKind;
- bot: string;
- /** Desktop only: signed in to a paid OpenMausBot Cloud plan (the desktop bridge). */
- plan?: boolean;
- /** Where cloud computers come from here: the plan's, the person's own Boat key, or nowhere. */
- boat: "included" | "own-key" | "none";
- /** The cloud computer's provider: Boat, or the person's own server. */
- backend?: "box" | "vps";
- engine: {
- name: string;
- model?: string;
- /** It can use computer tools. */
- computer: boolean;
- /** It can use the built-in browser. */
- browser: boolean;
- /** Not waiting on a sign-in. */
- signedIn: boolean;
- };
- /** The bot's tool selection includes the computer. */
- toolsAllowComputer: boolean;
- /** The built-in browser is switched on for this installation and bot. */
- browserOn: boolean;
- role: "admin" | "user";
- mode?: "simple" | "advanced";
- /** The cloud computer as last seen; unknown reads as not made yet. */
- computer?: "none" | "starting" | "waking" | "on" | "asleep";
- /** Auto uses a team's shared cloud computer by this name. */
- teamComputer?: string;
- /** This computer can be picked; `reason` says why not. */
- local?: { ready: boolean; reason?: string };
- /** A refusal already read from a failed start (cloudRefusal). */
- refusal?: { state: PlaceState; params: PlaceParams };
-}
-
-/** The English catalog, mirrored by en.json. */
-export const PLACE_EN = {
- "place.view.auto.short": "Chooses for you",
- "place.view.auto.lineMyCloud": "Uses the built-in browser. In a chat, it starts its cloud desktop by itself when a task needs desktop apps.",
- "place.view.auto.lineDesktop": "Uses the built-in browser, a private desktop on this computer, or this computer's screen, whichever the task needs.",
- "place.view.auto.lineLinux": "Uses the built-in browser, or a running private desktop when a task needs one.",
- "place.view.autoTeam.short": "Shared",
- "place.view.autoTeam.line": "Uses {computer}, the cloud desktop this department shares.",
- "place.view.ccCannot.short": "Not with this model",
- "place.view.ccCannot.line": "{model} can't use a desktop. Choose a model that can, such as Claude or ChatGPT.",
- "place.view.ccToolsOff.short": "Not allowed",
- "place.view.ccToolsOff.line": "What {bot} can use doesn't include a desktop.",
- "place.view.ccSignIn.short": "Sign in first",
- "place.view.ccSignIn.line": "Sign in to {engine} first. {bot} uses it on its cloud desktop too.",
- "place.view.ccSignIn.lineMyCloud": "Sign in to {engine} in the Cloud first. {bot} uses it on its cloud desktop too.",
- "place.view.ccNew.short": "Ready",
- "place.view.ccNew.line": "{bot} gets its own cloud desktop from Boat the first time a task needs one. The first start takes about a minute.",
- "place.view.ccStarting.short": "Starting…",
- "place.view.ccStarting.line": "Starting {bot}'s cloud desktop. The first start takes about a minute.",
- "place.view.ccWaking.short": "Waking…",
- "place.view.ccWaking.line": "Waking {bot}'s cloud desktop. This takes a few seconds.",
- "place.view.ccOn.short": "On",
- "place.view.ccOn.line": "{bot}'s cloud desktop is on. It goes to sleep after 10 minutes without use.",
- "place.view.ccAsleep.short": "Asleep",
- "place.view.ccAsleep.line": "{bot}'s cloud desktop is asleep. It wakes in a few seconds when {bot} needs it.",
- "place.view.ccNoHours.short": "No hours left",
- "place.view.ccNoHours.line": "This month's {hours} cloud desktop hours are used up. They come back on 1 {month}.",
- "place.view.ccNoHours.lineUnknown": "This month's cloud desktop hours are used up.",
- "place.view.ccNoHours.lineTrial": "The free trial's cloud desktop hours are used up. The full allowance starts with the first payment.",
- "place.view.ccAtOnce.short": "In use",
- "place.view.ccAtOnce.lineOne": "Your {plan} plan includes 1 cloud desktop, and {holders} has it.",
- "place.view.ccAtOnce.lineMany": "Your {plan} plan includes {max} cloud desktops, and {holders} have them.",
- "place.view.ccAtOnce.lineUnknown": "All the cloud desktops your plan includes are in use.",
- "place.view.ccUnavailable.short": "Not available now",
- "place.view.ccUnavailable.line": "Cloud desktops can't start right now. It isn't anything you did.",
- "place.view.ccEnded.short": "Plan ended",
- "place.view.ccEnded.line": "Your MausBot Cloud plan has ended, so cloud desktops are off.",
- "place.view.ccNoStart.short": "Didn't start",
- "place.view.ccNoStart.line": "{bot}'s cloud desktop didn't start.",
- "place.view.ccClearing.short": "Clearing up",
- "place.view.ccClearing.line": "{bot}'s previous cloud desktop is still being removed.",
- "place.view.ccProvider.short": "Couldn't start",
- "place.view.ccProvider.line": "Your Boat account couldn't start {bot}'s cloud desktop: {words}",
- "place.view.ccOnMyCloud.short": "For Cloud bots",
- "place.view.ccOnMyCloud.line": "Cloud desktops from your plan work for Cloud bots for now.",
- "place.view.ccNeedsKey.short": "Connect Boat first",
- "place.view.ccNeedsKey.line": "Bots here can get their own cloud desktops from Boat, a paid service.",
- "place.view.vps.short": "Your own machine",
- "place.view.vps.line": "Uses your own Linux machine, connected over SSH.",
- "place.view.browser.short": "Web pages only",
- "place.view.browser.line": "Works in the built-in browser only: web pages, no desktop apps.",
- "place.view.browserOff.short": "Switched off",
- "place.view.browserOff.line": "The bot's own browser is switched off, so it can't open web pages.",
- "place.view.browserCannot.short": "Not with this model",
- "place.view.browserCannot.line": "{model} can't use the built-in browser.",
- "place.view.local.short": "Your screen",
- "place.view.local.line": "Uses your screen, mouse, and keyboard.",
- "place.view.localUnavailable.short": "Can't use it yet",
- "place.view.localUnavailable.line": "{reason}",
- "place.view.vm.short": "Separate from your screen",
- "place.view.vm.line": "A private Linux desktop on this device, separate from your own screen.",
- "place.view.vmCannot.short": "Not with this model",
- "place.view.vmCannot.line": "{model} can't use a private desktop. Choose a model that can, such as Claude or ChatGPT.",
- "place.view.placeFailed.short": "Didn't start",
- "place.view.placeFailed.line": "{cause}",
- "place.view.off.short": "No screen",
- "place.view.off.line": "{bot} has no screen. It can still chat and do anything that doesn't need one.",
- "place.action.chooseModel": "Choose a model",
- "place.action.openTools": "Change what {bot} can use",
- "place.action.signIn": "Sign in",
- "place.action.start": "Start it now",
- "place.action.wake": "Wake it now",
- "place.action.watch": "Watch",
- "place.action.seePlan": "See your plan",
- "place.action.manageComputers": "Manage cloud desktops",
- "place.action.tryAgain": "Try again",
- "place.action.openMyCloud": "Open the Cloud",
- "place.action.addBoatKey": "Connect Boat",
- "place.action.turnOnBrowser": "Turn on the browser",
- "place.action.openTeamMap": "Open Team map",
- "place.action.openVmSettings": "Private desktop settings",
- "place.action.clearPin": "Clear this conversation's place",
- "place.action.usePlace": "Use {place}",
- "place.action.changeRoutine": "Change where it runs",
- "place.action.openComputerPanel": "Open the Screen panel",
- "place.askAdmin": "Ask an Admin to change it.",
- "place.backOnAuto": "This conversation is back on Auto.",
-} as const;
-export type PlaceKey = keyof typeof PLACE_EN;
-
-/** A stored row's next action as one English sentence: what a phone, which
- * shows only the row's words, reads instead of a button. English only, like
- * the row it ends. */
-export const PLACE_WORDS: Record<PlaceActionId, string> = {
- "choose-model": "Choose another model in {bot}'s settings.",
- "open-tools": "Change what {bot} can use in its settings.",
- "sign-in": "Sign in to {engine} in Settings.",
- start: "Start it from the Screen panel.",
- wake: "Wake it from the Screen panel.",
- watch: "Watch it from the Screen panel.",
- "see-plan": "See your plan on the Plan page.",
- "manage-computers": "Manage your cloud desktops in Settings → Bot desktops.",
- "try-again": "Try again.",
- "open-my-cloud": "Open My Cloud from the menu at the top of the sidebar.",
- "add-boat-key": "Connect your Boat account in AI › Other services.",
- "turn-on-browser": "Turn on the built-in browser in the Screen panel.",
- "open-team-map": "Open Team map to manage it.",
- "open-vm-settings": "Check it in Settings → Bot desktops.",
- "clear-pin": "Clear this conversation's place in the composer to continue.",
- "change-routine": "Change where this routine runs.",
- "open-computer-panel": "Check it in the Screen panel.",
-};
-
-/** The words a person reads, in some language: the app passes its t(), the
- * server the English mirror. */
-export type PlaceTranslate = (key: PlaceKey, params?: Record<string, string | number>) => string;
-
-function fill(template: string, params: Record<string, string | number> = {}): string {
- return template.replace(/\{(\w+)\}/g, (whole, name: string) => (Object.hasOwn(params, name) ? String(params[name]) : whole));
-}
-
-export const english: PlaceTranslate = (key, params) => fill(PLACE_EN[key], params);
-
-/** Each state's key segment, short and line keys, and own action. */
-const STATE: Record<PlaceState, { key: string; action: PlaceActionId | null }> = {
- auto: { key: "auto", action: null },
- "auto-team": { key: "autoTeam", action: "open-team-map" },
- "cc-cannot": { key: "ccCannot", action: "choose-model" },
- "cc-tools-off": { key: "ccToolsOff", action: "open-tools" },
- "cc-sign-in": { key: "ccSignIn", action: "sign-in" },
- "cc-new": { key: "ccNew", action: "start" },
- "cc-starting": { key: "ccStarting", action: "watch" },
- "cc-waking": { key: "ccWaking", action: "watch" },
- "cc-on": { key: "ccOn", action: "watch" },
- "cc-asleep": { key: "ccAsleep", action: "wake" },
- "cc-no-hours": { key: "ccNoHours", action: "see-plan" },
- "cc-at-once": { key: "ccAtOnce", action: "manage-computers" },
- "cc-unavailable": { key: "ccUnavailable", action: "try-again" },
- "cc-ended": { key: "ccEnded", action: "see-plan" },
- "cc-no-start": { key: "ccNoStart", action: "try-again" },
- "cc-clearing": { key: "ccClearing", action: "try-again" },
- "cc-provider": { key: "ccProvider", action: "try-again" },
- "cc-on-my-cloud": { key: "ccOnMyCloud", action: "open-my-cloud" },
- "cc-needs-key": { key: "ccNeedsKey", action: "add-boat-key" },
- vps: { key: "vps", action: null },
- browser: { key: "browser", action: null },
- "browser-off": { key: "browserOff", action: "turn-on-browser" },
- "browser-cannot": { key: "browserCannot", action: "choose-model" },
- local: { key: "local", action: null },
- "local-unavailable": { key: "localUnavailable", action: null },
- vm: { key: "vm", action: "open-vm-settings" },
- "vm-cannot": { key: "vmCannot", action: "choose-model" },
- "place-failed": { key: "placeFailed", action: "open-computer-panel" },
- off: { key: "off", action: null },
-};
-
-/** A passing cause: nothing to fix, so where the place came from decides the
- * way on (sourceAction). Every other state's action removes its cause. */
-const PASSING: ReadonlySet<PlaceState> = new Set(["cc-unavailable", "cc-no-start", "cc-clearing", "cc-provider", "place-failed"]);
-
-/** Actions that change a setting, a sign-in or the plan: a User can't take
- * them, so the line ends "Ask an Admin to change it." instead. */
-const ADMIN_ONLY: ReadonlySet<PlaceActionId> = new Set([
- "choose-model", "open-tools", "sign-in", "see-plan", "manage-computers", "open-my-cloud",
- "add-boat-key", "turn-on-browser", "open-team-map", "open-vm-settings", "change-routine",
-]);
-/** Starting or waking a computer early: a User's own message does it, so
- * there is nothing to ask anyone for. */
-const ADMIN_SHORTCUT: ReadonlySet<PlaceActionId> = new Set(["start", "wake"]);
-
-const ACTION_KEY: Record<PlaceActionId, PlaceKey> = {
- "choose-model": "place.action.chooseModel",
- "open-tools": "place.action.openTools",
- "sign-in": "place.action.signIn",
- start: "place.action.start",
- wake: "place.action.wake",
- watch: "place.action.watch",
- "see-plan": "place.action.seePlan",
- "manage-computers": "place.action.manageComputers",
- "try-again": "place.action.tryAgain",
- "open-my-cloud": "place.action.openMyCloud",
- "add-boat-key": "place.action.addBoatKey",
- "turn-on-browser": "place.action.turnOnBrowser",
- "open-team-map": "place.action.openTeamMap",
- "open-vm-settings": "place.action.openVmSettings",
- "clear-pin": "place.action.clearPin",
- "change-routine": "place.action.changeRoutine",
- "open-computer-panel": "place.action.openComputerPanel",
-};
-
-export function placeState(facts: PlaceFacts): { state: PlaceState; params: PlaceParams } {
- const bot = facts.bot;
- const model = facts.engine.model || facts.engine.name;
- if (facts.place === "off") return { state: "off", params: { bot } };
- if (facts.place === "auto") {
- return facts.teamComputer
- ? { state: "auto-team", params: { bot, computer: facts.teamComputer } }
- : { state: "auto", params: { bot } };
- }
- if (facts.place === "browser") {
- if (!facts.engine.browser) return { state: "browser-cannot", params: { bot, model } };
- return facts.browserOn ? { state: "browser", params: { bot } } : { state: "browser-off", params: { bot } };
- }
- if (facts.place === "local") {
- return facts.local?.ready === false
- ? { state: "local-unavailable", params: { bot, reason: facts.local.reason ?? "" } }
- : { state: "local", params: { bot } };
- }
- if (facts.place === "vm") {
- return facts.engine.computer ? { state: "vm", params: { bot } } : { state: "vm-cannot", params: { bot, model } };
- }
- // On the person's own server (VPS) or on Boat, one rule for both.
- const vps = facts.backend === "vps";
- if (!facts.engine.computer) return { state: "cc-cannot", params: { bot, model } };
- if (!facts.toolsAllowComputer) return { state: "cc-tools-off", params: { bot } };
- if (!facts.engine.signedIn) return { state: "cc-sign-in", params: { bot, engine: facts.engine.name } };
- if (vps) return { state: "vps", params: { bot } };
- if (facts.refusal) return { state: facts.refusal.state, params: { bot, ...facts.refusal.params } };
- if (facts.boat === "none") {
- // My Cloud always has the plan's computers while the plan is active.
- if (facts.server === "my-cloud") return { state: "cc-unavailable", params: { bot } };
- return { state: facts.plan ? "cc-on-my-cloud" : "cc-needs-key", params: { bot } };
- }
- switch (facts.computer) {
- case "starting": return { state: "cc-starting", params: { bot } };
- case "waking": return { state: "cc-waking", params: { bot } };
- case "on": return { state: "cc-on", params: { bot } };
- case "asleep": return { state: "cc-asleep", params: { bot } };
- default: return { state: "cc-new", params: { bot } };
- }
-}
-
-/** Where the person goes when a passing cause stops a place: try again in
- * place, clear the pin that holds this conversation, change where the
- * routine runs. A room member's turn has no retry of its own. */
-function sourceAction(source: PlaceSource, state: PlaceState): PlaceActionId | null {
- switch (source) {
- case "works-on": return state === "place-failed" ? "open-computer-panel" : "try-again";
- case "auto-pin": return "try-again";
- case "pin": return "clear-pin";
- case "routine": return "change-routine";
- case "room": return null;
- }
-}
-
-function lineKey(state: PlaceState, params: PlaceParams, server?: ServerKind): PlaceKey {
- const segment = STATE[state].key;
- if (state === "auto") {
- return server === "my-cloud" ? "place.view.auto.lineMyCloud" : server === "linux" || server === "remote" ? "place.view.auto.lineLinux" : "place.view.auto.lineDesktop";
- }
- if (state === "cc-sign-in" && server === "my-cloud") return "place.view.ccSignIn.lineMyCloud";
- if (state === "cc-no-hours" && params.trial) return "place.view.ccNoHours.lineTrial";
- // A refusal read from a code alone has no numbers or names to give.
- if (state === "cc-no-hours" && (params.hours === undefined || !params.month)) return "place.view.ccNoHours.lineUnknown";
- if (state === "cc-at-once") {
- if (!params.holders?.length || !params.plan || params.max === undefined) return "place.view.ccAtOnce.lineUnknown";
- return params.max === 1 ? "place.view.ccAtOnce.lineOne" : "place.view.ccAtOnce.lineMany";
- }
- return `place.view.${segment}.line` as PlaceKey;
-}
-
-/** Join names the way a sentence lists them, in the reader's language. */
-export function listNames(names: readonly string[], locale = "en"): string {
- try {
- return new Intl.ListFormat(locale, { style: "long", type: "conjunction" }).format(names);
- } catch {
- return names.join(", ");
- }
-}
-
-function templateParams(params: PlaceParams, locale: string): Record<string, string | number> {
- const out: Record<string, string | number> = {};
- for (const [name, value] of Object.entries(params)) {
- if (value === undefined) continue;
- out[name] = Array.isArray(value) ? listNames(value, locale) : value;
- }
- return out;
-}
-
-export interface PlaceContext {
- server?: ServerKind;
- role: "admin" | "user";
- mode?: "simple" | "advanced";
- source?: PlaceSource;
- /** Simple mode words a pin's way back as "Use {place}", the grid's own label. */
- worksOnLabel?: string;
- translate?: PlaceTranslate;
- locale?: string;
-}
-
-/** One state, worded: its short label, its one line and its one action. */
-export function placeViewOf(state: PlaceState, params: PlaceParams, context: PlaceContext): PlaceView {
- const translate = context.translate ?? english;
- const values = templateParams(params, context.locale ?? "en");
- const segment = STATE[state].key;
- let line = translate(lineKey(state, params, context.server), values);
- let action: PlaceActionId | null = context.source && PASSING.has(state) ? sourceAction(context.source, state) : STATE[state].action;
- // A failed row never offers what only the panel can do on the spot.
- if (context.source && (action === "start" || action === "wake" || action === "watch")) action = null;
- if (context.source === "auto-pin") line = `${line} ${translate("place.backOnAuto")}`;
- // Simple mode leaves Local VM setup to Advanced.
- if (action === "open-vm-settings" && context.mode === "simple") action = null;
- if (action && context.role === "user" && ADMIN_SHORTCUT.has(action)) action = null;
- if (action && context.role === "user" && ADMIN_ONLY.has(action)) {
- action = null;
- line = `${line} ${translate("place.askAdmin")}`;
- }
- // Simple mode has no composer chip, so a pin's way back is the grid's
- // choice, by the grid's own name for it.
- const label = !action ? null
- : action === "clear-pin" && context.mode === "simple" && context.worksOnLabel
- ? translate("place.action.usePlace", { place: context.worksOnLabel })
- : translate(ACTION_KEY[action], values);
- return {
- state,
- params,
- short: translate(`place.view.${segment}.short` as PlaceKey, values),
- line,
- action: action && label ? { id: action, label } : null,
- };
-}
-
-/** The view of a place from its facts. */
-export function placeView(facts: PlaceFacts, options: { translate?: PlaceTranslate; locale?: string } = {}): PlaceView {
- const { state, params } = placeState(facts);
- return placeViewOf(state, params, { server: facts.server, role: facts.role, mode: facts.mode, ...options });
-}
-
-/** A stored failed-turn row, worded for this reader. */
-export function placeRowView(row: PlaceRow, context: Omit<PlaceContext, "source">): PlaceView {
- return placeViewOf(row.state, row.params, { ...context, source: row.source });
-}
-
-/** What the server stores as the row's words: the line and its action as a
- * sentence, in English, so a phone that reads only the words knows both. */
-export function placeRowText(row: PlaceRow, server?: ServerKind): string {
- const view = placeViewOf(row.state, row.params, { server, role: "admin", source: row.source });
- if (!view.action) return view.line;
- const words = row.source === "auto-pin" && view.action.id === "try-again"
- ? "Send your message again."
- : fill(PLACE_WORDS[view.action.id], templateParams(row.params, "en"));
- return `${view.line} ${words}`;
-}
-
-
-const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] as const;
-const MONTH = `(${MONTHS.join("|")})`;
-const HOURS_USED = new RegExp(`Your (.+?) plan's (\\d+) cloud computer hours for \\w+ are used up\\. They reset on 1 ${MONTH}`);
-const TRIAL_HOURS_USED = new RegExp(`Your (.+?) free trial's (\\d+) cloud computer hours are used up\\. Your full allowance starts with your first payment on (\\d{1,2}) (${MONTHS.map((name) => name.slice(0, 3)).join("|")})`);
-const AT_ONCE = /Your (.+?) (plan|free trial) includes (\d+) cloud computers? at once/;
-const TOO_OFTEN = /(?:started|woken) too often\. Try again (in a minute|in an hour|tomorrow)/;
-const WINDOWS = { "in a minute": "minute", "in an hour": "hour", tomorrow: "day" } as const;
-const PASSING_WORDS = [
- /cloud computers are busy right now/i, /temporarily unavailable/i, /can't be checked right now/i, /could not be reached/i,
- /returned an unexpected answer/i, /could not complete that request/i, /started too often/i, /woken too often/i,
- /included with your Cloud plan aren't available/i, /are not available right now/i, /fetch failed/i, /ECONNREFUSED/,
- /rate-limiting/i, /\b50[234]\b/,
-];
-const NO_START_WORDS = [
- /did not become ready/i, /desktop link could not be created/i, /could not be created or reached/i, /did not wake/i,
- /no computer yet/i, /didn't start in time/i,
-];
-const CLEARING_WORDS = [/is being deleted/i, /previous cloud computer deletion/i, /deletion was not confirmed/i, /deletion is still being reconciled/i];
-
-/** Why the Admin turned a start of a plan's cloud desktop away, by its own limits. */
-export const CLOUD_LIMIT_REASONS = ["hours_used", "at_once", "too_many_starts", "usage_unavailable"] as const;
-export type CloudLimitReason = (typeof CLOUD_LIMIT_REASONS)[number];
-
-/** The Admin's refusal of a start, beside its code and sentence: `reason`;
- * `trial` while the Cloud is on a free trial; the plan's name; the limit and
- * what is used of it; when it lifts (ISO: for a trial's hours, its first
- * payment); and, for starts, the window whose limit was reached. */
-export interface CloudLimit {
- reason: CloudLimitReason;
- trial?: boolean;
- plan?: string;
- limit?: number;
- used?: number;
- resetsAt?: string;
- window?: "minute" | "hour" | "day";
-}
-
-/** A refusal body's limit fields, at its top or in its `error`; undefined
- * from an Admin that sends no `reason`, or one this app doesn't know. */
-export function cloudLimitFromBody(body: unknown): CloudLimit | undefined {
- const top = body && typeof body === "object" ? body as Record<string, unknown> : undefined;
- const nested = top?.error && typeof top.error === "object" ? top.error as Record<string, unknown> : undefined;
- const fields = typeof top?.reason === "string" ? top : nested;
- const reason = fields?.reason;
- if (!fields || !(CLOUD_LIMIT_REASONS as readonly unknown[]).includes(reason)) return undefined;
- const count = (value: unknown) => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : undefined;
- const limit = count(fields.limit), used = count(fields.used);
- const plan = typeof fields.plan === "string" && fields.plan.length <= 40 ? fields.plan : undefined;
- const resetsAt = typeof fields.resetsAt === "string" && !Number.isNaN(Date.parse(fields.resetsAt)) ? fields.resetsAt : undefined;
- const window = fields.window === "minute" || fields.window === "hour" || fields.window === "day" ? fields.window : undefined;
- return {
- reason: reason as CloudLimitReason, ...(fields.trial === true ? { trial: true } : {}), ...(plan ? { plan } : {}),
- ...(limit !== undefined ? { limit } : {}), ...(used !== undefined ? { used } : {}), ...(resetsAt ? { resetsAt } : {}), ...(window ? { window } : {}),
- };
-}
-
-type CloudFailure = { message: string; code?: string; status?: number; limit?: CloudLimit };
-type LimitRead = { reason: CloudLimitReason; trial: boolean; plan?: string; max?: number; month?: string; resets?: string; window?: CloudLimit["window"] };
-
-function readLimit(failure: CloudFailure): LimitRead | null {
- const { limit, code } = failure;
- const message = failure.message.trim();
- if (limit) {
- const at = limit.resetsAt ? new Date(limit.resetsAt) : null;
- const month = at ? MONTHS[at.getUTCMonth()] : undefined;
- return {
- reason: limit.reason, trial: limit.trial === true, ...(limit.plan ? { plan: limit.plan } : {}), ...(limit.limit !== undefined ? { max: limit.limit } : {}),
- ...(at && month && !limit.trial ? { month } : {}),
- ...(at && month ? { resets: `${at.getUTCDate()} ${limit.trial ? month.slice(0, 3) : month}` } : {}),
- ...(limit.window ? { window: limit.window } : {}),
- };
- }
- if ((CLOUD_LIMIT_REASONS as readonly unknown[]).includes(code)) return { reason: code as CloudLimitReason, trial: false };
- const hours = HOURS_USED.exec(message);
- if (hours) return { reason: "hours_used", trial: false, plan: hours[1], max: Number(hours[2]), month: hours[3], resets: `1 ${hours[3]}` };
- const trialHours = TRIAL_HOURS_USED.exec(message);
- if (trialHours) return { reason: "hours_used", trial: true, plan: trialHours[1], max: Number(trialHours[2]), resets: `${trialHours[3]} ${trialHours[4]}` };
- const atOnce = AT_ONCE.exec(message);
- if (atOnce) return { reason: "at_once", trial: atOnce[2] === "free trial", plan: atOnce[1], max: Number(atOnce[3]) };
- const often = TOO_OFTEN.exec(message);
- if (often) return { reason: "too_many_starts", trial: false, window: WINDOWS[often[1] as keyof typeof WINDOWS] };
- if (code === "usage_unavailable") return { reason: "usage_unavailable", trial: false };
- return null;
-}
-
-/** The Admin's refusal of a start, worded for the bot, so it never says one
- * limit is another; null for any other failure. */
-export function cloudLimitSentence(failure: CloudFailure): string | null {
- const limit = readLimit(failure);
- switch (limit?.reason) {
- case "hours_used":
- return limit.trial
- ? `This Cloud's free trial cloud computer hours are used up${limit.resets ? `; they come back on ${limit.resets}` : ""}.`
- : `This Cloud's cloud computer hours for this month are used up${limit.resets ? `; they reset on ${limit.resets}` : ""}.`;
- case "at_once":
- return "This Cloud already has as many cloud computers running as its plan allows.";
- case "too_many_starts":
- return `Cloud computers were started too often; try again ${limit.window === "minute" ? "in a minute" : limit.window === "day" ? "tomorrow" : limit.window === "hour" ? "in an hour" : "later"}.`;
- case "usage_unavailable":
- return "Cloud computer use can't be checked right now.";
- default:
- return null;
- }
-}
-
-/** The Admin's `reason` comes first, then its codes; from an Admin that
- * sends neither, its English is read. `included`: the plan's computers, not
- * the person's own Boat key, whose provider's words are shown as they are. */
-export function cloudRefusal(failure: CloudFailure, included: boolean): { state: PlaceState; params: PlaceParams } {
- const message = failure.message.trim();
- const code = failure.code;
- const limit = readLimit(failure);
- if (limit?.reason === "hours_used") {
- if (limit.trial) return { state: "cc-no-hours", params: { trial: true } };
- return { state: "cc-no-hours", params: limit.plan && limit.max !== undefined && limit.month ? { plan: limit.plan, hours: limit.max, month: limit.month } : {} };
- }
- if (limit?.reason === "at_once") {
- return { state: "cc-at-once", params: limit.plan && limit.max !== undefined ? { plan: limit.plan, max: limit.max } : {} };
- }
- if (code === "subscription_inactive") return { state: "cc-ended", params: {} };
- if (limit || code === "rate_limited" || code === "usage_unavailable" || code === "service_unavailable"
- || code === "upstream_unavailable" || code === "invalid_response" || code === "upstream_error") {
- return { state: "cc-unavailable", params: {} };
- }
- // A start that failed and left its new computer still being removed
- // didn't start; the next attempt meets the removal.
- if (NO_START_WORDS.some((words) => words.test(message))) return { state: "cc-no-start", params: {} };
- if (CLEARING_WORDS.some((words) => words.test(message))) return { state: "cc-clearing", params: {} };
- if ((failure.status ?? 0) >= 500 || PASSING_WORDS.some((words) => words.test(message))) return { state: "cc-unavailable", params: {} };
- if (!included && message) return { state: "cc-provider", params: { words: message.replace(/[\s.]+$/, "") + "." } };
- return { state: "cc-no-start", params: {} };
-}
+export * from "../packages/phone-protocol/src/place-view.ts";
diff --git a/shared/profile-request.ts b/shared/profile-request.ts
index fa14c96ec4..58f3654a88 100644
--- a/shared/profile-request.ts
+++ b/shared/profile-request.ts
@@ -1,35 +1 @@
-/**
- * Durable payload carried by a profile confirmation card (propose_profile).
- *
- * The fields a bot may propose for itself (`cwd` is the working folder its
- * tools run in; "" means its private workspace; `notifications` and
- * `speakReplies` are the alert and voice toggles). `before` is the snapshot
- * the user was shown; `expectedRevision` is a hash of the target's whole
- * profile at proposal time so a confirmation fails closed if anything moved.
- */
-export const PROFILE_REQUEST_FIELDS = ["name", "title", "description", "soul", "cwd", "notifications", "speakReplies"] as const;
-export type ProfileRequestField = (typeof PROFILE_REQUEST_FIELDS)[number];
-export type ProfileRequestChanges = Partial<Record<Exclude<ProfileRequestField, "notifications" | "speakReplies">, string>> &
- Partial<Record<"notifications" | "speakReplies", boolean>>;
-
-export interface ProfileRequestCardData {
- version: 1;
- requestId: string;
- /** The proposing conversation; authority is fixed here. */
- botId: string;
- threadId: string;
- /** Whose profile changes: the proposer, or a section peer named by a Chief. */
- targetBotId: string;
- targetName: string;
- createdAt: number;
- reason: string;
- changes: ProfileRequestChanges;
- before: ProfileRequestChanges;
- expectedRevision: string;
- appliedAt?: number;
- /** Written when the change applied without a person: the profile's
- * revision right after it, so Undo refuses once anything moved. Absent
- * when the before values could not be kept exactly (credential-shaped
- * text is scrubbed from cards), which means no Undo. */
- undo?: { appliedRevision: string };
-}
+export * from "../packages/phone-protocol/src/profile-request.ts";
diff --git a/shared/published-page.ts b/shared/published-page.ts
index 560d4a86aa..c926303eed 100644
--- a/shared/published-page.ts
+++ b/shared/published-page.ts
@@ -1,36 +1 @@
-/** A page a bot published to a public link, as its chat card shows it (WireMessage.publishedPage). The message's `text`
- * says the same in words, with the link, for every client that does not draw the card. */
-export interface PublishedPageCard {
- /** live: the link works, or may work when `uncertain` is true. unpublished: its owner took it down. limit: the plan's
- * pages are used up, so nothing was published; `message` says so and `upgrade` offers a bigger plan. */
- state: "live" | "unpublished" | "limit";
- /** The upload's answer was lost. The page may be live and can still be unpublished. */
- uncertain?: boolean;
- title: string;
- pageId?: string;
- url?: string;
- /** This account's pages and its plan's limit after this publish, as "3 of 5 pages". */
- usage?: { pages: number; limit: number };
- message?: string;
- upgrade?: boolean;
- /** limit cards: "free" (signed in, no Cloud) or the Cloud plan's tier. */
- plan?: string;
-}
-
-/** The MausBot pages Worker's page ids: one DNS label of lowercase letters and digits. */
-export const PAGE_ID = /^[a-z0-9]{20,63}$/;
-
-/** What a page's files may be, by extension, and the Content-Type each is served with: the same list as the pages
- * Worker's (openmaus-cloud pages-worker/src/files.ts refuses the rest). */
-export const PAGE_FILE_TYPES: Readonly<Record<string, string>> = {
- html: "text/html; charset=utf-8", htm: "text/html; charset=utf-8", css: "text/css; charset=utf-8", js: "text/javascript; charset=utf-8",
- mjs: "text/javascript; charset=utf-8", json: "application/json; charset=utf-8", txt: "text/plain; charset=utf-8", csv: "text/csv; charset=utf-8",
- tsv: "text/tab-separated-values; charset=utf-8", ndjson: "application/x-ndjson; charset=utf-8", md: "text/markdown; charset=utf-8",
- geojson: "application/geo+json", topojson: "application/json; charset=utf-8",
- parquet: "application/vnd.apache.parquet", arrow: "application/vnd.apache.arrow.file", svg: "image/svg+xml",
- png: "image/png", jpg: "image/jpeg", jpeg: "image/jpeg", gif: "image/gif", webp: "image/webp", avif: "image/avif", ico: "image/x-icon",
- woff: "font/woff", woff2: "font/woff2", ttf: "font/ttf", otf: "font/otf",
-};
-export const PAGE_FILE_EXTENSIONS: ReadonlySet<string> = new Set(Object.keys(PAGE_FILE_TYPES));
-export const PAGE_MAX_BYTES = 5 * 1024 * 1024;
-export const PAGE_MAX_FILES = 200;
+export * from "../packages/phone-protocol/src/published-page.ts";
diff --git a/shared/reactions.ts b/shared/reactions.ts
index 72a78ac14c..a6ef3b741b 100644
--- a/shared/reactions.ts
+++ b/shared/reactions.ts
@@ -1,34 +1 @@
-// Reactions on chat messages. A 👍 or 👎 on a bot's message is the person's reply to it; the others say how they feel.
-
-/** Every reaction a client offers and the server accepts, in the order clients show them. */
-export const REACTIONS = ["👍", "👎", "❤️", "😂", "🎉", "👀"] as const;
-export type Reaction = (typeof REACTIONS)[number];
-
-/** What a reaction did, as POST /api/threads/:threadId/messages/:messageId/reactions reports it: a turn `started` with
- * it as the person's reply to that message, or the reply waits `queued` behind the running turn; the open card on the
- * message was `answered`; a feeling the bot reads with its next turn (`noted`); or nothing reached a bot. */
-export type ReactionDelivery = "started" | "queued" | "answered" | "noted" | "none";
-
-/** 👍 answers yes and 👎 answers no; any other reaction answers nothing. */
-export function reactionAnswer(emoji: string | null | undefined): "yes" | "no" | null {
- return emoji === "👍" ? "yes" : emoji === "👎" ? "no" : null;
-}
-
-/** Slack sends a reaction's short name. Telegram, Discord and WhatsApp send the emoji itself. */
-const SLACK_NAMES: Readonly<Record<string, Reaction>> = {
- "+1": "👍", thumbsup: "👍", "-1": "👎", thumbsdown: "👎", heart: "❤️", joy: "😂", tada: "🎉", eyes: "👀",
-};
-const SLACK_NAME = /^:?([a-z0-9_+-]+)(?:::skin-tone-[2-6])?:?$/;
-/** Skin tones and the emoji presentation selector, which each platform adds or drops on its own. */
-const VARIANTS = /[\u{1F3FB}-\u{1F3FF}]|\uFE0F/gu;
-
-/** The reaction a person meant, from any client or chat channel: the emoji in any skin tone or presentation, or
- * Slack's name for it. Null for anything outside REACTIONS. */
-export function normalizeReaction(raw: unknown): Reaction | null {
- if (typeof raw !== "string" || raw.length > 64) return null;
- const value = raw.trim();
- const name = SLACK_NAME.exec(value.toLowerCase())?.[1];
- if (name) return Object.hasOwn(SLACK_NAMES, name) ? SLACK_NAMES[name]! : null;
- const bare = value.replace(VARIANTS, "");
- return REACTIONS.find((reaction) => reaction.replace(VARIANTS, "") === bare) ?? null;
-}
+export * from "../packages/phone-protocol/src/reactions.ts";
diff --git a/shared/reply-style.ts b/shared/reply-style.ts
index 5d8f24671c..c5575dfbd4 100644
--- a/shared/reply-style.ts
+++ b/shared/reply-style.ts
@@ -1,44 +1 @@
-/** An absent style means "default". */
-export const REPLY_STYLES = ["default", "conversational"] as const;
-export type ReplyStyle = (typeof REPLY_STYLES)[number];
-
-export function isConversational(style: ReplyStyle | undefined): boolean {
- return style === "conversational";
-}
-
-const FENCE = /^ {0,3}(`{3,}|~{3,})/;
-const LIST_OR_TABLE = /^ {0,3}([-*+]\s|\d{1,3}[.)]\s|\|)/;
-
-/** Splits on blank lines but never inside a code fence, and keeps one loose list or table together. An unclosed fence keeps the rest in the last part, so finished parts never change. */
-export function splitConversationalReply(text: string): string[] {
- const parts: string[] = [];
- let current: string[] = [];
- let fence: string | null = null;
- const flush = () => {
- // Leading indentation can make a code block, so only trailing space goes.
- const block = current.join("\n").trimEnd();
- current = [];
- if (!block.trim()) return;
- const prev = parts.at(-1);
- if (prev !== undefined && LIST_OR_TABLE.test(block) && LIST_OR_TABLE.test(prev.split("\n").at(-1) ?? "")) {
- parts[parts.length - 1] = `${prev}\n\n${block}`;
- } else parts.push(block);
- };
- for (const line of text.split("\n")) {
- const open = FENCE.exec(line);
- if (fence) {
- current.push(line);
- if (open && open[1][0] === fence[0] && open[1].length >= fence.length && line.trim() === open[1]) fence = null;
- continue;
- }
- if (open) {
- fence = open[1];
- current.push(line);
- continue;
- }
- if (!line.trim()) flush();
- else current.push(line);
- }
- flush();
- return parts;
-}
+export * from "../packages/phone-protocol/src/reply-style.ts";
diff --git a/shared/routine-request.ts b/shared/routine-request.ts
index 2edcfd2899..af6edf4e65 100644
--- a/shared/routine-request.ts
+++ b/shared/routine-request.ts
@@ -1,130 +1 @@
-/**
- * Durable payload carried by a chat routine confirmation card. Tool input
- * arrives normalized (milliseconds, numeric weekdays, credential-scrubbed
- * text), so a confirmation survives a restart without asking the model again.
- */
-
-import type { LimitResetRepeat } from "./limit-reset.ts";
-import type { RoutineCronSchedule } from "./routine-schedule.ts";
-
-export type RoutineRequestRunOn = "maus" | "cloud";
-
-export interface RoutineRequestIntervalWindow {
- start: string;
- end: string;
-}
-
-export type RoutineRequestSchedule =
- | { type: "once"; at: number }
- /** The time is the engine's, derived when the routine is saved. */
- | { type: "limit_reset"; engine: string; repeat: LimitResetRepeat }
- | { type: "daily"; time: string; weekdays: number[] }
- | RoutineCronSchedule
- | {
- type: "interval";
- everyMinutes: number;
- anchorAt?: number;
- /** Local weekdays (Sunday = 0). Missing means every day. */
- weekdays?: number[];
- /** Local wall-clock window. Missing means all day. */
- window?: RoutineRequestIntervalWindow;
- /** Inclusive epoch-millisecond cutoff. Missing means never. */
- endsAt?: number;
- };
-
-export type RoutineRequestScheduleChanges =
- | Exclude<RoutineRequestSchedule, { type: "interval" }>
- | {
- type: "interval";
- everyMinutes: number;
- anchorAt?: number;
- /** `null` explicitly restores the every-day default. */
- weekdays?: number[] | null;
- /** `null` explicitly restores the all-day default. */
- window?: RoutineRequestIntervalWindow | null;
- /** `null` explicitly removes an existing end date. */
- endsAt?: number | null;
- };
-
-export interface RoutineRequestDefinition {
- name: string;
- instructions: string;
- schedule: RoutineRequestSchedule;
- runOn: RoutineRequestRunOn;
- /** Calendar/display length only: it does not stop an active run. */
- durationMinutes: number;
- /** Optional safety cap for active work. Missing means no timeout. */
- timeoutMinutes?: number;
- /** Carry the previous run's report into the next run. */
- continuity?: boolean;
- /** Skip by default, or keep at most one scheduled run waiting. */
- overlap?: "skip" | "queue";
- /** Also run once each time OpenMausBot starts. Repeating routines only. */
- runOnStartup?: boolean;
-}
-
-export type RoutineRequestChanges =
- & Omit<Partial<RoutineRequestDefinition>, "schedule" | "timeoutMinutes">
- & {
- schedule?: RoutineRequestScheduleChanges;
- /** `null` removes an existing safety cap. */
- timeoutMinutes?: number | null;
- };
-
-/** Another bot in the proposer's section that this proposal targets: a
- * routine scheduled for it, or one of its routines being changed. Captured
- * (id + display name) when the card is created so the card stays meaningful
- * if the bot is later renamed; authority over the card remains with the
- * proposing conversation. */
-export interface RoutineRequestTargetBot {
- botId: string;
- name: string;
-}
-
-export type RoutineRequestOperation =
- | { action: "create"; routine: RoutineRequestDefinition; forBot?: RoutineRequestTargetBot }
- | { action: "update"; routineId: string; expectedUpdatedAt: number; changes: RoutineRequestChanges; forBot?: RoutineRequestTargetBot }
- | { action: "pause"; routineId: string; expectedUpdatedAt: number; forBot?: RoutineRequestTargetBot }
- | { action: "resume"; routineId: string; expectedUpdatedAt: number; forBot?: RoutineRequestTargetBot }
- | { action: "run_now"; routineId: string; expectedUpdatedAt: number; forBot?: RoutineRequestTargetBot }
- | { action: "delete"; routineId: string; expectedUpdatedAt: number; forBot?: RoutineRequestTargetBot };
-
-/** A routine as it stood before a change applied without a person, so Undo
- * can put it back. Room goals keep their room; attachments are not kept, so
- * a routine that has any is not offered an Undo for its update or delete. */
-export interface RoutineRequestSnapshot extends RoutineRequestDefinition {
- enabled: boolean;
- target?: "room-goal";
- groupId?: string;
- resultsThreadId?: string;
-}
-
-/** Written on a card whose change applied without a person (the bot's own
- * routine, or Full access): what the one-line receipt shows, and what its
- * Undo needs. */
-export interface RoutineRequestUndo {
- /** The routine's name and schedule as the change left them. */
- name: string;
- schedule?: RoutineRequestSchedule;
- /** The routine's revision right after the change; Undo refuses once it moved. */
- appliedUpdatedAt?: number;
- /** The routine before an update or a delete. */
- before?: RoutineRequestSnapshot;
- /** On a Cloud home: the routine was the owner's before the change. */
- ownersBefore?: boolean;
-}
-
-export interface RoutineRequestCardData {
- version: 1;
- /** Also used as the scheduler's idempotency key after confirmation. */
- requestId: string;
- /** Authority is fixed when the card is created; an agent cannot redirect it later. */
- botId: string;
- threadId: string;
- createdAt: number;
- operation: RoutineRequestOperation;
- /** Written after a successful confirmation. */
- appliedAt?: number;
- resultId?: string;
- undo?: RoutineRequestUndo;
-}
+export * from "../packages/phone-protocol/src/routine-request.ts";
diff --git a/shared/routine-run.ts b/shared/routine-run.ts
index e6bfc6cbbb..0e70ec11c0 100644
--- a/shared/routine-run.ts
+++ b/shared/routine-run.ts
@@ -1,49 +1 @@
-/** Durable, non-actionable projection of one background routine run.
- *
- * The provider still runs in its isolated execution task. This small card is
- * upserted into the trusted conversation that created the routine so the user
- * can see progress, results, and where to review an approval without hunting
- * through the routines calendar.
- */
-import type { RoutineRunTrigger } from "./routines.ts";
-
-export interface RoutineRunCardData {
- runId: string;
- routineId: string;
- routineName: string;
- scheduledFor?: number;
- status: "queued" | "running" | "waiting" | "completed" | "failed" | "cancelled" | "missed";
- /** Present while a queued run is being held because its target bot or room
- * is busy. The status stays queued; this is the surfaced deferral fact. */
- deferredAt?: number;
- /** Exact terminal team-goal outcome when this run targeted a room. */
- goalStatus?: "completed" | "needs-input" | "blocked" | "limit-reached" | "paused" | "stopped" | "failed";
- executionThreadId?: string;
- summary?: string;
- error?: string;
-}
-
-/** A bot line one automation run wrote into the chat it reports to: the run's
- * result, a copy of a card the run waits on (answering it there answers the
- * run), or why the run failed. The run works in its own hidden conversation,
- * `executionThreadId`, which keeps its full transcript. */
-export interface AutomationLine {
- routineId: string;
- runId: string;
- name: string;
- /** What started the run; "app" is a connected-app event, "wait" a wait's follow-up. A Bot API call starts a turn,
- * never a run, so "api" is never seen here. */
- trigger: RoutineRunTrigger | "app" | "wait";
- executionThreadId: string;
- scheduledFor: number;
- /** The run needs the person: it asked them something or cannot go on without them. */
- needsYou?: true;
- failed?: true;
- /** With `failed`: the run's reply came back; only a step it ran failed or wasn't allowed. */
- partial?: true;
- /** A run that had nothing new, posted only because this automation's line before it in the chat said a run failed. */
- recovered?: true;
- /** The card in the run's conversation this line stands for: an option card
- * is copied whole, a sign-in, connection or credential card is named. */
- copyOf?: string;
-}
+export * from "../packages/phone-protocol/src/routine-run.ts";
diff --git a/shared/routine-schedule.ts b/shared/routine-schedule.ts
index 110068c0f4..77f13e4c17 100644
--- a/shared/routine-schedule.ts
+++ b/shared/routine-schedule.ts
@@ -1,88 +1 @@
-import { Cron } from "croner";
-
-export interface RoutineCronSchedule {
- type: "cron";
- expression: string;
- /** Explicit IANA timezone; independent of the server or viewer's timezone. */
- timeZone: string;
-}
-
-const MAX_EXPRESSION_LENGTH = 256;
-const MAX_PREVIEW_RUNS = 1000;
-
-function cronCalculator(value: unknown): { schedule: RoutineCronSchedule; cron: Cron } {
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Choose a valid cron schedule");
- const input = value as Partial<RoutineCronSchedule>;
- if (input.type !== "cron" || typeof input.expression !== "string") throw new Error("Choose a valid cron schedule");
- if (Object.keys(input).some(key => !["type", "expression", "timeZone"].includes(key))) {
- throw new Error("Cron schedules accept only type, expression and timeZone; start/end dates and other restrictions are not supported");
- }
- const expression = input.expression.trim().replace(/\s+/g, " ");
- if (expression.length > MAX_EXPRESSION_LENGTH || expression.split(" ").length !== 5 || expression.includes("@")) {
- throw new Error("Cron must have five fields: minute hour day-of-month month weekday (no seconds, year, or macros)");
- }
- const timeZone = typeof input.timeZone === "string" ? input.timeZone.trim() : "";
- // Intl also accepts numeric offsets in newer runtimes. Require a named zone
- // so wall-clock schedules follow its daylight-saving rules instead.
- if (timeZone.length > 128 || !(timeZone === "UTC" || /^[A-Za-z][A-Za-z0-9_+-]*(?:\/[A-Za-z0-9_+-]+)+$/.test(timeZone))) {
- throw new Error("Choose an IANA timezone such as America/New_York, Asia/Kolkata, or UTC");
- }
- try { new Intl.DateTimeFormat("en-US", { timeZone }).format(0); }
- catch { throw new Error("Choose a valid IANA timezone such as America/New_York, Asia/Kolkata, or UTC"); }
- try {
- // Date calculator only: no callback, name, or timer. RoutineManager owns
- // dispatch, persistence, catch-up and cancellation. Croner bounds its
- // five-field search at year 3000, including impossible calendar dates.
- const cron = new Cron(expression, { timezone: timeZone, mode: "5-part", paused: true });
- return { schedule: { type: "cron", expression, timeZone }, cron };
- } catch (error) {
- throw new Error(`Invalid cron expression: ${(error as Error).message}`);
- }
-}
-
-function calculationDate(after: number): Date {
- const date = new Date(after);
- if (!Number.isFinite(after) || !Number.isFinite(date.getTime())) throw new Error("Choose a valid cron preview date");
- return date;
-}
-
-function futureRuns(cron: Cron, after: number, count: number): number[] {
- const from = calculationDate(after);
- // Croner resolves an ambiguous wall-clock time to its first occurrence.
- // If the cursor is already in the second occurrence, its first candidate
- // can therefore be in the past. Ask the same calculator for more candidates
- // and discard those, rather than moving the scheduler cursor backwards.
- // Minute precision bounds even a full-day historical timezone fold at 1440.
- const maximum = count + 1440;
- let requested = count;
- while (true) {
- const candidates = cron.nextRuns(requested, from);
- const runs: number[] = [];
- for (const date of candidates) {
- const at = date.getTime();
- if (!Number.isFinite(at)) throw new Error("The cron schedule produced an invalid date");
- if (at > (runs.at(-1) ?? after)) runs.push(at);
- if (runs.length === count) return runs;
- }
- if (candidates.length < requested || requested === maximum) return runs;
- // Sparse schedules normally need just one more candidate. Grow only when
- // needed, so a daily preview never scans years to skip one repeated hour.
- requested = Math.min(maximum, requested * 2);
- }
-}
-
-/** Normalize once at the trust boundary, rejecting impossible schedules. */
-export function normalizeCronSchedule(value: unknown, after = Date.now()): RoutineCronSchedule {
- const { schedule, cron } = cronCalculator(value);
- if (!futureRuns(cron, after, 1).length) throw new Error("This cron expression has no future runs. Choose dates that exist.");
- return schedule;
-}
-
-/** Strictly-future instants, shared by the scheduler, cards and calendar.
- * Croner's DST policy is intentional: missing clock times advance through
- * the gap, and repeated clock times use their first occurrence only. */
-export function nextCronRuns(schedule: RoutineCronSchedule, after: number, count: number): number[] {
- if (!Number.isInteger(count) || count < 1 || count > MAX_PREVIEW_RUNS) throw new Error("Choose between 1 and 1000 cron preview runs");
- const { cron } = cronCalculator(schedule);
- return futureRuns(cron, after, count);
-}
+export * from "../packages/phone-protocol/src/routine-schedule.ts";
diff --git a/shared/routines.ts b/shared/routines.ts
index cf01c5cea4..c3a956b3bd 100644
--- a/shared/routines.ts
+++ b/shared/routines.ts
@@ -1,258 +1 @@
-/** Routine wire shapes: the routine and run records as they ride the REST
- * snapshot and the `routine` / `routine.run` live frames. */
-import type { LimitResetSchedule, LimitResetScheduleInput } from "./limit-reset.ts";
-import type { RoutineCronSchedule } from "./routine-schedule.ts";
-import type { ModelSelection } from "./wire.ts";
-import type { ServerTextParams } from "./server-text.ts";
-
-export interface RoutineIntervalWindow {
- start: string;
- end: string;
-}
-
-export type RoutineSchedule =
- | RoutineCronSchedule
- | LimitResetSchedule
- | { type: "once"; at: number }
- | { type: "daily"; time: string; weekdays: number[] }
- | {
- type: "interval";
- everyMinutes: number;
- anchorAt: number;
- /** Local weekdays (Sunday = 0). Missing means every day. */
- weekdays?: number[];
- /** Local wall-clock window. Missing means all day. */
- window?: RoutineIntervalWindow;
- /** Inclusive epoch-millisecond cutoff. Missing means never. */
- endsAt?: number;
- };
-
-export type RoutineScheduleInput =
- | Extract<RoutineSchedule, { type: "once" | "daily" | "cron" }>
- | LimitResetScheduleInput
- | {
- type: "interval";
- everyMinutes: number;
- anchorAt: number;
- /** `null` explicitly restores the every-day default on updates. */
- weekdays?: number[] | null;
- /** `null` explicitly restores the all-day default on updates. */
- window?: RoutineIntervalWindow | null;
- /** `null` explicitly removes an existing end date on updates. */
- endsAt?: number | null;
- };
-
-export type RoutineRunOn = "maus" | "cloud";
-
-export type RoutineTarget = "bot" | "room-goal";
-export type RoutineGoalStatus =
- | "completed"
- | "needs-input"
- | "blocked"
- | "limit-reached"
- | "paused"
- | "stopped"
- | "failed";
-
-export interface RoutineContextAttachment {
- id: string;
- kind: "file" | "image";
- name: string;
- path: string;
- size: number;
-}
-
-/** "api": an outside caller through the bot's API; "webhook": an outside event. Both run as nobody's work. */
-export type RoutineRunTrigger = "schedule" | "manual" | "webhook" | "startup" | "api";
-
-/** A check a routine runs on each tick before any AI turn, in plain code: `calendar` reads the next 36 hours, `mail`
- * new inbox mail since the last check, `runs` other routines' finished runs. Nothing new means no AI turn. */
-export type RoutineCheck = "calendar" | "mail" | "runs";
-export const ROUTINE_CHECKS: readonly RoutineCheck[] = ["calendar", "mail", "runs"];
-
-/** What a routine's runs may do. `read-and-draft`: read Gmail and Google Calendar and write reply drafts; every other
- * tool is refused outright, never turned into a card. Missing means the bot's own level. */
-export type RoutineAccess = "read-and-draft";
-
-/** Where a routine's results go. `brief`: they become rows of the main agent's brief, not chat lines of their own. */
-export type RoutineDelivery = "brief";
-
-/** Why OpenMausBot paused a routine by itself, after its owner left: no AI of theirs is signed in here any more, they
- * removed every connected app and server, or the plan was cancelled. It turns back on once that changes. */
-export type RoutineHoldCause = "plan_cancelled" | "no_engine" | "no_connections";
-export const ROUTINE_HOLD_CAUSES: readonly RoutineHoldCause[] = ["plan_cancelled", "no_engine", "no_connections"];
-
-/** What a finished run left in the chat it reports to: nothing, because it
- * found nothing to tell; a report waiting for a turn there to end; or the bot
- * message it wrote. */
-export type RoutineRunReport =
- | { state: "quiet" }
- | { state: "pending" }
- | { state: "posted"; threadId: string; messageId: string };
-
-export type RoutineRunStatus =
- | "queued"
- | "running"
- | "waiting"
- | "completed"
- | "failed"
- | "cancelled"
- | "missed";
-
-/** Why a run started a second time by itself: its engine stalled, OpenMausBot
- * restarted while it ran, the provider rate-limited it or failed for a moment,
- * it waited for its engine's usage limit to reset, or it failed some other way.
- * A run gets one. */
-export type RoutineRetryCause = "stalled" | "restarted" | "rate_limited" | "provider" | "usage_limit" | "failed";
-
-/** The statuses both failure indicators count: a run that went wrong and has
- * not been acknowledged. */
-export const ROUTINE_PROBLEM_STATUSES: readonly RoutineRunStatus[] = ["failed", "missed"];
-
-/** A run's `attention` while it waits only on work it handed to teammates: nothing is asked of the person. */
-export const ROUTINE_HANDOFF_WAIT = "Waiting for work it handed on to finish";
-
-export function isRoutineProblemRun(run: { status: RoutineRunStatus }): boolean {
- return ROUTINE_PROBLEM_STATUSES.includes(run.status);
-}
-
-/** The logs view's status filter: every run, the composite problem set the
- * indicators count, or one exact status. */
-export type RoutineRunStatusFilter = "all" | "problems" | RoutineRunStatus;
-
-export interface Routine {
- id: string;
- name: string;
- prompt: string;
- target: RoutineTarget;
- botId: string;
- /** The room a "room-goal" runs in; none runs the goal in the bot's own one-on-one chat, a room of one. */
- groupId?: string;
- runOn: RoutineRunOn;
- enabled: boolean;
- schedule: RoutineSchedule;
- durationMinutes: number;
- /** Optional wall-clock safety limit. Missing means the run is unlimited. */
- timeoutMinutes?: number;
- overlap?: "skip" | "queue";
- /** Each run starts with the previous run's report. */
- continuity?: boolean;
- /** The model each run's thread uses instead of its bot's. Missing means the bot's model. */
- modelSelection?: ModelSelection;
- /** Also run once each time OpenMausBot starts. */
- runOnStartup?: boolean;
- checks?: RoutineCheck[];
- access?: RoutineAccess;
- deliver?: RoutineDelivery;
- /** When its checks last read everything and found nothing for the AI. */
- checkedAt?: number;
- /** A plain sentence while its checks cannot read an app, so a failed read never looks like nothing new. */
- checkTrouble?: string;
- /** Catalog key for `checkTrouble` when it is one of the server's fixed lines; `checkTrouble` keeps the English. */
- checkTroubleCode?: string;
- /** The next time its checks have something to do on time (a reminder, meeting prep): only this may keep the
- * computer awake or wake a sleeping Cloud. */
- wakeAt?: number;
- skippedRuns?: number;
- lastSkippedAt?: number;
- failureStreak?: number;
- /** Runs that finished in the last seven days, and how many of them completed. */
- weekRuns?: { ok: number; total: number };
- /** A plain sentence when the routine names a path that cannot exist on the computer that runs it. */
- warning?: string;
- /** Set while OpenMausBot keeps it paused because its owner left; turning it on or off clears it. */
- heldFor?: RoutineHoldCause;
- attachments?: RoutineContextAttachment[];
- sourceThreadId?: string;
- resultsThreadId?: string;
- nextRunAt: number | null;
- createdAt: number;
- updatedAt: number;
-}
-
-export interface RoutineRun {
- id: string;
- routineId: string;
- routineName: string;
- prompt?: string;
- durationMinutes?: number;
- timeoutMinutes?: number;
- attachments?: RoutineContextAttachment[];
- target: RoutineTarget;
- goalStatus?: RoutineGoalStatus;
- botId: string;
- groupId?: string;
- runOn: RoutineRunOn;
- scheduledFor: number;
- status: RoutineRunStatus;
- manual: boolean;
- triggerSource?: RoutineRunTrigger;
- /** "app": a connected-app event started it; "wait": a wait's follow-up did. triggerSource is then "webhook" (an outside event). */
- eventSource?: "app" | "wait";
- webhookId?: string;
- deliveryId?: string;
- /** Room task created for a team-goal run. */
- executionThreadId?: string;
- sourceThreadId?: string;
- resultsThreadId?: string;
- threadId?: string;
- startedAt?: number;
- finishedAt?: number;
- output?: string;
- /** Catalog key for `output` when it is one of the server's fixed lines; `output` keeps the English. */
- outputCode?: string;
- /** Catalog key and params for `error` and for `attention` when the server wrote them from a fixed line. A client words
- * one only while its field still reads as that line's English; the field always keeps the English. */
- errorCode?: string;
- errorParams?: ServerTextParams;
- attentionCode?: string;
- attentionParams?: ServerTextParams;
- error?: string;
- /** A failed run whose reply still came back: only a step it ran failed or wasn't allowed. */
- partial?: boolean;
- /** Set when the run used its one automatic second start, and why. */
- retried?: RoutineRetryCause;
- /** Concise, redacted question or approval reason while status is waiting,
- * or why a queued run starts later. */
- attention?: string;
- cost?: number | null;
- denials?: string[];
- report?: RoutineRunReport;
- access?: RoutineAccess;
- deliver?: RoutineDelivery;
- /** The items its routine's checks handed this run, so they are kept or released once it ends. */
- checkKey?: string;
- createdAt: number;
- seenAt?: number;
-}
-
-export interface RoutineInput {
- name: string;
- prompt: string;
- target?: RoutineTarget;
- botId: string;
- groupId?: string | null;
- runOn?: RoutineRunOn;
- enabled?: boolean;
- schedule: RoutineScheduleInput;
- durationMinutes?: number;
- /** `null` explicitly removes the limit; omission preserves it on updates. */
- timeoutMinutes?: number | null;
- overlap?: "skip" | "queue";
- /** Each run starts with the previous run's report. */
- continuity?: boolean;
- /** `null` removes it on updates; omission preserves it. */
- modelSelection?: ModelSelection | null;
- runOnStartup?: boolean;
- /** `null` explicitly removes them on updates; omission preserves them. */
- checks?: RoutineCheck[] | null;
- access?: RoutineAccess | null;
- deliver?: RoutineDelivery | null;
- attachments?: RoutineContextAttachment[];
- /** Omission preserves routing; null resets it to the bot's main thread (on a Team Cloud, a results chat everyone who
- * sees the bot reads); RESULTS_JUST_ME, on a Team Cloud only, the person's own private chat with the bot. */
- resultsThreadId?: string | null;
-}
-
-/** On a Team Cloud, "Just me": the routine reports into the person's own private chat with the bot, theirs alone. */
-export const RESULTS_JUST_ME = "just-me";
+export * from "../packages/phone-protocol/src/routines.ts";
diff --git a/shared/runtime-events.ts b/shared/runtime-events.ts
index 9c6e1bf2e5..d3de6ca2ab 100644
--- a/shared/runtime-events.ts
+++ b/shared/runtime-events.ts
@@ -1,211 +1 @@
-/** Canonical runtime-event shapes, as they ride the live wire and the
- * inspector log. */
-import type { AskQuestion } from "./ask-question.ts";
-import type { ServerText, ServerTextParams } from "./server-text.ts";
-import type { LiveStep, TurnProgressFields } from "./turn-progress.ts";
-
-export type DriverKind = string;
-export type InstanceId = string;
-export type ThreadId = string;
-export type TurnId = string;
-
-export interface ModelVariantOption {
- id: string;
- label: string;
-}
-
-export interface ModelVariantState {
- options: ModelVariantOption[];
- currentValue?: string;
-}
-
-// A subset of upstream's ProviderRuntimeEvent union, sharing one base. `raw`
-// carries the native protocol message behind the normalization.
-export interface RuntimeEventBase {
- eventId: string;
- provider: DriverKind;
- providerInstanceId?: InstanceId;
- threadId: ThreadId;
- createdAt: string;
- turnId?: TurnId;
- itemId?: string;
- requestId?: string;
- raw?: { source: string; payload: unknown };
- /** Text the provider's own client produced instead of the model (an API
- * error it reports as a reply). Rendered like any other item, but not a
- * sign that the model received or acted on the prompt. */
- synthetic?: boolean;
-}
-
-export type RuntimeEvent = RuntimeEventBase &
- (
- | {
- type: "session.started"; sessionId: string | null; model?: string | null;
- /** the provider refused the turn's resumeCursor and this new session
- * was started from the turn's recoveryText */
- rebuilt?: boolean;
- /** the turn's `custom` MCP servers the engine reported could not connect */
- mcpFailed?: string[];
- }
- | { type: "session.model-variants"; model: string; variants: ModelVariantState }
- | { type: "session.exited"; reason?: string }
- | { type: "turn.started" }
- | {
- type: "turn.retrying";
- /** 1-based: the retry about to be launched (1 = first relaunch). */
- attempt: number;
- delayMs: number;
- /** Why this failure was judged retry-worthy. */
- reason: string;
- }
- | {
- type: "turn.completed";
- ok: boolean;
- stopReason?: string | null;
- cost?: number | null;
- denials?: string[];
- /** THIS turn's token total, as the provider reports it at the end: the
- * one figure the harness accumulates. thread.token-usage.updated means
- * something different per driver and must never be summed. */
- usage?: { input: number; output: number; cachedInput?: number };
- }
- | {
- /** A resumable terminal: the turn exhausted its model/tool budget and
- * a structured handoff was persisted. */
- type: "cap.exhausted";
- /** Absolute path to the persisted handoff for the dead turn. */
- handoffPath: string;
- /** What stopped the turn without a final answer. */
- reason: "cap";
- }
- | {
- type: "turn.wait_started";
- /** The computer or browser this turn queued behind (e.g. "computer:box:bx_…", "browser:bot-…"). */
- resource: string;
- /** Where this turn sat in the resource's arrival-ordered waitlist when
- * the wait began. */
- position?: number;
- /** Who held the computer when the wait began, if the holder was known. */
- holder?: { name: string; task?: string };
- }
- | {
- type: "turn.wait_ended";
- resource: string;
- holder?: { name: string; task?: string };
- /** How long the turn actually waited. */
- waitedMs: number;
- /** acquired: the claim landed; stopped: the turn was stopped or
- * cancelled while waiting; parked: the wait ceiling settled the turn
- * for resume; gave_up: only in older recorded logs. */
- outcome: "acquired" | "gave_up" | "parked" | "stopped";
- }
- | {
- type: "item.started";
- itemType: "tool" | "reasoning";
- title?: string;
- /** The shell command the call runs, on one redacted line of at most
- * 200 characters, for the chip and the Verify card. Absent for calls
- * that run no command (a Read, a fetch). */
- summary?: string;
- /** Bounded, redacted display preview; never raw tool arguments. */
- input?: string;
- /** What the call works on, read from `summary` and `input` as the event passes the bus. */
- step?: LiveStep;
- }
- | { type: "item.updated"; itemType: "tool" | "reasoning"; tokens?: number | null }
- /** Output a running call printed, as its engine streams it: a chunk to append, or with `whole` all of it so far.
- * Live only: the bus folds it into the status line's `tail` and never logs or forwards it. */
- | { type: "item.output"; itemType: "tool"; text: string; whole?: boolean }
- /** What the engine is doing right now (a tool call being written or run), for the chat's status line. Live only:
- * the bus coalesces it and never writes it to the event log; nothing stores it. */
- | Omit<TurnProgressFields, "itemId">
- | { type: "item.completed"; itemType: "tool"; ok: boolean; output?: string }
- | { type: "item.completed"; itemType: "assistant_text"; text: string }
- /** Provider-generated raster bytes, folded into the private attachment
- * store and never forwarded to renderer SSE. `fromTool`: a tool's result
- * returned the image to the engine; the bot did not make or send it. */
- | { type: "item.completed"; itemType: "assistant_image"; data: string; alt?: string; fromTool?: true }
- | { type: "content.delta"; streamKind: "assistant_text" | "reasoning_text"; delta: string; /** A room reply as it goes out: the member speaking. */ botId?: string }
- | {
- type: "request.opened";
- requestType: "permission" | "question";
- tool: string;
- summary: string;
- /** Fixed `chat.notice.*` summary words beside their English fallback; absent for provider-authored text. */
- summaryCode?: string;
- summaryParams?: ServerTextParams;
- /** Complete native shell input and its effective working directory.
- * Used for exact-command grants; never reconstructed from a display
- * summary, tool title, or argv. Absent when either value is unknown. */
- command?: { command: string; cwd: string };
- /** The shell command line exactly as the engine sent it, even when `command` is absent for want of a cwd.
- * Read only by the safety floor; no grant is ever made from it, and like `command` it is never broadcast. */
- commandLine?: string;
- /** The files a read tool's ask reads (absolute): a request that reads only the bot's own files is answered
- * without the person. Like `command`, never broadcast. */
- reads?: string[];
- choices?: string[];
- /** A provider's structured ask (Claude's AskUserQuestion): the whole
- * set of questions, each with its own options, so the card can offer
- * them instead of an Allow/Deny a person cannot answer. */
- questions?: AskQuestion[];
- /** "tool" (or absent): a harness tool call; "output": a block parsed
- * from model-authored final output. Untrusted-input rules apply either
- * way. */
- origin?: "tool" | "output";
- approvalScope?: "local-computer";
- /** Provider asks to widen its configured sandbox. Only explicit Full
- * access may answer this automatically; Auto/remembered grants may not. */
- requiresExplicitApproval?: boolean;
- /** Whether the provider's own automatic reviewer was running when it
- * raised this request. Claude reports its effective permission mode in
- * its init frame and silently starts in Manual when Auto is unavailable
- * for the model. "inactive": the app's own safe-Auto rules may answer;
- * unset: nobody knows. */
- nativeReview?: "active" | "inactive";
- /** The provider can keep an allow for the rest of its session
- * ("Always allow this session"): Claude through its own suggested
- * permission rules, ACP agents through `allow_always` or the
- * driver's per-session memory. Unset when answers are one-shot. */
- allowSession?: boolean;
- }
- | {
- type: "request.resolved";
- behavior: "allow" | "deny" | "answer";
- /** who decided: a person, auto mode, the ask's own timeout, the
- * harness (turn ended / settings changed), or nobody — the answerer
- * was already gone and the action never ran */
- source: "user" | "auto" | "timeout" | "system" | "unavailable" | "peer";
- approvalScope?: "local-computer";
- }
- | {
- type: "thread.token-usage.updated"; input: number; output: number; cachedInput?: number;
- /** What the model's window held on the most recent model call — the
- * whole prompt, cache reads included — and the window's size when the
- * driver knows it. The figure that predicts the next message's cost. */
- contextTokens?: number; contextWindow?: number;
- /** The part of `output` spent reasoning, where the engine reports it. A per-call report carries the call's own
- * message id in `itemId`, repeated on every frame of that call. */
- reasoning?: number;
- }
- // `setup`: fixed by installing or configuring something, not by retrying.
- // `terminal`: the complete turn failed, not a transient error.
- // `claudeUpdate`: this Claude Code is too old for the model.
- // `trialCredit`: the trial's Claude credit refused the call.
- // `stalled`: the engine went silent and the turn was stopped as stuck.
- // `limitResetsAt`: epoch ms when the usage limit refusing this account resets, when the engine says.
- // `limit`: a usage limit refused this turn: the account's on this engine ("engine"), one model's own window
- // ("model"), or that model's extra usage credits ("credits"); the engine's other models still work for the last two.
- // `limitModels`: the models a "model" limit holds, when one allowance is shared (OpenCode's free models).
- | { type: "runtime.error"; message: string; partial?: boolean; setup?: boolean; terminal?: boolean; claudeUpdate?: boolean; trialCredit?: "used_up" | "ended" | "paused" | "too_low";
- stalled?: boolean; limitResetsAt?: number; limit?: "engine" | "model" | "credits"; limitModels?: string[];
- /** `message` as a `chat.notice.*` key and params, when it is one of the server's fixed sentences. */
- text?: ServerText }
- /** Something the person should know that did not fail the turn — for
- * example, a saved model the engine no longer offers was replaced. */
- | { type: "runtime.notice"; message: string; text?: ServerText }
- /** The engine condensed the conversation into its own summary (Claude Code's compact_boundary); the chat marks it. */
- | { type: "context.compacted" }
- );
-
-export type RuntimeEventListener = (event: RuntimeEvent) => void;
+export * from "../packages/phone-protocol/src/runtime-events.ts";
diff --git a/shared/saved-steps.ts b/shared/saved-steps.ts
index fbaaf5a0e0..63c8ee4e00 100644
--- a/shared/saved-steps.ts
+++ b/shared/saved-steps.ts
@@ -1,3 +1 @@
-/** Set on the reply of a request whose computer steps were saved (`learned`) or that was answered from saved steps
- * with no AI (`replayed`), as `WireMessage.savedSteps`. Clients that do not know it ignore it. */
-export interface SavedStepsMark { recipeId: string; learned?: true; replayed?: true }
+export * from "../packages/phone-protocol/src/saved-steps.ts";
diff --git a/shared/server-text.ts b/shared/server-text.ts
index ec73f815f3..1b8c2d28fe 100644
--- a/shared/server-text.ts
+++ b/shared/server-text.ts
@@ -1,60 +1 @@
-/** Values for the `{placeholders}` of a sentence the server words. */
-export type ServerTextParams = Record<string, string | number>;
-
-/** A sentence the server words for a person, named by its key in
- * src/locales/en.json so a client can say it in the person's language. The
- * server always sends the English beside it, which is what a client that does
- * not know the key shows. */
-export interface ServerText {
- key: string;
- params?: ServerTextParams;
-}
-
-/** A message's `text` the server wrote from a fixed line. */
-export interface ServerTextLine {
- /** Catalog key (`chat.notice.*`) for `text`. `text` keeps the English, which phones, exports, the bot's own context
- * and older clients read. */
- textCode?: string;
- /** Values for the placeholders of `textCode`. */
- textParams?: ServerTextParams;
-}
-
-/** The fixed name and summary of an activity chip, beside their English fallbacks. */
-export interface ServerToolText {
- /** Catalog key (`chat.notice.*`) for the words of `name` after any
- * `error:` marker, when they are one of the server's fixed notices.
- * `name` keeps the English, which phones, exports and older clients show. */
- nameCode?: string;
- /** Values for the placeholders of `nameCode`. */
- nameParams?: ServerTextParams;
- /** Fixed summary words, only while they rebuild `summary`. */
- summaryCode?: string;
- summaryParams?: ServerTextParams;
-}
-
-/** The JSON body of a refused request. */
-export interface ServerErrorBody {
- /** English, always present: what a client that does not know `errorKey` shows. */
- error: string;
- /** A machine code clients branch on (`cloud_personal`, `managed_policy`, …). Never a catalog key. */
- code?: string;
- /** A `serverError.*` catalog key a client may show instead of `error`. */
- errorKey?: string;
- /** Values for the placeholders of `errorKey`. */
- errorParams?: ServerTextParams;
-}
-
-const REFERENCE_PARAMS = new Set(["limit", "meanwhile", "why"]);
-const PART_KEY = /^(?:chat\.notice|routines\.server)\.part\.\w+$/;
-
-/** Only these params may name a catalog piece (`chat.notice.part.*`, `routines.server.part.*`) that a client words;
- * every other param is data, such as a name, a quote or a failure, and is shown exactly as sent. */
-export function isReferenceParam(name: string, value: string | number): boolean {
- return REFERENCE_PARAMS.has(name) && typeof value === "string" && PART_KEY.test(value);
-}
-
-export function formatServerText(template: string, params: ServerTextParams = {}): string {
- return template.replace(/\{(\w+)\}/g, (match, name: string) =>
- Object.hasOwn(params, name) ? String(params[name]) : match,
- );
-}
+export * from "../packages/phone-protocol/src/server-text.ts";
diff --git a/shared/setup-card.ts b/shared/setup-card.ts
index 3ca89c250b..389c0b5c85 100644
--- a/shared/setup-card.ts
+++ b/shared/setup-card.ts
@@ -1,19 +1 @@
-/** What clients draw the setup card under a new bot's greeting from. */
-export interface SetupCardFields {
- /** A new bot's greeting while it has no role or instructions: clients that know it draw the setup card under the
- * text; `text` reads on its own for older ones. It stays once the card is answered, so the card can show the answer;
- * closing the card clears it. */
- setupOffer?: true;
- /** The setup card's answers, in the app's language. Picking one sends its words; absent on older greetings, where a
- * client offers its own. Replaced only in the change that clears setupChoicesPending or setupChoicesUpdating. */
- setupChoices?: string[];
- /** Personal answers for this card are being written: clients show the card without answers until it clears. The
- * server clears it within 6 s, in the same change that sets setupChoices if they came in time; a client still seeing
- * it 8 s after showing the card, or on a greeting older than 20 s, shows setupChoices. */
- setupChoicesPending?: true;
- /** Epoch ms the bot's latest rename started rewriting setupChoices, while the card was unanswered: clients keep
- * showing them but take no pick until it clears. The server clears it within 7 s of the stamp, in the same change
- * that sets the new setupChoices if they came in time; a client still seeing a stamp 8 s after it first saw it, or
- * one older than 20 s, takes picks again. */
- setupChoicesUpdating?: number;
-}
+export * from "../packages/phone-protocol/src/setup-card.ts";
diff --git a/shared/sign-in-request.ts b/shared/sign-in-request.ts
index f15641fc05..be3aa13a5b 100644
--- a/shared/sign-in-request.ts
+++ b/shared/sign-in-request.ts
@@ -1,80 +1 @@
-/**
- * A bot asking the person to sign in to a website themselves, in the place the
- * bot works. OpenMausBot never receives a website password: the person types it
- * into the page, and the bot uses the session the page keeps.
- */
-import type { Surface } from "./wire.ts";
-
-/** Where the login has to happen: the place the asking turn worked in.
- * The built-in browser keeps its own sign-ins, apart from any computer's
- * browser, so a login made anywhere else would not reach the bot. */
-export type SignInPlace = Surface;
-
-/** The site as a page address and the host shown on the card. A bare
- * domain means its https home page. Anything that is not a plain http(s)
- * address — a script URL, a file, an address carrying a username or
- * password — is refused, so the card can never open more than a page. */
-export function normalizeSignInSite(raw: unknown): { url: string; site: string } | null {
- if (typeof raw !== "string") return null;
- const text = raw.trim();
- // eslint-disable-next-line no-control-regex -- Reject control characters and spaces before URL parsing normalizes them.
- if (!text || text.length > 2048 || /[\u0000- \u007f\\]/u.test(text)) return null;
- let url: URL;
- try {
- url = new URL(/^[a-z][a-z\d+.-]*:/i.test(text) ? text : `https://${text}`);
- } catch {
- return null;
- }
- if ((url.protocol !== "https:" && url.protocol !== "http:") || !url.hostname || url.username || url.password) return null;
- // A bare word is no site ("example" would parse as a host); localhost and
- // addresses are the exceptions a developer's own app needs.
- if (!url.hostname.includes(".") && url.hostname !== "localhost" && !url.hostname.startsWith("[")) return null;
- return { url: url.href, site: url.hostname.replace(/^www\./, "") };
-}
-
-/** A still-open sign-in card for this site — the set a newer request
- * supersedes. Done, cancelled, already-superseded and answered-in-chat
- * cards keep their settled state. In a room only the asking bot's own
- * cards count. */
-export function isPendingSignInRequest(
- message: {
- kind?: unknown;
- signIn?: { site?: unknown; done?: unknown; cancelled?: unknown; superseded?: unknown; answeredInChat?: unknown };
- from?: { botId?: unknown };
- },
- site: string,
- requestingBotId: string,
- roomThread: boolean,
-): boolean {
- return (
- message.kind === "signin" &&
- message.signIn?.site === site &&
- signInWaits(message.signIn) &&
- (!roomThread || message.from?.botId === requestingBotId)
- );
-}
-
-/** Whether the card still waits on the person: not done, cancelled, superseded or answered in the chat. */
-export function signInWaits(card: { done?: unknown; cancelled?: unknown; superseded?: unknown; answeredInChat?: unknown }): boolean {
- return card.done !== true && card.cancelled !== true && card.superseded !== true && card.answeredInChat !== true;
-}
-
-/** Whether a sign-in card, if there still is one, waits on the person: not stopped and still open. */
-export function signInCardWaits(card: ({ stopped?: unknown } & Parameters<typeof signInWaits>[0]) | undefined): boolean {
- return card !== undefined && card.stopped !== true && signInWaits(card);
-}
-
-/** How a card ended, or null while it is open. */
-export function signInOutcome(state: { done?: unknown; cancelled?: unknown }): "done" | "cancelled" | null {
- if (state.done === true) return "done";
- if (state.cancelled === true) return "cancelled";
- return null;
-}
-
-/** The line that resumes the bot, through the same continuation the
- * credential card uses. */
-export function signInResumePrompt(site: string, outcome: "done" | "cancelled"): string {
- return outcome === "done"
- ? `OpenMausBot sign-in update: the person finished signing in to ${site}. Check you are signed in, then continue the task that paused for it. Never ask them for a password or a one-time code in chat.`
- : `OpenMausBot sign-in update: the person declined to sign in to ${site}. Continue without it if you can, or briefly explain what you could not do. Never ask them for a password or a one-time code in chat.`;
-}
+export * from "../packages/phone-protocol/src/sign-in-request.ts";
diff --git a/shared/skill-request.ts b/shared/skill-request.ts
index 0a70e54026..50b7ff2b0a 100644
--- a/shared/skill-request.ts
+++ b/shared/skill-request.ts
@@ -1,73 +1 @@
-/**
- * Durable payload on a learned-skill confirmation card. None of the staged
- * SKILL.md reaches the bot's enabled skill index until the user confirms; during
- * an update the approved version stays live.
- */
-export type SkillRequestAction = "create" | "update" | SkillSwitchAction;
-
-/** Turning one of the bot's existing skills on or off, or deleting it: no new
- * SKILL.md, so the card shows the current one and approval binds to it. */
-export type SkillSwitchAction = "enable" | "disable" | "delete";
-
-export function isSkillSwitchAction(action: unknown): action is SkillSwitchAction {
- return action === "enable" || action === "disable" || action === "delete";
-}
-
-export function skillSwitchVerb(action: SkillSwitchAction): string {
- return action === "enable" ? "turn on" : action === "disable" ? "turn off" : "delete";
-}
-
-/** Kept on the receipt so Undo reverts the library write and the assignments together. */
-export interface SkillShareRecord {
- /** deduplicated: identical bytes were already in the library; assigned: it already was a library skill. */
- library: "installed" | "deduplicated" | "assigned" | "updated";
- sha256: string;
- sharedAt: number;
- assigned: Array<{ botId: string; name: string }>;
- skipped: Array<{ botId: string; name: string; reason: string }>;
-}
-
-export interface SkillRequestCardData {
- version: 1;
- requestId: string;
- botId: string;
- threadId: string;
- stagedId: string;
- action: SkillRequestAction;
- name: string;
- gist: string;
- /** Human-readable provenance retained with the installed skill. */
- source?: string;
- /** Exact, secret-scrubbed SKILL.md shown as plain text before approval. */
- preview?: string;
- /** Binds approval to the exact bytes shown in preview. */
- sha256?: string;
- /** references/<topic>.md files shown in full beside the SKILL.md; absent when the skill is SKILL.md alone. */
- references?: Array<{ path: string; content: string }>;
- /** Binds approval to the exact references shown. */
- referencesSha256?: string;
- warnings: string[];
- createdAt: number;
- /** An update or delete that applied without a person: the SKILL.md it replaced or removed, so
- * Undo can put it back while the skill is unchanged since. enabled is false for a deleted skill that was off. */
- previous?: { preview: string; source: string; references?: Array<{ path: string; content: string }>; enabled?: boolean };
- shared?: SkillShareRecord;
- shareError?: string;
-}
-
-/** The hash a current client may echo after it displayed the complete
- * proposal. Old cards deliberately return undefined and remain deny-only. */
-export function reviewedSkillSha256(request: SkillRequestCardData): string | undefined {
- if (!request.preview || !request.sha256 || !/^[a-f0-9]{64}$/i.test(request.sha256)) return undefined;
- return request.sha256;
-}
-
-/** Map the server-authored affirmative labels explicitly and fail closed for
- * anything else. This keeps new Update/Apply wording working without turning
- * an unknown or corrupted card answer into approval. */
-export function skillRequestBehavior(answer: string): "allow" | "deny" {
- const normalized = answer.trim().toLowerCase();
- return ["enable", "turn on", "turn off", "delete", "update", "apply", "allow", "allow once", "confirm", "yes"].includes(normalized)
- ? "allow"
- : "deny";
-}
+export * from "../packages/phone-protocol/src/skill-request.ts";
diff --git a/shared/task-provenance.ts b/shared/task-provenance.ts
index f08c97af82..d4558d8295 100644
--- a/shared/task-provenance.ts
+++ b/shared/task-provenance.ts
@@ -1,33 +1 @@
-/** The bot that opened a thread on itself or a teammate. */
-export interface TaskOpenedBy {
- botId: string;
- name: string;
- delegationId?: string;
- /** What kind of conversation the opener made this: "pair" is the one
- * durable conversation between two bots; "work" closes itself once its
- * result has been reported. */
- kind?: "pair" | "work";
- /** The burst this thread is one part of: it is listed under that burst's card. */
- burstId?: string;
- /** The opener's own conversation this "work" thread was opened from.
- * Everything that conversation later sends this bot continues here. */
- threadId?: string;
- /** A parallel room job's thread: `threadId` is the room thread it came from, and the member must stay in that room. */
- roomLane?: true;
- /** Security invariant: harness-set only when the opening turn could use the owner's lent computer. */
- forOwner?: true;
- at: number;
-}
-
-/** The bot that closed a thread it opened (or one of its own). */
-export interface TaskClosedBy {
- botId: string;
- name: string;
- at: number;
-}
-
-/** The completed message whose visible history seeded an independent conversation. */
-export interface ForkOrigin {
- threadId: string;
- messageId: string;
-}
+export * from "../packages/phone-protocol/src/task-provenance.ts";
diff --git a/shared/team-presence.ts b/shared/team-presence.ts
index ac18129267..9abbfa9f00 100644
--- a/shared/team-presence.ts
+++ b/shared/team-presence.ts
@@ -1,44 +1 @@
-// Who is here on a Team Cloud (docs/team-cloud.md "Who is here"): the wire between the server and the app. A person is
-// named by their address, as in GET /api/team/people. Nothing here ever names a private chat: a conversation only one
-// person can read is never reported, and its person only counts as here.
-
-/** POST {tab, threadId}: this app window is open, with that conversation in front of the person (null: none, or one that
- * is theirs alone). `tab` is the window's own id, made when it loads. Sent when the conversation changes and every
- * HERE_REPEAT_MS while the window shows. */
-export const PRESENCE_HERE_PATH = "/api/presence/here";
-
-export interface PresenceHereBody {
- tab: string;
- threadId: string | null;
-}
-
-/** How often a showing window repeats its POST; a window not heard from for a few of these no longer counts. */
-export const HERE_REPEAT_MS = 60_000;
-
-/** A person on GET /api/team/people, with presence: `here` while one of their apps is open. A server that sends no
- * `here` has no presence, and the app shows none. */
-export interface PersonPresence {
- here?: boolean;
-}
-
-/** A teammate came or went. Sent to everyone signed in to the team, at most once every few seconds per person. */
-export interface TeamPresenceFrame {
- kind: "team.presence";
- email: string;
- here: boolean;
-}
-
-/** Who has a shared conversation (a bot's shared chat, a group chat) open now, the receiver included. Sent only to the
- * people listed, each of whom may read it; never for a conversation that is one person's own. */
-export interface ThreadPresenceFrame {
- kind: "thread.presence";
- threadId: string;
- people: string[];
-}
-
-/** Someone joined the team, left it or changed role: the app reads the people and its own session again. */
-export interface TeamPeopleFrame {
- kind: "team.people";
-}
-
-export type PresenceFrame = TeamPresenceFrame | ThreadPresenceFrame | TeamPeopleFrame;
+export * from "../packages/phone-protocol/src/team-presence.ts";
diff --git a/shared/team-setup.ts b/shared/team-setup.ts
index c4a01a30f0..656eaff2f5 100644
--- a/shared/team-setup.ts
+++ b/shared/team-setup.ts
@@ -1,70 +1 @@
-import type { ModelSelection } from "./wire.ts";
-
-export interface TeamSetupFields {
- name?: string;
- title?: string;
- description?: string;
- soul?: string;
- /** Create only: the folder the new bot's tools work in. "" = private workspace. */
- cwd?: string;
- section?: string;
- modelSelection?: ModelSelection;
- chiefOfStaff?: boolean;
-}
-
-export interface TeamSetupOperation {
- action: "create" | "update";
- botId: string;
- threadId?: string;
- fields: TeamSetupFields;
- expectedRevision?: string;
-}
-
-export interface TeamSetupResult {
- state: "applied" | "denied" | "cancelled" | "failed";
- bots: Array<{ id: string; name: string; action: "created" | "updated" | "deleted"; section?: string; modelSelection?: ModelSelection; chiefOfStaff?: boolean }>;
- newTeams: string[];
- error?: string;
-}
-
-/** The complete, reviewed operation. It never accepts executable permissions. */
-export interface TeamSetupRequest {
- version: 1;
- requestId: string;
- botId: string;
- threadId: string;
- reason: string;
- createdAt: number;
- requesterRevision: string;
- operations: TeamSetupOperation[];
- newTeams: string[];
- deletion?: { botId: string; name: string; expectedRevision: string };
- result?: TeamSetupResult;
- resumed?: boolean;
- /** Set when the setup applied on its own (direct-apply.ts) and Undo can reverse it. */
- undo?: TeamSetupUndo;
-}
-
-/** Undo deletes the bots a setup created while still unused, gives each updated bot back the values the card showed and
- * the Chief its earlier teams; `revisions` pin every bot it touched as it applied, so a later change refuses Undo. */
-export interface TeamSetupUndo {
- created: string[];
- before: Array<{ botId: string; fields: TeamSetupFields; managedSections?: string[] | null }>;
- revisions: Record<string, string>;
-}
-
-/** A new bot gets no cloud computer until the person writes in its chat, unless it is set to work on one (it then starts one on its first turn), uses a VPS or the team's computer. */
-export function startsWithoutCloudComputer(bot: { computer?: string; cloudBackend?: string }, place: { cloudOn: boolean; teamComputer: boolean }): boolean {
- return place.cloudOn && !place.teamComputer && bot.cloudBackend !== "vps" && bot.computer !== "cloud";
-}
-
-/** Told to a Chief about a bot it just made that has no cloud computer of its own yet. */
-export function noCloudComputerNote(name: string): string {
- return ` @${name} has no cloud computer yet: work you hand it runs without one until the person writes to it in its own chat, which sets one up. If its first job needs a computer, tell the person that in one line.`;
-}
-
-/** The Chief's resumed turn once its team setup card is decided. `lacksComputer` names newly created bots with no cloud computer yet. */
-export function teamSetupDecisionText(request: TeamSetupRequest, lacksComputer: (botId: string) => boolean): string {
- const bare = request.result?.state === "applied" ? request.result.bots.filter((bot) => bot.action === "created" && lacksComputer(bot.id)) : [];
- return `OpenMausBot team setup decision ${request.requestId}: ${JSON.stringify(request.result)}. Report this exact result and continue the user's already requested work. Do not ask for confirmation again or repeat this setup/deletion. A denied or cancelled operation did not authorize any substitute action. Existing thread models were not changed.${bare.map((bot) => noCloudComputerNote(bot.name)).join("")}`;
-}
+export * from "../packages/phone-protocol/src/team-setup.ts";
diff --git a/shared/tool-scope.ts b/shared/tool-scope.ts
index d798c4cb5c..b40a62b5a7 100644
--- a/shared/tool-scope.ts
+++ b/shared/tool-scope.ts
@@ -1,148 +1 @@
-import { agentsCallIdentities } from "./agents-tool-names.ts";
-import { PHONE_STEP_TOOLS } from "./phone-steps.ts";
-
-export type ToolScope = {
- allow?: string[];
- deny?: string[];
-};
-
-export type ToolIdentity =
- | { kind: "native"; name: string }
- | { kind: "mcp"; server: string; name: string };
-
-type ParsedToolScope = { ok: true; scope: ToolScope | undefined } | { ok: false; error: string };
-
-const SERVER_NAME = /^[a-z][a-z0-9_-]{0,31}$/;
-// Selectors must never contain protocol control characters.
-// eslint-disable-next-line no-control-regex
-const CONTROL_CHARACTER = /[\x00-\x1f\x7f]/;
-const MAX_SELECTORS = 256;
-const MAX_SELECTOR_LENGTH = 1024;
-
-function validName(name: unknown): name is string {
- return typeof name === "string" && name.trim().length > 0
- && name.length <= MAX_SELECTOR_LENGTH && !CONTROL_CHARACTER.test(name)
- && !name.includes("*");
-}
-
-function selectorIdentity(selector: string): ToolIdentity | undefined {
- if (selector.length > MAX_SELECTOR_LENGTH || CONTROL_CHARACTER.test(selector)) return;
- if (selector.startsWith("native:")) {
- const name = selector.slice(7);
- if (name === "*" || validName(name)) return { kind: "native", name };
- } else if (selector.startsWith("mcp:")) {
- const separator = selector.indexOf(":", 4);
- if (separator < 0) return;
- const server = selector.slice(4, separator);
- const name = selector.slice(separator + 1);
- if (SERVER_NAME.test(server) && (name === "*" || validName(name))) {
- return { kind: "mcp", server, name };
- }
- }
-}
-
-/** Undefined inherits the existing catalog. A present invalid value never does. */
-export function parseToolScope(value: unknown): ParsedToolScope {
- if (value === undefined) return { ok: true, scope: undefined };
- const invalid = { ok: false, error: "Tool selection must contain only valid allow and deny lists." } as const;
- if (!value || typeof value !== "object" || Array.isArray(value)) return invalid;
- const prototype = Object.getPrototypeOf(value);
- if (prototype !== Object.prototype && prototype !== null) return invalid;
- const scope: ToolScope = {};
- for (const key of Reflect.ownKeys(value)) {
- if (key !== "allow" && key !== "deny") return invalid;
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
- if (!descriptor || !("value" in descriptor)) return invalid;
- const list: unknown = descriptor.value;
- if (!Array.isArray(list) || list.length > MAX_SELECTORS) return invalid;
- // Array.from exposes holes as undefined instead of silently skipping them.
- if (!Array.from(list).every((entry: unknown) => typeof entry === "string" && selectorIdentity(entry))) return invalid;
- scope[key] = [...new Set(list as string[])];
- }
- return { ok: true, scope };
-}
-
-function matches(selector: string, tool: ToolIdentity, names: readonly string[] = [tool.name]): boolean {
- const selected = selectorIdentity(selector);
- return selected?.kind === tool.kind
- && (selected.kind !== "mcp" || (tool.kind === "mcp" && selected.server === tool.server))
- && (selected.name === "*" || names.includes(selected.name));
-}
-
-function permitsNamed(scope: ToolScope | undefined, tool: ToolIdentity, names: readonly string[]): boolean {
- return (scope?.allow === undefined || scope.allow.some((selector) => matches(selector, tool, names)))
- && !scope?.deny?.some((selector) => matches(selector, tool, names));
-}
-
-function permits(scope: ToolScope | undefined, tool: ToolIdentity, args?: unknown): boolean {
- if (!validName(tool.name) || (tool.kind === "mcp" && !SERVER_NAME.test(tool.server))) return false;
- // A phone batch runs the step tools, so a selection that refuses any of them refuses the batch.
- if (tool.kind === "mcp" && tool.server === "phone" && tool.name === "batch") {
- return ["batch", ...PHONE_STEP_TOOLS].every((name) => permitsNamed(scope, tool, [name]));
- }
- // An agents call is named by what it does: a selector naming one action's own tool name allows or refuses that action.
- const named = tool.kind === "mcp" && tool.server === "agents" ? agentsCallIdentities(tool.name, args) : [[tool.name]];
- return named.some((names) => permitsNamed(scope, tool, names));
-}
-
-/** Whether the selection lets this tool run: with the call's arguments, this call; without them, any call it makes. */
-export function allowsTool(scope: unknown, tool: ToolIdentity, args?: unknown): boolean {
- const parsed = parseToolScope(scope);
- return parsed.ok && permits(parsed.scope, tool, args);
-}
-
-/** Whether an engine needs a native catalog contract, in addition to MCP gates. */
-export function narrowsNativeTools(value: unknown): boolean {
- const parsed = parseToolScope(value);
- if (!parsed.ok) return true;
- const scope = parsed.scope;
- return scope !== undefined && ((scope.allow !== undefined && !scope.allow.includes("native:*"))
- || Boolean(scope.deny?.some((selector) => selector.startsWith("native:"))));
-}
-
-/** Without a catalog, asks whether this server could have a permitted tool. */
-export function canUseMcpServer(scope: unknown, server: string, names?: readonly string[]): boolean {
- const parsed = parseToolScope(scope);
- if (!parsed.ok || !SERVER_NAME.test(server)) return false;
- if (names !== undefined) {
- return names.some((name) => permits(parsed.scope, { kind: "mcp", server, name }));
- }
- if (parsed.scope?.deny?.includes(`mcp:${server}:*`)) return false;
- if (parsed.scope?.allow === undefined) return true;
- return parsed.scope.allow.some((selector) => {
- const selected = selectorIdentity(selector);
- return selected?.kind === "mcp" && selected.server === server
- && (selected.name === "*" || permits(parsed.scope, selected));
- });
-}
-
-/** Compare the selector partitions, including a tool/server outside all exact names. */
-export function toolScopeWidens(previous: unknown, next: unknown): boolean {
- const before = parseToolScope(previous);
- const after = parseToolScope(next);
- if (!after.ok) return false;
- const namespaces = new Map<string, Set<string>>([["native", new Set()]]);
- const scopes = [before.ok ? before.scope : undefined, after.scope];
- for (const scope of scopes) {
- for (const selector of [...(scope?.allow ?? []), ...(scope?.deny ?? [])]) {
- const tool = selectorIdentity(selector)!;
- const namespace = tool.kind === "native" ? "native" : `mcp:${tool.server}`;
- if (!namespaces.has(namespace)) namespaces.set(namespace, new Set());
- if (tool.name !== "*") namespaces.get(namespace)!.add(tool.name);
- }
- }
- let server = "unlisted";
- for (let i = 0; namespaces.has(`mcp:${server}`); i++) server = `unlisted${i}`;
- namespaces.set(`mcp:${server}`, new Set());
- for (const [namespace, names] of namespaces) {
- let other = "__unlisted_tool__";
- for (let i = 0; names.has(other); i++) other = `__unlisted_tool_${i}__`;
- names.add(other);
- for (const name of names) {
- const tool: ToolIdentity = namespace === "native" ? { kind: "native", name }
- : { kind: "mcp", server: namespace.slice(4), name };
- if (permits(after.scope, tool) && (!before.ok || !permits(before.scope, tool))) return true;
- }
- }
- return false;
-}
+export * from "../packages/phone-protocol/src/tool-scope.ts";
diff --git a/shared/turn-progress.ts b/shared/turn-progress.ts
index 0cc6e1e1aa..e4e3697946 100644
--- a/shared/turn-progress.ts
+++ b/shared/turn-progress.ts
@@ -1,68 +1 @@
-// The live status line's vocabulary, shared by the drivers that report it, the bus that coalesces it and the chat that
-// shows it. A turn.progress event is live only: it is never written to the event log or the message log.
-
-/** What a tool call is doing, in the status line's words: writing or changing a file, running a command, searching the
- * web, reading a file or a page, searching files, or any other tool. */
-export type TurnProgressActivity = "write" | "edit" | "command" | "web" | "read" | "fetch" | "search" | "tool";
-
-/** What one tool call works on, in the words the status line, its chip and the sidebar use: a command's program and
- * main target ("scrape.py", "pnpm test"), a web search's query, a page's site, a file's name. Server-made from redacted
- * text and redacted again: never an environment variable's value or a credential. */
-export interface LiveStep {
- activity: TurnProgressActivity;
- /** At most 60 characters. */
- target: string;
- /** The whole command, query or page address the target was read from, environment values left out; at most 200
- * characters, and absent when it says no more than the target. */
- detail?: string;
-}
-
-/** How a call that has run a while is doing: when its output last arrived (epoch ms), or, while it has sent none, what
- * its processes show: holding a network connection, using the CPU, or neither. */
-export type StepQuiet = { kind: "output"; at: number } | { kind: "network" | "busy" | "idle" };
-
-export interface TurnProgressFields {
- type: "turn.progress";
- activity: TurnProgressActivity;
- /** The engine's own tool name, for a tool the activity does not name. */
- tool?: string;
- /** The bare file name the call works on, once the engine has said it. */
- file?: string;
- /** Bytes of the call's input generated so far: for a write, about the size of the file. */
- bytes?: number;
- itemId?: string;
- /** The call's LiveStep target, once the server has read one from the call. */
- target?: string;
- /** The call's LiveStep detail, for the phrase's tooltip. */
- detail?: string;
- /** Set once the call has run past the quiet notice. */
- quiet?: StepQuiet;
- /** A running command's last lines of output, redacted, oldest first. */
- tail?: string[];
-}
-
-const KB = 1024;
-const MB = 1024 * KB;
-
-/** The size the status line shows: whole KB under a megabyte, tenths of a MB above; nothing under 1 KB. */
-export function progressSize(bytes: number | undefined): { unit: "kb" | "mb"; count: number } | null {
- if (typeof bytes !== "number" || !Number.isFinite(bytes) || bytes < KB) return null;
- if (bytes < MB) return { unit: "kb", count: Math.floor(bytes / KB) };
- return { unit: "mb", count: Math.floor((bytes / MB) * 10) / 10 };
-}
-
-/** A path's last part, without control characters and at most 60 characters: never a whole path on the wire. */
-export function progressFile(path: unknown): string | undefined {
- if (typeof path !== "string") return undefined;
- const name = path.replace(/[\\/]+$/, "").split(/[\\/]/).pop()?.replace(/\p{Cc}/gu, "").trim();
- if (!name) return undefined;
- return name.length > 60 ? `${name.slice(0, 57)}…` : name;
-}
-
-/** Two reports that read the same on screen share a key, so only a visible change is worth a frame. */
-export function progressKey(event: Omit<TurnProgressFields, "type" | "activity"> & { activity: string; turnId?: string }): string {
- const size = progressSize(event.bytes);
- const quiet = event.quiet ? `${event.quiet.kind}${event.quiet.kind === "output" ? `@${event.quiet.at}` : ""}` : "";
- return [event.turnId ?? "", event.itemId ?? "", event.activity, event.tool ?? "", event.file ?? "", size ? `${size.count}${size.unit}` : "",
- event.target ?? "", event.detail ?? "", quiet, (event.tail ?? []).join("\n")].join("|");
-}
+export * from "../packages/phone-protocol/src/turn-progress.ts";
diff --git a/shared/vega-config.ts b/shared/vega-config.ts
index e2fe2fea5f..9df9768cd0 100644
--- a/shared/vega-config.ts
+++ b/shared/vega-config.ts
@@ -1,95 +1 @@
-// The one Vega config every chart is drawn with (the Data panel, the server's
-// SVG/PNG, the headless render check): Vega-Lite's `config`, or Vega's runtime
-// config. Light and dark only. Skin accents are not used for marks, so a series
-// keeps its colour between the panel and a PNG in an email.
-
-export type VegaTheme = "light" | "dark";
-
-/** The app's `--font-sans` stack. Node renders through resvg, which walks
- * the list against the system fonts it finds, so the stack ends in a
- * generic family. */
-export const VEGA_FONT = '"Inter", -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI", system-ui, sans-serif';
-
-/** Ten categorical colours of middling luminance, each ≥ 3:1 on both #111111
- * and white. Hue order alternates warm and cool so neighbouring series differ. */
-export const VEGA_CATEGORY_RANGE: readonly string[] = [
- "#3b82f6", // blue
- "#ea580c", // orange
- "#059669", // emerald
- "#c026d3", // fuchsia
- "#a16207", // gold
- "#8b5cf6", // violet
- "#0d9488", // teal
- "#e11d48", // rose
- "#4d7c0f", // olive
- "#6b7280", // grey
-];
-
-const INK = {
- dark: { text: "#fcfcfc", muted: "#a3a3a3", hairline: "#333333", surface: "#111111" },
- light: { text: "#1a1a18", muted: "#6b6559", hairline: "#c8bda8", surface: "#fbf8f2" },
-} as const;
-
-/** The surface a PNG is laid on when it cannot be transparent (email, Slack). */
-export function vegaSurface(theme: VegaTheme): string {
- return INK[theme].surface;
-}
-
-export function vegaConfig(theme: VegaTheme): Record<string, unknown> {
- const ink = INK[theme];
- const text = { font: VEGA_FONT, labelFont: VEGA_FONT, titleFont: VEGA_FONT, labelFontSize: 11, titleFontSize: 11, titleFontWeight: 500 };
- return {
- // The panel's card and the phone's view supply the ground; a PNG adds its own.
- background: "transparent",
- font: VEGA_FONT,
- padding: 8,
- view: { stroke: null },
- title: { color: ink.text, subtitleColor: ink.muted, font: VEGA_FONT, fontSize: 13, fontWeight: 600, anchor: "start", offset: 12 },
- axis: {
- ...text,
- labelColor: ink.muted,
- titleColor: ink.muted,
- titlePadding: 8,
- labelPadding: 6,
- domainColor: ink.hairline,
- domainWidth: 1,
- tickColor: ink.hairline,
- tickSize: 4,
- gridColor: ink.hairline,
- gridWidth: 1,
- gridOpacity: 0.6,
- },
- // Hairline grid behind the values only; the category axis keeps its baseline.
- axisX: { grid: false },
- axisY: { grid: true, domain: false, ticks: false },
- legend: {
- ...text,
- labelColor: ink.muted,
- titleColor: ink.muted,
- symbolSize: 60,
- symbolType: "circle",
- labelLimit: 140,
- padding: 0,
- rowPadding: 2,
- columnPadding: 8,
- offset: 12,
- },
- range: {
- category: [...VEGA_CATEGORY_RANGE],
- // High values must pop against the ground: light-to-dark blues on
- // paper, dark-to-bright viridis on a dark surface.
- heatmap: { scheme: theme === "dark" ? "viridis" : "blues" },
- ramp: { scheme: theme === "dark" ? "viridis" : "blues" },
- },
- mark: { color: VEGA_CATEGORY_RANGE[0] },
- line: { strokeWidth: 2, strokeJoin: "round", strokeCap: "round" },
- area: { opacity: 0.75, line: false },
- point: { filled: true, size: 36, opacity: 0.8 },
- circle: { size: 36, opacity: 0.8 },
- // A hairline in the surface colour separates pie slices and heatmap cells.
- arc: { stroke: ink.surface, strokeWidth: 1 },
- rect: { stroke: ink.surface, strokeWidth: 1 },
- text: { color: ink.text, font: VEGA_FONT },
- scale: { bandPaddingInner: 0.25 },
- };
-}
+export * from "../packages/phone-protocol/src/vega-config.ts";
diff --git a/shared/wait-request.ts b/shared/wait-request.ts
index a8ee36bf5b..a5613aaa9d 100644
--- a/shared/wait-request.ts
+++ b/shared/wait-request.ts
@@ -1,23 +1 @@
-/** The line a wait (wait_until) posted when it ended (`WireMessage.wait`). */
-export interface WaitLine {
- id: string;
- status: "fired" | "expired" | "stopped";
-}
-
-/** `WireMessage.wait`: set on the line a wait posted when it ended. */
-export interface WaitLineField {
- wait?: WaitLine;
-}
-
-/** A wait with a follow-up a bot set up from chat (wait_until, `OptionCardData.waitRequest`); its Cancel stops it until it settles. */
-export interface WaitCardData {
- waitId: string;
- label: string;
- followUp: string;
- settled?: "fired" | "expired" | "cancelled";
-}
-
-/** `OptionCardData.waitRequest`: set on the card a wait with a follow-up showed. */
-export interface WaitCardField {
- waitRequest?: WaitCardData;
-}
+export * from "../packages/phone-protocol/src/wait-request.ts";
diff --git a/shared/webhook-request.ts b/shared/webhook-request.ts
index 8e5162cd69..0e491ed7a3 100644
--- a/shared/webhook-request.ts
+++ b/shared/webhook-request.ts
@@ -1,45 +1 @@
-/**
- * Durable payload of a webhook trigger change a bot made from chat. Every change applies at once (there is no
- * confirmation), so the card is a receipt: what changed, and what Undo needs to put it back.
- */
-
-export interface WebhookRequestDefinition {
- name: string;
- /** Instructions for every call; empty means each call's own task is used. */
- instructions: string;
- runOn: "maus" | "cloud";
- eventTypes?: string[];
- /** Field path -> text it must have; all must match before a run starts. Empty removes it on an update. */
- payloadFilter?: Record<string, string>;
- /** Each run continues the webhook's previous run conversation. */
- sameConversation?: boolean;
-}
-
-export type WebhookRequestOperation =
- | { action: "create"; webhook: WebhookRequestDefinition; forBot?: { botId: string; name: string } }
- | { action: "update"; webhookId: string; changes: Partial<WebhookRequestDefinition>; forBot?: { botId: string; name: string } }
- | { action: "pause" | "resume" | "run_now" | "delete"; webhookId: string; forBot?: { botId: string; name: string } };
-
-/** The webhook as it stood before an update, so Undo can restore it. */
-export interface WebhookRequestSnapshot extends WebhookRequestDefinition {
- enabled: boolean;
-}
-
-export interface WebhookRequestUndo {
- name: string;
- /** The webhook's revision right after the change; Undo refuses once it moved. */
- appliedUpdatedAt?: number;
- before?: WebhookRequestSnapshot;
-}
-
-export interface WebhookRequestCardData {
- version: 1;
- requestId: string;
- botId: string;
- threadId: string;
- createdAt: number;
- operation: WebhookRequestOperation;
- /** The webhook the change applied to (the new one for a create). */
- resultId?: string;
- undo?: WebhookRequestUndo;
-}
+export * from "../packages/phone-protocol/src/webhook-request.ts";
diff --git a/shared/webhooks.ts b/shared/webhooks.ts
index 7871008830..7e31db22d2 100644
--- a/shared/webhooks.ts
+++ b/shared/webhooks.ts
@@ -1,90 +1 @@
-/** Webhook wire shapes: triggers and delivery attempts as they ride the REST
- * snapshot and the `webhook` / `webhook.attempt` live frames. */
-import type { RoutineRunOn } from "./routines.ts";
-
-export interface WebhookTrigger {
- id: string;
- endpointId: string;
- name: string;
- prompt: string;
- botId: string;
- runOn: RoutineRunOn;
- enabled: boolean;
- createdAt: number;
- updatedAt: number;
- lastReceivedAt?: number;
- lastRunId?: string;
- /** delivery:"post" only: the stable thread this webhook's messages land in,
- * created on first delivery and reused after, never the bot's
- * currently-selected thread. Unset on a room webhook (`groupId`), whose
- * messages land in the room's own thread. */
- resultsThreadId?: string;
- /** delivery:"post" only, optional: a room id. Set, each delivery appends
- * one bot-authored message (plus optional voice note and images) straight
- * into that room, starting no turn and creating no task thread. The
- * trigger's bot must be a member of the room, checked on create, on edit,
- * and again at every delivery. */
- groupId?: string;
- deliveryCount: number;
- verificationPending?: boolean;
- verifiedAt?: number;
- verificationSample?: WebhookVerificationSample;
- eventTypes?: string[];
- /** Field path in the call's JSON (dots for nesting, e.g. "pull_request.state") -> the text it must have. Every field must
- * match (case-insensitive; a list matches when any item does), else the call is recorded as ignored and starts no run. */
- payloadFilter?: Record<string, string>;
- /** Unfinished runs this webhook may hold before new deliveries get 429.
- * Absent means the default (3). */
- maxPendingRuns?: number;
- /** Each run continues this webhook's previous run conversation instead of starting a new one. */
- sameConversation?: boolean;
-}
-
-export interface WebhookTriggerInput {
- name: string;
- prompt: string;
- botId: string;
- runOn?: RoutineRunOn;
- /** Requires `delivery: "post"`; a room webhook with any other delivery is refused. `null` on an edit
- * takes the room off, so deliveries go back to the webhook's own thread. */
- groupId?: string | null;
- enabled?: boolean;
- verificationPending?: boolean;
- eventTypes?: string[];
- /** `null` or `{}` on an edit removes the filter. */
- payloadFilter?: Record<string, string> | null;
- /** 1–50; `null` goes back to the default. */
- maxPendingRuns?: number | null;
- sameConversation?: boolean;
-}
-
-export interface WebhookVerificationSample {
- receivedAt: number;
- eventName?: string;
- contentType?: string;
- preview: string;
-}
-
-export type WebhookAttemptOutcome = "accepted" | "captured" | "duplicate" | "ignored" | "rejected";
-
-export interface WebhookAttempt {
- id: string;
- webhookId: string;
- receivedAt: number;
- outcome: WebhookAttemptOutcome;
- statusCode: number;
- eventName?: string;
- preview?: string;
- deliveryId?: string;
- runId?: string;
- /** room post deliveries: the room whose thread received the message. */
- threadId?: string;
- reason?: string;
-}
-
-export interface WebhookIngressStatus {
- available: boolean;
- baseUrl: string;
- error?: string;
-}
-
+export * from "../packages/phone-protocol/src/webhooks.ts";
diff --git a/shared/widget-button-style.ts b/shared/widget-button-style.ts
index 43f0efcace..5b74755659 100644
--- a/shared/widget-button-style.ts
+++ b/shared/widget-button-style.ts
@@ -1,6 +1 @@
-export function buttonStyle(raw: Record<string, unknown>): string {
- if (raw.color === "danger" || raw.style === "danger") return "danger";
- if (raw.variant === "ghost" || raw.style === "quiet") return "quiet";
- if (raw.style === "secondary" || raw.variant === "outline" || raw.variant === "soft" || raw.color === "secondary") return "secondary";
- return raw.style === "primary" || raw.color === "primary" || raw.variant === "solid" || raw.submit === true ? "primary" : "secondary";
-}
+export * from "../packages/phone-protocol/src/widget-button-style.ts";
diff --git a/shared/widget-chart.ts b/shared/widget-chart.ts
index fa7f771ac0..0f7a7b9a0a 100644
--- a/shared/widget-chart.ts
+++ b/shared/widget-chart.ts
@@ -1,126 +1 @@
-// A widget's Chart as a Vega-Lite spec, drawn with the same config as every
-// other chart, so its palette, type and hairlines match the Data panel's. Pure,
-// so the server can render the same spec headless for a client that cannot.
-import { widgetNumber, type WidgetNode } from "./widget.ts";
-
-interface ChartSeries {
- type: "bar" | "line" | "area";
- dataKey: string;
- label: string;
- stack?: string;
-}
-
-/** The inside of a 600px card, used until the chart has been measured. */
-export const WIDGET_CHART_WIDTH = 560;
-/** The legend's line under the plot. */
-const LEGEND_BAND = 24;
-
-function readChart(node: WidgetNode): { rows: Array<Record<string, unknown>>; series: ChartSeries[]; xKey: string } {
- const rows = (Array.isArray(node.data) ? node.data as unknown[] : []).filter((row): row is Record<string, unknown> => Boolean(row) && typeof row === "object" && !Array.isArray(row));
- const series = (Array.isArray(node.series) ? node.series as unknown[] : []).flatMap((item): ChartSeries[] => {
- const record: Record<string, unknown> = item && typeof item === "object" ? item as Record<string, unknown> : {};
- if (typeof record.dataKey !== "string") return [];
- return [{
- type: record.type === "line" || record.type === "area" ? record.type : "bar",
- dataKey: record.dataKey,
- label: typeof record.label === "string" ? record.label : record.dataKey,
- ...(typeof record.stack === "string" ? { stack: record.stack } : {}),
- }];
- }).slice(0, 4);
- const axis = node.xAxis && typeof node.xAxis === "object" ? node.xAxis as { dataKey?: unknown } : {};
- return { rows, series, xKey: typeof axis.dataKey === "string" ? axis.dataKey : "" };
-}
-
-/** A legend is worth its line when there is more than one series, or the one
- * series has a name of its own. */
-function hasLegend(node: WidgetNode, series: ChartSeries[]): boolean {
- return node.showLegend !== false && (series.length > 1 || (series.length === 1 && series[0]!.label !== series[0]!.dataKey));
-}
-
-/** The chart's height, legend included, for a card `width` wide: its own
- * height, else its aspect ratio, else 160; the plot never under 80 or over 400. */
-export function widgetChartHeight(node: WidgetNode, width: number): number {
- const ratio = widgetNumber(node, "aspectRatio");
- const plot = Math.round(Math.min(400, Math.max(80, widgetNumber(node, "height") ?? (ratio ? width / ratio : 160))));
- return plot + (hasLegend(node, readChart(node).series) ? LEGEND_BAND : 0);
-}
-
-/** The Vega-Lite spec for a Chart node, its rows inline and its width the
- * container's; null when there is nothing to draw. Bars that share a `stack`
- * pile up in one slot of the row's band (rising and falling piles apart); the
- * rest sit side by side. Lines and areas break where a row has no value. */
-export function widgetChartSpec(node: WidgetNode, width = WIDGET_CHART_WIDTH): Record<string, unknown> | null {
- const { rows, series, xKey } = readChart(node);
- if (!rows.length || !series.length) return null;
- const compact = new Intl.NumberFormat(undefined, { notation: "compact", maximumFractionDigits: 2 });
- const rowLabels = rows.map((row) => {
- const value = row[xKey];
- return typeof value === "string" || typeof value === "number" ? String(value) : "";
- });
- // Rows and series are keyed by position, so two rows named alike stay two
- // bands and two series labelled alike keep their own colours.
- const groups: string[] = [];
- const values = rows.flatMap((row, at) => series.map((item, index) => {
- const raw = row[item.dataKey];
- const value = typeof raw === "number" && Number.isFinite(raw) ? raw : null;
- const group = item.stack ? `stack:${item.stack}` : `series:${index}`;
- if (item.type === "bar" && !groups.includes(group)) groups.push(group);
- return { row: at, series: index, group, mark: item.type, value, tip: value === null ? null : `${rowLabels[at]} · ${item.label}: ${compact.format(value)}` };
- }));
- const highest = Math.max(0, ...values.map((datum) => Math.abs(datum.value ?? 0)));
- const showGrid = node.showGrid !== false;
- const yAxis = node.showYAxis === true
- ? { title: null, grid: showGrid, tickCount: 4, ...(highest >= 10_000 ? { format: "~s", labelExpr: "replace(datum.label, 'G', 'B')" } : {}) }
- : showGrid ? { title: null, grid: true, tickCount: 4, labels: false, ticks: false, domain: false } : null;
- const y = (stack: "zero" | null) => ({ field: "value", type: "quantitative", stack, axis: yAxis });
- const has = (type: ChartSeries["type"]) => series.some((item) => item.type === type);
- const stacked = series.some((item) => item.type === "bar" && item.stack);
- const point = rows.length > 40 ? false : { size: rows.length > 16 ? 8 : 24 };
- const layer = [
- has("bar") && {
- transform: [{ filter: "datum.mark === 'bar' && datum.value !== null" }],
- mark: { type: "bar", ...(stacked ? {} : { cornerRadiusEnd: 3 }) },
- encoding: {
- y: y("zero"),
- // the first series at the foot of its pile, as it is listed
- order: { field: "series", type: "quantitative" },
- ...(groups.length > 1 ? { xOffset: { field: "group", type: "nominal", scale: { domain: groups, paddingInner: 0.08 } } } : {}),
- },
- },
- has("area") && {
- transform: [{ filter: "datum.mark === 'area'" }],
- mark: { type: "area", opacity: 0.18, line: false },
- encoding: { y: y(null) },
- },
- (has("line") || has("area")) && {
- transform: [{ filter: "datum.mark !== 'bar'" }],
- mark: { type: "line", point },
- encoding: { y: y(null) },
- },
- ].filter(Boolean);
- const legend = hasLegend(node, series)
- ? { title: null, orient: "bottom", direction: "horizontal", symbolOpacity: 1, labelExpr: "seriesLabels[datum.value]", ...(series.reduce((sum, item) => sum + item.label.length, 0) > 48 ? { columns: 2 } : {}) }
- : null;
- return {
- $schema: "https://vega.github.io/schema/vega-lite/v6.json",
- width: "container",
- height: widgetChartHeight(node, width),
- autosize: { type: "fit", contains: "padding" },
- padding: { top: 4, right: 0, bottom: 0, left: 0 },
- params: [{ name: "rowLabels", value: rowLabels }, { name: "seriesLabels", value: series.map((item) => item.label) }],
- data: { values },
- encoding: {
- x: {
- field: "row",
- type: "ordinal",
- scale: { domain: rows.map((_, at) => at) },
- axis: { title: null, labelAngle: 0, labelLimit: 90, labelOverlap: "greedy", labelExpr: "rowLabels[datum.value]" },
- },
- color: { field: "series", type: "nominal", scale: { domain: series.map((_, index) => index) }, legend },
- // what a mark says on hover is also what it is called to a screen reader
- tooltip: { field: "tip", type: "nominal" },
- description: { field: "tip", type: "nominal" },
- },
- layer,
- };
-}
+export * from "../packages/phone-protocol/src/widget-chart.ts";
diff --git a/shared/widget-text.ts b/shared/widget-text.ts
index 6f118ad83f..1b1faa3073 100644
--- a/shared/widget-text.ts
+++ b/shared/widget-text.ts
@@ -1,58 +1 @@
-/** A moment a client words in the reader's language: `clock` "10:30 AM" (marked UTC when there is no zone),
- * `bareClock` the same never marked, `longDate` "Thursday, October 22", `shortDate` "Thu, Oct 22". */
-export interface WidgetMoment {
- at: number;
- style: "clock" | "bareClock" | "longDate" | "shortDate";
- zone?: string;
-}
-
-export type WidgetTextParam = string | number | WidgetText | WidgetMoment;
-
-/** A server card's words as a `brief.*` or `server.meetings.*` (or a cause's `chat.notice.*`) catalog key and its params, which may name other keys or moments. The node
- * keeps its English beside it, which older clients and every bot widget show. */
-export interface WidgetText {
- key: string;
- params?: Record<string, WidgetTextParam>;
-}
-
-/** The fields of one widget node a server card names by key. */
-export type WidgetTextFields = Partial<Record<"value" | "label" | "title" | "caption", WidgetText>>;
-
-const FIELDS = ["value", "label", "title", "caption"] as const;
-const KEY = /^(?:brief|chat\.notice|server\.meetings)\.[\w.]{1,80}$/;
-const STYLES = new Set<WidgetMoment["style"]>(["clock", "bareClock", "longDate", "shortDate"]);
-const MAX_PARAMS = 8;
-const MAX_DEPTH = 3;
-const MAX_STRING = 400;
-
-const isRecord = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === "object" && !Array.isArray(value);
-
-function readParam(raw: unknown, depth: number): WidgetTextParam | undefined {
- if (typeof raw === "string") return raw.slice(0, MAX_STRING);
- if (typeof raw === "number") return Number.isFinite(raw) ? raw : undefined;
- if (!isRecord(raw)) return undefined;
- if (typeof raw.at === "number" && Number.isFinite(raw.at) && STYLES.has(raw.style as WidgetMoment["style"])) {
- return { at: raw.at, style: raw.style as WidgetMoment["style"], ...(typeof raw.zone === "string" && raw.zone.length <= 64 ? { zone: raw.zone } : {}) };
- }
- return readText(raw, depth + 1);
-}
-
-function readText(raw: unknown, depth: number): WidgetText | undefined {
- if (!isRecord(raw) || typeof raw.key !== "string" || !KEY.test(raw.key) || depth > MAX_DEPTH) return undefined;
- if (raw.params === undefined) return { key: raw.key };
- if (!isRecord(raw.params)) return undefined;
- const entries = Object.entries(raw.params).slice(0, MAX_PARAMS).map(([name, value]) => [name, readParam(value, depth)] as const);
- if (entries.some(([name, value]) => value === undefined || !/^\w{1,32}$/.test(name))) return undefined;
- return { key: raw.key, params: Object.fromEntries(entries) as Record<string, WidgetTextParam> };
-}
-
-/** A node's `i18n` as it may be kept: anything malformed is dropped, and the node keeps its English. */
-export function readWidgetText(raw: unknown): WidgetTextFields | undefined {
- if (!isRecord(raw)) return undefined;
- const fields: WidgetTextFields = {};
- for (const field of FIELDS) {
- const text = readText(raw[field], 0);
- if (text) fields[field] = text;
- }
- return Object.keys(fields).length ? fields : undefined;
-}
+export * from "../packages/phone-protocol/src/widget-text.ts";
diff --git a/shared/widget.ts b/shared/widget.ts
index 7311f281fd..73464df109 100644
--- a/shared/widget.ts
+++ b/shared/widget.ts
@@ -1,996 +1 @@
-// A bot-authored chat widget: the JSON tree `show_widget` posts as a message
-// of kind "widget". Node names and props follow ChatKit's widget components.
-// Model input is normalised here once; every renderer reads canonical trees only.
-import type { JsonValue } from "./json.ts";
-import { readWidgetText } from "./widget-text.ts";
-import { buttonStyle } from "./widget-button-style.ts";
-
-export const WIDGET_VERSION = 1;
-
-/** Past any of these, model input is refused with the path of the problem. */
-export const WIDGET_LIMITS = {
- bytes: 32_000,
- nodes: 250,
- depth: 10,
- listItems: 40,
- options: 40,
- fields: 20,
- tableRows: 60,
- tableCols: 8,
- chartRows: 100,
- chartSeries: 4,
- images: 6,
- text: 2_000,
- markdown: 6_000,
- title: 120,
- caption: 240,
- label: 80,
- actionPayloadBytes: 2_000,
- fieldValue: 2_000,
- fallback: 1_500,
-} as const;
-
-/** ChatKit's icon names, plus a few this app needs. Each platform maps them
- * to its own set; a name outside this list never reaches a renderer. */
-export const WIDGET_ICON_NAMES: readonly string[] = [
- "info", "agent", "analytics", "atom", "batch", "bolt", "book-open", "book-closed", "book-clock", "bug", "calendar",
- "chart", "check", "check-circle", "check-circle-filled", "chevron-left", "chevron-right", "circle-question", "compass",
- "confetti", "cube", "desktop", "document", "dot", "dots-horizontal", "dots-vertical", "empty-circle", "external-link",
- "globe", "keys", "lab", "images", "lifesaver", "lightbulb", "mail", "map-pin", "maps", "mobile", "name", "notebook",
- "notebook-pencil", "page-blank", "phone", "play", "plus", "profile", "profile-card", "reload", "star", "star-filled",
- "search", "sparkle", "sparkle-double", "square-code", "square-image", "square-text", "suitcase", "settings-slider",
- "user", "wreath", "write", "write-alt", "write-alt2",
- "pull-request", "upload", "download", "clock", "lock", "link", "file", "folder", "bell", "warning", "close", "arrow-right",
-];
-
-export interface WidgetAction {
- type: string;
- payload?: JsonValue;
-}
-
-/** The shape of a thread id a widget action may name. */
-export const THREAD_ID = /^[\w-]{1,128}$/;
-
-/** `open_thread` is handled on the device. The ids are written by a bot: untrusted, and only their shape is checked here. */
-export function threadActionTarget(action: WidgetAction): { botId?: string; groupId?: string; threadId: string } | undefined {
- if (action.type !== "open_thread" || !isRecord(action.payload)) return undefined;
- const { botId, groupId, threadId } = action.payload;
- if (typeof threadId !== "string" || !THREAD_ID.test(threadId)) return undefined;
- if (typeof botId === "string" && THREAD_ID.test(botId) && groupId === undefined) return { botId, threadId };
- if (typeof groupId === "string" && THREAD_ID.test(groupId) && botId === undefined) return { groupId, threadId };
- return undefined;
-}
-
-export const isThreadAction = (action: WidgetAction): boolean => threadActionTarget(action) !== undefined;
-
-/** `open_phone_pairing` opens the app's own phone pairing (the QR code and link) on the device. */
-export const PHONE_PAIRING_ACTION = "open_phone_pairing";
-const CLIENT_ACTION = (action: WidgetAction): boolean => action.type === "open_url" || action.type === "open_thread" || action.type === PHONE_PAIRING_ACTION;
-
-/** `confirm` and `cancel` on a root: the buttons under the card. */
-export interface WidgetButtonSpec {
- label: string;
- action: WidgetAction;
-}
-
-/** One canonical node. `id` is assigned here ("n1", "n2", ... in document
- * order) and is how a press names its button. */
-export interface WidgetNode {
- type: string;
- id: string;
- children?: WidgetNode[];
- [prop: string]: unknown;
-}
-
-/** A canonical root: type "Card" or "ListView". */
-export type WidgetRoot = WidgetNode;
-
-/** A widget that took its one answer: it folds to a line and takes no more presses. */
-export interface WidgetSettled {
- ref: string;
- label: string;
- tone: "confirm" | "cancel" | "submit";
- at: number;
- sendId?: string;
- /** The field values that went with the press, for the read-only Details view. */
- values?: WidgetValues;
- /** The person's own words for a choice they answered with Other, by field name. */
- other?: WidgetOther;
- /** Set while the press waits in the steer queue behind a running turn:
- * cancelling that queued message reopens the widget. */
- queueId?: string;
-}
-
-export interface WidgetPayload {
- v: 1;
- root: WidgetRoot;
- /** How many times show_widget has replaced the tree (absent: never). An
- * update renumbers node ids, so a press names the revision it was made on
- * and one made on an older tree is refused instead of landing on whatever
- * now holds that id. */
- rev?: number;
- settled?: WidgetSettled;
-}
-
-export type WidgetValues = Record<string, string | boolean>;
-
-/** A press's answers in the person's own words, by field name: only for a field where
- * `widgetTakesOther` holds, and that field's own value is then "". */
-export type WidgetOther = Record<string, string>;
-
-export type ParsedWidgetInput = { ok: true; value: WidgetRoot } | { ok: false; error: string };
-
-const ROOT_TYPES = new Set(["Card", "ListView"]);
-const FIELD_TYPES = new Set(["Select", "DatePicker", "TimePicker", "DayPicker", "Checkbox", "RadioGroup", "Input", "Textarea"]);
-const TYPE_ALIASES: Record<string, string> = { TableRow: "Table.Row", TableCell: "Table.Cell" };
-const ACTION_TYPE = /^[A-Za-z0-9_.:-]{1,64}$/;
-const FIELD_NAME = /^[A-Za-z0-9_.-]{1,64}$/;
-const ISO_DATE = /^\d{4}-\d{2}-\d{2}$/;
-const TIME_OF_DAY = /^([01]\d|2[0-3]):[0-5]\d$/;
-/** Days of the week as a DayPicker stores them, in the order it draws them. */
-export const WIDGET_WEEKDAYS: readonly string[] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
-
-class WidgetInputError extends Error {}
-
-function fail(path: string, message: string): never {
- throw new WidgetInputError(`${path}: ${message}`);
-}
-
-function isRecord(value: unknown): value is Record<string, unknown> {
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
-}
-
-const clamp = (value: number, low: number, high: number) => Math.min(high, Math.max(low, value));
-
-// A reader turns one raw prop into its canonical value. `undefined` drops the
-// prop (a lenient miss: an unknown token, a CSS value this app does not take).
-// A reader throws only where a silently dropped value would post a broken or
-// misleading card (a missing label, a bad action, a password field).
-
-type Reader = (raw: unknown, path: string) => unknown;
-
-function text(max: number, mode: "optional" | "required" | "nonEmpty" = "optional"): Reader {
- return (raw, path) => {
- if (raw === undefined || raw === null) return mode === "optional" ? undefined : fail(path, "is required");
- if (typeof raw !== "string" && typeof raw !== "number") return fail(path, "must be a string");
- const value = String(raw).trim();
- if (value.length > max) return fail(path, `must be at most ${max} characters`);
- if (!value && mode === "nonEmpty") return fail(path, "must not be blank");
- if (!value && mode === "optional") return undefined;
- return value;
- };
-}
-
-/** One line of text: a label, a title, a placeholder. A run of whitespace,
- * line breaks included, becomes one space, so nothing a bot writes into a
- * label can add a line to the message a press is recorded as. */
-function line(max: number, mode: "optional" | "required" | "nonEmpty" = "optional"): Reader {
- const read = text(max, mode);
- return (raw, path) => read(typeof raw === "string" ? raw.replace(/\s+/g, " ") : raw, path);
-}
-
-function oneOf(...values: string[]): Reader {
- return (raw) => (typeof raw === "string" && values.includes(raw) ? raw : undefined);
-}
-
-function mapped(map: Record<string, string>): Reader {
- return (raw) => (typeof raw === "string" && Object.hasOwn(map, raw) ? map[raw] : undefined);
-}
-
-const on: Reader = (raw) => (raw === true ? true : undefined);
-/** For props whose default is on: only an explicit `false` is kept. */
-const off: Reader = (raw) => (raw === false ? false : undefined);
-
-function pxOf(raw: unknown): number | undefined {
- const match = typeof raw === "string" ? /^(\d+(?:\.\d+)?)px$/.exec(raw.trim()) : null;
- return match ? Number(match[1]) : undefined;
-}
-
-/** A ChatKit spacing value: a unit (4px each) or a px string. */
-function spacing(max = 64): Reader {
- return (raw) => {
- const px = typeof raw === "number" && Number.isFinite(raw) ? raw * 4 : pxOf(raw);
- return px === undefined ? undefined : clamp(Math.round(px), 0, max);
- };
-}
-
-/** A ChatKit size: px as a number or a px string; "100%" is "full". */
-function length(max = 2_000): Reader {
- return (raw) => {
- if (raw === "100%" || raw === "full") return "full";
- const px = typeof raw === "number" && Number.isFinite(raw) ? raw : pxOf(raw);
- // under a pixel is not a size: it is how content gets hidden
- return px === undefined || px < 1 ? undefined : clamp(Math.round(px), 1, max);
- };
-}
-
-function integer(min: number, max: number): Reader {
- return (raw) => {
- const value = typeof raw === "string" && raw.trim() ? Number(raw) : raw;
- return typeof value === "number" && Number.isFinite(value) ? clamp(Math.round(value), min, max) : undefined;
- };
-}
-
-function decimal(min: number, max: number): Reader {
- return (raw) => {
- const value = typeof raw === "string" && raw.trim() ? Number(raw) : raw;
- return typeof value === "number" && Number.isFinite(value) ? clamp(value, min, max) : undefined;
- };
-}
-
-const padding: Reader = (raw) => {
- const side = spacing();
- if (!isRecord(raw)) {
- const all = side(raw, "");
- return typeof all === "number" ? [all, all, all, all] : undefined;
- }
- const pick = (...keys: string[]) => {
- for (const key of keys) {
- const value = side(raw[key], "");
- if (typeof value === "number") return value;
- }
- return 0;
- };
- const sides = [pick("top", "y"), pick("right", "x"), pick("bottom", "y"), pick("left", "x")];
- return sides.some(Boolean) ? sides : undefined;
-};
-
-const RADII: Record<string, number> = { none: 0, "2xs": 2, xs: 4, sm: 6, md: 8, lg: 12, xl: 16, "2xl": 20, "3xl": 24, "4xl": 28, full: 999, "100%": 999 };
-const radius: Reader = (raw) => (typeof raw === "number" && Number.isFinite(raw) ? clamp(Math.round(raw), 0, 999) : typeof raw === "string" && Object.hasOwn(RADII, raw) ? RADII[raw] : undefined);
-
-const aspectRatio: Reader = (raw) => {
- const parts = typeof raw === "string" ? /^(\d+(?:\.\d+)?)\s*\/\s*(\d+(?:\.\d+)?)$/.exec(raw.trim()) : null;
- const value = parts ? Number(parts[1]) / Number(parts[2]) : typeof raw === "string" ? Number(raw) : raw;
- return typeof value === "number" && Number.isFinite(value) && value > 0 ? clamp(value, 0.1, 10) : undefined;
-};
-
-const background = mapped({
- surface: "surface", secondary: "secondary", tertiary: "tertiary", elevated: "elevated",
- "surface-secondary": "secondary", "surface-tertiary": "tertiary", "surface-elevated": "elevated", "surface-elevated-secondary": "elevated",
-});
-const inkColor = mapped({ prose: "primary", primary: "primary", emphasis: "primary", secondary: "secondary", tertiary: "tertiary", success: "success", warning: "warning", danger: "danger" });
-const border: Reader = (raw) => {
- const size = isRecord(raw) ? raw.size : raw;
- return typeof size === "number" && Number.isFinite(size) && size > 0 ? clamp(Math.round(size), 1, 2) : undefined;
-};
-const weight = oneOf("normal", "medium", "semibold", "bold");
-const textAlign = oneOf("start", "center", "end");
-
-function icon(fallback?: string): Reader {
- return (raw) => (typeof raw === "string" && WIDGET_ICON_NAMES.includes(raw) ? raw : raw === undefined || raw === null ? undefined : fallback);
-}
-
-/** A layout share. Two decimals is finer than any screen; a share that rounds
- * to nothing is dropped, because a zero weight is an error in a renderer. */
-const flexShare: Reader = (raw, path) => {
- const share = decimal(0, 12)(raw, path);
- const rounded = typeof share === "number" ? Math.round(share * 100) / 100 : 0;
- return rounded > 0 ? rounded : undefined;
-};
-
-/** The dates a picker may be asked to show. Far outside them a platform's own
- * calendar range runs out. */
-const DATE_YEARS = { min: 1900, max: 2200 } as const;
-
-const isoDate: Reader = (raw) => {
- if (typeof raw !== "string" || !ISO_DATE.test(raw) || Number.isNaN(Date.parse(`${raw}T00:00:00Z`))) return undefined;
- const year = Number(raw.slice(0, 4));
- return year >= DATE_YEARS.min && year <= DATE_YEARS.max ? raw : undefined;
-};
-
-/** A time of day, "HH:MM" on a 24-hour clock. "9:05" and "09:05:00" are read as 09:05. */
-const timeOfDay: Reader = (raw) => {
- const match = typeof raw === "string" ? /^(\d{1,2}):(\d{2})(?::\d{2})?$/.exec(raw.trim()) : null;
- const value = match ? `${match[1].padStart(2, "0")}:${match[2]}` : undefined;
- return value && TIME_OF_DAY.test(value) ? value : undefined;
-};
-
-/** Days of the week: an array or a comma list of names ("mon", "Monday",
- * "MON"), stored as a comma list in week order with no repeats. */
-function weekdays(raw: unknown): string | undefined {
- const items = Array.isArray(raw) ? raw : typeof raw === "string" ? raw.split(",") : [];
- const picked = new Set(items.filter((item): item is string => typeof item === "string").map((item) => item.trim().toLowerCase().slice(0, 3)));
- const days = WIDGET_WEEKDAYS.filter((day) => picked.has(day));
- return days.length ? days.join(",") : undefined;
-}
-const weekdaysReader: Reader = (raw) => weekdays(raw);
-
-/** A Progress value: a fraction from 0 to 1. A bot that writes a percentage
- * (75, or "75%") means a percentage. */
-const progressValue: Reader = (raw) => {
- const percent = typeof raw === "string" ? /^\s*(\d+(?:\.\d+)?)\s*%\s*$/.exec(raw) : null;
- const value = percent ? Number(percent[1]) / 100 : typeof raw === "string" && raw.trim() ? Number(raw) : raw;
- if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return undefined;
- return clamp(value > 1 && value <= 100 ? value / 100 : value, 0, 1);
-};
-
-const action: Reader = (raw, path) => {
- if (raw === undefined || raw === null) return undefined;
- if (!isRecord(raw) || typeof raw.type !== "string" || !ACTION_TYPE.test(raw.type)) {
- return fail(path, 'must be {type, payload?} with a type of letters, digits and "_.:-"');
- }
- const out: WidgetAction = { type: raw.type };
- if (raw.payload !== undefined) {
- const json = JSON.stringify(raw.payload);
- if (json === undefined) return fail(`${path}.payload`, "must be JSON");
- if (json.length > WIDGET_LIMITS.actionPayloadBytes) return fail(`${path}.payload`, `must be at most ${WIDGET_LIMITS.actionPayloadBytes} characters of JSON`);
- out.payload = JSON.parse(json) as JsonValue;
- }
- if (out.type === "open_url" && !isWebUrl(isRecord(out.payload) ? out.payload.url : undefined, ["http:", "https:"])) {
- return fail(`${path}.payload.url`, "open_url needs an http or https url");
- }
- if (out.type === "open_thread" && !threadActionTarget(out)) {
- return fail(`${path}.payload`, "open_thread needs {botId, threadId} or {groupId, threadId}");
- }
- return out;
-};
-
-/** The longest url a widget action or image may carry. */
-export const WEB_URL_MAX = 2_000;
-
-function isWebUrl(value: unknown, protocols: string[]): value is string {
- if (typeof value !== "string" || value.length > WEB_URL_MAX) return false;
- try {
- return protocols.includes(new URL(value).protocol);
- } catch {
- return false;
- }
-}
-
-const buttonSpec: Reader = (raw, path) => {
- if (raw === undefined || raw === null) return undefined;
- if (!isRecord(raw)) return fail(path, "must be {label, action}");
- const spec: WidgetButtonSpec = {
- label: line(WIDGET_LIMITS.label, "nonEmpty")(raw.label, `${path}.label`) as string,
- action: (action(raw.action, `${path}.action`) ?? fail(`${path}.action`, "is required")) as WidgetAction,
- };
- return spec;
-};
-
-const status: Reader = (raw, path) => {
- if (raw === undefined || raw === null) return undefined;
- const record: Record<string, unknown> = isRecord(raw) ? raw : { text: raw };
- const label = line(WIDGET_LIMITS.caption, "nonEmpty")(record.text, `${path}.text`);
- const name = icon()(record.icon, `${path}.icon`);
- return name ? { text: label, icon: name } : { text: label };
-};
-
-const options: Reader = (raw, path) => {
- if (!Array.isArray(raw) || raw.length < 1 || raw.length > WIDGET_LIMITS.options) return fail(path, `needs 1 to ${WIDGET_LIMITS.options} items`);
- const seen = new Set<string>();
- return raw.map((item, index) => {
- const at = `${path}[${index}]`;
- const record: Record<string, unknown> = isRecord(item) ? item : { value: item };
- const value = line(200, "nonEmpty")(typeof record.value === "boolean" ? String(record.value) : record.value, `${at}.value`) as string;
- if (seen.has(value)) return fail(at, `repeats the value ${JSON.stringify(value)}`);
- seen.add(value);
- return { label: (line(WIDGET_LIMITS.label)(record.label, `${at}.label`) as string | undefined) ?? value, value };
- });
-};
-
-/** Names that would write to an object's prototype instead of naming a value. */
-const UNSAFE_KEYS = new Set(["__proto__", "constructor", "prototype"]);
-const fieldName: Reader = (raw, path) => (typeof raw === "string" && FIELD_NAME.test(raw) && !raw.split(".").some((part) => UNSAFE_KEYS.has(part))
- ? raw
- : fail(path, 'is required: letters, digits and "_.-", at most 64'));
-
-const optionalFieldName: Reader = (raw, path) => (raw === undefined || raw === null ? undefined : fieldName(raw, path));
-
-const inputType: Reader = (raw, path) => {
- if (raw === "password") return fail(path, "password fields are not allowed in a widget; use request_credential for secrets");
- return oneOf("text", "number", "email", "tel", "url")(raw, path);
-};
-
-const imageSrc: Reader = (raw, path) => (isWebUrl(raw, ["https:"]) ? raw : fail(path, "must be an https url"));
-
-const CHART_MAX = 1e12;
-
-const chartData: Reader = (raw, path) => {
- if (!Array.isArray(raw) || raw.length < 1 || raw.length > WIDGET_LIMITS.chartRows) return fail(path, `needs 1 to ${WIDGET_LIMITS.chartRows} rows`);
- return raw.map((row, index) => {
- if (!isRecord(row)) return fail(`${path}[${index}]`, "must be an object");
- const out: Record<string, string | number | null> = {};
- for (const [key, value] of Object.entries(row).slice(0, 12)) {
- if (UNSAFE_KEYS.has(key)) continue;
- if (typeof value === "number" ? Number.isFinite(value) : typeof value === "string" || value === null) {
- // a chart library lays out what it is given: keep numbers within what every one of them can
- out[key.slice(0, 64)] = typeof value === "string" ? value.slice(0, 120) : typeof value === "number" ? clamp(value, -CHART_MAX, CHART_MAX) : null;
- }
- }
- return out;
- });
-};
-
-const chartSeries: Reader = (raw, path) => {
- if (!Array.isArray(raw) || raw.length < 1 || raw.length > WIDGET_LIMITS.chartSeries) return fail(path, `needs 1 to ${WIDGET_LIMITS.chartSeries} series`);
- return raw.map((item, index) => {
- const at = `${path}[${index}]`;
- if (!isRecord(item)) return fail(at, "must be {type, dataKey}");
- const series: Record<string, string> = {
- type: (oneOf("bar", "line", "area")(item.type, at) as string | undefined) ?? "bar",
- dataKey: text(64, "nonEmpty")(item.dataKey, `${at}.dataKey`) as string,
- };
- const label = line(WIDGET_LIMITS.label)(item.label, `${at}.label`);
- if (typeof label === "string") series.label = label;
- const stack = text(32)(item.stack, `${at}.stack`);
- if (typeof stack === "string") series.stack = stack;
- return series;
- });
-};
-
-const chartAxis: Reader = (raw, path) => ({ dataKey: text(64, "nonEmpty")(isRecord(raw) ? raw.dataKey : raw, `${path}.dataKey`) });
-
-
-const LAYOUT: Record<string, Reader> = {
- gap: spacing(),
- padding,
- align: oneOf("start", "center", "end", "baseline", "stretch"),
- justify: oneOf("start", "center", "end", "between", "around", "evenly", "stretch"),
- wrap: (raw) => (raw === true || raw === "wrap" ? true : undefined),
- flex: flexShare,
- width: length(), height: length(), minWidth: length(), maxWidth: length(), minHeight: length(), maxHeight: length(),
- aspectRatio, background, border, radius,
-};
-const TEXT_STYLE: Record<string, Reader> = { weight, color: inkColor, textAlign, truncate: on, maxLines: integer(1, 20), width: length() };
-const ROOT: Record<string, Reader> = {
- title: line(WIDGET_LIMITS.title), caption: line(WIDGET_LIMITS.caption), meta: line(WIDGET_LIMITS.label), status,
- confirm: buttonSpec, cancel: buttonSpec,
-};
-/** Every control: its name, and a label drawn with it, which also names it in
- * the message a press is recorded as. */
-const FIELD: Record<string, Reader> = { name: fieldName, label: line(WIDGET_LIMITS.title), disabled: on, required: on };
-const PLACEHOLDER = line(WIDGET_LIMITS.title);
-
-interface NodeSpec {
- props: Record<string, Reader>;
- children?: "any" | "items" | "rows" | "cells" | "one";
-}
-
-const SPECS: Record<string, NodeSpec> = {
- Card: { props: { ...ROOT, size: oneOf("sm", "md", "lg", "full"), padding }, children: "any" },
- // `name` makes the list a choice: its rows are selectable, one at a time, and
- // the chosen row's `value` travels with confirm like any other field.
- ListView: { props: { ...ROOT, limit: integer(1, WIDGET_LIMITS.listItems), name: optionalFieldName, defaultValue: line(200) }, children: "items" },
- ListViewItem: { props: { gap: spacing(), align: LAYOUT.align, onClickAction: action, value: line(200) }, children: "any" },
- Box: { props: { ...LAYOUT, direction: oneOf("row", "col") }, children: "any" },
- Row: { props: LAYOUT, children: "any" },
- Col: { props: LAYOUT, children: "any" },
- Form: { props: { ...LAYOUT, direction: oneOf("row", "col"), onSubmitAction: action }, children: "any" },
- Spacer: { props: { minSize: length(400) } },
- Divider: { props: { spacing: spacing(), flush: on } },
- Table: { props: {}, children: "rows" },
- "Table.Row": { props: { header: on }, children: "cells" },
- "Table.Cell": {
- props: { align: textAlign, vAlign: textAlign, colSpan: integer(1, WIDGET_LIMITS.tableCols), rowSpan: integer(1, 20), width: length(), colSize: oneOf("xs", "sm", "md", "lg", "xl"), padding },
- children: "any",
- },
- Text: { props: { value: text(WIDGET_LIMITS.text, "required"), size: oneOf("xs", "sm", "md", "lg", "xl"), ...TEXT_STYLE, italic: on, lineThrough: on, minLines: integer(1, 20) } },
- Title: { props: { value: text(WIDGET_LIMITS.text, "required"), size: oneOf("sm", "md", "lg", "xl", "2xl", "3xl", "4xl", "5xl"), ...TEXT_STYLE } },
- Caption: { props: { value: text(WIDGET_LIMITS.text, "required"), size: oneOf("sm", "md", "lg"), ...TEXT_STYLE } },
- Label: { props: { value: line(WIDGET_LIMITS.title, "nonEmpty"), fieldName: text(64), size: oneOf("xs", "sm", "md", "lg", "xl"), weight, color: inkColor, textAlign, width: length() } },
- Markdown: { props: { value: text(WIDGET_LIMITS.markdown, "required") } },
- Image: {
- props: {
- src: imageSrc, alt: line(WIDGET_LIMITS.caption), fit: oneOf("none", "fill", "cover", "contain", "scale-down"),
- position: oneOf("center", "top", "bottom", "left", "right", "top left", "top right", "bottom left", "bottom right"),
- frame: on, flush: on, width: length(), height: length(), minWidth: length(), maxWidth: length(), minHeight: length(), maxHeight: length(), aspectRatio, radius,
- },
- },
- Icon: { props: { name: icon("dot"), color: inkColor, size: oneOf("xs", "sm", "md", "lg", "xl", "2xl", "3xl") } },
- Chart: { props: { data: chartData, series: chartSeries, xAxis: chartAxis, showYAxis: on, showLegend: off, showGrid: off, height: length(400), aspectRatio, flex: flexShare, width: length() } },
- Badge: { props: { label: line(WIDGET_LIMITS.label, "nonEmpty"), color: oneOf("secondary", "success", "danger", "warning", "info", "discovery"), variant: oneOf("soft", "solid", "outline", "dot"), size: oneOf("sm", "md", "lg"), pill: off } },
- Progress: { props: { value: progressValue, label: line(WIDGET_LIMITS.caption) } },
- Button: { props: { label: line(WIDGET_LIMITS.label), iconStart: icon(), iconEnd: icon(), block: on, disabled: on, submit: on, onClickAction: action } },
- Select: { props: { ...FIELD, options, placeholder: PLACEHOLDER, defaultValue: text(200), clearable: on, block: on } },
- DatePicker: { props: { ...FIELD, placeholder: PLACEHOLDER, defaultValue: isoDate, min: isoDate, max: isoDate, clearable: on, block: on } },
- // MausBot additions: a time of day, and days of the week
- TimePicker: { props: { ...FIELD, placeholder: PLACEHOLDER, defaultValue: timeOfDay, min: timeOfDay, max: timeOfDay, step: integer(1, 60), clearable: on, block: on } },
- DayPicker: { props: { ...FIELD, defaultValue: weekdaysReader } },
- Checkbox: { props: { ...FIELD, defaultChecked: on } },
- RadioGroup: { props: { ...FIELD, options, defaultValue: text(200), direction: oneOf("row", "col"), ariaLabel: line(WIDGET_LIMITS.title) } },
- Input: { props: { ...FIELD, inputType, placeholder: PLACEHOLDER, defaultValue: text(WIDGET_LIMITS.fieldValue), pattern: text(200) } },
- Textarea: { props: { ...FIELD, placeholder: PLACEHOLDER, defaultValue: text(WIDGET_LIMITS.fieldValue), rows: integer(1, 12), maxRows: integer(1, 20), autoResize: on } },
- Transition: { props: {}, children: "one" },
-};
-
-/** Every node type a widget may contain, roots first. */
-export const WIDGET_NODE_TYPES: readonly string[] = Object.keys(SPECS);
-
-interface Context {
- nodes: number;
- images: number;
- fields: Set<string>;
-}
-
-function typeOf(raw: Record<string, unknown>): string {
- return typeof raw.type === "string" ? TYPE_ALIASES[raw.type] ?? raw.type : "";
-}
-
-function normalize(input: unknown, path: string, depth: number, slot: "root" | "any" | "items" | "rows" | "cells", context: Context): WidgetNode {
- if (!isRecord(input)) return fail(path, "must be an object with a type");
- let raw = input;
- let type = typeOf(raw);
- if (!Object.hasOwn(SPECS, type)) return fail(path, `unknown type ${JSON.stringify(raw.type)}; use one of ${WIDGET_NODE_TYPES.join(", ")}`);
- if (slot === "items" && type !== "ListViewItem") [raw, type] = [{ type: "ListViewItem", children: [raw] }, "ListViewItem"];
- if (slot === "cells" && type !== "Table.Cell") [raw, type] = [{ type: "Table.Cell", children: [raw] }, "Table.Cell"];
- if (slot === "rows" && type !== "Table.Row") return fail(path, "a Table takes Table.Row children");
- if (slot !== "root" && ROOT_TYPES.has(type)) return fail(path, `${type} is a root and cannot be nested`);
- if (slot === "any" && (type === "Table.Row" || type === "Table.Cell")) return fail(path, `${type} belongs inside a Table`);
- if (depth > WIDGET_LIMITS.depth) return fail(path, `is nested deeper than ${WIDGET_LIMITS.depth} levels`);
- context.nodes += 1;
- if (context.nodes > WIDGET_LIMITS.nodes) return fail(path, `the widget has more than ${WIDGET_LIMITS.nodes} nodes`);
-
- const spec = SPECS[type];
- const node: WidgetNode = { type, id: `n${context.nodes}` };
- const source: Record<string, unknown> = { ...raw };
- // ChatKit's shorthands for both axes.
- for (const [shorthand, a, b] of [["size", "width", "height"], ["minSize", "minWidth", "minHeight"], ["maxSize", "maxWidth", "maxHeight"]] as const) {
- const both = source[shorthand];
- // `size` on text, icons and badges is a token, not a length.
- if (type === "Card" || type === "Spacer" || !(typeof both === "number" || both === "100%" || pxOf(both) !== undefined)) continue;
- source[a] ??= both;
- source[b] ??= both;
- }
- for (const [key, read] of Object.entries(spec.props)) {
- const value = read(source[key], `${path}.${key}`);
- if (value !== undefined) node[key] = value;
- }
- if (type === "Button") node.style = buttonStyle(raw);
- if (raw.i18n !== undefined) node.i18n = readWidgetText(raw.i18n);
- if (type === "Icon") node.name ??= "dot";
- if (type === "Progress") {
- const max = typeof raw.max === "number" && Number.isFinite(raw.max) && raw.max > 0 ? raw.max : undefined;
- const given = typeof raw.value === "number" && Number.isFinite(raw.value) ? raw.value : undefined;
- // {value: 3, max: 4} is three quarters
- if (max !== undefined && given !== undefined) node.value = clamp(given / max, 0, 1);
- if (node.value === undefined) return fail(`${path}.value`, "is required: a number from 0 to 1");
- }
- if (type === "Image" && ++context.images > WIDGET_LIMITS.images) return fail(path, `the widget has more than ${WIDGET_LIMITS.images} images`);
- if (FIELD_TYPES.has(type)) {
- const name = node.name as string;
- if (context.fields.has(name)) return fail(`${path}.name`, `repeats the field name ${JSON.stringify(name)}`);
- context.fields.add(name);
- if (context.fields.size > WIDGET_LIMITS.fields) return fail(path, `the widget has more than ${WIDGET_LIMITS.fields} fields`);
- if (type === "TimePicker" || type === "DatePicker") {
- if (typeof node.min === "string" && typeof node.max === "string" && node.min > node.max) delete node.max;
- const picked = node.defaultValue;
- if (typeof picked === "string" && ((typeof node.min === "string" && picked < node.min) || (typeof node.max === "string" && picked > node.max))) delete node.defaultValue;
- }
- const chosen = node.defaultValue;
- if ((type === "Select" || type === "RadioGroup") && chosen !== undefined && !(node.options as Array<{ value: string }>).some((option) => option.value === chosen)) delete node.defaultValue;
- if (type === "Select" || type === "RadioGroup") node.allowOther = raw.allowOther !== false;
- }
-
- if (spec.children) {
- const list = raw.children === undefined || raw.children === null ? [] : Array.isArray(raw.children) ? raw.children : [raw.children];
- const kept = spec.children === "one" ? list.slice(0, 1) : list;
- if (type === "ListView" && kept.length > WIDGET_LIMITS.listItems) return fail(`${path}.children`, `a list takes at most ${WIDGET_LIMITS.listItems} items`);
- if (type === "Table" && kept.length > WIDGET_LIMITS.tableRows) return fail(`${path}.children`, `a table takes at most ${WIDGET_LIMITS.tableRows} rows`);
- if (type === "Table.Row" && kept.length > WIDGET_LIMITS.tableCols) return fail(`${path}.children`, `a row takes at most ${WIDGET_LIMITS.tableCols} cells`);
- const childSlot = spec.children === "one" ? "any" : spec.children;
- node.children = kept.map((child, index) => normalize(child, `${path}.children[${index}]`, depth + 1, childSlot, context));
- }
- if (type === "ListView") {
- if (typeof node.name === "string") selectable(node, raw, path, context);
- else {
- // not a choice: a row's value and a default mean nothing here
- delete node.defaultValue;
- for (const row of node.children ?? []) delete row.value;
- }
- }
- if (type === "ListViewItem" && slot !== "items") delete node.value;
- return node;
-}
-
-/** A list with a `name`: each row gets a distinct `value` (its own, else the
- * row's name, else its position), a press on a row selects it, and the list
- * is required unless it says otherwise. It needs `confirm`, the only thing
- * that can send the choice. */
-function selectable(list: WidgetNode, raw: Record<string, unknown>, path: string, context: Context): void {
- const name = list.name as string;
- if (context.fields.has(name)) fail(`${path}.name`, `repeats the field name ${JSON.stringify(name)}`);
- context.fields.add(name);
- if (context.fields.size > WIDGET_LIMITS.fields) fail(path, `the widget has more than ${WIDGET_LIMITS.fields} fields`);
- if (!isRecord(list.confirm)) fail(`${path}.confirm`, "a list with a name lets the person choose a row; it needs confirm: {label, action} to send the choice");
- const rows = list.children ?? [];
- if (rows.length < 2) fail(`${path}.children`, "a list with a name needs at least two rows to choose from");
- const seen = new Set<string>();
- rows.forEach((row, index) => {
- const at = `${path}.children[${index}]`;
- if (row.onClickAction !== undefined) fail(`${at}.onClickAction`, "the rows of a list with a name are selected, not pressed; remove onClickAction from the rows, or remove name from the list");
- const value = widgetString(row, "value") ?? (firstText(row) || String(index + 1));
- if (seen.has(value)) fail(`${at}.value`, `repeats the value ${JSON.stringify(value)}; give each row its own value`);
- seen.add(value);
- row.value = value;
- });
- if (raw.required !== false) list.required = true;
- list.allowOther = raw.allowOther !== false;
- if (typeof list.defaultValue === "string" && !seen.has(list.defaultValue)) delete list.defaultValue;
-}
-
-/** Whether a field offers Other: the person may answer in their own words instead of an option. A tree stored
- * before this existed has no `allowOther`, so it offers only its options. */
-export function widgetTakesOther(node: WidgetNode): boolean {
- return node.allowOther === true && (node.type === "Select" || node.type === "RadioGroup" || (node.type === "ListView" && typeof node.name === "string"));
-}
-
-/** Normalise untrusted model input into a canonical tree, or say what is
- * wrong with it in one sentence that names the path. */
-export function parseWidgetInput(value: unknown): ParsedWidgetInput {
- let raw = value;
- if (typeof raw === "string") {
- try {
- raw = JSON.parse(raw);
- } catch {
- return { ok: false, error: "widget: must be a JSON object, not text." };
- }
- }
- if (!isRecord(raw)) return { ok: false, error: "widget: must be an object with a type." };
- let bytes: number;
- try {
- bytes = JSON.stringify(raw).length;
- } catch {
- return { ok: false, error: "widget: must be plain JSON." };
- }
- if (bytes > WIDGET_LIMITS.bytes) return { ok: false, error: `widget: is ${bytes} characters of JSON; keep it under ${WIDGET_LIMITS.bytes}.` };
- try {
- const rooted = ROOT_TYPES.has(typeOf(raw)) ? raw : { type: "Card", children: [raw] };
- const root = normalize(rooted, "widget", 1, "root", { nodes: 0, images: 0, fields: new Set() });
- const seen = new Map<string, string>();
- for (const entry of collectActions(root, true)) {
- if (!entry.label) return { ok: false, error: `widget: the ${entry.kind} at ${entry.ref} has an action but no label; give it a label (a list item takes its first Text or Title).` };
- if (entry.client) continue;
- if (seen.has(entry.label)) return { ok: false, error: `widget: two actions are both labelled ${JSON.stringify(entry.label)}; give each a distinct label.` };
- seen.set(entry.label, entry.ref);
- }
- return { ok: true, value: root };
- } catch (error) {
- if (error instanceof WidgetInputError) return { ok: false, error: `${error.message}.` };
- throw error;
- }
-}
-
-
-export const widgetString = (node: WidgetNode, key: string): string | undefined => (typeof node[key] === "string" ? node[key] as string : undefined);
-export const widgetNumber = (node: WidgetNode, key: string): number | undefined => (typeof node[key] === "number" ? node[key] as number : undefined);
-
-function buttonSpecOf(root: WidgetRoot, key: "confirm" | "cancel"): WidgetButtonSpec | undefined {
- const spec = root[key];
- return isRecord(spec) && typeof spec.label === "string" && isRecord(spec.action) ? spec as unknown as WidgetButtonSpec : undefined;
-}
-
-function walk(node: WidgetNode, visit: (node: WidgetNode, ancestors: WidgetNode[]) => void, ancestors: WidgetNode[] = []): void {
- visit(node, ancestors);
- const next = [...ancestors, node];
- for (const child of Array.isArray(node.children) ? node.children : []) if (isRecord(child)) walk(child, visit, next);
-}
-
-function lastOf<T>(items: readonly T[], match: (item: T) => boolean): T | undefined {
- for (let index = items.length - 1; index >= 0; index -= 1) if (match(items[index])) return items[index];
- return undefined;
-}
-
-/** What a row is called: its first Title or Text, on one line. A text held
- * to a fixed width is a column label ("TO"), or can be squeezed to nothing,
- * so it never names the row; and the name stops at the label limit, so what
- * is recorded for a press is what fits on the row the person pressed. */
-function firstText(node: WidgetNode): string {
- let found = "";
- walk(node, (inner) => {
- if (found || (inner.type !== "Title" && inner.type !== "Text") || typeof inner.value !== "string" || typeof inner.width === "number") return;
- found = inner.value.replace(/\s+/g, " ").trim().slice(0, WIDGET_LIMITS.label);
- });
- return found;
-}
-
-export interface WidgetActionEntry {
- /** "confirm", "cancel", or the node id of the button or list item. */
- ref: string;
- /** What the person is recorded as having said. */
- label: string;
- action: WidgetAction;
- /** Present when the press settles the widget. */
- tone?: "confirm" | "cancel" | "submit";
- /** Handled on the device and never sent (open_url, open_thread, open_phone_pairing). */
- client?: true;
- kind: "button" | "item" | "confirm" | "cancel";
-}
-
-function collectActions(root: WidgetRoot, strict: boolean): WidgetActionEntry[] {
- const found: Array<WidgetActionEntry & { row?: string }> = [];
- walk(root, (node, ancestors) => {
- if (node.type === "Button") {
- if (node.disabled === true) return;
- const form = lastOf(ancestors, (ancestor) => ancestor.type === "Form");
- const own = isRecord(node.onClickAction) ? node.onClickAction as unknown as WidgetAction : undefined;
- const submitted = node.submit === true && isRecord(form?.onSubmitAction) ? form.onSubmitAction as unknown as WidgetAction : undefined;
- const picked = own ?? submitted;
- if (!picked) {
- if (strict && node.submit === true) throw new WidgetInputError(`widget: the submit Button at ${node.id} needs a Form with onSubmitAction around it`);
- return;
- }
- const row = lastOf(ancestors, (ancestor) => ancestor.type === "ListViewItem" || ancestor.type === "Table.Row" || ancestor.type === "Row");
- found.push({ ref: node.id, label: widgetString(node, "label") ?? "", action: picked, kind: "button", ...(node.submit === true ? { tone: "submit" as const } : {}), ...(row ? { row: firstText(row) } : {}) });
- } else if (node.type === "ListViewItem" && isRecord(node.onClickAction)) {
- found.push({ ref: node.id, label: firstText(node), action: node.onClickAction as unknown as WidgetAction, kind: "item" });
- }
- });
- for (const key of ["confirm", "cancel"] as const) {
- const spec = buttonSpecOf(root, key);
- if (spec) found.push({ ref: key, label: spec.label, action: spec.action, tone: key, kind: key });
- }
- // "View" on three rows is three presses: each takes its row's name.
- const counts = new Map<string, number>();
- for (const entry of found) counts.set(entry.label, (counts.get(entry.label) ?? 0) + 1);
- return found.map(({ row, ...entry }) => ({
- ...entry,
- ...(CLIENT_ACTION(entry.action) ? { client: true as const } : {}),
- label: row && entry.label && (counts.get(entry.label) ?? 0) > 1 ? `${entry.label}: ${row}`.slice(0, WIDGET_LIMITS.label * 2) : entry.label,
- }));
-}
-
-/** Every pressable thing in a canonical widget, in document order. */
-export function widgetActions(root: WidgetRoot): WidgetActionEntry[] {
- return collectActions(root, false);
-}
-
-/** The action a recorded label stands for, for the model's reading of a press. */
-export function widgetActionByLabel(root: WidgetRoot, label: string): WidgetActionEntry | undefined {
- return widgetActions(root).find((entry) => !entry.client && entry.label === label);
-}
-
-/** Where a press collects its values: the nearest Form around the pressed
- * node, or the whole widget. */
-export function widgetScope(root: WidgetRoot, ref: string): WidgetNode {
- let scope: WidgetNode = root;
- walk(root, (node, ancestors) => {
- if (node.id === ref) scope = lastOf(ancestors, (ancestor) => ancestor.type === "Form") ?? root;
- });
- return scope;
-}
-
-export interface WidgetField {
- name: string;
- type: string;
- /** Its Label's text, else a Checkbox's own label, else its name: only words
- * drawn beside the field, because this is how the field is named in the
- * message a press is recorded as. */
- label: string;
- node: WidgetNode;
-}
-
-/** The named fields under `scope`. Labels are looked up across `root`. */
-export function widgetFields(scope: WidgetNode, root: WidgetRoot = scope): WidgetField[] {
- const labels = new Map<string, string>();
- walk(root, (node) => {
- if (node.type === "Label" && typeof node.fieldName === "string" && typeof node.value === "string") labels.set(node.fieldName, node.value);
- });
- const fields: WidgetField[] = [];
- walk(scope, (node) => {
- if (typeof node.name !== "string" || !(FIELD_TYPES.has(node.type) || node.type === "ListView")) return;
- const own = node.type === "ListView" ? widgetString(node, "title") : widgetString(node, "label");
- fields.push({ name: node.name, type: node.type, node, label: labels.get(node.name) ?? own ?? node.name });
- });
- return fields;
-}
-
-/** What a choice field offers: a Select's or RadioGroup's options, or the
- * rows of a list with a name (each row's name, and the value it stands for). */
-export function widgetFieldOptions(node: WidgetNode): Array<{ label: string; value: string }> {
- if (node.type === "ListView") {
- return (Array.isArray(node.children) ? node.children : []).filter(isRecord).map((row) => {
- const value = String((row as WidgetNode).value ?? "");
- return { label: firstText(row as WidgetNode) || value, value };
- });
- }
- return Array.isArray(node.options) ? node.options as Array<{ label: string; value: string }> : [];
-}
-
-/** What each field holds before the person touches it. */
-export function widgetInitialValues(scope: WidgetNode): WidgetValues {
- const values: WidgetValues = {};
- for (const field of widgetFields(scope)) {
- values[field.name] = field.type === "Checkbox" ? field.node.defaultChecked === true : widgetString(field.node, "defaultValue") ?? "";
- }
- return values;
-}
-
-export type ResolvedWidgetAction =
- | { ok: true; ref: string; label: string; action: WidgetAction; values: WidgetValues; other?: WidgetOther; text: string; tone?: "confirm" | "cancel" | "submit" }
- | { ok: false; status: 400 | 404 | 409; error: string };
-
-/** Check one press against the stored widget. `text` is the user message it
- * becomes: the label, then one "Field: value" line per filled field. `other`
- * holds answers in the person's own words (see `WidgetOther`). */
-export function resolveWidgetAction(payload: WidgetPayload, ref: string, values: unknown, other?: unknown): ResolvedWidgetAction {
- if (payload.settled) return { ok: false, status: 409, error: "This was already answered." };
- const entry = widgetActions(payload.root).find((candidate) => candidate.ref === ref);
- if (!entry) return { ok: false, status: 404, error: "That button is no longer on this widget." };
- if (entry.client) return { ok: false, status: 400, error: "That action opens on the device and is not sent." };
- const done = (clean: WidgetValues, own: WidgetOther, lines: string[]): ResolvedWidgetAction => ({
- ok: true, ref, label: entry.label, action: entry.action, values: clean, ...(Object.keys(own).length ? { other: own } : {}),
- text: [entry.label, ...lines].join("\n"), ...(entry.tone ? { tone: entry.tone } : {}),
- });
- if (entry.tone === "cancel") return done({}, {}, []);
-
- const scope = widgetScope(payload.root, ref);
- const fields = widgetFields(scope, payload.root);
- const given = values === undefined || values === null ? {} : values;
- if (!isRecord(given)) return { ok: false, status: 400, error: "values must be an object of field names." };
- const typed = other === undefined || other === null ? {} : other;
- if (!isRecord(typed)) return { ok: false, status: 400, error: "other must be an object of field names." };
- const known = new Set(fields.map((field) => field.name));
- for (const key of [...Object.keys(given), ...Object.keys(typed)]) if (!known.has(key)) return { ok: false, status: 400, error: `There is no field named ${JSON.stringify(key)} here.` };
-
- const initial = widgetInitialValues(scope);
- const clean: WidgetValues = {};
- const own: WidgetOther = {};
- const lines: string[] = [];
- const mustFill = entry.tone === "confirm" || entry.tone === "submit";
- for (const field of fields) {
- const words = Object.hasOwn(typed, field.name) ? typed[field.name] : undefined;
- if (words !== undefined && (field.node.disabled === true || !widgetTakesOther(field.node))) {
- return { ok: false, status: 400, error: `${field.label} takes only the offered options.` };
- }
- if (words !== undefined && typeof words !== "string") return { ok: false, status: 400, error: `${field.label} must be text.` };
- const answer = typeof words === "string" ? words.trim().replace(/\s+/g, " ") : "";
- if (answer.length > WIDGET_LIMITS.fieldValue) return { ok: false, status: 400, error: `${field.label} must be at most ${WIDGET_LIMITS.fieldValue} characters.` };
- // a field the person could not change keeps what it was drawn with
- const raw = Object.hasOwn(given, field.name) && field.node.disabled !== true ? given[field.name] : initial[field.name];
- if (answer) {
- if (typeof raw !== "string") return { ok: false, status: 400, error: `${field.label} must be text.` };
- if (raw.trim()) return { ok: false, status: 400, error: `${field.label} is one of the options or their own answer, not both.` };
- clean[field.name] = "";
- own[field.name] = answer;
- lines.push(`${field.label}: ${answer}`);
- continue;
- }
- if (field.type === "Checkbox") {
- if (typeof raw !== "boolean") return { ok: false, status: 400, error: `${field.label} must be on or off.` };
- if (mustFill && field.node.required === true && !raw) return { ok: false, status: 400, error: `${field.label} is required.` };
- clean[field.name] = raw;
- if (raw) lines.push(`${field.label}: yes`);
- continue;
- }
- if (typeof raw !== "string") return { ok: false, status: 400, error: `${field.label} must be text.` };
- const value = field.type === "Textarea" ? raw.trim() : raw.trim().replace(/\s+/g, " ");
- if (value.length > WIDGET_LIMITS.fieldValue) return { ok: false, status: 400, error: `${field.label} must be at most ${WIDGET_LIMITS.fieldValue} characters.` };
- if (mustFill && field.node.required === true && !value) return { ok: false, status: 400, error: `${field.label} is required.` };
- let shown = value;
- let kept = value;
- if (value && (field.type === "Select" || field.type === "RadioGroup" || field.type === "ListView")) {
- const option = widgetFieldOptions(field.node).find((candidate) => candidate.value === value);
- if (!option) return { ok: false, status: 400, error: `${field.label} must be one of the offered options.` };
- shown = option.label;
- }
- if (value && field.type === "TimePicker") {
- const time = timeOfDay(value, "");
- if (time === undefined) return { ok: false, status: 400, error: `${field.label} must be a time like 09:30.` };
- const min = widgetString(field.node, "min");
- const max = widgetString(field.node, "max");
- if ((min && (time as string) < min) || (max && (time as string) > max)) return { ok: false, status: 400, error: `${field.label} is outside the times offered.` };
- kept = shown = time as string;
- }
- if (field.type === "DayPicker" && value) {
- const days = weekdays(value);
- if (!days || days.split(",").length !== value.split(",").length) return { ok: false, status: 400, error: `${field.label} must be days of the week.` };
- kept = days;
- shown = dayList(days);
- }
- if (value && field.type === "DatePicker") {
- if (isoDate(value, "") === undefined) return { ok: false, status: 400, error: `${field.label} must be a date like 2026-10-14.` };
- const min = widgetString(field.node, "min");
- const max = widgetString(field.node, "max");
- if ((min && value < min) || (max && value > max)) return { ok: false, status: 400, error: `${field.label} is outside the dates offered.` };
- }
- clean[field.name] = kept;
- // whole: this line is all the bot reads of what the person typed
- if (value) lines.push(`${field.label}: ${shown}`);
- }
- return done(clean, own, lines);
-}
-
-/** A word to the bot about a widget that parses but does not do what it
- * looks like it is for: rows to choose between and no way to choose, or one
- * time, date or set of days typed in a one-line field (a Textarea may list
- * several). Undefined when there is nothing to say. */
-export function widgetAdvice(root: WidgetRoot): string | undefined {
- const notes: string[] = [];
- const rows = Array.isArray(root.children) ? root.children.length : 0;
- if (root.type === "ListView" && rows >= 2 && buttonSpecOf(root, "confirm") && widgetFields(root).length === 0
- && !widgetActions(root).some((entry) => entry.kind === "item" || entry.kind === "button")) {
- notes.push("No row of this list can be chosen: the person can only confirm or cancel it as a whole. If they are meant to pick one row, show it again with its widget_id and give the ListView a name (and each row a value), so the rows become selectable and confirm sends the pick.");
- }
- const fields = widgetFields(root);
- const sending = widgetActions(root).filter((entry) => !entry.client && entry.tone !== "cancel");
- if (fields.length > 0 && !sending.length) {
- notes.push("Nothing in this widget sends what the person fills in. Show it again with its widget_id and confirm: {label, action} (and cancel if they may decline) so they can send it.");
- } else if (fields.length > 0) {
- const sent = new Set(sending.flatMap((entry) => widgetFields(widgetScope(root, entry.ref), root).map((field) => field.name)));
- const unsent = fields.filter((field) => !sent.has(field.name)).map((field) => JSON.stringify(field.label));
- if (unsent.length) notes.push(`${unsent.join(", ")} sits outside the Form whose button is the only way to send, so it is never sent. Show it again with its widget_id, with it inside that Form or with confirm on the Card.`);
- }
- const typed = fields.filter((field) => field.type === "Input");
- // "each time", "every time" and "how many times" are not a time of day
- const phrase = (field: WidgetField) => `${field.name} ${field.label} ${widgetString(field.node, "placeholder") ?? ""}`
- .replace(/\b(each|every|this|next|first|last|any|some|one|other|same|spare|free|full|part|lead|over|down)[\s-]+times?\b/gi, " ")
- .replace(/\btimes\b/gi, " ");
- const asks = (pattern: RegExp) => typed.filter((field) => pattern.test(phrase(field))).map((field) => field.label);
- const pickers: Array<[RegExp, string]> = [
- [/\b(time|o'?clock|hh:mm)\b|\b\d{1,2}(:\d{2})?\s?[ap]m\b|\b\d{1,2}:\d{2}\b/i, "TimePicker"],
- [/\b(days|weekdays?|weekly|repeats?|repeating|(which|what) days?|days? of the week)\b/i, "DayPicker"],
- [/\b(dates?|deadline|due)\b/i, "DatePicker"],
- ];
- const seen = new Set<string>();
- for (const [pattern, picker] of pickers) {
- const labels = asks(pattern).filter((label) => !seen.has(label));
- labels.forEach((label) => seen.add(label));
- if (labels.length) notes.push(`${labels.map((label) => JSON.stringify(label)).join(", ")} asks the person to type what a ${picker} lets them pick. Show it again with its widget_id and a ${picker} in its place.`);
- }
- return notes.length ? notes.join(" ") : undefined;
-}
-
-/** Days as a person says them: "Every day", "Weekdays", "Weekends", or the names. */
-export function dayList(days: string): string {
- const picked = days.split(",").filter(Boolean);
- if (picked.length === 7) return "Every day";
- if (picked.join(",") === "mon,tue,wed,thu,fri") return "Weekdays";
- if (picked.join(",") === "sat,sun") return "Weekends";
- const names: Record<string, string> = { mon: "Mon", tue: "Tue", wed: "Wed", thu: "Thu", fri: "Fri", sat: "Sat", sun: "Sun" };
- return picked.map((day) => names[day] ?? day).join(", ");
-}
-
-
-function inlineText(node: WidgetNode): string {
- switch (node.type) {
- case "Text": case "Title": case "Caption": case "Label":
- return widgetString(node, "value") ?? "";
- case "Markdown":
- return (widgetString(node, "value") ?? "").replace(/\s+/g, " ");
- case "Badge":
- return widgetString(node, "label") ?? "";
- case "Button":
- return node.label ? `[${String(node.label)}]` : "";
- case "Image":
- return node.alt ? `[image: ${String(node.alt)}]` : "[image]";
- case "Progress":
- return [widgetString(node, "label"), `${Math.round((widgetNumber(node, "value") ?? 0) * 100)}%`].filter(Boolean).join(" ");
- case "Chart":
- return `[chart: ${(Array.isArray(node.series) ? node.series as Array<{ label?: string; dataKey: string }> : []).map((series) => series.label ?? series.dataKey).join(", ")}]`;
- case "Checkbox":
- return `[ ] ${widgetString(node, "label") ?? String(node.name)}`;
- case "Select": case "RadioGroup":
- return `(${(Array.isArray(node.options) ? node.options as Array<{ label: string }> : []).slice(0, 6).map((option) => option.label).join(" / ")})`;
- case "DayPicker":
- return `[${typeof node.defaultValue === "string" ? dayList(node.defaultValue) : "days"}]`;
- case "Input": case "Textarea": case "DatePicker": case "TimePicker":
- return `[${widgetString(node, "placeholder") ?? String(node.name)}]`;
- default:
- return (Array.isArray(node.children) ? node.children : []).map(inlineText).filter(Boolean).join(" · ");
- }
-}
-
-function blockLines(node: WidgetNode): string[] {
- const children = Array.isArray(node.children) ? node.children : [];
- if (node.type === "ListViewItem") return [`- ${inlineText(node)}`];
- if (node.type === "Table") return children.map((row) => (Array.isArray(row.children) ? row.children : []).map(inlineText).join(" | "));
- if (node.type === "Markdown") return [widgetString(node, "value") ?? ""];
- const stacked = node.type === "Col" || node.type === "Form" || node.type === "Transition" || (node.type === "Box" && node.direction !== "row");
- return stacked ? children.flatMap(blockLines) : [inlineText(node)];
-}
-
-/** The readable version of a widget: the message `text`, read by previews,
- * notifications, exports, replayed history and clients that do not know the kind. */
-export function widgetToText(root: WidgetRoot): string {
- const lines: string[] = [];
- const statusText = isRecord(root.status) && typeof root.status.text === "string" ? root.status.text : "";
- if (statusText) lines.push(statusText);
- const title = widgetString(root, "title");
- const head = [title ? `**${title}**` : "", widgetString(root, "caption"), widgetString(root, "meta")].filter(Boolean).join(" · ");
- if (head) lines.push(head);
- for (const child of Array.isArray(root.children) ? root.children : []) lines.push(...blockLines(child));
- const buttons = (["confirm", "cancel"] as const).map((key) => buttonSpecOf(root, key)?.label).filter(Boolean).map((label) => `[${label}]`).join(" ");
- if (buttons) lines.push(buttons);
- const out = lines.map((line) => line.trimEnd()).filter(Boolean).join("\n");
- return out.length <= WIDGET_LIMITS.fallback ? out : `${out.slice(0, WIDGET_LIMITS.fallback - 1).trimEnd()}…`;
-}
+export * from "../packages/phone-protocol/src/widget.ts";
diff --git a/shared/wire-tool.ts b/shared/wire-tool.ts
index f0fb4cfb1c..bde5be1af4 100644
--- a/shared/wire-tool.ts
+++ b/shared/wire-tool.ts
@@ -1,23 +1 @@
-import type { PlaceRow } from "./place-view.ts";
-import type { ServerToolText } from "./server-text.ts";
-
-/** An activity chip serialized beside a transcript line. */
-export interface WireTool extends ServerToolText {
- name: string; ok?: boolean; spoken?: string; setup?: boolean; terminal?: boolean; summary?: string; input?: string; output?: string;
- /** What the call works on, as its live status said it: the chip's and the "Now" card's specific words. `whose`: the person whose own app or MCP server the call used. */
- step?: import("./turn-progress.ts").LiveStep; whose?: { person: string; app: string };
- /** error rows: the installed Claude Code is too old for the model, and
- * the UI can offer to update it in place. notice rows: `rescue`, a turn that heard nothing from its AI for a while. */
- claudeUpdate?: boolean; rescue?: import("./first-reply-rescue.ts").FirstReplyRescue;
- /** error rows: the place this turn could not use. */
- place?: PlaceRow;
- /** error rows: epoch ms when the usage limit that stopped the turn resets. */
- limitResetsAt?: number;
- /** A failed step on an MCP server, in the reader's language: which server, why, and what to do. */
- problem?: string;
- /** Provider item identity, scoped to the owning turn. */
- itemId?: string;
- /** Whether the harness captured the full redacted result. Private
- * server-local spill paths are not exposed to clients. */
- fullResult?: boolean;
-}
+export * from "../packages/phone-protocol/src/wire-tool.ts";
diff --git a/shared/wire.ts b/shared/wire.ts
index fc0341c3e2..bd90363f8f 100644
--- a/shared/wire.ts
+++ b/shared/wire.ts
@@ -1,984 +1 @@
-/** The client-visible wire model for tasks, bots, messages and rooms. A field
- * here is one the server emits in every response and SSE frame that carries
- * the shape. */
-import type { PresenceFrame } from "./team-presence.ts";
-import type { DataBroadcast } from "./data-surface.ts";
-import type { ApprovalMode } from "./approval-mode.ts";
-import type { ToolScope } from "./tool-scope.ts";
-import type { CommandAllowlistCandidate } from "./command-allowlist.ts";
-import type { TurnDigest } from "./digest.ts";
-import type { BotAvatarCrop, MascotFaceColor } from "./bot-avatar.ts";
-import type { BotBodyId } from "./bot-body.ts";
-import type { ReplyStyle } from "./reply-style.ts";
-import type { CredentialTargetId, CUSTOM_SECRET_TARGET, SecretDelivery } from "./credential-request.ts"; import type { EmailOutgoingFields } from "./email.ts";
-import type { TeamSetupRequest } from "./team-setup.ts"; import type { DefaultBotFields, HelperIntroField } from "./default-bot.ts";
-import type { SetupCardFields } from "./setup-card.ts"; import type { BugReportField } from "./devs-report-status.ts"; import type { AccessRequestCardField, BotAccessFields } from "./bot-access.ts";
-import type { RoutineRequestCardData } from "./routine-request.ts"; import type { SavedStepsMark } from "./saved-steps.ts";
-import type { WebhookRequestCardData } from "./webhook-request.ts"; import type { WaitCardField, WaitLineField } from "./wait-request.ts"; import type { ComputerAskField } from "./computer-ask.ts";
-import type { AppEventAttempt, AppTrigger, AppTriggerRequestCardData, AppTriggerService } from "./app-triggers.ts";
-import type { ProfileRequestCardData } from "./profile-request.ts";
-import type { ServerTextLine, ServerTextParams } from "./server-text.ts";
-import type { WireTool } from "./wire-tool.ts";
-import type { ModelRequestCardData } from "./model-request.ts";
-import type { ConnectorCardData } from "./connector-card.ts"; import type { McpChangeRequest } from "./mcp-request.ts"; import type { AppSettingCardField, WindowPrefFrame } from "./app-settings.ts";
-import type { SkillRequestCardData } from "./skill-request.ts"; import type { OutsideWriteCardField } from "./outside-write.ts";
-import type { QuestionRequestCardData } from "./ask-question.ts";
-import type { AutomationLine, RoutineRunCardData } from "./routine-run.ts";
-import type { WidgetPayload } from "./widget.ts";
-import type { AppFromRef, AppPayload, AppPointedRef } from "./app.ts";
-import type { GroupGoalRunCardData } from "./group-goal-run.ts"; import type { BurstCardData } from "./burst.ts";
-import type { RuntimeEvent } from "./runtime-events.ts";
-import type { NotificationLogEntry } from "./notification.ts";
-import type { Routine, RoutineRun } from "./routines.ts";
-import type { WebhookAttempt, WebhookTrigger } from "./webhooks.ts";
-import type { PublishedPageCard } from "./published-page.ts";
-import type { InboxItem, InboxTask } from "./inbox.ts";
-import type { LiveCallRecord, LiveCallState } from "./live-call-wire.ts";
-import type { ForkOrigin, TaskClosedBy, TaskOpenedBy } from "./task-provenance.ts";
-/** What a team bot's main chat is called, beside each person's own chats. */
-export const SHARED_CHAT_TITLE = "Shared chat";
-
-export type { LiveCallRecord, LiveCallState, LiveCallStatus, LiveClient, LiveEndReason, LiveFishRelayCommand, LiveFishRelayEvent, LiveFishSessionToken, LiveFishTransport, LiveKeySource, LiveProvider, LiveSettings } from "./live-call-wire.ts";
-export type { ForkOrigin, TaskClosedBy, TaskOpenedBy } from "./task-provenance.ts";
-
-/** Reasoning-effort levels, ascending: a union of what any engine accepts;
- * each driver declares the subset its CLI will take. */
-export const EFFORT_LEVELS = ["none", "low", "medium", "high", "xhigh", "max"] as const;
-export type EffortLevel = (typeof EFFORT_LEVELS)[number];
-
-export function isEffortLevel(value: unknown): value is EffortLevel {
- return typeof value === "string" && (EFFORT_LEVELS as readonly string[]).includes(value);
-}
-
-/** instanceId is the routing key. */
-export interface ModelSelection {
- instanceId: string;
- model: string;
- /** Optional: no effort means no flag, and the CLI keeps its own default. */
- effort?: EffortLevel;
- /** Explicit model-specific variant. Omitted leaves the native session alone. */
- variant?: string;
-}
-
-/** Which cloud computer backs computer: "cloud"; absent means Boat. */
-export type CloudBackend = "box" | "vps";
-
-/** A place a bot can act. `cloud` covers both cloud backends. */
-export type Surface = "cloud" | "vm" | "local" | "browser";
-
-export const MAUS_COLOR_NAMES = [
- "green", "blue", "red", "orange", "purple", "cyan", "pink",
- "yellow", "teal", "coral", "silver", "chrome",
-] as const;
-export type MausColor = (typeof MAUS_COLOR_NAMES)[number];
-
-export function isMausColor(value: unknown): value is MausColor {
- return typeof value === "string" && (MAUS_COLOR_NAMES as readonly string[]).includes(value);
-}
-
-/** The face a bot rests on, as one of the engine's state names. */
-export type MausExpression = string;
-
-/** What the bot is doing right now, as the harness sees it. `parked.computer`
- * is task-level only: a turn that settled at the computer wait ceiling and
- * resumes when the seat frees. It never elevates the bot-level activity and
- * never counts as busy. */
-export type BotActivity = "working" | "waiting-on-you" | "idle" | "no-signal" | "dead" | "parked.computer";
-
-/** What a task has spent, banked once per settled turn. */
-export interface TaskUsage {
- input: number;
- output: number;
- /** cached share of input (context the model re-read) */
- cachedInput?: number;
- /** null until any turn reported a cost — most engines never do */
- costUsd: number | null;
- turns: number;
- /** the most recent settled turn on its own */
- lastTurn?: { input: number; output: number; cachedInput?: number; costUsd: number | null };
- /** what filled the model's window on the last model call, and the window's size when known */
- context?: { tokens: number; window?: number };
-}
-
-/** Accounting for the currently displayed room thread, across all speakers. */
-export interface GroupThreadUsage extends TaskUsage {
- lastSpeaker?: { botId: string; name: string };
-}
-
-export interface BotMovedTo {
- team: { id: string; name: string };
- state: "moving" | "moved";
- at: number;
-}
-
-/** One task = one conversation with its own context, thread and provider session. */
-export interface WireTask extends InboxTask {
- /** Outstanding handoffs, not an active provider turn. */
- waitingForTeammates?: boolean;
- threadId: string;
- /** The completed message whose visible history seeded this conversation. */
- origin?: ForkOrigin;
- title: string;
- createdAt: number;
- /** The first message already drove a title attempt for this thread, so a
- * later one does not rename a thread the person may have retitled. */
- titleFromFirstMessage?: true;
- /** Team Cloud only: this is the bot's main chat, everyone's who sees the bot. Its title is SHARED_CHAT_TITLE on every
- * person's copy, whatever is stored, and it can't be renamed. */
- sharedChat?: true;
- /** Organizational grouping only; never a directory or provider context. */
- projectId?: string;
- /** Detached routine execution, reachable through its visible results card. */ routineRunId?: string;
- /** Work from outside (a webhook, an app's event) reached this conversation: what it starts or runs stays confined, for good. */ outside?: true;
- /** An outside caller opened this thread through the bot's API, so only it may continue it; such a thread is outside too. */ botApi?: true;
- /** Set when a bot, not a person, opened this thread. */ openedBy?: TaskOpenedBy;
- /** On a team's server: one person's conversation, seen by them alone (never by another member or an admin). */
- private?: true;
- /** On a team's server: a private conversation its person shared, never private again. `sharedWith`: shared with one person,
- * the other reader as this viewer sees them (`byYou` to the one who shared it); nobody else, an admin included, is sent it. */
- shared?: true; sharedWith?: { name: string; byYou?: true };
- /** Team Cloud, where several people write, while it works: whose request runs (they or an Owner or Admin stop it). */ askedBy?: ResolvedSender;
- /** Set by close_thread; absent while the thread is open. */
- closedBy?: TaskClosedBy;
- archivedAt?: number;
- /** Only true is stored; absent means unpinned. */
- pinned?: boolean;
- link?: string;
- linkAuto?: boolean;
- /** Epoch ms of the newest message, or createdAt when the thread has none.
- * Server-derived. Clients must not write it. */
- updatedAt?: number;
- lastThreadOrderAt?: number;
- /** 0 means "until new activity"; a future epoch ms means "until then", and
- * an expired value reads as absent. Absent = not snoozed. */
- snoozedUntil?: number;
- /** The thread's own model when a person picked one in it, else its bot's.
- * Always the effective one on the wire. */
- modelSelection?: ModelSelection;
- /** true: the thread runs on its bot's model and moves with it; false: a
- * person picked this thread's model. Derived at projection, never stored. */
- followsBotModel?: boolean;
- approvalMode?: ApprovalMode;
- autoApprove?: boolean;
- alwaysAllow?: string[];
- unread?: boolean;
- /** The newest message on screen the last time the person read this
- * conversation. The New divider goes after it. */
- lastReadMessageId?: string;
- /** true after an edit/branch-switch rewound the visible conversation. */
- rewound?: boolean;
- pinnedMessageId?: string;
- /** Runtime-only state, reset on load and never persisted. */
- activity?: BotActivity;
- busy?: boolean;
- /** Epoch ms when this task's current busy stretch began; runtime-only. */
- turnStartedAt?: number;
- /** Where this conversation works when pinned; absent = follow the bot. */
- surface?: Surface;
- /** The pin above was set by the machine (an Auto turn or the bot's
- * select_computer), not a person, so the next Works on change moves it.
- * Derived at projection, never stored. */
- surfaceAuto?: true;
- usage?: TaskUsage;
- /** Prompt-cache keep-warm status for this thread, derived at projection;
- * absent when no window is open. */
- cacheKeepWarm?: CacheKeepWarmStatus;
- /** the folder this task's turns run in, pinned on its first turn; one in its own folder moves to its bot's working folder. */
- cwd?: string | null;
- /** Set me up was pressed here (server/setup-request.ts): the person's next line in this conversation runs as a
- * setup request. Server-owned; a client only shows it. `by`: who pressed, where several people share the place (their
- * reactor key); only their next line takes it, and only they see its chip. */
- setupRequest?: { at: number; by?: string };
-}
-
-/** One thread's keep-warm window as a client shows it. Times are epoch ms. */
-export interface CacheKeepWarmStatus {
- state: "warm" | "stopped";
- until?: number;
- nextPingAt?: number;
- last?: { at: number; read: number; write: number; costUsd: number | null };
- stopped?: string;
-}
-
-/** A lightweight organizational label within one bot. */
-export interface BotProject {
- id: string;
- name: string;
- emoji?: string;
-}
-
-/** Public, package-authored playbooks installed for a bot. Process
- * guidance only — never executable code, credentials, or grants. */
-export interface InstalledPlaybook {
- key: string;
- name: string;
- summary: string;
- triggers: string[];
- instructions: string;
-}
-
-/** Listing provenance and connector intent. It never means the apps are
- * authorized. */
-export interface InstalledPackageMetadata {
- id: string;
- name: string;
- release: string;
- requiredApps: Array<{ slug: string; label: string; reason: string; optional?: boolean }>;
- /** Absent means "file". */
- source?: "file" | "org";
- /** file: a random id per import; org: derived from the organization and package. */
- installId?: string;
- /** This bot's key in the package, so a re-export keeps its identity. */
- agentKey?: string;
- /** Set when the bot was created from a package preset. */
- presetKey?: string;
- /** What the package suggested. Never applied: imported bots start at the default level. */
- suggestedApproval?: "ask" | "auto";
- /** org only */
- publisher?: { organizationId: string; slug: string; name: string };
- /** org only: "<publisher slug>/<package id>" */
- ref?: string;
- /** org only: the release bytes that were applied */
- sha256?: string;
-}
-
-/** One service's connector tool grant: `"*"` widens to every tool on the
- * service, an explicit list names exact tools. */
-export interface ConnectorToolGrant {
- tools: "*" | string[];
-}
-
-/** Lowercased Composio service slug, e.g. `gmail`. */
-export const CONNECTOR_SLUG_PATTERN = /^[a-z0-9][a-z0-9_-]{0,80}$/;
-/** Composio tool names are upper-snake, e.g. `GMAIL_SEND_EMAIL`. */
-export const CONNECTOR_TOOL_NAME_PATTERN = /^[A-Z][A-Z0-9_]{0,127}$/;
-
-/** Fails closed: only an absent switch or a strict true allows the helper model; a hand-edited "false" or 0 reads as never. */
-export const helperModelAllowed = (bot: { helperModel?: unknown }): boolean => bot.helperModel === undefined || bot.helperModel === true;
-
-/** A bot as a client may see it. avatarUrl is always present (null when the
- * bot has none). */
-export interface WireBot extends DefaultBotFields, BotAccessFields {
- waitingForTeammates?: boolean;
- id: string;
- /** The task selected in the UI; running turns keep their own thread id. */
- threadId: string;
- /** Where a routine without a thread of its own reports. Absent only for a
- * bot without threads. */
- mainThreadId?: string;
- /** newest first */
- tasks?: WireTask[];
- projects?: BotProject[];
- name: string;
- title: string;
- description: string;
- /** Standing instructions — the persona body. */
- soul?: string;
- /** sha256 of soul, for spotting a SOUL.md edited outside the app. */
- soulHash?: string;
- /** The SOUL.md mirror differed from soul at the last turn dispatch. */
- soulDrift?: boolean;
- notifications: boolean;
- color: MausColor;
- mascotExpression?: MausExpression | null;
- mascotBody?: BotBodyId | null;
- /** Overrides both eyes and mouth. Absent or null preserves the body's default inks. */
- mascotFaceColor?: MascotFaceColor | null;
- /** App-owned attachment served as this bot's custom profile image;
- * always present on the wire, null when the bot has none. */
- avatarUrl: string | null;
- /** Mascot, or the crop applied to avatarUrl. */
- avatarCrop?: BotAvatarCrop;
- /** Zoom of a custom image. Absent means 1, the unzoomed cover crop. */
- avatarZoom?: number;
- /** Horizontal point of the image kept in the crop, 0–1. Absent means center. */
- avatarFocusX?: number;
- /** Vertical point of the image kept in the crop, 0–1. Absent means center. */
- avatarFocusY?: number;
- /** True when any task has unread output. */
- unread: boolean;
- /** The bot's model: every thread without a model of its own runs on it
- * and moves with it. Navigating tasks never changes this value. */
- modelSelection: ModelSelection;
- /** where the bot works ("Works on"). Unset = auto. */
- computer?: Surface | "off";
- /** Which cloud computer backs computer: "cloud"; absent means Boat. */
- cloudBackend?: CloudBackend;
- /** Auto mode may prepare/start this bot's managed VPS container. */
- autoStartVps?: boolean;
- /** This bot's own SSH config alias for its managed VPS computer; absent
- * means the default server from Settings → API keys. */
- vpsAlias?: string;
- /** where its tasks run their tools; absent = each task's own folder. Its .claude/settings.json (else the bot folder's) applies in all. */
- cwd?: string;
- /** Auto mode: the bot approves its own tool permissions. */
- autoApprove?: boolean;
- /** Canonical approval level. Missing resolves through autoApprove. */
- approvalMode?: ApprovalMode;
- /** Tools this bot may always use without asking. */
- alwaysAllow?: string[];
- /** Speak this bot's replies aloud as they settle, without being asked. */
- speakReplies?: boolean;
- /** How replies are shaped. Absent = "default". */
- replyStyle?: ReplyStyle;
- /** This bot's own voice id, so a room of bots doesn't sound like one person. */
- voice?: string;
- /** Whether this bot may send voice notes. Absent/true = allowed; false
- * hides the tool and refuses the route even with a voice configured. */
- voiceNotes?: boolean; /** The harness speaks each reply as a voice note; absent follows the installation's `tts.everyReply`. */ voiceNoteEveryReply?: boolean;
- /** Whether this bot may use the X research tools (x_search and its
- * actions), which spend the workspace's treg balance.
- * Absent/false = off: the person turns it on per bot. */
- xResearch?: boolean;
- /** Whether this bot uses native memory. Absent/true = enabled. */
- memoryEnabled?: boolean;
- /** Queue direct-chat messages behind outstanding delegated work. */
- parkDirectMessages?: boolean;
- /** true after an edit/branch-switch rewound the visible conversation. */
- rewound?: boolean;
- pinned?: boolean;
- hidden?: boolean;
- /** On My Cloud, a bot its person moved into one of their teams: `moving` while it goes (no turns, its routines off),
- * `moved` once it lives there (archived here, shown as a line that opens the team). */
- movedTo?: BotMovedTo;
- /** Optional labeled divider used to organize this bot in the sidebar. */
- section?: string;
- /** the one message pinned to the top of this bot's active thread */
- pinnedMessageId?: string;
- /** The coordinator for this bot's sidebar section. */
- chiefOfStaff?: boolean;
- /** Owner-selected additional teams this Chief may coordinate. */
- managedSections?: string[];
- /** Team Cloud only: the lowercased email of the member who created the bot (or moved it in). */
- createdBy?: string;
- /** Team Cloud only: the lowercased email of the member the bot reports to, whose inbox its questions, approvals,
- * failures and routine results reach. Absent: it reports to `createdBy`. */
- reportsTo?: string;
- /** Whether this bot may use the workspace's connected apps. */
- composio?: boolean;
- /** Which connected-app tools this bot may call, by service slug. Absent
- * defers to `composio` (unset/true = every tool, false = none); `{}` grants
- * none. Grants never travel in shareable exports. */
- connectorTools?: Record<string, ConnectorToolGrant>;
- connectorScopes?: { apps: Record<string, "read" | "write"> };
- outbound?: { policy: "ask" | "allow" };
- /** Which of a paired phone's apps this bot may use; absent: every bot may use what the phone allows (shared/phone-apps.ts). */
- phoneApps?: import("./phone-apps.ts").PhoneApps;
- /** Ordered backups used only by opt-in, pre-prompt startup recovery. */
- fallback?: Array<{ instanceId: string; model: string }>;
- /** Whether this bot gets the app's built-in browser. */
- browser?: boolean;
- /** Record a screenshot and a short note of each browser action, kept with
- * the conversation. Off unless true. */
- recordBrowserSteps?: boolean;
- /** Memory upkeep: the harness captures facts from finished chats into
- * MEMORY.md and topic files, adds facts about the person to About me and
- * tidies nightly. On unless explicitly false. */
- memoryUpkeep?: boolean;
- /** Prompt-cache keep-warm for this bot's Claude threads: true or false
- * overrides the workspace setting; absent follows it. */
- cacheKeepWarm?: boolean;
- /** false: the workspace's helper model never writes this bot's background texts. Absent or true: allowed. */
- helperModel?: boolean;
- /** Which of the app-wide MCP servers this bot mounts, by name. */
- mcpServers?: string[];
- /** Owner-selected original tool identities. An empty allowlist permits none. */
- toolScope?: ToolScope;
- /** Id of a named browser profile; absent = the bot's own private session. */
- browserProfile?: string;
- playbooks?: InstalledPlaybook[];
- installedPackage?: InstalledPackageMetadata;
- /** Aggregate of task and room activity; transient, reset on load. */
- busy?: boolean;
- /** What the bot is doing right now; transient like busy. */
- activity?: BotActivity;
- createdAt: number;
- /** Who may see this bot on a workspace several people share. Absent means
- * everyone. Sent to admins only; a member's copy of a bot never carries it. */
- visibility?: BotVisibility;
-}
-
-/** Who may see a bot: every signed-in person, admins only, or the listed
- * addresses (and `@domain` entries) plus admins. */
-export type BotVisibility = "everyone" | "admins" | { people: string[] };
-
-/** The person a user message is from, as the server resolved it from their
- * own session; no request body can supply it. `name` is attribution only:
- * nothing may be allowed or refused because of it. `id` is an opaque
- * server-derived key that decides only whose session may answer a card this
- * request raised. */
-export interface ResolvedSender {
- name: string;
- id?: string;
-}
-
-/** Who answered a card: a signed-in person (named as their messages are), the owner on this machine, a session-less
- * local caller on a shared server (`worker`: the Slack worker, or any other process on that machine), or at Full access
- * the bot that decides a teammate's question (`bot`: no `answeredText` yet while it decides; "" when it picks itself). */
-export type CardAnswerer = (
- /** `person`: the answering session's opaque person key, so the owner checks
- * can tell whose answer it was. */
- | { kind: "session"; name: string; person?: string }
- | { kind: "loopback" }
- | { kind: "worker" } | { kind: "bot"; name: string }
-) & {
- /** "call": decided by voice on a Live call; "reaction": by a 👍 or 👎 on the
- * card. Absent: tapped. */
- via?: "call" | "reaction";
-};
-
-/** Opens every compaction summary written without a model (recent excerpts only); the chat labels stored records by it. */
-export const EXCERPT_SUMMARY_HEADER = "Historical excerpts in chronological order; newer corrections override older requests. These excerpts may omit earlier details.";
-
-/** One transcript line, serialized as stored. */
-export interface WireMessage extends ServerTextLine, HelperIntroField, SetupCardFields, WaitLineField, BugReportField {
- roomRequest?: { id: string; phase: "request" | "result" };
- id: string;
- role: "bot" | "user";
- kind: "text" | "options" | "activity" | "screen" | "connector" | "secret" | "signin" | "routine.run" | "goal.run" | "burst" | "digest" | "compaction" | "call" | "widget" | "app";
- text?: string;
- digest?: TurnDigest;
- /** kind "compaction" with no `compaction` record: the engine condensed its own session. A marker for people, never context. */
- engineCompaction?: true;
- compaction?: { summary: string; firstKeptId: string; foldedThroughId: string; tokensBefore: number; by: "person" | "harness";
- /** The divider "Start fresh" leaves: no summary, and a provider reads nothing before it. */ fresh?: true };
- /** Renderers receive only the allowlisted /api/attachments URL. `file` entries are opened through the message-scoped
- * file route, never by path. `source`: a bot attach-file copy's original path on the server, for Show in folder.
- * `fromTool`: an image a tool's result returned while the bot worked, which it did not make or send. */
- attachments?: Array<
- | { kind: "image"; path: string; mime: string; name?: string; source?: string; fromTool?: true }
- | { kind: "file"; path: string; mime: string; name: string; source?: string }
- /** `text` is the words the note speaks (secret-redacted when stored): clients show it behind a
- * collapsed transcript, never as message body, and the model's replay folds it back after `text`. */
- | { kind: "audio"; path: string; mime: string; durationMs?: number; text?: string }
- >;
- card?: OptionCardData;
- /** widget rows (kind "widget"): a bot-authored UI tree. `text` is its
- * readable fallback for clients that do not know the kind. */
- widget?: WidgetPayload;
- /** widget rows the server built from records (mail, calendar, other
- * bots' work) rather than the bot: replayed to the bot only as labelled
- * data, never as its own words, and never edited by a bot. */
- serverCard?: true;
- /** A setup suggestion the device renders in its own words (server/host/helper-suggestion.ts); `text` is the English. */
- setupSuggestion?: { kind: "helperKey"; answer?: "notNow" };
- /** A person's line Set me up turned into a setup request: the bot reads it as `/setup <text>`; the chat shows `text`. */
- setupRequest?: true;
- /** app rows (kind "app"): bot HTML or an MCP server's UI. `text` is always the readable fallback. */
- app?: AppPayload;
- /** user rows sent by an app's ui/message: the app row that sent them. Every client draws "Sent from <title>". */
- fromApp?: AppFromRef;
- /** user rows sent with parts of a bot's page the person pointed at in the preview: what each chip said. */
- pointed?: AppPointedRef[];
- connector?: ConnectorCardData;
- secret?: SecretRequestCardData;
- /** signin rows: the bot asked the person to sign in to a site themselves. */
- signIn?: SignInRequestCardData;
- /** One idempotently updated status card for a routine run. */
- routineRun?: RoutineRunCardData; /** The card a burst shows in its parent chat: first a preview, then its progress. */ burst?: BurstCardData;
- automation?: AutomationLine;
- /** Terminal receipt for a bounded multi-bot channel goal. */
- goalRun?: GroupGoalRunCardData;
- /** call rows (kind "call"): the finished Live call this row records. */
- call?: LiveCallRecord;
- /** activity messages: tool name + outcome. */
- tool?: WireTool & {
- clipped?: boolean;
- /** Words the harness wrote for what the call did, shown in place of `name`; `name` stays the tool's own. */
- label?: string;
- /** error rows: the reply came back; only a step the turn ran failed or wasn't allowed. */
- partial?: boolean;
- };
- /** A bot line a "post" webhook wrote: whoever called the webhook chose
- * its words. On a room line this also carries `from`, so the room renders
- * the webhook's bot as the speaker. */
- webhookPost?: boolean;
- /** user messages sent INTO a running turn (capabilities.queueing). */
- steered?: boolean;
- /** user messages a peer bot handed to this thread's RUNNING turn: peer
- * context folded in mid-turn, never a new request. The text is stored
- * enveloped exactly as injected. */
- aside?: boolean;
- /** A user-role message that arrived through the server's HTTP API
- * ("api"), or a request a person spoke on a Live call ("call"). */
- via?: "api" | "call";
- /** The Live call a "call" line was spoken on (LiveCallState.callId). Set
- * only on user messages with `via: "call"`; a turn's own messages point
- * at their request through `requestMessageId` instead. */
- callId?: string;
- /** A user line an external interface relayed through the guarded send
- * route (the Slack worker): nobody typed it in one of this workspace's
- * clients. A Live call never reads it back as what the caller typed. */
- relayed?: boolean;
- /** Which person sent this user message, when the workspace has more than
- * one. Absent reads as the profile name. */
- sender?: ResolvedSender;
- /** Provider turn that produced this message. */
- turnId?: string; /** A stopped row where several people use the server: who pressed Stop. */ stoppedBy?: ResolvedSender; /** A bot reply: the `itemId` its words streamed under, so a client swaps the streamed text for this message. */ itemId?: string;
- /** Server-proven originating user message, including supported harness
- * continuations. Absent means external clients must not infer ownership. */
- requestMessageId?: string;
- /** Provider completion outcome, independent of whether it emitted text. */
- turnSucceeded?: boolean;
- /** An exact request was stopped; a restart must not revive an old result. */
- requestCancelled?: boolean;
- /** Set before execution and cleared only after the request's verified
- * final turn and dependencies settle. A restart never clears it. */
- requestPending?: boolean;
- /** The last assistant text item from a settled provider turn. */
- turnTerminal?: boolean;
- turnCompletedAt?: number; savedSteps?: SavedStepsMark;
- /** screen messages: a frame of the bot's computer (base64 image) */
- png?: string;
- mime?: string;
- at: number;
- /** the message this one follows; null = thread root. */
- parentId?: string | null;
- /** Optional flat reply reference for an inline quote. */
- replyToId?: string;
- /** Stable client identity for at-most-once chat POST retries. */
- sendId?: string;
- /** Per-send channel behavior. Absent is legacy quick chat. */
- channelMode?: "chat" | "goal";
- /** from: which member said this (group threads, and post_to_thread). threadPost: a bot posted this row with post_to_thread; seen once a run has read it. */
- from?: { botId: string; name: string; color: string }; threadPost?: { deliveryId: string; fromBotId: string; fromThreadId: string; seen?: boolean };
- /** Set on a room message a bot pushed in with post_to_room. */
- peerPost?: { unattended?: boolean };
- /** A room reply whose speaker the decision model picked (an Auto room),
- * with how sure it was. Absent on every other message; clients that do
- * not know it ignore it. */
- routedBy?: { provider: "jev" | "workersai" | "openrouter"; probability: number };
- /** On a conversational bot's user line: the picker label of the quick model its reply ran on. */
- quickModel?: string;
- /** On a "Sent to" hand-off row: the done_when the sender set, redacted, so the chip can show what counts as finished. */
- doneWhen?: string;
- /** Set on the user-role line another bot delivered into this bot's own
- * conversation (coordinate_bots, start_thread). `incident`: the line is a
- * Team incidents report about that bot's thread
- * in `threadId`, not its words; `notified`: the person was already buzzed. */
- peerAsk?: { botId: string; name: string; unattended?: boolean; incident?: { threadId: string; notified?: boolean } };
- /** One reaction per person (shared/reactions.ts REACTIONS). `by` is "user"
- * on a workspace one person uses, otherwise that person's opaque key, the
- * one GET /api/auth/session returns as `reactor`. `name` is attribution
- * only; `at` is when they chose it. */
- reactions?: Array<{ emoji: string; by: string; name?: string; at?: number }>;
- /** user lines a 👍 or 👎 made: the person reacted with this emoji to
- * `replyToId` instead of typing. Clients show the reaction on that message
- * and draw no bubble for this line. */
- reaction?: string;
- /** comm chips: "Messaged @X", linking to the bot-bot channel. */
- comm?: { groupId: string; threadId?: string; withBotId: string; withName: string; withColor: string };
- /** On a Team Cloud, a message passed between people: "told" on the chip in the asking conversation names whose inbox
- * got it, "reply" on an answer that came back names who answered, "assistant" one their assistant answered for them. */
- relay?: { kind: "told" | "reply" | "assistant"; email: string; name: string };
- /** On a Team Cloud, a line in its person's inbox: who it is from and where it came from. */
- inbox?: InboxItem;
- /** thread chips: "Opened thread #Title on @X". */
- threadRef?: { botId: string; threadId: string; title: string };
- /** A "Sent to" row for work addressed into a room the bot `name` isn't in, so it went to the bot directly. `room`
- * names that room when this row is not in it. Clients say it in their own words; `tool.name` is the English. */
- sentDirectly?: { name: string; room?: string };
- /** A page the bot published to a public link (publish_page), or why it couldn't. `text` carries the link too. */
- publishedPage?: PublishedPageCard;
- /** A published Data result, linked to its bot's main viewer. */
- dataResult?: { botId: string; cardId: string; title: string; kind: "table" | "chart" | "text"; sql?: string };
- /** user messages: the Data result the person was viewing when they sent
- * this. `text` stays exactly what they typed. */
- dataContext?: { cardId: string; draftSql?: string };
- /** user messages waiting in the steer-queue while the bot is mid-turn. */
- queued?: boolean;
- /** steer-queue entry this drained user line came from. */
- queueId?: string;
-}
-
-export const movesThreadToTop = (message: Pick<WireMessage, "role" | "kind" | "peerAsk" | "turnId" | "turnTerminal">): boolean =>
- message.role === "user" ? !message.peerAsk : message.kind === "text" && (message.turnTerminal === true || !message.turnId);
-
-export function orderedThreadList<T extends { pinned?: boolean; lastThreadOrderAt?: number; createdAt?: number }>(tasks: readonly T[]): T[] {
- return tasks
- .map((task, index) => ({ task, index }))
- .sort((a, b) => {
- const pin = Number(b.task.pinned === true) - Number(a.task.pinned === true);
- if (pin) return pin;
- const recency = (b.task.lastThreadOrderAt ?? b.task.createdAt ?? 0) - (a.task.lastThreadOrderAt ?? a.task.createdAt ?? 0);
- if (recency) return recency;
- return a.index - b.index;
- })
- .map((entry) => entry.task);
-}
-
-/** 0 is the "until new activity" sentinel. The event stream never drops an expired snooze, so check the clock too. */
-export const isSnoozed = (task: Pick<WireTask, "snoozedUntil">, now = Date.now()): boolean =>
- task.snoozedUntil !== undefined && (task.snoozedUntil === 0 || task.snoozedUntil > now);
-
-type OpenThreadCandidate = Pick<WireTask, "routineRunId" | "archivedAt" | "closedBy" | "openedBy" | "snoozedUntil" | "pinned" | "lastThreadOrderAt" | "createdAt">;
-
-/** The top row of the bot's thread list, so deleting the open thread never pulls a hidden one into view. */
-export function nextOpenThread<T extends OpenThreadCandidate>(tasks: readonly T[], now = Date.now()): T | undefined {
- const own = tasks.filter((task) => !task.routineRunId);
- const open = own.filter((task) => task.archivedAt === undefined);
- const listed = open.filter((task) => task.pinned === true || !(task.closedBy || task.openedBy || isSnoozed(task, now)));
- return [listed, open, own].map((candidates) => orderedThreadList(candidates)[0]).find((task) => task !== undefined);
-}
-
-export interface OptionCardData extends WaitCardField, ComputerAskField, AccessRequestCardField, OutsideWriteCardField, AppSettingCardField {
- /** The harness asks the owner to let this line of theirs use the lent computer (server/host/lending-lifts.ts). */ lendingLift?: { requestMessageId: string; memoryToken?: string; outside?: true; botOpened?: true; allowedAt?: number };
- /** calls: one per outbound call the card covers, in subtitle order. */
- outboundRequest?: { tool: string; app: string | null; calls?: Array<{ app: string | null; label: string }> };
- /** `revision`: the entry as it applied without a person, so Undo can tell it changed since. */
- teamMemoryRequest?: { section: string; entryId: string; kind: string; revision?: string };
- title: string;
- subtitle: string;
- /** Fixed `chat.notice.*` words for `subtitle`; the English fallback stays stored in `subtitle`. */
- summaryCode?: string;
- summaryParams?: ServerTextParams;
- options: string[];
- /** Distinguishes a provider question from an approval after its live run ends. */
- requestType?: "permission" | "question";
- answered?: string;
- /** What was actually answered, when the answer is words rather than a
- * verdict. */
- answeredText?: string;
- dismissed?: boolean;
- /** Who settled the card, when a person or service answered it. */
- answeredBy?: CardAnswerer;
- /** Present when this card is a live provider ask (approval/question). */
- requestId?: string;
- /** permission cards: the tool being requested. */
- tool?: string;
- /** why this card is waiting: guard, mode, sandbox or delivery error. */
- held?: string;
- /** Terminal: no answer came in time, or this proposal went stale while open (revision mismatch or a superseding
- * request). Nothing can answer it; a fresh proposal is needed, and clients must not offer its options. */
- expired?: boolean;
- /** Stop ended the work that asked: nothing can answer it any more. */
- stopped?: boolean;
- /** Catalog key for held when it is one of the fixed notes. */
- heldCode?: string;
- /** the narrow grant "always allow" remembers for a harness-native card. */
- allowKey?: string;
- /** the provider can remember an allow for the rest of its session. */
- allowSession?: boolean;
- /** Exact native command offered for an owner/admin to remember. */
- commandAllowlist?: CommandAllowlistCandidate;
- /** Local actions never share remembered grants with cloud/tool approvals. */
- approvalScope?: "local-computer";
- /** The bot's change applied without a person (a change to the bot itself,
- * or Full access): clients show a one-line receipt with Undo instead of
- * the approval box. */
- autoApplied?: boolean;
- /** A person undid that change. */
- undone?: boolean;
- /** A durable chat-created routine proposal. */
- routineRequest?: RoutineRequestCardData;
- /** A webhook trigger a bot made or changed from chat. */
- webhookRequest?: WebhookRequestCardData;
- /** An app-event automation a bot made or changed from chat. */
- appTriggerRequest?: AppTriggerRequestCardData;
- /** A durable profile-change proposal (propose_profile). */
- profileRequest?: ProfileRequestCardData;
- /** A durable default-model proposal (propose_model). */
- modelRequest?: ModelRequestCardData;
- teamSetupRequest?: TeamSetupRequest;
- /** A bot's MCP server change waiting on the person (Ask, Edits or Auto). */
- mcpRequest?: McpChangeRequest;
- /** A durable learned-skill proposal. */
- skillRequest?: SkillRequestCardData;
- /** A provider's structured question set. */
- questionRequest?: QuestionRequestCardData;
- /** The options are the whole answer: clients offer no free-text reply. */
- fixedOptions?: boolean;
- quotaSwitch?: QuotaSwitchCardData;
- /** Asks before a bot uses the person's own computer; what its first call names, for the question in their language. */
- yourComputer?: { app?: string; site?: string };
-}
-
-/** Kept on the card so the offer survives a restart. `engines` follow the card's options; `messageId` is the
- * message to resend, `rootId` the failed request's job-runtime root. */
-export interface QuotaSwitchCardData {
- engines: Array<{ instanceId: string; name: string }>;
- messageId?: string;
- rootId?: string;
-}
-
-export interface SecretRequestCardData {
- /** Fixed allowlisted credential id, never a config path; CUSTOM_SECRET_TARGET: a secret the bot names, kept off Settings. */
- target: CredentialTargetId | typeof CUSTOM_SECRET_TARGET;
- label: string;
- description: string;
- /** Optional named-key copy for client localization; `description` remains the complete fallback for English and older cards. */
- descriptionParts?: {
- baseCode: "secretCard.greenference.description" | "secretCard.modelgo.description" | "secretCard.geminiTts.description";
- reason: string;
- bot: string;
- };
- placeholder: string;
- helpUrl: string;
- /** A custom secret's use: "ref", OpenMausBot's own tools only; "file", the bot's commands; "email", the Email connector, never a bot. */ delivery?: SecretDelivery | "email";
- /** An email card: the mailbox it is for, when known; off a phone the person can change it on the card. */ address?: string;
- /** An email card: the incoming server that took the password, once it did, while sending is still being checked. */
- emailReading?: string;
- /** An email card for a connected mailbox that can't send: only its outgoing server, from what is known, never a password. */ emailOutgoing?: EmailOutgoingFields;
- /** A custom secret: the bot's own words on why; `description` adds what the bot may do with it, and helpUrl is empty. */
- reason?: string;
- /** A file secret's Local VM target key, when the asking turn ran in one. */
- vm?: string;
- /** When a custom secret was saved; its file goes a day later. */
- savedAt?: number;
- requestKey: string;
- phoneOperationId?: string;
- provided?: boolean;
- dismissed?: boolean;
- /** A newer request for the same credential replaced this card; it no
- * longer offers entry and cannot be provided or dismissed. */
- superseded?: boolean;
- resumed?: boolean;
- error?: string;
- /** Stop ended the turn this card paused: it offers no entry, and a key
- * saved afterwards is kept but continues nothing. */
- stopped?: boolean;
-}
-
-/** A bot asked the person to sign in to a website themselves: they type the
- * password into the page, or save a login the server fills for the bot. The
- * bot never sees the password either way. */
-export interface SignInRequestCardData {
- /** The page to open, an http(s) address. */
- url: string;
- /** Its host, the card's headline. */
- site: string;
- /** The bot's own words: why it needs the sign-in. */
- reason?: string;
- /** Where the login has to happen: the place the asking turn worked in. */
- place: Surface;
- done?: boolean;
- cancelled?: boolean;
- /** A newer request for the same site in this conversation replaced this
- * card; it no longer offers Done or Cancel. */
- superseded?: boolean;
- /** Answered by saving a login: the site it was saved for (and a sign-in
- * host on another site the person confirmed), which the bot then fills
- * with fill_login. */
- savedLogin?: string;
- resumed?: boolean;
- error?: string;
- /** Stop ended the turn this card paused: it offers no Done or Cancel,
- * and an answer given afterwards is kept but continues nothing. */
- stopped?: boolean;
- /** The person answered in the conversation instead of pressing Done: it
- * offers no Done or Cancel, and the turn their line started goes on. */
- answeredInChat?: boolean;
-}
-
-/** The open sign-in request a bot's computer plea stands for, so whichever
- * panel shows the plea can settle that card. */
-export interface ComputerHelpRef {
- /** The asking bot: a team computer's plea reaches every member's panel. */
- botId: string;
- threadId: string;
- messageId: string;
- site: string;
- place: Surface;
-}
-
-/** Who answers a room message nobody was @mentioned in. `auto` asks the
- * decision model and falls back to `fallbackBotId` (else the first member)
- * whenever it is off or unsure. Readers must treat any kind they do not know
- * as the default lead. */
-export type GroupDefaultResponder =
- | { kind: "member"; botId: string }
- | { kind: "everyone" }
- | { kind: "mentions" }
- | { kind: "auto"; fallbackBotId?: string };
-
-/** One independent conversation inside a user-created channel. */
-export interface GroupTask {
- threadId: string;
- /** Replies in this conversation that have not been read. */
- unread?: boolean;
- lastReadMessageId?: string;
- /** The completed message whose visible history seeded this conversation. */
- origin?: ForkOrigin;
- title: string;
- createdAt: number;
- pinnedCwd?: string | null;
- pinnedMessageId?: string;
- /** The person pinned this channel thread above the update-ordered list. */
- pinned?: boolean;
- /** This conversation's own turn limit: whole minutes a turn may go without progress. Absent uses
- * the global group turn limit. Direct chats do not use this limit. */
- turnTimeoutMinutes?: number;
- /** Epoch ms when the person archived this thread; absent while it is in the list. */ archivedAt?: number;
- /** A card in this thread waits on the person, with no turn running. */ activity?: "waiting-on-you";
- /** Epoch ms of the newest message, or createdAt when the thread has none. */
- updatedAt?: number;
- lastThreadOrderAt?: number;
- /** The first message already drove a title attempt for this thread, so a
- * later one does not rename a room the person may have retitled. */
- titleFromFirstMessage?: true;
- /** Whether a turn is actively running in this thread. */
- working?: boolean;
- /** The member bot currently speaking or generating in this thread, if any. */
- busyBotId?: string | null;
-}
-
-/** A room as a client may see it: the record plus the computed working flag. */
-export interface WireGroup {
- /** Computed from the usage ledger, not stored in groups.json. */
- usage?: GroupThreadUsage | null; /** Transient: the department's Chief of Staff, when this room is without it. Null clears an earlier value. */ chiefAbsent?: { botId: string; name: string } | null;
- /** transient: each member's context in the active thread, from its last
- * turn there, and whether its next turn there was asked to start
- * compacted. */
- memberContext?: Record<string, { tokens: number; window: number; compactRequested?: true }> | null;
- id: string;
- /** The active task's thread. Direct-message channels stay single-threaded. */
- threadId: string;
- /** User-created channels have independent tasks, newest first. */
- tasks?: GroupTask[];
- name: string;
- memberIds: string[];
- defaultResponder: GroupDefaultResponder;
- /** The room's shared instructions. */
- bulletin: string;
- /** Short one-line description shown under the room name; distinct from
- * the bulletin (long-form instructions) and any member bot's title.
- * null = explicitly cleared, so a client's shallow merge drops a stale value. */
- description?: string | null;
- unread: boolean;
- /** The newest message on screen the last time the person read this
- * conversation. The New divider goes after it. */
- lastReadMessageId?: string;
- createdAt: number;
- /** true for auto-created bot-bot channels. */
- dm?: boolean;
- /** transient: the member currently running a turn. */
- busyBotId?: string | null;
- /** transient: when the busy member's turn started; never persisted. */
- turnStartedAt?: number;
- /** the room's shared desk; absent = each member's own default. */
- cwd?: string;
- pinnedCwd?: string | null;
- pinnedMessageId?: string;
- /** sidebar section heading this room is filed under. */
- section?: string;
- /** New user-created rooms start with setup pending. */
- setupCompletedAt?: number | null;
- setupSkippedAt?: number | null;
- /** The narrowest audience this room has ever had: a bot leaving never
- * widens who may see the transcript. Sent to admins only. */
- audienceFloor?: BotVisibility;
- /** True while any member (or hand-off) is mid-turn. Computed at
- * projection time, never persisted. */
- working: boolean;
- /** A direct-message channel's turn limit (minutes without progress). Null on the wire means the
- * global group limit. Channel conversations store theirs on each task. */
- turnTimeoutMinutes?: number | null;
- /** Members the person stopped in this room ("stop @Bot"), by bot id. A
- * held member gets no turn until it is @mentioned again or resumed. */
- holds?: Record<string, RoomHold>;
- /** Room messages addressed to a member while it was held, by bot id;
- * its next turn is shown them, then they are cleared. */
- heldMessages?: Record<string, RoomHeldMessage[]>;
- /** transient: who waits in each of the room's threads, and on whom; absent or empty when nobody waits. */
- queue?: RoomQueueEntry[];
-}
-
-export interface RoomQueueEntry {
- botId: string;
- threadId: string;
- state: "running" | "queued";
- /** 1-based place in that thread's line; `of` counts the whole line. */
- position: number;
- of: number;
- /** Who a queued member waits on: the member running now, else the one speaking (or the one ahead). */
- waitingForBotId?: string;
- assignmentId?: string;
-}
-
-/** One member's hold in a room: when the person stopped it, and whether the
- * room has already said so (the held line is written once per hold). */
-export interface RoomHold {
- at: number;
- noted?: boolean;
-}
-
-/** A room message that reached a member while it was held. */
-export interface RoomHeldMessage {
- threadId: string;
- messageId: string;
-}
-
-/** Why a steer-queue entry waits: a shared thread slot, or the bot's room
- * turn (which runs one at a time per bot). */
-export type SteerQueueReason = "capacity" | "group-turn";
-
-/** Pending steer-queue chips, as `queuedSteerSnapshot` emits them and the `bot.queued` frame carries them: threadId → queued items. */
-export type BotQueuedMessages = Record<string, Array<{ queueId: string; text: string; reason?: SteerQueueReason; /** The reason in plain words, shown as it is. */ why?: string;
- /** Team Cloud, where several people write: whose line waits; only they remove it, and it runs after as their own turn. */ sender?: ResolvedSender }>>;
-
-/** Skills library browse surface: one row per library entry, with the bots
- * currently assigned to it. Version is null for locally imported skills. */
-export interface SkillsLibrarySkillWire {
- name: string;
- description: string;
- source: string;
- enabled: boolean;
- everyBot: boolean;
- tags: string[];
- version: string | null;
- importedAt: string;
- license?: string;
- compatibility?: string;
- warnings: string[];
- assignedBots: Array<{ id: string; name: string }>;
-}
-
-/** PUT body for a bot's assignment list: the full list, applied
- * idempotently. */
-export interface BotAssignedSkillsWire {
- skills: string[];
-}
-
-export type ServerFrame =
- | { kind: "sections"; sections: string[] }
- | { kind: "bot.queued"; queues: BotQueuedMessages }
- | { kind: "message"; threadId: string; message: WireMessage }
- | { kind: "message.patch"; threadId: string; message: WireMessage }
- | { kind: "thread"; threadId: string; activeLeafId: string }
- | { kind: "bot"; bot: WireBot }
- | { kind: "group"; group: WireGroup }
- | { kind: "notify"; notification: NotificationLogEntry }
- | { kind: "notifications.read"; threadId: string; ids: string[] }
- | { kind: "group.deleted"; groupId: string }
- | { kind: "routine"; routine: Routine }
- | { kind: "routine.deleted"; routineId: string }
- | { kind: "routine.run"; run: RoutineRun }
- | { kind: "webhook"; webhook: WebhookTrigger }
- | { kind: "webhook.attempt"; attempt: WebhookAttempt }
- | { kind: "webhook.deleted"; webhookId: string }
- | { kind: "app-trigger"; botId: string; trigger: AppTrigger }
- | { kind: "app-trigger.attempt"; botId: string; attempt: AppEventAttempt }
- | { kind: "app-trigger.deleted"; triggerId: string }
- | { kind: "app-trigger.service"; service: AppTriggerService }
- | { kind: "runtime"; event: RuntimeEvent }
- /** An MCP server was added, changed or removed: a list of them is stale. */
- | { kind: "mcp.changed" }
- /** `surface` names what the frame shows: the bot's desktop (`computer`) or its built-in browser. */
- | { kind: "screen"; botId: string; threadId: string; png: string; mime?: string; surface?: "browser" | "computer" }
- /** A bot's computer is being set up or woken for a turn; the chat shows
- * one progress line until its first screen frame. `place` names a cloud
- * computer (absent: a Local VM). */
- | { kind: "computer"; botId: string; state: "provisioning" | "waking"; place?: "cloud" }
- | { kind: "computer-control"; botId: string; held: boolean; helpReason: string | null; help?: ComputerHelpRef | null }
- /** A bot's data sheet changed. Whole sheet each time. */
- | DataBroadcast
- | { kind: "bot.deleted"; botId: string }
- /** The whole fleet (PUT /api/bots/order) or every room (PUT /api/groups/order) in its new order; a member is sent only the ones they see. */
- | { kind: "bots.order"; botIds: string[] } | { kind: "groups.order"; groupIds: string[] } | WindowPrefFrame
- | { kind: "live.call"; botId: string; threadId: string; call: LiveCallState | null }
- /** A job is waiting for the phone whose registry key this is; it polls now. */
- | { kind: "device.job"; phone: string; id: string }
- /** Who is here on a Team Cloud (shared/team-presence.ts). */
- | PresenceFrame
- /** The config status object spread flat into the frame. */
- | ({ kind: "config" } & Record<string, unknown>);
+export * from "../packages/phone-protocol/src/wire.ts";
diff --git a/src/locales/server-lines.test.ts b/src/locales/server-lines.test.ts
index 0c8961ea32..b7de530a93 100644
--- a/src/locales/server-lines.test.ts
+++ b/src/locales/server-lines.test.ts
@@ -18,7 +18,7 @@ import de from "./de.json";
import en from "./en.json";
const ROOT = fileURLToPath(new URL("../../", import.meta.url));
-const SCANNED = ["server", "shared"];
+const SCANNED = ["server", "shared", "packages/phone-protocol/src"];
const SKIPPED_DIRS = new Set(["node_modules", "testing", "dist", "resources"]);
const isSource = (name: string) => name.endsWith(".ts") && !/\.test\.|\.d\.ts$/.test(name);
@@ -41,6 +41,8 @@ interface Source {
sf: ts.SourceFile;
decls: Map<string, ts.FunctionDeclaration | ts.VariableDeclaration>;
imports: Map<string, { file: string; name: string }>;
+ /** The files of its `export * from "./x.ts"` lines. */
+ reexports: string[];
calls?: Map<string, ts.CallExpression[]>;
}
@@ -77,7 +79,9 @@ export function findServerLines(paths: readonly string[], read: (path: string) =
const file = resolve(dirname(path), specifier);
for (const element of bindings.elements) imports.set(element.name.text, { file, name: (element.propertyName ?? element.name).text });
}
- const source = { sf, decls, imports };
+ const reexports = sf.statements.flatMap((statement) => ts.isExportDeclaration(statement) && !statement.exportClause && statement.moduleSpecifier
+ && ts.isStringLiteral(statement.moduleSpecifier) && statement.moduleSpecifier.text.startsWith(".") ? [resolve(dirname(path), statement.moduleSpecifier.text)] : []);
+ const source = { sf, decls, imports, reexports };
sources.set(path, source);
return source;
}
@@ -156,9 +160,19 @@ export function findServerLines(paths: readonly string[], read: (path: string) =
const local = declarationOf(source, node, name);
if (local) return { source, decl: local };
const imported = source.imports.get(name);
- const target = imported ? load(imported.file) : null;
- const decl = imported && target ? target.decls.get(imported.name) : undefined;
- return target && decl ? { source: target, decl } : null;
+ return imported ? exportedFrom(imported.file, imported.name, 0) : null;
+ }
+
+ function exportedFrom(file: string, name: string, depth: number): { source: Source; decl: ts.FunctionDeclaration | ts.VariableDeclaration } | null {
+ const target = depth > 4 ? null : load(file);
+ if (!target) return null;
+ const decl = target.decls.get(name);
+ if (decl) return { source: target, decl };
+ for (const next of target.reexports) {
+ const found = exportedFrom(next, name, depth + 1);
+ if (found) return found;
+ }
+ return null;
}
const functionOf = (decl: ts.FunctionDeclaration | ts.VariableDeclaration): FunctionLike | null =>
@@ -492,7 +506,7 @@ const PENDING: Readonly<Record<string, ReadonlyArray<readonly [file: string, sni
["server/index.ts", "context compacted — re-sent the last … digest …"],
["server/index.ts", "generated image could not be attached — …"],
["server/index.ts", "invalid image"],
- ["shared/first-reply-rescue.ts", "notice: … hasn't heard back from … yet."],
+ ["packages/phone-protocol/src/first-reply-rescue.ts", "notice: … hasn't heard back from … yet."],
],
"moves to the Cloud": [
],
diff --git a/src/locales/vocabulary.test.ts b/src/locales/vocabulary.test.ts
index df73eaa359..ecc1bb0ca7 100644
--- a/src/locales/vocabulary.test.ts
+++ b/src/locales/vocabulary.test.ts
@@ -49,14 +49,14 @@ const EN_ALLOWED: Record<string, string> = {
};
const ROOT = fileURLToPath(new URL("../../", import.meta.url));
-const SCANNED = ["src", "server", "electron", "shared"];
+const SCANNED = ["src", "server", "electron", "shared", "packages/phone-protocol/src"];
// Test fixtures and generated output are not copy anyone reads.
const SKIPPED_DIRS = new Set(["node_modules", "resources", "testing", "dist"]);
const isSource = (name: string) => /\.(?:ts|tsx|mjs|cjs|js)$/.test(name) && !/\.test\.|\.node-test\.|\.d\.ts$/.test(name);
/** No snippet keeps the word file-wide; otherwise only literals containing the snippet. */
const ALLOWED: ReadonlyArray<{ file: string; snippet?: string; why: string }> = [
- { file: "shared/credential-request.ts", snippet: "when Boat is selected", why: "the card that asks for a person's own Boat key" },
+ { file: "packages/phone-protocol/src/credential-request.ts", snippet: "when Boat is selected", why: "the card that asks for a person's own Boat key" },
{ file: "server/boat-create-idempotency.ts", snippet: "unnamed Boat", why: "own-key repair: boat.dev's own name for a machine" },
{ file: "src/lib/boat-offer.ts", snippet: "MausBot introduced me", why: "the email a person sends Boat to claim its credit" },
{ file: "server/workspace-backup.ts", snippet: "OMB-WORKSPACE-1", why: "a backup file's format marker" },