Skip to content

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

Move the phone job, registration and sealed-credential schemas, portable Live call code and cron-label into packages/phone-protocol (#5956)

Milind Soni3cc240adf3c4
diff --git a/packages/phone-protocol/src/cron-label.ts b/packages/phone-protocol/src/cron-label.ts
new file mode 100644
index 0000000000..79561c9db1
--- /dev/null
+++ b/packages/phone-protocol/src/cron-label.ts
@@ -0,0 +1,55 @@
+import { plainTimeZone } from "./plain-time-zone.ts";
+import type { RoutineCronSchedule } from "./routine-schedule.ts";
+
+const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
+const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
+const ORDERS = { 1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth", last: "last" } as const;
+
+/** A familiar cron preset: `weekday` 0 (Sunday) to 6, `month` 0 (January) to 11, `time` "HH:MM". */
+export type CronPreset =
+ | { kind: "everyDay" | "monthlyLastDay" | "weekdays"; time: string }
+ | { kind: "monthlyDay"; day: number; time: string }
+ | { kind: "yearly"; month: number; day: number; time: string }
+ | { kind: "weekly"; weekday: number; time: string }
+ | { kind: "monthlyNth"; nth: keyof typeof ORDERS; weekday: number; time: string };
+
+export function cronPreset(expression: string): CronPreset | null {
+ const [minute, hour, day, month, weekday] = expression.trim().split(/\s+/);
+ if (!/^\d+$/.test(minute ?? "") || !/^\d+$/.test(hour ?? "")) return null;
+ const time = `${hour!.padStart(2, "0")}:${minute!.padStart(2, "0")}`;
+ const monthDay = /^\d+$/.test(day ?? "") ? Number(day) : null;
+ if (weekday === "*" && month === "*") {
+ if (day === "*") return { kind: "everyDay", time };
+ if (day === "L") return { kind: "monthlyLastDay", time };
+ return monthDay === null ? null : { kind: "monthlyDay", day: monthDay, time };
+ }
+ if (weekday === "*" && /^\d+$/.test(month ?? "") && monthDay !== null) {
+ return MONTHS[Number(month) - 1] ? { kind: "yearly", month: Number(month) - 1, day: monthDay, time } : null;
+ }
+ if (day !== "*" || month !== "*") return null;
+ if (weekday === "1-5" || weekday?.toUpperCase() === "MON-FRI") return { kind: "weekdays", time };
+ if (/^[0-7]$/.test(weekday ?? "")) return { kind: "weekly", weekday: Number(weekday) % 7, time };
+ const nth = /^([0-7])#([1-5]|L)$/i.exec(weekday ?? "");
+ if (!nth) return null;
+ return { kind: "monthlyNth", nth: nth[2]!.toUpperCase() === "L" ? "last" : (Number(nth[2]) as 1 | 2 | 3 | 4 | 5), weekday: Number(nth[1]) % 7, time };
+}
+
+function englishPreset(preset: CronPreset): string {
+ const time = preset.time.replace(/^0(?=\d:)/, "");
+ switch (preset.kind) {
+ case "everyDay": return `Every day at ${time}`;
+ case "monthlyLastDay": return `Monthly on the last day at ${time}`;
+ case "monthlyDay": return `Monthly on day ${preset.day} at ${time}`;
+ case "yearly": return `Yearly on ${MONTHS[preset.month]} ${preset.day} at ${time}`;
+ case "weekdays": return `Every weekday at ${time}`;
+ case "weekly": return `Weekly on ${WEEKDAYS[preset.weekday]} at ${time}`;
+ case "monthlyNth": return `Monthly on the ${ORDERS[preset.nth]} ${WEEKDAYS[preset.weekday]} at ${time}`;
+ }
+}
+
+/** Describe familiar presets; retain the exact expression for everything else.
+ * This is presentation only, never a second parser or source of scheduling truth. */
+export function cronScheduleLabel(schedule: RoutineCronSchedule): string {
+ const preset = cronPreset(schedule.expression);
+ return `${preset ? englishPreset(preset) : `Cron ${schedule.expression}`} ${plainTimeZone(schedule.timeZone)}`;
+}
diff --git a/packages/phone-protocol/src/live-call.ts b/packages/phone-protocol/src/live-call.ts
new file mode 100644
index 0000000000..590653de6c
--- /dev/null
+++ b/packages/phone-protocol/src/live-call.ts
@@ -0,0 +1,148 @@
+// Pure pieces of a Live (GPT-Live) call. With client delegation GPT-Live says
+// *that* it wants help, never *what*: `session.delegation.created` carries an id
+// and a timeline offset, so the request is rebuilt from the input transcript.
+
+export interface TranscriptSegment {
+ text: string;
+ startMs: number;
+ endMs: number;
+}
+
+/** Collects `session.input_transcript.delta` fragments on the session
+ * timeline. Fragments are appended in delivery order, as the API asks. */
+export class LiveTranscript {
+ private input: TranscriptSegment[] = [];
+ /** when the voice itself was speaking, on the same timeline */
+ private output: Array<{ startMs: number; endMs: number }> = [];
+ private cutoffMs = -1;
+
+ addInput(text: string, startMs: number, endMs: number): void {
+ if (!text) return;
+ this.input.push({ text, startMs: Number.isFinite(startMs) ? startMs : 0, endMs: Number.isFinite(endMs) ? endMs : 0 });
+ // keep memory bounded on long calls: only the unconsumed tail matters
+ if (this.input.length > 2_000) this.input = this.input.filter((segment) => segment.startMs > this.cutoffMs);
+ }
+
+ /** A stretch of the voice's own speech (a `session.output_transcript.delta`
+ * with its timing). Input heard during it may be the voice itself, picked
+ * up again by the microphone of a phone on speaker. Deltas without timing
+ * are ignored. */
+ addOutput(startMs: number, endMs: number): void {
+ if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs < startMs) return;
+ const last = this.output.at(-1);
+ if (last && startMs <= last.endMs) last.endMs = Math.max(last.endMs, endMs);
+ else this.output.push({ startMs, endMs });
+ if (this.output.length > 500) this.output.splice(0, this.output.length - 500);
+ }
+
+ /** The words spoken since the previous request, up to a little past the
+ * delegation point (transcription can trail the delegation event, and the
+ * person may finish the sentence that triggered it). Consumes them, so the
+ * next request starts after this one. */
+ takeRequest(offsetMs: number, graceMs = 1_500): string {
+ return this.takeRequestParts(offsetMs, graceMs).text;
+ }
+
+ /** takeRequest, plus the same words without those heard while the voice
+ * spoke (`withoutEcho`), for reading a spoken yes/no. Consumes all of them. */
+ takeRequestParts(offsetMs: number, graceMs = 1_500): { text: string; withoutEcho: string } {
+ const until = offsetMs + graceMs;
+ const taken = this.input.filter((segment) => segment.startMs > this.cutoffMs && segment.startMs <= until);
+ if (!taken.length) return { text: "", withoutEcho: "" };
+ this.cutoffMs = Math.max(this.cutoffMs, ...taken.map((segment) => segment.startMs));
+ return {
+ text: joinFragments(taken.map((segment) => segment.text)),
+ withoutEcho: joinFragments(taken.filter((segment) => !this.echoed(segment)).map((segment) => segment.text)),
+ };
+ }
+
+ /** Everything heard since the last taken request, without consuming it —
+ * used to read a spoken yes/no while a permission question is open.
+ * `skipEcho` leaves out what was heard while the voice itself spoke. */
+ pending(options: { skipEcho?: boolean } = {}): string {
+ return joinFragments(this.input
+ .filter((segment) => segment.startMs > this.cutoffMs && !(options.skipEcho && this.echoed(segment)))
+ .map((segment) => segment.text));
+ }
+
+ private echoed(segment: TranscriptSegment): boolean {
+ return this.output.some((span) => segment.startMs < span.endMs && segment.endMs > span.startMs);
+ }
+
+ /** Mark everything heard so far as handled (e.g. after a spoken decision). */
+ consumeAll(): void {
+ for (const segment of this.input) this.cutoffMs = Math.max(this.cutoffMs, segment.startMs);
+ }
+}
+
+/** Transcript deltas are fragments of words, not words: glue them as sent. */
+export function joinFragments(fragments: string[]): string {
+ return fragments.join("").replace(/\s+/g, " ").trim();
+}
+
+export const FULL_ANSWER_IN_CHAT = "The full answer is in the chat.";
+
+/** GPT-Live voices from OpenAI's documentation (Managing GPT-Live sessions,
+ * "Voice options", and the SDK's BuiltInVoice list), with the regional
+ * notes the docs give for the additional ones. */
+export const LIVE_VOICE_OPTIONS: ReadonlyArray<{ id: string; label: string }> = [
+ { id: "marin", label: "Marin (default)" },
+ { id: "cedar", label: "Cedar" },
+ { id: "alloy", label: "Alloy" },
+ { id: "ash", label: "Ash" },
+ { id: "ballad", label: "Ballad" },
+ { id: "coral", label: "Coral" },
+ { id: "echo", label: "Echo" },
+ { id: "sage", label: "Sage" },
+ { id: "shimmer", label: "Shimmer" },
+ { id: "verse", label: "Verse" },
+ { id: "gleam", label: "Gleam — North American, feminine" },
+ { id: "meridian", label: "Meridian — North American, masculine" },
+ { id: "quartz", label: "Quartz — Australian, feminine" },
+ { id: "ripple", label: "Ripple — Australian, masculine" },
+ { id: "vesper", label: "Vesper — British, masculine" },
+ { id: "willow", label: "Willow — Irish, feminine" },
+ { id: "stone", label: "Stone — Irish, masculine" },
+ { id: "delta", label: "Delta — Southern U.S., feminine" },
+ { id: "cinder", label: "Cinder — Southern U.S., masculine" },
+ { id: "beacon", label: "Beacon — Filipino, masculine" },
+ { id: "bossa", label: "Bossa — Brazilian Portuguese, feminine" },
+ { id: "tempo", label: "Tempo — Brazilian Portuguese, masculine" },
+];
+
+/** Gemini Live's prebuilt voices (Gemini API docs, "Live API capabilities", voices), with the docs' one-word character.
+ * Gemini names them with a capital letter. */
+export const GEMINI_LIVE_VOICE_OPTIONS: ReadonlyArray<{ id: string; label: string }> = [
+ { id: "Puck", label: "Puck — upbeat (default)" },
+ { id: "Charon", label: "Charon — informative" },
+ { id: "Kore", label: "Kore — firm" },
+ { id: "Fenrir", label: "Fenrir — excitable" },
+ { id: "Aoede", label: "Aoede — breezy" },
+ { id: "Leda", label: "Leda — youthful" },
+ { id: "Orus", label: "Orus — firm" },
+ { id: "Zephyr", label: "Zephyr — bright" },
+];
+
+export const GEMINI_LIVE_DEFAULT_VOICE = "Puck";
+
+/** A saved Gemini voice when it is one of Gemini's, else the default. */
+export function geminiLiveVoice(voice: string | undefined): string {
+ return GEMINI_LIVE_VOICE_OPTIONS.find((option) => option.id === voice?.trim())?.id ?? GEMINI_LIVE_DEFAULT_VOICE;
+}
+
+/** A call's length as a clock: m:ss under an hour ("0:07", "1:42"),
+ * h:mm:ss from an hour on ("1:02:05"). Whole seconds; a value that is not a
+ * length reads as 0:00. */
+export function formatCallDuration(seconds: number): string {
+ const total = Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0;
+ const hours = Math.floor(total / 3_600);
+ const minutes = Math.floor((total % 3_600) / 60);
+ const rest = String(total % 60).padStart(2, "0");
+ return hours > 0 ? `${hours}:${String(minutes).padStart(2, "0")}:${rest}` : `${minutes}:${rest}`;
+}
+
+/** A Live call row's text: what a client that does not know kind "call"
+ * shows as a plain line ("Call with Ada · 1:42"). */
+export function liveCallRowText(botName: string, seconds: number): string {
+ return `Call with ${botName} · ${formatCallDuration(seconds)}`;
+}
diff --git a/packages/phone-protocol/src/phone-jobs.ts b/packages/phone-protocol/src/phone-jobs.ts
new file mode 100644
index 0000000000..3344bf36cf
--- /dev/null
+++ b/packages/phone-protocol/src/phone-jobs.ts
@@ -0,0 +1,37 @@
+// What a paired phone and its server exchange when the phone's own apps are bot tools: the phone registers
+// (PUT /api/phones/self), takes jobs (GET /api/phones/self/jobs) and answers each one.
+import { z } from "zod";
+
+import { PHONE_CAPABILITIES, PHONE_PLATFORMS } from "./phone-apps.ts";
+
+const KNOWN_CAPABILITIES: readonly string[] = PHONE_CAPABILITIES;
+/** Only the apps this server knows: a newer phone's extra app is dropped, never a reason to refuse the rest. */
+const knownCapabilities = (value: unknown) => (value && typeof value === "object" && !Array.isArray(value)
+ ? Object.fromEntries(Object.entries(value).filter(([capability]) => KNOWN_CAPABILITIES.includes(capability)))
+ : value);
+
+/** The phones ship on their own schedule, so a field this server does not know yet is stripped, not refused. */
+export const phoneRegistration = z.object({
+ installId: z.string().regex(/^[\w-]{8,64}$/),
+ name: z.string().min(1).max(120),
+ platform: z.enum(PHONE_PLATFORMS),
+ appVersion: z.string().max(40),
+ timeZone: z.string().max(64),
+ /** Capability → the OS grant the phone holds ("full", "limited", "when_in_use", "send", "listener"); present means allowed. */
+ capabilities: z.preprocess(knownCapabilities, z.partialRecord(z.enum(PHONE_CAPABILITIES), z.string().min(1).max(32))),
+});
+export type PhoneRegistration = z.infer<typeof phoneRegistration>;
+
+export const PHONE_JOB_CODES = ["denied", "foreground_required", "not_found", "too_large", "unsupported", "offline", "timeout", "turn_ended"] as const;
+export type PhoneJobCode = (typeof PHONE_JOB_CODES)[number];
+export type PhoneJobOutcome = { ok: true; result: unknown } | { ok: false; error: string; code?: PhoneJobCode };
+const KNOWN_CODES: readonly unknown[] = PHONE_JOB_CODES;
+/** A newer phone's extra field is stripped, and a code this server does not know yet reads as none: the error still
+ * reaches the bot. */
+export const phoneJobOutcome = z.union([
+ z.object({ ok: z.literal(true), result: z.unknown() }),
+ z.object({ ok: z.literal(false), error: z.string().max(2000), code: z.preprocess((code) => (KNOWN_CODES.includes(code) ? code : undefined), z.enum(PHONE_JOB_CODES).optional()) }),
+]);
+
+/** One job as GET /api/phones/self/jobs hands it to the phone. */
+export type PhoneJobDelivery = { id: string; tool: string; arguments: Record<string, unknown>; expiresAt: number };
diff --git a/packages/phone-protocol/src/phone-secret-envelope.ts b/packages/phone-protocol/src/phone-secret-envelope.ts
new file mode 100644
index 0000000000..37ac17c7e5
--- /dev/null
+++ b/packages/phone-protocol/src/phone-secret-envelope.ts
@@ -0,0 +1,19 @@
+// The credential a paired phone seals for one secure credential card, sent as
+// POST /api/bots/<bot>/secret-cards/<message>/provide. The value inside is HPKE-sealed to this server's key; the
+// server refuses any other version.
+import { z } from "zod";
+
+export const PHONE_SECRET_PROTOCOL_VERSION = 1 as const;
+export const PHONE_SECRET_INFO = "OpenMausBot phone credential v1";
+export const PHONE_SECRET_MAX_BYTES = 4_096;
+
+export const phoneSecretEnvelopeSchema = z.object({
+ version: z.literal(PHONE_SECRET_PROTOCOL_VERSION),
+ threadId: z.string().regex(/^[\w-]{1,128}$/),
+ keyId: z.string().regex(/^[A-Za-z0-9_-]{22}$/),
+ deviceId: z.string().regex(/^[\w-]{1,128}$/),
+ target: z.string().regex(/^[A-Za-z][A-Za-z0-9]{0,63}$/),
+ requestKey: z.string().regex(/^[\w-]{1,128}$/),
+ encapsulatedKey: z.string().regex(/^[A-Za-z0-9_-]{87}$/),
+ ciphertext: z.string().regex(/^[A-Za-z0-9_-]{23,5483}$/),
+}).strict();
diff --git a/packages/phone-protocol/src/plain-time-zone.ts b/packages/phone-protocol/src/plain-time-zone.ts
new file mode 100644
index 0000000000..ffabea839f
--- /dev/null
+++ b/packages/phone-protocol/src/plain-time-zone.ts
@@ -0,0 +1,39 @@
+/** Zones whose generic name reads oddly in a sentence ("United Kingdom Time"), said the way people say them. */
+const SAID: Record<string, string> = {
+ "Europe/London": "UK time", "Europe/Belfast": "UK time", "America/Phoenix": "Arizona time", "Asia/Dubai": "UAE time",
+};
+const UNIVERSAL = /^(?:Etc\/)?(?:UTC|UCT|GMT|Universal|Zulu|Greenwich)(?:[+-]0)?$/i;
+const ABBREVIATION = /^(?:[A-Z]{1,5}|GMT.*|UTC.*)$/;
+
+function zoneName(zone: string, locale: string, style: "shortGeneric" | "longGeneric"): string | null {
+ try {
+ const name = new Intl.DateTimeFormat(locale, { timeZone: zone, timeZoneName: style })
+ .formatToParts(new Date()).find((part) => part.type === "timeZoneName")?.value;
+ return name && !ABBREVIATION.test(name) ? name : null;
+ } catch {
+ return null;
+ }
+}
+
+/** A time zone as a person says it: "India time", "Pacific time", "Germany time", "UTC". Never the IANA id
+ * ("Asia/Calcutta"), an abbreviation ("PT") or an offset ("GMT+5:30"). */
+export function plainTimeZone(zone: string, locale = "en"): string {
+ const english = locale.toLowerCase().startsWith("en");
+ if (UNIVERSAL.test(zone.trim())) return "UTC";
+ if (english && SAID[zone]) return SAID[zone]!;
+ const name = zoneName(zone, locale, "shortGeneric") ?? zoneName(zone, locale, "longGeneric");
+ if (name) return english ? name.replace(/ Time$/, " time") : name;
+ const city = zone.split("/").at(-1)?.replaceAll("_", " ").trim();
+ return city ? `${city} time` : zone;
+}
+
+/** "09:00" as people write it: "9:00". */
+export const plainClock = (time: string) => time.replace(/^0(\d):/, "$1:");
+
+const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
+
+/** Local weekdays (Sunday = 0) as people say them: "every day", "weekdays", "Monday, Wednesday". */
+export function plainWeekdays(weekdays: readonly number[]): string {
+ const days = [...weekdays].sort((a, b) => a - b).join(",");
+ return days === "0,1,2,3,4,5,6" ? "every day" : days === "1,2,3,4,5" ? "weekdays" : weekdays.map((day) => WEEKDAYS[day]).join(", ");
+}
diff --git a/scripts/sync-phone-protocol.test.mjs b/scripts/sync-phone-protocol.test.mjs
index 17939e1c29..8116939d2b 100644
--- a/scripts/sync-phone-protocol.test.mjs
+++ b/scripts/sync-phone-protocol.test.mjs
@@ -47,6 +47,7 @@ describe("sync-phone-protocol", () => {
for (const name of [
"wire", "responses", "pairing-code", "app-rpc", "cursor-face-data", "failed-turn", "mention-boundary", "upload-limits",
"markdown-plain-paths", "bot-limit", "codex-usage-limit", "cloud-hints", "waits",
+ "phone-jobs", "phone-secret-envelope", "live-call", "cron-label", "plain-time-zone",
]) {
expect(sources).toContain(`packages/phone-protocol/src/${name}.ts`);
}
diff --git a/server/host/secret-cards.ts b/server/host/secret-cards.ts
index 69791695ec..bd7248c278 100644
--- a/server/host/secret-cards.ts
+++ b/server/host/secret-cards.ts
@@ -4,7 +4,6 @@ import { userError } from "../user-errors.ts";
import { randomUUID } from "node:crypto";
import { readdirSync } from "node:fs";
import { join } from "node:path";
-import { z } from "zod";
import {
CREDENTIAL_TARGETS,
@@ -28,7 +27,6 @@ import { HOSTED_PROVIDER_SETTINGS_ERROR } from "../hosted-models.ts";
import { addHeldSecretScrubber } from "../redact.ts";
import { SECRET_VALUE_MAX_BYTES, SecretVault, type SavedSecret, type SecretFileHome } from "../secret-vault.ts";
import {
- PHONE_SECRET_PROTOCOL_VERSION,
PhoneSecretError,
assertPhoneSecretRequestMatches,
phoneSecretOperationId,
@@ -44,17 +42,9 @@ import { fittingChoices } from "../vault/choices.ts";
import { linkedSecretNames } from "../vault/providers.ts";
import type { BotRecord, GroupRecord, Message, Store } from "../store.ts";
import { serverLine } from "../server-lines.ts";
+import { phoneSecretEnvelopeSchema } from "../../shared/phone-secret-envelope.ts";
-export const phoneSecretEnvelopeSchema = z.object({
- version: z.literal(PHONE_SECRET_PROTOCOL_VERSION),
- threadId: z.string().regex(/^[\w-]{1,128}$/),
- keyId: z.string().regex(/^[A-Za-z0-9_-]{22}$/),
- deviceId: z.string().regex(/^[\w-]{1,128}$/),
- target: z.string().regex(/^[A-Za-z][A-Za-z0-9]{0,63}$/),
- requestKey: z.string().regex(/^[\w-]{1,128}$/),
- encapsulatedKey: z.string().regex(/^[A-Za-z0-9_-]{87}$/),
- ciphertext: z.string().regex(/^[A-Za-z0-9_-]{23,5483}$/),
-}).strict();
+export { phoneSecretEnvelopeSchema };
export interface SecretCardsDeps {
store: Pick<Store, "activePath" | "appendMessage" | "patchMessage" | "messagesFor" | "botByThread" | "groupByThread" | "onChange">;
diff --git a/server/phone-secret.ts b/server/phone-secret.ts
index 3db407af5b..b3316ebfdd 100644
--- a/server/phone-secret.ts
+++ b/server/phone-secret.ts
@@ -3,9 +3,9 @@ import { createECDH, createHash, type webcrypto } from "node:crypto";
import { isCredentialTargetId, isProviderCredentialTarget } from "../shared/credential-request.ts";
import type { CipherSuite } from "@hpke/core";
-export const PHONE_SECRET_PROTOCOL_VERSION = 1 as const;
-export const PHONE_SECRET_INFO = "OpenMausBot phone credential v1";
-export const PHONE_SECRET_MAX_BYTES = 4_096;
+import { PHONE_SECRET_INFO, PHONE_SECRET_MAX_BYTES, PHONE_SECRET_PROTOCOL_VERSION } from "../shared/phone-secret-envelope.ts";
+
+export { PHONE_SECRET_INFO, PHONE_SECRET_MAX_BYTES, PHONE_SECRET_PROTOCOL_VERSION };
const BASE64URL = /^[A-Za-z0-9_-]+$/;
const ROUTE_ID = /^[\w-]{1,128}$/;
diff --git a/server/phones/jobs.ts b/server/phones/jobs.ts
index 122a5e05b9..e29ae282c9 100644
--- a/server/phones/jobs.ts
+++ b/server/phones/jobs.ts
@@ -1,18 +1,9 @@
import { randomUUID } from "node:crypto";
-import { z } from "zod";
import { isPhoneWrite } from "../../shared/phone-apps.ts";
+import type { PhoneJobDelivery, PhoneJobOutcome } from "../../shared/phone-jobs.ts";
-export const PHONE_JOB_CODES = ["denied", "foreground_required", "not_found", "too_large", "unsupported", "offline", "timeout", "turn_ended"] as const;
-export type PhoneJobCode = (typeof PHONE_JOB_CODES)[number];
-export type PhoneJobOutcome = { ok: true; result: unknown } | { ok: false; error: string; code?: PhoneJobCode };
-const KNOWN_CODES: readonly unknown[] = PHONE_JOB_CODES;
-/** A newer phone's extra field is stripped, and a code this server does not know yet reads as none: the error still
- * reaches the bot. */
-export const phoneJobOutcome = z.union([
- z.object({ ok: z.literal(true), result: z.unknown() }),
- z.object({ ok: z.literal(false), error: z.string().max(2000), code: z.preprocess((code) => (KNOWN_CODES.includes(code) ? code : undefined), z.enum(PHONE_JOB_CODES).optional()) }),
-]);
+export { PHONE_JOB_CODES, phoneJobOutcome, type PhoneJobCode, type PhoneJobDelivery, type PhoneJobOutcome } from "../../shared/phone-jobs.ts";
export const PHONE_JOB_TIMEOUT_MS = 45_000;
export const PHONE_SEND_TIMEOUT_MS = 120_000;
@@ -24,7 +15,6 @@ export const PHONE_RECONNECT_WAIT_MS = 15_000;
const RESTARTING = "This server is restarting. Phone jobs resume by themselves once it is back.";
export type PhoneJobOptions = { active: () => boolean; timeoutMs: number; offlineText: string; online: () => boolean; background?: boolean };
-export type PhoneJobDelivery = { id: string; tool: string; arguments: Record<string, unknown>; expiresAt: number };
type Job = {
id: string; tool: string; args: Record<string, unknown>; active: () => boolean; background: boolean; seq: number; expiresAt: number;
diff --git a/server/phones/registry.ts b/server/phones/registry.ts
index 9ae30d0806..f8ce3ba9a9 100644
--- a/server/phones/registry.ts
+++ b/server/phones/registry.ts
@@ -1,26 +1,10 @@
import { existsSync, readFileSync } from "node:fs";
import { z } from "zod";
-import { PHONE_CAPABILITIES, PHONE_PLATFORMS } from "../../shared/phone-apps.ts";
+import { phoneRegistration, type PhoneRegistration } from "../../shared/phone-jobs.ts";
import { writeFileAtomic } from "../atomic.ts";
-const KNOWN_CAPABILITIES: readonly string[] = PHONE_CAPABILITIES;
-/** Only the apps this server knows: a newer phone's extra app is dropped, never a reason to refuse the rest. */
-const knownCapabilities = (value: unknown) => (value && typeof value === "object" && !Array.isArray(value)
- ? Object.fromEntries(Object.entries(value).filter(([capability]) => KNOWN_CAPABILITIES.includes(capability)))
- : value);
-
-/** The phones ship on their own schedule, so a field this server does not know yet is stripped, not refused. */
-export const phoneRegistration = z.object({
- installId: z.string().regex(/^[\w-]{8,64}$/),
- name: z.string().min(1).max(120),
- platform: z.enum(PHONE_PLATFORMS),
- appVersion: z.string().max(40),
- timeZone: z.string().max(64),
- /** Capability → the OS grant the phone holds ("full", "limited", "when_in_use", "send", "listener"); present means allowed. */
- capabilities: z.preprocess(knownCapabilities, z.partialRecord(z.enum(PHONE_CAPABILITIES), z.string().min(1).max(32))),
-});
-export type PhoneRegistration = z.infer<typeof phoneRegistration>;
+export { phoneRegistration, type PhoneRegistration };
const KEY = z.string().min(1).max(300);
const recordSchema = z.object({
diff --git a/shared/cron-label.ts b/shared/cron-label.ts
index 79561c9db1..80bc3d502d 100644
--- a/shared/cron-label.ts
+++ b/shared/cron-label.ts
@@ -1,55 +1 @@
-import { plainTimeZone } from "./plain-time-zone.ts";
-import type { RoutineCronSchedule } from "./routine-schedule.ts";
-
-const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
-const MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
-const ORDERS = { 1: "first", 2: "second", 3: "third", 4: "fourth", 5: "fifth", last: "last" } as const;
-
-/** A familiar cron preset: `weekday` 0 (Sunday) to 6, `month` 0 (January) to 11, `time` "HH:MM". */
-export type CronPreset =
- | { kind: "everyDay" | "monthlyLastDay" | "weekdays"; time: string }
- | { kind: "monthlyDay"; day: number; time: string }
- | { kind: "yearly"; month: number; day: number; time: string }
- | { kind: "weekly"; weekday: number; time: string }
- | { kind: "monthlyNth"; nth: keyof typeof ORDERS; weekday: number; time: string };
-
-export function cronPreset(expression: string): CronPreset | null {
- const [minute, hour, day, month, weekday] = expression.trim().split(/\s+/);
- if (!/^\d+$/.test(minute ?? "") || !/^\d+$/.test(hour ?? "")) return null;
- const time = `${hour!.padStart(2, "0")}:${minute!.padStart(2, "0")}`;
- const monthDay = /^\d+$/.test(day ?? "") ? Number(day) : null;
- if (weekday === "*" && month === "*") {
- if (day === "*") return { kind: "everyDay", time };
- if (day === "L") return { kind: "monthlyLastDay", time };
- return monthDay === null ? null : { kind: "monthlyDay", day: monthDay, time };
- }
- if (weekday === "*" && /^\d+$/.test(month ?? "") && monthDay !== null) {
- return MONTHS[Number(month) - 1] ? { kind: "yearly", month: Number(month) - 1, day: monthDay, time } : null;
- }
- if (day !== "*" || month !== "*") return null;
- if (weekday === "1-5" || weekday?.toUpperCase() === "MON-FRI") return { kind: "weekdays", time };
- if (/^[0-7]$/.test(weekday ?? "")) return { kind: "weekly", weekday: Number(weekday) % 7, time };
- const nth = /^([0-7])#([1-5]|L)$/i.exec(weekday ?? "");
- if (!nth) return null;
- return { kind: "monthlyNth", nth: nth[2]!.toUpperCase() === "L" ? "last" : (Number(nth[2]) as 1 | 2 | 3 | 4 | 5), weekday: Number(nth[1]) % 7, time };
-}
-
-function englishPreset(preset: CronPreset): string {
- const time = preset.time.replace(/^0(?=\d:)/, "");
- switch (preset.kind) {
- case "everyDay": return `Every day at ${time}`;
- case "monthlyLastDay": return `Monthly on the last day at ${time}`;
- case "monthlyDay": return `Monthly on day ${preset.day} at ${time}`;
- case "yearly": return `Yearly on ${MONTHS[preset.month]} ${preset.day} at ${time}`;
- case "weekdays": return `Every weekday at ${time}`;
- case "weekly": return `Weekly on ${WEEKDAYS[preset.weekday]} at ${time}`;
- case "monthlyNth": return `Monthly on the ${ORDERS[preset.nth]} ${WEEKDAYS[preset.weekday]} at ${time}`;
- }
-}
-
-/** Describe familiar presets; retain the exact expression for everything else.
- * This is presentation only, never a second parser or source of scheduling truth. */
-export function cronScheduleLabel(schedule: RoutineCronSchedule): string {
- const preset = cronPreset(schedule.expression);
- return `${preset ? englishPreset(preset) : `Cron ${schedule.expression}`} ${plainTimeZone(schedule.timeZone)}`;
-}
+export * from "../packages/phone-protocol/src/cron-label.ts";
diff --git a/shared/live-call.ts b/shared/live-call.ts
index 0b0e054894..7e092562f3 100644
--- a/shared/live-call.ts
+++ b/shared/live-call.ts
@@ -1,84 +1,6 @@
-// Pure pieces of a Live (GPT-Live) call. With client delegation GPT-Live says
-// *that* it wants help, never *what*: `session.delegation.created` carries an id
-// and a timeline offset, so the request is rebuilt from the input transcript.
+import { FULL_ANSWER_IN_CHAT } from "../packages/phone-protocol/src/live-call.ts";
-export interface TranscriptSegment {
- text: string;
- startMs: number;
- endMs: number;
-}
-
-/** Collects `session.input_transcript.delta` fragments on the session
- * timeline. Fragments are appended in delivery order, as the API asks. */
-export class LiveTranscript {
- private input: TranscriptSegment[] = [];
- /** when the voice itself was speaking, on the same timeline */
- private output: Array<{ startMs: number; endMs: number }> = [];
- private cutoffMs = -1;
-
- addInput(text: string, startMs: number, endMs: number): void {
- if (!text) return;
- this.input.push({ text, startMs: Number.isFinite(startMs) ? startMs : 0, endMs: Number.isFinite(endMs) ? endMs : 0 });
- // keep memory bounded on long calls: only the unconsumed tail matters
- if (this.input.length > 2_000) this.input = this.input.filter((segment) => segment.startMs > this.cutoffMs);
- }
-
- /** A stretch of the voice's own speech (a `session.output_transcript.delta`
- * with its timing). Input heard during it may be the voice itself, picked
- * up again by the microphone of a phone on speaker. Deltas without timing
- * are ignored. */
- addOutput(startMs: number, endMs: number): void {
- if (!Number.isFinite(startMs) || !Number.isFinite(endMs) || endMs < startMs) return;
- const last = this.output.at(-1);
- if (last && startMs <= last.endMs) last.endMs = Math.max(last.endMs, endMs);
- else this.output.push({ startMs, endMs });
- if (this.output.length > 500) this.output.splice(0, this.output.length - 500);
- }
-
- /** The words spoken since the previous request, up to a little past the
- * delegation point (transcription can trail the delegation event, and the
- * person may finish the sentence that triggered it). Consumes them, so the
- * next request starts after this one. */
- takeRequest(offsetMs: number, graceMs = 1_500): string {
- return this.takeRequestParts(offsetMs, graceMs).text;
- }
-
- /** takeRequest, plus the same words without those heard while the voice
- * spoke (`withoutEcho`), for reading a spoken yes/no. Consumes all of them. */
- takeRequestParts(offsetMs: number, graceMs = 1_500): { text: string; withoutEcho: string } {
- const until = offsetMs + graceMs;
- const taken = this.input.filter((segment) => segment.startMs > this.cutoffMs && segment.startMs <= until);
- if (!taken.length) return { text: "", withoutEcho: "" };
- this.cutoffMs = Math.max(this.cutoffMs, ...taken.map((segment) => segment.startMs));
- return {
- text: joinFragments(taken.map((segment) => segment.text)),
- withoutEcho: joinFragments(taken.filter((segment) => !this.echoed(segment)).map((segment) => segment.text)),
- };
- }
-
- /** Everything heard since the last taken request, without consuming it —
- * used to read a spoken yes/no while a permission question is open.
- * `skipEcho` leaves out what was heard while the voice itself spoke. */
- pending(options: { skipEcho?: boolean } = {}): string {
- return joinFragments(this.input
- .filter((segment) => segment.startMs > this.cutoffMs && !(options.skipEcho && this.echoed(segment)))
- .map((segment) => segment.text));
- }
-
- private echoed(segment: TranscriptSegment): boolean {
- return this.output.some((span) => segment.startMs < span.endMs && segment.endMs > span.startMs);
- }
-
- /** Mark everything heard so far as handled (e.g. after a spoken decision). */
- consumeAll(): void {
- for (const segment of this.input) this.cutoffMs = Math.max(this.cutoffMs, segment.startMs);
- }
-}
-
-/** Transcript deltas are fragments of words, not words: glue them as sent. */
-export function joinFragments(fragments: string[]): string {
- return fragments.join("").replace(/\s+/g, " ").trim();
-}
+export * from "../packages/phone-protocol/src/live-call.ts";
/** GPT-Live caps each append at 500 tokens. A 500 UTF-8 byte budget is
* conservative even for emoji/CJK, unlike a prose-only character estimate.
@@ -92,7 +14,6 @@ function bytePrefix(text: string, budget: number): string {
return new TextDecoder().decode(encoder.encode(text).subarray(0, budget), { stream: true });
}
const MAX_SPOKEN_CHUNKS = 3;
-export const FULL_ANSWER_IN_CHAT = "The full answer is in the chat.";
/** Group speakable utterances (from /api/tts/prepare) into appends. Long
* answers are cut at a sentence boundary with a pointer to the chat, because
@@ -149,68 +70,3 @@ export function clampAppend(content: string): string {
const text = content.replace(/\s+/g, " ").trim();
return bytes(text) <= APPEND_BYTE_LIMIT ? text : `${bytePrefix(text, APPEND_BYTE_LIMIT - bytes("…")).replace(/\s+\S*$/, "")}…`;
}
-
-/** GPT-Live voices from OpenAI's documentation (Managing GPT-Live sessions,
- * "Voice options", and the SDK's BuiltInVoice list), with the regional
- * notes the docs give for the additional ones. */
-export const LIVE_VOICE_OPTIONS: ReadonlyArray<{ id: string; label: string }> = [
- { id: "marin", label: "Marin (default)" },
- { id: "cedar", label: "Cedar" },
- { id: "alloy", label: "Alloy" },
- { id: "ash", label: "Ash" },
- { id: "ballad", label: "Ballad" },
- { id: "coral", label: "Coral" },
- { id: "echo", label: "Echo" },
- { id: "sage", label: "Sage" },
- { id: "shimmer", label: "Shimmer" },
- { id: "verse", label: "Verse" },
- { id: "gleam", label: "Gleam — North American, feminine" },
- { id: "meridian", label: "Meridian — North American, masculine" },
- { id: "quartz", label: "Quartz — Australian, feminine" },
- { id: "ripple", label: "Ripple — Australian, masculine" },
- { id: "vesper", label: "Vesper — British, masculine" },
- { id: "willow", label: "Willow — Irish, feminine" },
- { id: "stone", label: "Stone — Irish, masculine" },
- { id: "delta", label: "Delta — Southern U.S., feminine" },
- { id: "cinder", label: "Cinder — Southern U.S., masculine" },
- { id: "beacon", label: "Beacon — Filipino, masculine" },
- { id: "bossa", label: "Bossa — Brazilian Portuguese, feminine" },
- { id: "tempo", label: "Tempo — Brazilian Portuguese, masculine" },
-];
-
-/** Gemini Live's prebuilt voices (Gemini API docs, "Live API capabilities", voices), with the docs' one-word character.
- * Gemini names them with a capital letter. */
-export const GEMINI_LIVE_VOICE_OPTIONS: ReadonlyArray<{ id: string; label: string }> = [
- { id: "Puck", label: "Puck — upbeat (default)" },
- { id: "Charon", label: "Charon — informative" },
- { id: "Kore", label: "Kore — firm" },
- { id: "Fenrir", label: "Fenrir — excitable" },
- { id: "Aoede", label: "Aoede — breezy" },
- { id: "Leda", label: "Leda — youthful" },
- { id: "Orus", label: "Orus — firm" },
- { id: "Zephyr", label: "Zephyr — bright" },
-];
-
-export const GEMINI_LIVE_DEFAULT_VOICE = "Puck";
-
-/** A saved Gemini voice when it is one of Gemini's, else the default. */
-export function geminiLiveVoice(voice: string | undefined): string {
- return GEMINI_LIVE_VOICE_OPTIONS.find((option) => option.id === voice?.trim())?.id ?? GEMINI_LIVE_DEFAULT_VOICE;
-}
-
-/** A call's length as a clock: m:ss under an hour ("0:07", "1:42"),
- * h:mm:ss from an hour on ("1:02:05"). Whole seconds; a value that is not a
- * length reads as 0:00. */
-export function formatCallDuration(seconds: number): string {
- const total = Number.isFinite(seconds) && seconds > 0 ? Math.floor(seconds) : 0;
- const hours = Math.floor(total / 3_600);
- const minutes = Math.floor((total % 3_600) / 60);
- const rest = String(total % 60).padStart(2, "0");
- return hours > 0 ? `${hours}:${String(minutes).padStart(2, "0")}:${rest}` : `${minutes}:${rest}`;
-}
-
-/** A Live call row's text: what a client that does not know kind "call"
- * shows as a plain line ("Call with Ada · 1:42"). */
-export function liveCallRowText(botName: string, seconds: number): string {
- return `Call with ${botName} · ${formatCallDuration(seconds)}`;
-}
diff --git a/shared/phone-jobs.ts b/shared/phone-jobs.ts
new file mode 100644
index 0000000000..52ed8ea7a4
--- /dev/null
+++ b/shared/phone-jobs.ts
@@ -0,0 +1 @@
+export * from "../packages/phone-protocol/src/phone-jobs.ts";
diff --git a/shared/phone-secret-envelope.ts b/shared/phone-secret-envelope.ts
new file mode 100644
index 0000000000..d37a47ef28
--- /dev/null
+++ b/shared/phone-secret-envelope.ts
@@ -0,0 +1 @@
+export * from "../packages/phone-protocol/src/phone-secret-envelope.ts";
diff --git a/shared/plain-time-zone.ts b/shared/plain-time-zone.ts
index ffabea839f..f556b3d115 100644
--- a/shared/plain-time-zone.ts
+++ b/shared/plain-time-zone.ts
@@ -1,39 +1 @@
-/** Zones whose generic name reads oddly in a sentence ("United Kingdom Time"), said the way people say them. */
-const SAID: Record<string, string> = {
- "Europe/London": "UK time", "Europe/Belfast": "UK time", "America/Phoenix": "Arizona time", "Asia/Dubai": "UAE time",
-};
-const UNIVERSAL = /^(?:Etc\/)?(?:UTC|UCT|GMT|Universal|Zulu|Greenwich)(?:[+-]0)?$/i;
-const ABBREVIATION = /^(?:[A-Z]{1,5}|GMT.*|UTC.*)$/;
-
-function zoneName(zone: string, locale: string, style: "shortGeneric" | "longGeneric"): string | null {
- try {
- const name = new Intl.DateTimeFormat(locale, { timeZone: zone, timeZoneName: style })
- .formatToParts(new Date()).find((part) => part.type === "timeZoneName")?.value;
- return name && !ABBREVIATION.test(name) ? name : null;
- } catch {
- return null;
- }
-}
-
-/** A time zone as a person says it: "India time", "Pacific time", "Germany time", "UTC". Never the IANA id
- * ("Asia/Calcutta"), an abbreviation ("PT") or an offset ("GMT+5:30"). */
-export function plainTimeZone(zone: string, locale = "en"): string {
- const english = locale.toLowerCase().startsWith("en");
- if (UNIVERSAL.test(zone.trim())) return "UTC";
- if (english && SAID[zone]) return SAID[zone]!;
- const name = zoneName(zone, locale, "shortGeneric") ?? zoneName(zone, locale, "longGeneric");
- if (name) return english ? name.replace(/ Time$/, " time") : name;
- const city = zone.split("/").at(-1)?.replaceAll("_", " ").trim();
- return city ? `${city} time` : zone;
-}
-
-/** "09:00" as people write it: "9:00". */
-export const plainClock = (time: string) => time.replace(/^0(\d):/, "$1:");
-
-const WEEKDAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
-
-/** Local weekdays (Sunday = 0) as people say them: "every day", "weekdays", "Monday, Wednesday". */
-export function plainWeekdays(weekdays: readonly number[]): string {
- const days = [...weekdays].sort((a, b) => a - b).join(",");
- return days === "0,1,2,3,4,5,6" ? "every day" : days === "1,2,3,4,5" ? "weekdays" : weekdays.map((day) => WEEKDAYS[day]).join(", ");
-}
+export * from "../packages/phone-protocol/src/plain-time-zone.ts";
diff --git a/src/locales/server-lines.test.ts b/src/locales/server-lines.test.ts
index b7de530a93..11797f351a 100644
--- a/src/locales/server-lines.test.ts
+++ b/src/locales/server-lines.test.ts
@@ -391,7 +391,7 @@ const PENDING: Readonly<Record<string, ReadonlyArray<readonly [file: string, sni
["server/routine-requests.ts", "Runs only on its schedule"],
["server/webhook-requests.ts", "When another app sends something … , … …"],
["server/webhook-requests.ts", "does what it is asked"],
- ["shared/plain-time-zone.ts", "every day"],
+ ["packages/phone-protocol/src/plain-time-zone.ts", "every day"],
],
"rooms and teammates": [
["server/host/delegated-level.ts", "… — handed on by … , … a Chief of Staff on …"],
@@ -511,7 +511,7 @@ const PENDING: Readonly<Record<string, ReadonlyArray<readonly [file: string, sni
"moves to the Cloud": [
],
"calls": [
- ["shared/live-call.ts", "Call with … · …"],
+ ["packages/phone-protocol/src/live-call.ts", "Call with … · …"],
],
};