From e750c4002bdad223444ab8cf29439466eed084df Mon Sep 17 00:00:00 2001 From: Ryan Cartwright Date: Thu, 5 Nov 2026 11:06:56 +1100 Subject: [PATCH 1/2] refactor(avatars): export the numbers faces move by, and the moods each screen uses, so the native apps can generate them --- packages/avatars/package.json | 2 + packages/avatars/src/eyes.tsx | 36 +++-- packages/avatars/src/face-marks.ts | 31 ++++ packages/avatars/src/face-rig.ts | 207 +++++++++++++++++--------- packages/avatars/src/group-pacing.ts | 24 +++ packages/avatars/src/hop.ts | 94 ++++++++---- packages/avatars/src/index.ts | 1 + packages/avatars/src/layer-motion.ts | 70 +++++---- packages/avatars/src/lively-group.tsx | 26 +--- packages/avatars/src/mood-loop.ts | 8 +- packages/avatars/src/moods.ts | 60 ++++++-- packages/avatars/src/random.ts | 4 +- packages/avatars/src/screen-moods.ts | 26 ++++ packages/avatars/src/watching.ts | 4 +- packages/web/src/shell/Agent.tsx | 12 +- packages/web/src/shell/NewAgent.tsx | 12 +- 16 files changed, 400 insertions(+), 217 deletions(-) create mode 100644 packages/avatars/src/group-pacing.ts create mode 100644 packages/avatars/src/screen-moods.ts diff --git a/packages/avatars/package.json b/packages/avatars/package.json index 54015c0dd..e4438d22c 100644 --- a/packages/avatars/package.json +++ b/packages/avatars/package.json @@ -7,6 +7,8 @@ "exports": { ".": "./src/index.ts", "./bot-colors": "./src/bot-colors.ts", + "./hop": "./src/hop.ts", + "./layer-motion": "./src/layer-motion.ts", "./bot-crowd.svg": "./assets/bot-crowd.svg", "./sugabots-logo.svg": "./assets/sugabots-logo.svg", "./app-icons/*": "./assets/app-icons/*" diff --git a/packages/avatars/src/eyes.tsx b/packages/avatars/src/eyes.tsx index cf1b5d43e..96a551f8d 100644 --- a/packages/avatars/src/eyes.tsx +++ b/packages/avatars/src/eyes.tsx @@ -4,9 +4,17 @@ import type { RefObject } from "react"; import { Mark, markKey } from "./face-drawing.tsx"; import { ARC_EYE_STROKE_WIDTH, + ARC_SHUT_RISE, type FaceMark, + FLATTEST_ARC_HEIGHT, faceMarks, + OPEN_EYE_FADES, + SMILE_ARC_BASELINE_SHARE, + SMILE_ARC_SHOWS, + SMILE_ARC_WIDENING, THINKING_DOT_RADIUS, + THINKING_DOT_XS, + THINKING_DOT_Y, viewboxPercentage, } from "./face-marks.ts"; import type { FaceDrawing } from "./face-rig.ts"; @@ -75,7 +83,7 @@ function OpenEye({ const scaleY = useTransform(height, (shown) => Math.max(shown, ARC_EYE_STROKE_WIDTH / drawnHeight), ); - const opacity = useTransform(smile, [0, 0.5], [1, 0]); + const opacity = useTransform(smile, [...OPEN_EYE_FADES], [1, 0]); return ( @@ -97,7 +105,7 @@ function SmileArc({ color: string; smile: MotionValue; }) { - const opacity = useTransform(smile, [0, 0.3], [0, 1]); + const opacity = useTransform(smile, [...SMILE_ARC_SHOWS], [0, 1]); return ( - `a${width} ${Math.max(Number(height) * (1 - flat), 0.01)}`, + `a${width} ${Math.max(Number(height) * (1 - flat), FLATTEST_ARC_HEIGHT)}`, ); } -/* - * A thinking bot's three dots, across where its eyes were, on the 40-unit - * face the eyes are drawn for. They're HTML, not SVG, so the browser can raise - * them on the GPU (see face-rig.ts). +/** + * The thinking dots, grown in as the mood turns to thinking; the middle one + * grows last. They're HTML, not SVG, so the browser can raise them on the GPU + * (see face-rig.ts). */ -const THINKING_DOT_XS = [14, 20, 26] as const; -const THINKING_DOT_Y = 20; - -/** The thinking dots, grown in as the mood turns to thinking; the middle one grows last. */ export function ThinkingDots({ color, drawing }: { color: string; drawing: FaceDrawing }) { const [left, middle, right] = drawing.layers.dots; return ( diff --git a/packages/avatars/src/face-marks.ts b/packages/avatars/src/face-marks.ts index 043154c11..f5745591a 100644 --- a/packages/avatars/src/face-marks.ts +++ b/packages/avatars/src/face-marks.ts @@ -14,6 +14,37 @@ export const THINKING_DOT_RADIUS = 2.4; /** How thick an arc eye's line is; a shut or smiling eye is drawn as thick. */ export const ARC_EYE_STROKE_WIDTH = 1.8; +/** + * How far an arc eye rises as it shuts: its arcs stand on a line about two + * units below where open eyes are centred. + */ +export const ARC_SHUT_RISE = 2; + +/** The flattest an arc eye's arc is drawn, so it never becomes a straight line its path can't bend. */ +export const FLATTEST_ARC_HEIGHT = 0.01; + +/** + * The smile arc an open eye closes into is the top half of a ring + * `SMILE_ARC_WIDENING` wider on each side than the eye, standing + * `SMILE_ARC_BASELINE_SHARE` of its radius below the eye's centre. + */ +export const SMILE_ARC_WIDENING = 0.6; +export const SMILE_ARC_BASELINE_SHARE = 0.4; + +/** + * As the bot's smile grows from 0 to 1, an open eye fades out over + * `OPEN_EYE_FADES` of it, and the smile arc fades in over `SMILE_ARC_SHOWS`. + */ +export const OPEN_EYE_FADES = [0, 0.5] as const; +export const SMILE_ARC_SHOWS = [0, 0.3] as const; + +/* + * A thinking bot's three dots, across where its eyes were: their centres' + * x, left to right, and their y. + */ +export const THINKING_DOT_XS = [14, 20, 26] as const; +export const THINKING_DOT_Y = 20; + /** One mark drawn on the face disc: an eye, or both eyes as one stroked path. */ export type FaceMark = | { shape: "circle"; cx: number; cy: number; r: number } diff --git a/packages/avatars/src/face-rig.ts b/packages/avatars/src/face-rig.ts index 903f42b83..52919a4f6 100644 --- a/packages/avatars/src/face-rig.ts +++ b/packages/avatars/src/face-rig.ts @@ -9,7 +9,13 @@ import { import { createRef, type RefObject, useEffect, useRef, useState } from "react"; import { THINKING_DOT_RADIUS, viewboxPercentage } from "./face-marks.ts"; import { HOP_SECONDS, hopPaths } from "./hop.ts"; -import { LayerMotion, type LayerName, layerKinds } from "./layer-motion.ts"; +import { + type KeyframesPath, + LayerMotion, + type LayerName, + layerKinds, + type Values, +} from "./layer-motion.ts"; /* * Why the face is built from HTML layers: Chrome can't hand a transform on an @@ -93,37 +99,65 @@ export interface FaceDrawing { * as depth. */ /** How far the eyes slide sideways, and up or down, looking all the way. */ -const EYE_TRAVEL_X = 5; -const EYE_TRAVEL_Y = 3; +export const EYE_TRAVEL_X = 5; +export const EYE_TRAVEL_Y = 3; /** How far the eyes dip as they near the side, so they follow the head's curve rather than a straight line. */ -const EYE_EDGE_DIP = 0.8; +export const EYE_EDGE_DIP = 0.8; /** How much narrower the eyes get looking all the way to one side, as if turned away on a ball. */ -const EYE_FORESHORTENING = 0.18; -const HEAD_TRAVEL_X = 1.2; -const HEAD_TRAVEL_Y = 0.6; -const HEAD_TILT_DEGREES = 4; +export const EYE_FORESHORTENING = 0.18; +export const HEAD_TRAVEL_X = 1.2; +export const HEAD_TRAVEL_Y = 0.6; +export const HEAD_TILT_DEGREES = 4; /** Eyes jump to what they look at almost at once; they never drift. */ -const EYES_SPRING = { stiffness: 1000, damping: 60 }; +export const EYES_SPRING = { stiffness: 1000, damping: 60 } as const; /** The head follows the eyes late, and overshoots a little before it settles. */ -const HEAD_SPRING = { stiffness: 140, damping: 13 }; +export const HEAD_SPRING = { stiffness: 140, damping: 13 } as const; /** How a mood settles in when it changes: gently, without overshoot. */ -const MOOD_SPRING = { stiffness: 120, damping: 20 }; +export const MOOD_SPRING = { stiffness: 120, damping: 20 } as const; /** * The same, for the eyes' shapes, which ease in script: they stop once within * `restDelta` of where they're going and slower than `restSpeed`, far below * what shows even on a large face. */ -const EYE_SHAPE_MOOD_SPRING = { ...MOOD_SPRING, restDelta: 0.01, restSpeed: 0.02 }; +export const EYE_SHAPE_MOOD_SPRING = { ...MOOD_SPRING, restDelta: 0.01, restSpeed: 0.02 } as const; + +/** + * One value's keyframes, as motion's `animate` plays them on a motion value: + * through `frames` at `times` (shares of `seconds`), eased between each pair by `ease`. + */ +export interface ValueKeyframes { + readonly frames: readonly number[]; + readonly times: readonly number[]; + readonly ease: readonly Easing[]; + readonly seconds: number; +} -/** How far a blink squeezes an eye, and its timing: quick to shut, a beat closed, slower to open. */ -const BLINK_CLOSED = 0.1; -const BLINK = { duration: 0.24, times: [0, 0.33, 0.5, 1] }; +const easeEachWay = (segments: number): Easing[] => + Array.from({ length: segments }, () => "easeInOut"); + +/** How far a blink squeezes an eye. */ +export const BLINK_CLOSED = 0.1; +/** A blink, as how open the eye is: quick to shut, a beat closed, slower to open. */ +export const BLINK: ValueKeyframes = { + frames: [1, BLINK_CLOSED, BLINK_CLOSED, 1], + times: [0, 0.33, 0.5, 1], + ease: easeEachWay(3), + seconds: 0.24, +}; +/** How long a double blink waits between its two blinks. */ +export const BLINK_TWICE_GAP_SECONDS = 0.08; /** Once the pointer and typing have rested this long, idle glances take over again. */ -const WATCHING_REST_MS = 4000; -/** How far open a sleepy bot's eyes flutter, and how long the flutter takes. */ -const FLUTTER_OPEN = 0.5; -const FLUTTER_SECONDS = 1.2; +export const WATCHING_REST_MS = 4000; +/** How far open a sleepy bot's eyes flutter. */ +export const FLUTTER_OPEN = 0.5; +/** A flutter, as how far open it holds the eyes: quickly open, slowly shut. */ +export const FLUTTER: ValueKeyframes = { + frames: [0, FLUTTER_OPEN, 0], + times: [0, 0.3, 1], + ease: ["easeOut", "easeIn"], + seconds: 1.2, +}; /** The width a face is taken to have, in CSS pixels, while it can't be measured. */ const UNMEASURED_FACE_PIXELS = 128; /** How long a face's measured size is trusted before it's measured again. */ @@ -137,17 +171,77 @@ const WIGGLE_SECONDS = 0.7; const WIGGLE_SIDES = [0, 1, 0, -1, 0]; const WIGGLE_TIMES = [0, 0.25, 0.5, 0.75, 1]; -/** How high a thinking dot rises against its own height, and its timing, like the app's typing dots. */ +/** One wiggle there and back, for a layer that leans `reach` to each side. */ +function wiggleSway(reach: number): KeyframesPath { + return { + kind: "keyframes", + frames: WIGGLE_SIDES.map((side) => [side * reach]), + times: WIGGLE_TIMES, + ease: easeEachWay(WIGGLE_SIDES.length - 1), + seconds: WIGGLE_SECONDS, + }; +} + +/** One wiggle of the head's sideways move, in percentages of the face, and of its lean, in degrees. */ +export const WIGGLE_MOVE = wiggleSway(viewboxPercentage(WIGGLE_SHIFT)); +export const WIGGLE_TILT = wiggleSway(WIGGLE_DEGREES); + +/** How high a thinking dot rises against its own height, like the app's typing dots, and how bright it is then. */ const DOT_RISE_SHARE = 2.6 / (THINKING_DOT_RADIUS * 2); -const DOT_CYCLE_SECONDS = 1.2; -const DOT_STAGGER_SECONDS = 0.15; const DOT_BRIGHTEST = 1; +/** When in each rise a dot is at its height and back down, as shares of the cycle; it rests for the rest. */ +const DOT_RISE_TIMES = [0, 0.3, 0.6, 1]; -/** How quickly a wiggle or the thinking dots ease back to rest when they stop. */ -const STILLING_SECONDS = 0.25; +/** One rise of a thinking dot, from where it rests and back. */ +export const DOT_RISE: KeyframesPath = { + kind: "keyframes", + frames: [ + layerKinds.dot.rest, + [DOT_RISE_SHARE, DOT_BRIGHTEST], + layerKinds.dot.rest, + layerKinds.dot.rest, + ], + times: DOT_RISE_TIMES, + ease: easeEachWay(DOT_RISE_TIMES.length - 1), + seconds: 1.2, +}; +/** How long each thinking dot rises after the one before. */ +export const DOT_STAGGER_SECONDS = 0.15; +/** + * How far the mood has turned to thinking when the outer dots, and then the + * middle one, start and finish growing, from 0 to 1; the middle one comes last. + */ +export const OUTER_DOTS_GROW = [0, 0.6] as const; +export const MIDDLE_DOT_GROWS = [0.4, 1] as const; -const easeEachWay = (segments: number): Easing[] => - Array.from({ length: segments }, () => "easeInOut"); +/** How a wiggle or the thinking dots ease back to rest when they stop: quickly, slowing as they arrive. */ +export const STILLING = { seconds: 0.25, ease: "easeOut" } as const; + +/** Eases from wherever a layer is to `rest`, as a wiggle or the thinking dots do when they stop. */ +function stillingTo(rest: Values): KeyframesPath { + return { + kind: "keyframes", + frames: [rest, rest], + times: [0, 1], + ease: [STILLING.ease], + seconds: STILLING.seconds, + }; +} + +/** Plays `keyframes` on `value`, `repeat` more times after the first, waiting `repeatDelay` seconds between. */ +function playKeyframes( + value: MotionValue, + { frames, times, ease, seconds }: ValueKeyframes, + { repeat = 0, repeatDelay = 0 } = {}, +): void { + animate(value, [...frames], { + duration: seconds, + times: [...times], + ease: [...ease], + repeat, + repeatDelay, + }); +} /** * A face's moving parts, held as `look` says; `controls` move it and `drawing` @@ -158,8 +252,8 @@ export function useFaceRig( look: MoodLook, face: RefObject, ): { controls: FaceControls; drawing: FaceDrawing } { - const [blink] = useState(() => motionValue(1)); - const [flutter] = useState(() => motionValue(0)); + const [blink] = useState(() => motionValue(BLINK.frames[0] ?? 1)); + const [flutter] = useState(() => motionValue(FLUTTER.frames[0] ?? 0)); const [layers] = useState(() => ({ ...(Object.fromEntries(headLayerNames.map((name) => [name, createRef()])) as Record< HeadLayerName, @@ -221,66 +315,39 @@ export function useFaceRig( return performance.now() - watchedAt.current < WATCHING_REST_MS; }, blink(twice = false) { - animate(blink, [1, BLINK_CLOSED, BLINK_CLOSED, 1], { - ...BLINK, + playKeyframes(blink, BLINK, { repeat: twice ? 1 : 0, - repeatDelay: 0.08, + repeatDelay: BLINK_TWICE_GAP_SECONDS, }); }, hop(size = 1) { landsAt.current = performance.now() + HOP_SECONDS * 1000; const paths = hopPaths(size); - motions.hopRise.play(paths.rise); - motions.hopSquash.play(paths.squash); - motions.hopEyesDrop.play(paths.eyesDrop); + motions.hopRise.play(paths.hopRise); + motions.hopSquash.play(paths.hopSquash); + motions.hopEyesDrop.play(paths.hopEyesDrop); }, isAirborne() { return performance.now() < landsAt.current; }, wiggle() { - const swing = (layer: LayerMotion, reach: number) => - layer.play( - { - kind: "keyframes", - frames: WIGGLE_SIDES.map((side) => [side * reach]), - times: WIGGLE_TIMES, - ease: easeEachWay(WIGGLE_SIDES.length - 1), - seconds: WIGGLE_SECONDS, - }, - { repeat: true }, - ); - swing(motions.wiggleMove, viewboxPercentage(WIGGLE_SHIFT)); - swing(motions.wiggleTilt, WIGGLE_DEGREES); + motions.wiggleMove.play(WIGGLE_MOVE, { repeat: true }); + motions.wiggleTilt.play(WIGGLE_TILT, { repeat: true }); return () => { easeToRest(motions.wiggleMove); easeToRest(motions.wiggleTilt); }; }, riseDots() { - const resting = layerKinds.dot.rest; - const risen = [DOT_RISE_SHARE, DOT_BRIGHTEST]; motions.dots.forEach((dot, index) => { - dot.play( - { - kind: "keyframes", - frames: [resting, risen, resting, resting], - times: [0, 0.3, 0.6, 1], - ease: easeEachWay(3), - seconds: DOT_CYCLE_SECONDS, - }, - { repeat: true, delaySeconds: index * DOT_STAGGER_SECONDS }, - ); + dot.play(DOT_RISE, { repeat: true, delaySeconds: index * DOT_STAGGER_SECONDS }); }); return () => { for (const dot of motions.dots) easeToRest(dot); }; }, flutter() { - animate(flutter, [0, FLUTTER_OPEN, 0], { - duration: FLUTTER_SECONDS, - times: [0, 0.3, 1], - ease: ["easeOut", "easeIn"], - }); + playKeyframes(flutter, FLUTTER); }, })); @@ -295,8 +362,8 @@ export function useFaceRig( eyesShrink: useTransform(dots, (shown) => 1 - shown), smile, arcsFlat, - outerDotsGrow: useTransform(dots, [0, 0.6], [0, 1]), - middleDotGrows: useTransform(dots, [0.4, 1], [0, 1]), + outerDotsGrow: useTransform(dots, [...OUTER_DOTS_GROW], [0, 1]), + middleDotGrows: useTransform(dots, [...MIDDLE_DOT_GROWS], [0, 1]), }; return { controls, drawing }; } @@ -320,13 +387,7 @@ function measuredFacePixels(face: RefObject): () => number { /** Eases a layer back to its resting pose. */ function easeToRest(layer: LayerMotion): void { - layer.play({ - kind: "keyframes", - frames: [layer.rest, layer.rest], - times: [0, 1], - ease: ["easeOut"], - seconds: STILLING_SECONDS, - }); + layer.play(stillingTo(layer.rest)); } /** A value tracking `target`, easing to each new one the way a mood settles in. */ diff --git a/packages/avatars/src/group-pacing.ts b/packages/avatars/src/group-pacing.ts new file mode 100644 index 000000000..3036a9f8d --- /dev/null +++ b/packages/avatars/src/group-pacing.ts @@ -0,0 +1,24 @@ +import type { Liveliness } from "./liveliness.ts"; +import type { Span } from "./random.ts"; + +/** How the faces in a `LivelyGroup` take turns to move. */ +export interface GroupPacing { + /** How many faces may move at once. */ + movingAtOnce: number; + /** Seconds between turns starting, and how long a turn lasts, each picked at random from its range. */ + gapSeconds: Span; + turnSeconds: Span; +} + +export const pacingByLiveliness: Record, GroupPacing> = { + sometimes: { + movingAtOnce: 1, + gapSeconds: { least: 4, most: 10 }, + turnSeconds: { least: 1, most: 3 }, + }, + often: { + movingAtOnce: 2, + gapSeconds: { least: 1.5, most: 4 }, + turnSeconds: { least: 1.5, most: 4 }, + }, +}; diff --git a/packages/avatars/src/hop.ts b/packages/avatars/src/hop.ts index 0e87d6d46..b164e6073 100644 --- a/packages/avatars/src/hop.ts +++ b/packages/avatars/src/hop.ts @@ -1,6 +1,6 @@ import type { Easing } from "motion/react"; import { viewboxPercentage } from "./face-marks.ts"; -import type { Path } from "./layer-motion.ts"; +import { type KeyframesPath, layerKinds, type Path, type Values } from "./layer-motion.ts"; /* * One hop, as keyframes at these moments (seconds): crouch, take off, top, @@ -23,37 +23,69 @@ const SQUASHING: Easing[] = HOP_TIMES.slice(1).map(() => "easeInOut"); /** How the bot springs back to rest after landing: a quick wobble. */ const SETTLE = { stiffness: 500, damping: 12 }; -/** The paths of one hop, `size` times as big as a full one, for the layers it moves. */ -export function hopPaths(size: number): { rise: Path; squash: Path[]; eyesDrop: Path[] } { - const scaled = (frames: number[], rest: number) => - frames.map((frame) => rest + (frame - rest) * size); - const keyframes = (frames: number[][], ease: Easing[]): Path => ({ - kind: "keyframes", - frames, - times: HOP_TIMES, - ease, - seconds: HOP_SECONDS, - }); - const widths = scaled(HOP.scaleX, 1); - const heights = scaled(HOP.scaleY, 1); - return { - rise: keyframes( - scaled(HOP.rise, 0).map((height) => [viewboxPercentage(height)]), +/** The layers a hop moves. */ +type HopLayer = "hopRise" | "hopSquash" | "hopEyesDrop"; + +const hopKeyframes = (frames: Values[], ease: Easing[]): KeyframesPath => ({ + kind: "keyframes", + frames, + times: HOP_TIMES, + ease, + seconds: HOP_SECONDS, +}); + +const settleTo = (layer: HopLayer): Path => ({ + kind: "spring", + to: layerKinds[layer].rest, + ...SETTLE, +}); + +/** A full hop: the paths each layer it moves plays, one after another. */ +export const FULL_HOP: Readonly> = { + hopRise: [ + hopKeyframes( + HOP.rise.map((height) => [viewboxPercentage(height)]), RISE_AND_FALL, ), - squash: [ - keyframes( - widths.map((width, index) => [width, heights[index] ?? 1]), - SQUASHING, - ), - { kind: "spring", to: [1, 1], ...SETTLE }, - ], - eyesDrop: [ - keyframes( - scaled(HOP.eyesDrop, 0).map((drop) => [viewboxPercentage(drop)]), - SQUASHING, - ), - { kind: "spring", to: [0], ...SETTLE }, - ], + ], + hopSquash: [ + hopKeyframes( + HOP.scaleX.map((width, index) => [width, HOP.scaleY[index] ?? 1]), + SQUASHING, + ), + settleTo("hopSquash"), + ], + hopEyesDrop: [ + hopKeyframes( + HOP.eyesDrop.map((drop) => [viewboxPercentage(drop)]), + SQUASHING, + ), + settleTo("hopEyesDrop"), + ], +}; + +/** + * The paths of one hop, `size` times as big as `FULL_HOP`, for the layers it + * moves: each value's distance from where its layer rests is scaled by `size`. + */ +export function hopPaths(size: number): Record { + const scaled = (layer: HopLayer) => { + const rest = layerKinds[layer].rest; + const about = (values: Values) => + values.map((value, index) => { + const resting = rest[index] ?? 0; + return resting + (value - resting) * size; + }); + return FULL_HOP[layer].map( + (path): Path => + path.kind === "spring" + ? { ...path, to: about(path.to) } + : { ...path, frames: path.frames.map(about) }, + ); + }; + return { + hopRise: scaled("hopRise"), + hopSquash: scaled("hopSquash"), + hopEyesDrop: scaled("hopEyesDrop"), }; } diff --git a/packages/avatars/src/index.ts b/packages/avatars/src/index.ts index 5f5ad315d..db7ae6391 100644 --- a/packages/avatars/src/index.ts +++ b/packages/avatars/src/index.ts @@ -21,5 +21,6 @@ export { export { LivelyGroup, useGroupTurn } from "./lively-group.tsx"; export { type MoodLoop, useMoodLoop } from "./mood-loop.ts"; export { type BotMood, botMoods } from "./moods.ts"; +export { CREATION_MOODS, WATCHING_MOODS } from "./screen-moods.ts"; export * from "./sugabots-logo.ts"; export * from "./sugabots-mark.tsx"; diff --git a/packages/avatars/src/layer-motion.ts b/packages/avatars/src/layer-motion.ts index ba39a55d4..4163a7b0f 100644 --- a/packages/avatars/src/layer-motion.ts +++ b/packages/avatars/src/layer-motion.ts @@ -21,7 +21,7 @@ import { FACE_VIEWBOX_SIZE, THINKING_DOT_RADIUS } from "./face-marks.ts"; * second, and on a small face a glance is a handful of frames. */ -type Values = readonly number[]; +export type Values = readonly number[]; /** What a layer's values draw: its transform, and for some its opacity. */ interface LayerStyle { @@ -105,28 +105,41 @@ export function restingStyle(name: LayerName): LayerStyle { } /** A way of getting from one set of values to another, over time. */ -export type Path = - /** Springs to `to`, as motion's springs do. */ - | { kind: "spring"; to: Values; stiffness: number; damping: number } - /** - * Passes through `frames` at `times` (shares of `seconds`, from 0 to 1), - * eased between each pair by `ease`; the first frame is ignored and replaced - * by wherever the layer is. - */ - | { kind: "keyframes"; frames: Values[]; times: number[]; ease: Easing[]; seconds: number }; +export type Path = SpringPath | KeyframesPath; + +/** Springs to `to`, as motion's springs do. */ +export interface SpringPath { + readonly kind: "spring"; + readonly to: Values; + readonly stiffness: number; + readonly damping: number; +} + +/** + * Passes through `frames` at `times` (shares of `seconds`, from 0 to 1), + * eased between each pair by `ease`; the first frame is ignored and replaced + * by wherever the layer is. + */ +export interface KeyframesPath { + readonly kind: "keyframes"; + readonly frames: readonly Values[]; + readonly times: readonly number[]; + readonly ease: readonly Easing[]; + readonly seconds: number; +} /** Half a device pixel: no finer move could show. */ const STEP_PIXELS = 0.5; /** The shared clock's ticks, which every change falls on: a video's frame rate. */ -const TICK_SECONDS = 1 / 30; +export const TICK_SECONDS = 1 / 30; /** How finely a spring is stepped through to find when it settles. */ -const SPRING_SETTLE_STEP_MILLISECONDS = 1000 / 120; +export const SPRING_SETTLE_STEP_MILLISECONDS = 1000 / 120; /** A spring is cut off by this long at the latest, wherever it has got to. */ -const LONGEST_SPRING_MILLISECONDS = 3000; +export const LONGEST_SPRING_MILLISECONDS = 3000; /** How far ahead a layer's path is looked at to tell how fast it's moving. */ -const VELOCITY_SECONDS = 1 / 240; +export const VELOCITY_SECONDS = 1 / 240; /** How long a repeating path takes to ease to where it starts, from wherever the layer is. */ -const LEAD_IN_SECONDS = 0.25; +export const LEAD_IN_SECONDS = 0.25; interface Playing { animation: Animation; @@ -141,13 +154,16 @@ interface Playing { export class LayerMotion { private values: Values; private playing: Playing | undefined; + private readonly layer: RefObject; + private readonly kind: LayerKind; + /** The face's width in device pixels, read when a path starts. */ + private readonly facePixels: () => number; - constructor( - private readonly layer: RefObject, - private readonly kind: LayerKind, - /** The face's width in device pixels, read when a path starts. */ - private readonly facePixels: () => number, - ) { + // Fields set by hand rather than as parameter properties, so Node can load this file as it is, as the native apps' generator does. + constructor(layer: RefObject, kind: LayerKind, facePixels: () => number) { + this.layer = layer; + this.kind = kind; + this.facePixels = facePixels; this.values = kind.rest; } @@ -193,14 +209,14 @@ export class LayerMotion { * `delaySeconds`. A repeating path first eases to where it starts, so each * time round begins from the same place. */ - play(paths: Path | Path[], { repeat = false, delaySeconds = 0 } = {}): void { + play(paths: Path | readonly Path[], { repeat = false, delaySeconds = 0 } = {}): void { const element = this.layer.current; // Nothing to show it on, so nothing should be left playing. if (!element) { this.stop(); return; } - const list = Array.isArray(paths) ? paths : [paths]; + const list: readonly Path[] = isPathList(paths) ? paths : [paths]; const from = this.now(); const loopStart = repeat ? firstFrame(list[0]) : undefined; if (loopStart && this.visiblyApart(from, loopStart)) { @@ -317,13 +333,17 @@ export class LayerMotion { } } +function isPathList(paths: Path | readonly Path[]): paths is readonly Path[] { + return Array.isArray(paths); +} + /** * Paths one after another, each from where the last ends, as one function of * time; the first starts at `velocity`, where it's a spring. */ -function sequence( +export function sequence( from: Values, - paths: Path[], + paths: readonly Path[], velocity?: Values, ): { valuesAt: (seconds: number) => Values; seconds: number } { const parts: { valuesAt: (seconds: number) => Values; seconds: number; startsAt: number }[] = []; diff --git a/packages/avatars/src/lively-group.tsx b/packages/avatars/src/lively-group.tsx index b9fea4a05..44a85cfee 100644 --- a/packages/avatars/src/lively-group.tsx +++ b/packages/avatars/src/lively-group.tsx @@ -1,33 +1,13 @@ import { createContext, type ReactNode, useContext, useEffect, useState } from "react"; -import { type Liveliness, useLiveliness } from "./liveliness.ts"; -import { randomIn, repeatAtRandom, type Span } from "./random.ts"; +import { pacingByLiveliness } from "./group-pacing.ts"; +import { useLiveliness } from "./liveliness.ts"; +import { randomIn, repeatAtRandom } from "./random.ts"; /* * Faces in a group, such as a list of bots, mostly sit still and take short * turns moving, so only a few move at once and the list doesn't fidget. */ -interface GroupPacing { - /** How many faces may move at once. */ - movingAtOnce: number; - /** Seconds between turns starting, and how long a turn lasts, each picked at random from its range. */ - gapSeconds: Span; - turnSeconds: Span; -} - -const pacingByLiveliness: Record, GroupPacing> = { - sometimes: { - movingAtOnce: 1, - gapSeconds: { least: 4, most: 10 }, - turnSeconds: { least: 1, most: 3 }, - }, - often: { - movingAtOnce: 2, - gapSeconds: { least: 1.5, most: 4 }, - turnSeconds: { least: 1.5, most: 4 }, - }, -}; - /** The faces in a group, each told when its turn starts and ends. */ class Turns { private readonly members = new Set<(moving: boolean) => void>(); diff --git a/packages/avatars/src/mood-loop.ts b/packages/avatars/src/mood-loop.ts index 75046f443..f4635b1bf 100644 --- a/packages/avatars/src/mood-loop.ts +++ b/packages/avatars/src/mood-loop.ts @@ -5,9 +5,9 @@ import { randomIn, type Span } from "./random.ts"; /** One stretch of a mood in a loop: how likely it is to come next, and how long it lasts. */ interface MoodSpell { - mood: BotMood; - weight: number; - seconds: Span; + readonly mood: BotMood; + readonly weight: number; + readonly seconds: Span; } /** @@ -19,7 +19,7 @@ interface MoodSpell { export type MoodLoop = readonly [MoodSpell, ...MoodSpell[]]; /** How much shorter the resting spell is when faces should move often. */ -const OFTEN_REST_SHARE = 0.5; +export const OFTEN_REST_SHARE = 0.5; /** * The mood a bot is in now, moving through `loop`. While `running` is false it diff --git a/packages/avatars/src/moods.ts b/packages/avatars/src/moods.ts index 35a25e827..083647322 100644 --- a/packages/avatars/src/moods.ts +++ b/packages/avatars/src/moods.ts @@ -96,32 +96,50 @@ export const moods: Record = { }, }; +/** How often an idle bot blinks instead of glancing, and how often a blink is a double one. */ +export const IDLE_BLINK_CHANCE = 0.3; +export const DOUBLE_BLINK_CHANCE = 0.2; +/** How often an idle bot's glance is back to straight ahead, rather than somewhere new. */ +export const LOOK_AHEAD_CHANCE = 0.35; +/** How far an idle bot glances, at most, from straight ahead. */ +export const IDLE_GLANCE_REACH = 1; +/** How far the eyes must turn for a glance to count as long, and how often a bot blinks with one. */ +export const LONG_GLANCE_DISTANCE = 0.6; +export const LONG_GLANCE_BLINK_CHANCE = 0.5; + /** Blinks now and then; otherwise glances somewhere new, unless it's watching the pointer or typing. */ function glanceOrBlink(face: FaceControls): void { - if (face.isWatching() || Math.random() < 0.3) { - face.blink(Math.random() < 0.2); + if (face.isWatching() || Math.random() < IDLE_BLINK_CHANCE) { + face.blink(Math.random() < DOUBLE_BLINK_CHANCE); return; } - // Back to straight ahead about a third of the time, else somewhere new. - const [x, y] = Math.random() < 0.35 ? [0, 0] : randomGlance(1); + const [x, y] = Math.random() < LOOK_AHEAD_CHANCE ? [0, 0] : randomGlance(IDLE_GLANCE_REACH); // People blink as their eyes shift a long way. - if (face.lookAt(x, y) > 0.6 && Math.random() < 0.5) face.blink(); + if (face.lookAt(x, y) > LONG_GLANCE_DISTANCE && Math.random() < LONG_GLANCE_BLINK_CHANCE) { + face.blink(); + } } /** How big a happy bot's little bounces are, against a full hop. */ -const HAPPY_BOUNCE = 0.4; +export const HAPPY_BOUNCE = 0.4; +/** + * How often a happy bot's act is a bounce, and how often a blink; otherwise it + * glances, by at most `HAPPY_GLANCE_REACH`, so it keeps its face towards you. + */ +export const HAPPY_BOUNCE_CHANCE = 0.45; +export const HAPPY_BLINK_CHANCE = 0.25; +export const HAPPY_GLANCE_REACH = 0.4; function bounceOrBlink(face: FaceControls): void { const roll = Math.random(); - if (roll < 0.45) face.hop(HAPPY_BOUNCE); - else if (roll < 0.7) face.blink(); - // Small glances only: it keeps its face towards you. - else if (!face.isWatching()) face.lookAt(...randomGlance(0.4)); + if (roll < HAPPY_BOUNCE_CHANCE) face.hop(HAPPY_BOUNCE); + else if (roll < HAPPY_BOUNCE_CHANCE + HAPPY_BLINK_CHANCE) face.blink(); + else if (!face.isWatching()) face.lookAt(...randomGlance(HAPPY_GLANCE_REACH)); } /** How big an excited bot's bounces on the spot are against a full hop, and how often one is a full hop instead. */ -const EXCITED_BOUNCE: Span = { least: 0.25, most: 0.5 }; -const EXCITED_FULL_HOP_CHANCE = 0.3; +export const EXCITED_BOUNCE: Span = { least: 0.25, most: 0.5 }; +export const EXCITED_FULL_HOP_CHANCE = 0.3; function bounceOrHop(face: FaceControls): void { // Never cuts a hop short in the air. @@ -129,13 +147,23 @@ function bounceOrHop(face: FaceControls): void { face.hop(Math.random() < EXCITED_FULL_HOP_CHANCE ? 1 : randomIn(EXCITED_BOUNCE)); } +/** How often a sleepy bot's act is a flutter; otherwise it does nothing. */ +export const FLUTTER_CHANCE = 0.5; + function maybeFlutter(face: FaceControls): void { - if (Math.random() < 0.5) face.flutter(); + if (Math.random() < FLUTTER_CHANCE) face.flutter(); } -/** Somewhere to glance, up to `reach` from straight ahead: any direction, at least halfway out, more sideways than up or down. */ +/** + * A glance goes at least `GLANCE_LEAST_SHARE` of its reach from straight + * ahead, and only `GLANCE_VERTICAL_SHARE` as far up or down as sideways. + */ +export const GLANCE_LEAST_SHARE = 0.5; +export const GLANCE_VERTICAL_SHARE = 0.6; + +/** Somewhere to glance, up to `reach` from straight ahead, in any direction. */ function randomGlance(reach: number): [number, number] { const angle = Math.random() * Math.PI * 2; - const distance = (0.5 + Math.random() * 0.5) * reach; - return [Math.cos(angle) * distance, Math.sin(angle) * distance * 0.6]; + const distance = (GLANCE_LEAST_SHARE + Math.random() * (1 - GLANCE_LEAST_SHARE)) * reach; + return [Math.cos(angle) * distance, Math.sin(angle) * distance * GLANCE_VERTICAL_SHARE]; } diff --git a/packages/avatars/src/random.ts b/packages/avatars/src/random.ts index d16880070..a9b5ec2ac 100644 --- a/packages/avatars/src/random.ts +++ b/packages/avatars/src/random.ts @@ -1,7 +1,7 @@ /** A span from `least` to `most`, of seconds or a size, that something is picked from at random. */ export interface Span { - least: number; - most: number; + readonly least: number; + readonly most: number; } /** A number picked at random, evenly, from `span`. */ diff --git a/packages/avatars/src/screen-moods.ts b/packages/avatars/src/screen-moods.ts new file mode 100644 index 000000000..990831058 --- /dev/null +++ b/packages/avatars/src/screen-moods.ts @@ -0,0 +1,26 @@ +import type { MoodLoop } from "./mood-loop.ts"; + +/* + * The moods bots' faces move through on the apps' screens, here beside the + * moods themselves so every app moves its faces the same way. + */ + +/** + * How a bot's face carries itself while someone writes to it: watching them, + * now and then briefly pleased or excited. + */ +export const WATCHING_MOODS: MoodLoop = [ + { mood: "idle", weight: 1, seconds: { least: 25, most: 60 } }, + { mood: "happy", weight: 2, seconds: { least: 1.5, most: 2.5 } }, + { mood: "excited", weight: 1, seconds: { least: 1, most: 1.5 } }, +]; + +/** + * How the bot being made carries itself: mostly at ease, often pleased, and + * now and then briefly excited. + */ +export const CREATION_MOODS: MoodLoop = [ + { mood: "idle", weight: 1, seconds: { least: 4, most: 9 } }, + { mood: "happy", weight: 3, seconds: { least: 2, most: 4 } }, + { mood: "excited", weight: 1, seconds: { least: 1.2, most: 2 } }, +]; diff --git a/packages/avatars/src/watching.ts b/packages/avatars/src/watching.ts index e998f87ee..fefe8e674 100644 --- a/packages/avatars/src/watching.ts +++ b/packages/avatars/src/watching.ts @@ -3,13 +3,13 @@ import { type RefObject, useEffect } from "react"; import type { FaceControls } from "./face-rig.ts"; /** How many face-widths away something must be for the eyes to look all the way to it. */ -const WATCHING_REACH = 2.5; +export const WATCHING_REACH = 2.5; /** * The least time between the eyes' jumps to what they watch. Eyes move in * quick jumps rather than gliding, so following the pointer this way looks * natural, and each jump is one short animation rather than one a frame. */ -const JUMP_INTERVAL_MS = 100; +export const JUMP_INTERVAL_MS = 100; /** * Turns the face's eyes to the pointer as it moves and to where someone types, diff --git a/packages/web/src/shell/Agent.tsx b/packages/web/src/shell/Agent.tsx index 11e71e6cc..ba8c26c88 100644 --- a/packages/web/src/shell/Agent.tsx +++ b/packages/web/src/shell/Agent.tsx @@ -3,9 +3,9 @@ import { type LivelyBehaviour, LivelyBotFace, type LivelyFace, - type MoodLoop, useGroupTurn, useMoodLoop, + WATCHING_MOODS, } from "@sugabots/avatars"; import type { AgentColor, AgentFace, AgentShape } from "@sugabots/contracts"; import type { Ref } from "react"; @@ -91,16 +91,6 @@ interface AgentLook { shape: AgentShape; } -/** - * How a bot's face carries itself while someone writes to it: watching them, - * now and then briefly pleased or excited. - */ -const WATCHING_MOODS: MoodLoop = [ - { mood: "idle", weight: 1, seconds: { least: 25, most: 60 } }, - { mood: "happy", weight: 2, seconds: { least: 1.5, most: 2.5 } }, - { mood: "excited", weight: 1, seconds: { least: 1, most: 1.5 } }, -]; - /** * The face of a bot someone is talking to: thinking while the bot is `busy`; * else, while `watching`, following the pointer and the typing; else still. diff --git a/packages/web/src/shell/NewAgent.tsx b/packages/web/src/shell/NewAgent.tsx index ab20f30ce..cf2869065 100644 --- a/packages/web/src/shell/NewAgent.tsx +++ b/packages/web/src/shell/NewAgent.tsx @@ -1,4 +1,4 @@ -import { botColors, type LivelyFace, type MoodLoop, useMoodLoop } from "@sugabots/avatars"; +import { botColors, CREATION_MOODS, type LivelyFace, useMoodLoop } from "@sugabots/avatars"; import { AGENT_NAME_MAX_LENGTH, type Agent, @@ -644,16 +644,6 @@ function ModelRow({ ); } -/** - * How the bot being made carries itself: mostly at ease, often pleased, and - * now and then briefly excited. - */ -const CREATION_MOODS: MoodLoop = [ - { mood: "idle", weight: 1, seconds: { least: 4, most: 9 } }, - { mood: "happy", weight: 3, seconds: { least: 2, most: 4 } }, - { mood: "excited", weight: 1, seconds: { least: 1.2, most: 2 } }, -]; - /** The bot being made, large: hopping each time its look changes, and moving through `CREATION_MOODS`. */ function CreationFace({ look }: { look: Look }) { const mood = useMoodLoop(CREATION_MOODS); From 6bec12a378f4c6768d27a5645167cf10313e8a4c Mon Sep 17 00:00:00 2001 From: Ryan Cartwright Date: Thu, 5 Nov 2026 11:08:11 +1100 Subject: [PATCH 2/2] feat(android): add a Kotlin library for the API's client, generated from the OpenAPI document by apps/codegen --- .gitattributes | 2 + .github/workflows/native.yml | 31 + apps/android/api/.gitignore | 3 + apps/android/api/README.md | 32 + apps/android/api/build.gradle.kts | 23 + apps/android/api/settings.gradle.kts | 1 + .../kotlin/ai/sugabots/api/Api.generated.kt | 4350 +++++++++++++++++ .../main/kotlin/ai/sugabots/api/ApiSupport.kt | 277 ++ .../ai/sugabots/api/ApiSerializationTest.kt | 97 + apps/codegen/api/kotlin.ts | 624 +++ apps/codegen/api/model.ts | 943 ++++ apps/codegen/api/naming.ts | 108 + apps/codegen/generate-api.ts | 31 + apps/codegen/generate.test.ts | 45 + apps/codegen/generate.ts | 34 + apps/codegen/generated-files.ts | 26 + apps/codegen/vitest.config.ts | 13 + 17 files changed, 6640 insertions(+) create mode 100644 .github/workflows/native.yml create mode 100644 apps/android/api/.gitignore create mode 100644 apps/android/api/README.md create mode 100644 apps/android/api/build.gradle.kts create mode 100644 apps/android/api/settings.gradle.kts create mode 100644 apps/android/api/src/main/kotlin/ai/sugabots/api/Api.generated.kt create mode 100644 apps/android/api/src/main/kotlin/ai/sugabots/api/ApiSupport.kt create mode 100644 apps/android/api/src/test/kotlin/ai/sugabots/api/ApiSerializationTest.kt create mode 100644 apps/codegen/api/kotlin.ts create mode 100644 apps/codegen/api/model.ts create mode 100644 apps/codegen/api/naming.ts create mode 100644 apps/codegen/generate-api.ts create mode 100644 apps/codegen/generate.test.ts create mode 100644 apps/codegen/generate.ts create mode 100644 apps/codegen/generated-files.ts create mode 100644 apps/codegen/vitest.config.ts diff --git a/.gitattributes b/.gitattributes index d7e89e310..2c07470fc 100644 --- a/.gitattributes +++ b/.gitattributes @@ -2,3 +2,5 @@ packages/emoji/src/emoji.json linguist-generated=true # Generated by `bun run --cwd packages/contracts generate`; collapsed in diffs. packages/contracts/openapi.json linguist-generated=true +# Generated by `node apps/codegen/generate.ts`; collapsed in diffs. +apps/android/**/*.generated.kt linguist-generated=true diff --git a/.github/workflows/native.yml b/.github/workflows/native.yml new file mode 100644 index 000000000..7121fdd84 --- /dev/null +++ b/.github/workflows/native.yml @@ -0,0 +1,31 @@ +name: Native apps + +# Checks that the files the native apps generate from the web's packages and +# the API are what the generators make from them now. Only when the apps +# change: until then they keep the files they last took, so a change to the +# web or the API doesn't wait on them. Whoever changes an app regenerates +# first, with `node apps/codegen/generate.ts`, and catches it up then. + +on: + push: + branches: [main] + paths: + - "apps/**" + - ".github/workflows/native.yml" + pull_request: + paths: + - "apps/**" + - ".github/workflows/native.yml" + +concurrency: + group: native-${{ github.ref }} + cancel-in-progress: true + +jobs: + generated: + name: Generated files + runs-on: depot-ubuntu-24.04-4 + steps: + - uses: actions/checkout@v5 + - uses: ./.github/actions/setup + - run: bunx vitest run --config apps/codegen/vitest.config.ts diff --git a/apps/android/api/.gitignore b/apps/android/api/.gitignore new file mode 100644 index 000000000..5cc008e52 --- /dev/null +++ b/apps/android/api/.gitignore @@ -0,0 +1,3 @@ +build/ +.gradle/ +.kotlin/ diff --git a/apps/android/api/README.md b/apps/android/api/README.md new file mode 100644 index 000000000..8ea92f258 --- /dev/null +++ b/apps/android/api/README.md @@ -0,0 +1,32 @@ +# Sugabots API for Android + +The API's types and routes in Kotlin, package `ai.sugabots.api`, for the Android +app to depend on once there is one. It needs only kotlinx.serialization and +kotlinx.coroutines. + +- `Api.generated.kt` is generated from `packages/contracts/openapi.json`. Don't + edit it by hand. It stays as it was last generated while the API moves on; + from the repo root, regenerate it to take the API's changes: + + ```sh + node apps/codegen/generate.ts + ``` + + On a change under `apps/`, the `codegen` tests + (`bunx vitest run --config apps/codegen/vitest.config.ts`) fail while it is out of date. + The generator is `apps/codegen/generate-api.ts`: `api/model.ts` reads the + API, and `api/kotlin.ts` writes this file. +- `ApiSupport.kt` is what it's written against: `ApiTransport`, which the app + implements over OkHttp or Ktor to send requests with the API's address and the + bearer token; `ApiJson`; `Omittable`, for a field a request may leave out or + send as null; and the serializers that read enums and unions a newer server + sends. + +`ApiClient(transport)` groups the routes as the web's client does: +`api.threads.get(...)` there is `client.threads.get(...)` here. + +Build and test it with Gradle (JDK 17): + +```sh +gradle -p apps/android/api build +``` diff --git a/apps/android/api/build.gradle.kts b/apps/android/api/build.gradle.kts new file mode 100644 index 000000000..1fb08c236 --- /dev/null +++ b/apps/android/api/build.gradle.kts @@ -0,0 +1,23 @@ +plugins { + kotlin("jvm") version "2.0.21" + kotlin("plugin.serialization") version "2.0.21" +} + +repositories { + mavenCentral() +} + +dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3") + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0") + testImplementation(kotlin("test")) + testImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.9.0") +} + +kotlin { + jvmToolchain(17) +} + +tasks.test { + useJUnitPlatform() +} diff --git a/apps/android/api/settings.gradle.kts b/apps/android/api/settings.gradle.kts new file mode 100644 index 000000000..aa199c02a --- /dev/null +++ b/apps/android/api/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "sugabots-api" diff --git a/apps/android/api/src/main/kotlin/ai/sugabots/api/Api.generated.kt b/apps/android/api/src/main/kotlin/ai/sugabots/api/Api.generated.kt new file mode 100644 index 000000000..c5b428868 --- /dev/null +++ b/apps/android/api/src/main/kotlin/ai/sugabots/api/Api.generated.kt @@ -0,0 +1,4350 @@ +// Generated by apps/codegen/generate-api.ts from packages/contracts/openapi.json. Don't edit it by hand. +@file:OptIn(ExperimentalSerializationApi::class) +@file:UseSerializers(InstantSerializer::class) + +package ai.sugabots.api + +import java.time.Instant +import kotlinx.serialization.EncodeDefault +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.UseSerializers +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.decodeFromJsonElement +import kotlinx.serialization.json.encodeToJsonElement + +// MARK: Schemas + +@Serializable +data class AcceptedInvitation( + val workspaceId: String, +) + +@Serializable +data class AcceptedRoutineExecution( + val executionId: String, + val threadId: String, + val duplicate: Boolean, +) + +@Serializable +data class AcceptedRoutineWebhook( + val executionId: String, + val duplicate: Boolean, +) + +@Serializable +data class AccountRepository( + val repository: String, + val private: Boolean, +) + +@Serializable +data class ActivityFeed( + val items: List, +) + +@Serializable(with = ActivityItem.Serializer::class) +sealed interface ActivityItem { + @Serializable + data class MentionOrMessage( + val kind: Kind, + val messageId: String, + val author: ThreadParticipant, + val preview: String, + val podId: String, + val conversationId: String, + val at: Instant, + val unread: Boolean, + ) : ActivityItem { + @Serializable(with = Kind.Serializer::class) + enum class Kind(override val rawValue: String) : OpenEnum { + MENTION("mention"), + MESSAGE("message"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ActivityItem.MentionOrMessage.Kind", entries, UNKNOWN) + } + } + + @Serializable + data class Routine( + @EncodeDefault val kind: String = "routine", + val threadId: String, + val routineName: String, + val state: RoutineExecutionState, + val triggerKind: RoutineExecutionTriggerKind, + val agent: AgentParticipant, + @EncodeDefault val preview: String? = null, + val podId: String, + val conversationId: String, + val at: Instant, + val unread: Boolean, + ) : ActivityItem + + @Serializable + data class Collaboration( + @EncodeDefault val kind: String = "collaboration", + val threadId: String, + val initiator: AgentParticipant, + val recipient: AgentParticipant, + val status: CollaborationStatus, + val brief: String, + val podId: String, + val conversationId: String, + val at: Instant, + val unread: Boolean, + ) : ActivityItem + + /** A kind from a newer server than this app knows, by its `kind`, which can't be sent. */ + data class Unknown(val tag: String) : ActivityItem + + object Serializer : JsonUnionSerializer("ai.sugabots.api.ActivityItem") { + override fun decode(element: JsonElement, json: Json): ActivityItem = + when (val tag = tagOf(element, "kind")) { + "mention", "message" -> json.decodeFromJsonElement(element) + "routine" -> json.decodeFromJsonElement(element) + "collaboration" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: ActivityItem, json: Json): JsonElement = + when (value) { + is MentionOrMessage -> json.encodeToJsonElement(value) + is Routine -> json.encodeToJsonElement(value) + is Collaboration -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class Agent( + val id: String, + val workspaceId: String, + val podId: String, + val name: String, + val handle: String, + @EncodeDefault val systemAgentKey: SystemAgentKey? = null, + @EncodeDefault val description: String? = null, + val color: AgentColor, + val face: AgentFace, + val shape: AgentShape, + @EncodeDefault val model: String? = null, + val prompt: String, + val disabledTools: List, + val usesSandbox: Boolean, + val naturalBrowsing: Boolean, + @EncodeDefault val createdById: String? = null, + val createdAt: Instant, +) + +@Serializable(with = AgentColor.Serializer::class) +enum class AgentColor(override val rawValue: String) : OpenEnum { + RED("red"), + ORANGE("orange"), + AMBER("amber"), + YELLOW("yellow"), + LIME("lime"), + GREEN("green"), + EMERALD("emerald"), + TEAL("teal"), + SKY("sky"), + ICE("ice"), + INDIGO("indigo"), + VIOLET("violet"), + PURPLE("purple"), + FUCHSIA("fuchsia"), + PINK("pink"), + ROSE("rose"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.AgentColor", entries, UNKNOWN) +} + +@Serializable(with = AgentFace.Serializer::class) +enum class AgentFace(override val rawValue: String) : OpenEnum { + PILL("pill"), + DOT("dot"), + ARC("arc"), + SQUARE("square"), + WINK("wink"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.AgentFace", entries, UNKNOWN) +} + +@Serializable +data class AgentParticipant( + @EncodeDefault val kind: String = "agent", + val id: String, + val name: String, + val handle: String, + val color: AgentColor, + val face: AgentFace, + val shape: AgentShape, +) + +@Serializable(with = AgentShape.Serializer::class) +enum class AgentShape(override val rawValue: String) : OpenEnum { + CIRCLE("circle"), + SQUIRCLE("squircle"), + PEBBLE("pebble"), + BLOB("blob"), + WOBBLE("wobble"), + DROP("drop"), + LEAF("leaf"), + DOME("dome"), + BOWL("bowl"), + HEXAGON("hexagon"), + OCTAGON("octagon"), + TRIANGLE("triangle"), + PENTAGON("pentagon"), + DIAMOND("diamond"), + SHIELD("shield"), + STAR("star"), + FLOWER("flower"), + SCALLOP("scallop"), + GHOST("ghost"), + BEAR("bear"), + ANTENNA("antenna"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.AgentShape", entries, UNKNOWN) +} + +@Serializable +data class AgentUpdate( + val name: String? = null, + val handle: Omittable = Omittable.Omitted, + val description: Omittable = Omittable.Omitted, + val color: Omittable = Omittable.Omitted, + val face: Omittable = Omittable.Omitted, + val shape: Omittable = Omittable.Omitted, + val model: Omittable = Omittable.Omitted, + val prompt: Omittable = Omittable.Omitted, + val disabledTools: Omittable?> = Omittable.Omitted, + val usesSandbox: Omittable = Omittable.Omitted, + val naturalBrowsing: Omittable = Omittable.Omitted, +) + +@Serializable +data class AnsweredApproval( + val call: ToolCallPart, + val agent: AgentParticipant, + val podId: String, + val threadId: String, + @EncodeDefault val conversationId: String? = null, + val answer: Answer, +) { + @Serializable + data class Answer( + val status: Status, + @EncodeDefault val decidedByName: String? = null, + val decidedAt: Instant, + ) { + @Serializable(with = Status.Serializer::class) + enum class Status(override val rawValue: String) : OpenEnum { + ALLOWED("allowed"), + DENIED("denied"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.AnsweredApproval.Answer.Status", entries, UNKNOWN) + } + } +} + +@Serializable +data class ApprovalInbox( + val waiting: List, + val answered: List, +) + +@Serializable +data class ApprovalRequest( + val call: ToolCallPart, + val agent: AgentParticipant, + val podId: String, + val threadId: String, + @EncodeDefault val conversationId: String? = null, +) + +@Serializable +data class Artifact( + val id: String, + val podId: String, + val kind: ArtifactKind, + val title: String, + val version: Long, + @EncodeDefault val createdBy: ArtifactAuthor? = null, + val createdAt: Instant, + val updatedAt: Instant, + val content: String, + val shownVersion: ArtifactVersionSummary, +) + +@Serializable +data class ArtifactAuthor( + val agentId: String, + val name: String, +) + +@Serializable(with = ArtifactKind.Serializer::class) +enum class ArtifactKind(override val rawValue: String) : OpenEnum { + DOCUMENT("document"), + HTML("html"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ArtifactKind", entries, UNKNOWN) +} + +@Serializable +data class ArtifactPart( + @EncodeDefault val type: String = "artifact", + val artifactId: String, + val kind: ArtifactKind, + val title: String, + val version: Long, +) + +@Serializable +data class ArtifactSummary( + val id: String, + val podId: String, + val kind: ArtifactKind, + val title: String, + val version: Long, + @EncodeDefault val createdBy: ArtifactAuthor? = null, + val createdAt: Instant, + val updatedAt: Instant, +) + +@Serializable +data class ArtifactVersionSummary( + val number: Long, + @EncodeDefault val author: ArtifactAuthor? = null, + val createdAt: Instant, +) + +@Serializable(with = AssignableWorkspaceRole.Serializer::class) +enum class AssignableWorkspaceRole(override val rawValue: String) : OpenEnum { + ADMIN("admin"), + MEMBER("member"), + VIEWER("viewer"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.AssignableWorkspaceRole", entries, UNKNOWN) +} + +@Serializable +data class BadRequestEncoded( + @SerialName("_tag") @EncodeDefault val tag: String = "BadRequest", + val message: String, + val details: JsonElement? = null, + val error: ErrorEncoded? = null, +) { + @Serializable + data class ErrorEncoded( + @SerialName("_tag") val tag: String, + val userMessage: String, + val isRetryable: Boolean, + val retryAfterMillis: @Serializable(with = NonFiniteDoubleSerializer::class) Double? = null, + ) +} + +@Serializable +data class BotChannel( + @EncodeDefault val kind: String = "bot_channel", + val id: String, + val workspaceId: String, + val podId: String, + val title: String, + val createdAt: Instant, + val updatedAt: Instant, + val hostAgentId: String, +) + +@Serializable +data class BotMove( + val from: String, + val to: String, +) + +@Serializable +data class BotUsage( + val agentId: String, + @EncodeDefault val name: String? = null, + @EncodeDefault val color: AgentColor? = null, + @EncodeDefault val face: AgentFace? = null, + @EncodeDefault val shape: AgentShape? = null, + @EncodeDefault val podName: String? = null, + val usd: Double, + val unpricedRequests: Long, +) + +@Serializable +data class BulkProviderModelUpdate( + val modelIds: List, + val enabled: Boolean, +) + +@Serializable +data class ChatHistoryEntry( + val threadId: String, + @EncodeDefault val parentThreadId: String? = null, + val type: CustomerThreadType, + val title: String, + val participants: List, + val status: Status, + @EncodeDefault val routineExecution: RoutineExecutionSummary? = null, + val latestActivityAt: Instant, +) { + @Serializable(with = Status.Serializer::class) + enum class Status(override val rawValue: String) : OpenEnum { + QUEUED("queued"), + RUNNING("running"), + COMPLETED("completed"), + FAILED("failed"), + CANCELLED("cancelled"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ChatHistoryEntry.Status", entries, UNKNOWN) + } +} + +@Serializable +data class ChatHistoryPage( + val items: List, + @EncodeDefault val nextCursor: String? = null, +) + +@Serializable +data class ChatList( + val chats: List, + val channels: List, + val threads: List, + val routines: List, +) { + @Serializable + data class Chat( + val conversation: PodChat, + val unreadMessages: Long, + ) + + @Serializable + data class Channel( + val agent: Agent, + val conversation: BotChannel, + val unreadMessages: Long, + val needsApproval: Boolean, + val mentionsYou: Boolean, + ) +} + +@Serializable +data class ChatListItem( + @EncodeDefault val agent: Agent? = null, + val conversation: ConversationThread, + @EncodeDefault val lastMessage: LastMessage? = null, + val participants: List, + @EncodeDefault val waitingOn: String? = null, + val unreadMessages: Long, + val needsApproval: Boolean, + val mentionsYou: Boolean, +) { + @Serializable + data class LastMessage( + val preview: String, + @EncodeDefault val authorUserId: String? = null, + val at: Instant, + ) +} + +@Serializable(with = ChatMessageItem.Serializer::class) +sealed interface ChatMessageItem { + @Serializable + data class MessageItem( + @EncodeDefault val kind: String = "message", + val message: Message, + ) : ChatMessageItem + + @Serializable + data class Routine( + @EncodeDefault val kind: String = "routine", + val id: String, + val threadId: String, + val routineName: String, + val triggerKind: RoutineExecutionTriggerKind, + val state: RoutineExecutionState, + @EncodeDefault val error: String? = null, + @EncodeDefault val report: String? = null, + val createdAt: Instant, + ) : ChatMessageItem + + @Serializable + data class Collaboration( + @EncodeDefault val kind: String = "collaboration", + val id: String, + val threadId: String, + val title: String, + val initiator: AgentParticipant, + val state: State, + val createdAt: Instant, + ) : ChatMessageItem { + @Serializable(with = State.Serializer::class) + enum class State(override val rawValue: String) : OpenEnum { + RUNNING("running"), + DONE("done"), + FAILED("failed"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ChatMessageItem.Collaboration.State", entries, UNKNOWN) + } + } + + @Serializable + data class RoutinePaused( + @EncodeDefault val kind: String = "routine_paused", + val id: String, + val createdAt: Instant, + ) : ChatMessageItem + + @Serializable + data class Thread( + @EncodeDefault val kind: String = "thread", + val id: String, + val threadId: String, + @EncodeDefault val originMessageId: String? = null, + val title: String, + @EncodeDefault val agent: AgentParticipant? = null, + val replies: Long, + @EncodeDefault val lastReplyAt: Instant? = null, + val working: Boolean, + val createdAt: Instant, + ) : ChatMessageItem + + /** A kind from a newer server than this app knows, by its `kind`, which can't be sent. */ + data class Unknown(val tag: String) : ChatMessageItem + + object Serializer : JsonUnionSerializer("ai.sugabots.api.ChatMessageItem") { + override fun decode(element: JsonElement, json: Json): ChatMessageItem = + when (val tag = tagOf(element, "kind")) { + "message" -> json.decodeFromJsonElement(element) + "routine" -> json.decodeFromJsonElement(element) + "collaboration" -> json.decodeFromJsonElement(element) + "routine_paused" -> json.decodeFromJsonElement(element) + "thread" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: ChatMessageItem, json: Json): JsonElement = + when (value) { + is MessageItem -> json.encodeToJsonElement(value) + is Routine -> json.encodeToJsonElement(value) + is Collaboration -> json.encodeToJsonElement(value) + is RoutinePaused -> json.encodeToJsonElement(value) + is Thread -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class ChatMessagesPage( + val items: List, + @EncodeDefault val nextCursor: String? = null, +) + +@Serializable +data class CollaborationPart( + @EncodeDefault val type: String = "collaboration", + val id: String, + val agentId: String, + val agentName: String, + val threadId: String, + val brief: String, + val status: CollaborationStatus, + @EncodeDefault val answer: String? = null, + val atOffset: Long, +) + +@Serializable(with = CollaborationStatus.Serializer::class) +enum class CollaborationStatus(override val rawValue: String) : OpenEnum { + WAITING("waiting"), + PENDING("pending"), + ANSWERED("answered"), + FAILED("failed"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.CollaborationStatus", entries, UNKNOWN) +} + +@Serializable +data class CompleteOnboarding( + val workspaceId: String, + val podId: String, + val agentId: String, +) + +@Serializable +data class ConflictEncoded( + @SerialName("_tag") @EncodeDefault val tag: String = "Conflict", + val message: String, + val details: JsonElement? = null, + val error: ErrorEncoded? = null, +) { + @Serializable + data class ErrorEncoded( + @SerialName("_tag") val tag: String, + val userMessage: String, + val isRetryable: Boolean, + val retryAfterMillis: @Serializable(with = NonFiniteDoubleSerializer::class) Double? = null, + ) +} + +@Serializable +data class ConnectFromCatalog( + val name: String, + val url: String, +) + +@Serializable +data class ConnectFromCatalogResult( + val connectionId: String, + val authorizationUrl: String, +) + +@Serializable +data class Connection( + val id: String, + val workspaceId: String, + val podId: String, + val name: String, + val handle: String, + val kind: ConnectionKind, + val url: String, + val auth: ConnectionAuth, + val signedIn: Boolean, + val signInExpired: Boolean, + @EncodeDefault val secretHeader: String? = null, + val hasSecret: Boolean, + @EncodeDefault val appSettingsUrl: String? = null, + val status: ProviderStatus, + val toolCounts: ToolAccessCounts, + @EncodeDefault val lastTestedAt: Instant? = null, + @EncodeDefault val lastTestError: String? = null, + @EncodeDefault val connectedBy: String? = null, + val createdAt: Instant, +) + +@Serializable(with = ConnectionAccess.Serializer::class) +enum class ConnectionAccess(override val rawValue: String) : OpenEnum { + OFF("off"), + ASK("ask"), + ALLOW("allow"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ConnectionAccess", entries, UNKNOWN) +} + +@Serializable(with = ConnectionAuth.Serializer::class) +enum class ConnectionAuth(override val rawValue: String) : OpenEnum { + HEADER("header"), + OAUTH("oauth"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ConnectionAuth", entries, UNKNOWN) +} + +@Serializable(with = ConnectionKind.Serializer::class) +enum class ConnectionKind(override val rawValue: String) : OpenEnum { + MCP("mcp"), + GITHUB("github"), + HTTP("http"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ConnectionKind", entries, UNKNOWN) +} + +@Serializable +data class ConnectionOauthStart( + @EncodeDefault val authorizationUrl: String? = null, +) + +@Serializable +data class ConnectionRepositories( + @EncodeDefault val account: String? = null, + val repositories: List, +) { + @Serializable + data class Repository( + val repository: String, + @EncodeDefault val addedByName: String? = null, + val addedAt: Instant, + ) +} + +@Serializable +data class ConnectionRepositoryChange( + val repository: String, +) + +@Serializable +data class ConnectionTestResult( + val reachable: Boolean, + val latencyMs: Long, + val tools: Long? = null, + val error: String? = null, +) + +@Serializable +data class ConnectionToolSetting( + val name: String, + @EncodeDefault val readOnly: Boolean? = null, + @EncodeDefault val destructive: Boolean? = null, + val access: ConnectionAccess, +) + +@Serializable +data class ConnectionUpdate( + val name: String? = null, + val url: String? = null, + val secretHeader: Omittable = Omittable.Omitted, + val secret: Omittable = Omittable.Omitted, + val access: ConnectionAccess? = null, + val toolAccess: Map? = null, +) + +@Serializable +data class ConnectionWithTools( + val id: String, + val workspaceId: String, + val podId: String, + val name: String, + val handle: String, + val kind: ConnectionKind, + val url: String, + val auth: ConnectionAuth, + val signedIn: Boolean, + val signInExpired: Boolean, + @EncodeDefault val secretHeader: String? = null, + val hasSecret: Boolean, + @EncodeDefault val appSettingsUrl: String? = null, + val status: ProviderStatus, + val toolCounts: ToolAccessCounts, + @EncodeDefault val lastTestedAt: Instant? = null, + @EncodeDefault val lastTestError: String? = null, + @EncodeDefault val connectedBy: String? = null, + val createdAt: Instant, + val tools: List, +) + +@Serializable +data class ConversationThread( + @EncodeDefault val kind: String = "thread", + val id: String, + val workspaceId: String, + val podId: String, + val title: String, + val createdAt: Instant, + val updatedAt: Instant, + @EncodeDefault val hostAgentId: String? = null, + @EncodeDefault val startedInChatId: String? = null, + @EncodeDefault val doneAt: Instant? = null, +) + +@Serializable(with = CustomerThreadType.Serializer::class) +enum class CustomerThreadType(override val rawValue: String) : OpenEnum { + COLLABORATION("collaboration"), + ROUTINE("routine"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.CustomerThreadType", entries, UNKNOWN) +} + +@Serializable +data class DefaultModelUpdate( + val model: String, +) + +@Serializable +data class FilePart( + @EncodeDefault val type: String = "file", + val id: String, + val name: String, + val contentType: String, + val size: Long, +) + +@Serializable +data class ForbiddenEncoded( + @SerialName("_tag") @EncodeDefault val tag: String = "Forbidden", + val message: String, + val details: JsonElement? = null, + val error: ErrorEncoded? = null, +) { + @Serializable + data class ErrorEncoded( + @SerialName("_tag") val tag: String, + val userMessage: String, + val isRetryable: Boolean, + val retryAfterMillis: @Serializable(with = NonFiniteDoubleSerializer::class) Double? = null, + ) +} + +@Serializable +data class GitHubAppForm( + val url: String, + val manifest: String, +) + +@Serializable +data class GitHubAppInstall( + val url: String, +) + +@Serializable +data class HealthResponse( + @EncodeDefault val status: String = "ok", + val version: String, + @EncodeDefault val commit: String? = null, +) + +@Serializable +data class IgnoredRoutineWebhook( + val ignored: Boolean, +) + +@Serializable +data class InternalServerErrorEncoded( + @SerialName("_tag") @EncodeDefault val tag: String = "InternalServerError", + val message: String, + val details: JsonElement? = null, + val error: ErrorEncoded? = null, +) { + @Serializable + data class ErrorEncoded( + @SerialName("_tag") val tag: String, + val userMessage: String, + val isRetryable: Boolean, + val retryAfterMillis: @Serializable(with = NonFiniteDoubleSerializer::class) Double? = null, + ) +} + +@Serializable(with = InvitationPreview.Serializer::class) +sealed interface InvitationPreview { + @Serializable + data class Pending( + @EncodeDefault val status: String = "pending", + val workspaceName: String, + val inviterName: String, + ) : InvitationPreview + + @Serializable + data class Accepted( + @EncodeDefault val status: String = "accepted", + val workspaceId: String, + ) : InvitationPreview + + /** A kind from a newer server than this app knows, by its `status`, which can't be sent. */ + data class Unknown(val tag: String) : InvitationPreview + + object Serializer : JsonUnionSerializer("ai.sugabots.api.InvitationPreview") { + override fun decode(element: JsonElement, json: Json): InvitationPreview = + when (val tag = tagOf(element, "status")) { + "pending" -> json.decodeFromJsonElement(element) + "accepted" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: InvitationPreview, json: Json): JsonElement = + when (value) { + is Pending -> json.encodeToJsonElement(value) + is Accepted -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class ListedRoutine( + val routine: Routine, + val agent: Agent, + @EncodeDefault val conversation: RoutineFeed? = null, + val mentionsYou: Boolean, +) { + @Serializable + data class Routine( + val id: String, + val name: String, + val state: RoutineState, + val failed: Boolean, + val pausedAfterFailures: Boolean, + ) +} + +@Serializable +data class ManualRoutineRun( + val requestId: String, +) + +@Serializable +data class Me( + val user: SessionUser, + val workspaces: List, +) + +@Serializable +data class Message( + val id: String, + val threadId: String, + val author: MessageAuthor, + @EncodeDefault val kind: String = "text", + val status: MessageStatus, + val parts: List, + val content: String, + val error: String? = null, + val routineResultOf: RoutineResultOf? = null, + val replyTo: MessageReplyTo? = null, + val reactions: MessageReactions? = null, + val createdAt: Instant, +) + +@Serializable(with = MessageAuthor.Serializer::class) +sealed interface MessageAuthor { + data class Person(val value: PersonParticipant) : MessageAuthor + + data class Agent(val value: AgentParticipant) : MessageAuthor + + data class RoutineTrigger(val value: RoutineTriggerAuthor) : MessageAuthor + + /** A kind from a newer server than this app knows, by its `kind`, which can't be sent. */ + data class Unknown(val tag: String) : MessageAuthor + + object Serializer : JsonUnionSerializer("ai.sugabots.api.MessageAuthor") { + override fun decode(element: JsonElement, json: Json): MessageAuthor = + when (val tag = tagOf(element, "kind")) { + "person" -> Person(json.decodeFromJsonElement(element)) + "agent" -> Agent(json.decodeFromJsonElement(element)) + "routine_trigger" -> RoutineTrigger(json.decodeFromJsonElement(element)) + else -> Unknown(tag) + } + + override fun encode(value: MessageAuthor, json: Json): JsonElement = + when (value) { + is Person -> json.encodeToJsonElement(value.value) + is Agent -> json.encodeToJsonElement(value.value) + is RoutineTrigger -> json.encodeToJsonElement(value.value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable(with = MessagePart.Serializer::class) +sealed interface MessagePart { + data class Text(val value: TextPart) : MessagePart + + data class Collaboration(val value: CollaborationPart) : MessagePart + + data class ToolCall(val value: ToolCallPart) : MessagePart + + data class File(val value: FilePart) : MessagePart + + data class Artifact(val value: ArtifactPart) : MessagePart + + /** A kind from a newer server than this app knows, by its `type`, which can't be sent. */ + data class Unknown(val tag: String) : MessagePart + + object Serializer : JsonUnionSerializer("ai.sugabots.api.MessagePart") { + override fun decode(element: JsonElement, json: Json): MessagePart = + when (val tag = tagOf(element, "type")) { + "text" -> Text(json.decodeFromJsonElement(element)) + "collaboration" -> Collaboration(json.decodeFromJsonElement(element)) + "tool_call" -> ToolCall(json.decodeFromJsonElement(element)) + "file" -> File(json.decodeFromJsonElement(element)) + "artifact" -> Artifact(json.decodeFromJsonElement(element)) + else -> Unknown(tag) + } + + override fun encode(value: MessagePart, json: Json): JsonElement = + when (value) { + is Text -> json.encodeToJsonElement(value.value) + is Collaboration -> json.encodeToJsonElement(value.value) + is ToolCall -> json.encodeToJsonElement(value.value) + is File -> json.encodeToJsonElement(value.value) + is Artifact -> json.encodeToJsonElement(value.value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class MessageReaction( + val emoji: String, + val people: List, +) { + @Serializable + data class PeopleItem( + val id: String, + val name: String, + val at: Instant, + ) +} + +typealias MessageReactions = List + +@Serializable +data class MessageReplyTo( + val id: String, + val author: MessageAuthor, + val preview: String, +) + +@Serializable(with = MessageStatus.Serializer::class) +enum class MessageStatus(override val rawValue: String) : OpenEnum { + COMPLETE("complete"), + STREAMING("streaming"), + FAILED("failed"), + CANCELLED("cancelled"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.MessageStatus", entries, UNKNOWN) +} + +@Serializable +data class ModelProvider( + val id: String, + val workspaceId: String, + @EncodeDefault val preset: ProviderPresetId? = null, + val name: String, + val baseUrl: String, + val apiFormat: ProviderApiFormat, + val active: Boolean, + val status: ProviderStatus, + val hasApiKey: Boolean, + val signedIn: Boolean, + val customHeaders: List, + val modelCount: Long, + val enabledModelCount: Long, + @EncodeDefault val lastTestedAt: Instant? = null, + @EncodeDefault val lastTestError: String? = null, + val models: List, +) { + @Serializable + data class CustomHeader( + val name: String, + ) +} + +@Serializable +data class ModelProviderUpdate( + val active: Boolean? = null, + val baseUrl: String? = null, + val apiFormat: ProviderApiFormat? = null, + val apiKey: Omittable = Omittable.Omitted, + val customHeaders: List? = null, +) + +@Serializable +data class ModelTrial( + val systemAgentKey: SystemAgentKey, + val model: String, + val rating: TrialRating, + val accuracy: TrialAccuracy, + val speed: TrialSpeed, + val verdict: List, + val cases: List, +) + +@Serializable +data class ModelUsage( + val model: String, + @EncodeDefault val displayName: String? = null, + @EncodeDefault val providerName: String? = null, + @EncodeDefault val preset: ProviderPresetId? = null, + val usd: Double, + val unpricedRequests: Long, +) + +@Serializable +data class NewAgentInPod( + val name: String, + val handle: String? = null, + val description: Omittable = Omittable.Omitted, + val color: AgentColor? = null, + val face: AgentFace? = null, + val shape: AgentShape? = null, + val model: String, + val prompt: String? = null, + val disabledTools: List? = null, + val usesSandbox: Boolean? = null, + val naturalBrowsing: Boolean? = null, +) + +@Serializable +data class NewChat( + val name: String, +) + +@Serializable(with = NewConnection.Serializer::class) +sealed interface NewConnection { + @Serializable + data class Http( + @EncodeDefault val kind: String = "http", + val name: String, + val url: String, + val secretHeader: String? = null, + val secret: String? = null, + ) : NewConnection + + @Serializable + data class Mcp( + val kind: String? = null, + val name: String, + val url: String, + val auth: ConnectionAuth? = null, + val secretHeader: String? = null, + val secret: String? = null, + ) : NewConnection + + object Serializer : JsonUnionSerializer("ai.sugabots.api.NewConnection") { + override fun decode(element: JsonElement, json: Json): NewConnection { + json.decodeOrNull(element)?.let { return it } + json.decodeOrNull(element)?.let { return it } + throw SerializationException("None of NewConnection's kinds.") + } + + override fun encode(value: NewConnection, json: Json): JsonElement = + when (value) { + is Http -> json.encodeToJsonElement(value) + is Mcp -> json.encodeToJsonElement(value) + } + } +} + +@Serializable +data class NewCustomProvider( + val name: String, + val baseUrl: String, + val apiFormat: ProviderApiFormat, + val apiKey: String? = null, + val customHeaders: List? = null, +) { + @Serializable + data class CustomHeader( + val name: String, + val value: String, + ) +} + +@Serializable +data class NewGitHubApp( + val organization: String? = null, +) + +@Serializable +data class NewMessage( + val id: String, + val message: String, + val attachments: List? = null, + val replyTo: String? = null, +) + +@Serializable(with = NewModelProvider.Serializer::class) +sealed interface NewModelProvider { + data class NewCustomProviderProvider(val value: NewCustomProvider) : NewModelProvider + + data class NewProviderFromPresetProvider(val value: NewProviderFromPreset) : NewModelProvider + + object Serializer : JsonUnionSerializer("ai.sugabots.api.NewModelProvider") { + override fun decode(element: JsonElement, json: Json): NewModelProvider { + json.decodeOrNull(element)?.let { return NewCustomProviderProvider(it) } + json.decodeOrNull(element)?.let { return NewProviderFromPresetProvider(it) } + throw SerializationException("None of NewModelProvider's kinds.") + } + + override fun encode(value: NewModelProvider, json: Json): JsonElement = + when (value) { + is NewCustomProviderProvider -> json.encodeToJsonElement(value.value) + is NewProviderFromPresetProvider -> json.encodeToJsonElement(value.value) + } + } +} + +@Serializable +data class NewModelTrial( + val systemAgentKey: SystemAgentKey, + val model: String, +) + +@Serializable +data class NewPod( + val name: String, + val slug: String? = null, + val color: PodColor? = null, +) + +@Serializable +data class NewPodMember( + val userId: String, +) + +@Serializable +data class NewProviderFromPreset( + val preset: ProviderPresetId, + val apiKey: String? = null, + val baseUrl: String? = null, +) + +@Serializable +data class NewProviderModel( + val modelId: String, + val displayName: Omittable = Omittable.Omitted, + val capabilities: List? = null, + val contextLength: Omittable = Omittable.Omitted, +) + +@Serializable +data class NewRoutine( + val name: String, + val instructions: String, + val state: RoutineState? = null, + val results: RoutineResults? = null, + val chatId: Omittable = Omittable.Omitted, + val triggers: List, +) + +@Serializable +data class NewSandboxHost( + val host: String, +) + +@Serializable +data class NewSandboxProvider( + val settings: SandboxProviderSettings, + val enabled: Boolean? = null, + val apiKey: String? = null, +) + +@Serializable +data class NewSearchProvider( + val preset: SearchProviderPresetId, + val enabled: Boolean? = null, + val apiKey: String? = null, + val baseUrl: String? = null, +) + +@Serializable +data class NewThread( + val id: String, + val message: String, + val attachments: List? = null, + val hostAgentId: String? = null, + val replyTo: String? = null, +) + +@Serializable +data class NewWorkspace( + val name: String, + val slug: String, + val timeZone: String? = null, +) + +@Serializable +data class NewWorkspaceInvitation( + val email: String, + val role: AssignableWorkspaceRole, + val resend: Boolean? = null, +) + +@Serializable +data class NotFoundEncoded( + @SerialName("_tag") @EncodeDefault val tag: String = "NotFound", + val message: String, + val details: JsonElement? = null, + val error: ErrorEncoded? = null, +) { + @Serializable + data class ErrorEncoded( + @SerialName("_tag") val tag: String, + val userMessage: String, + val isRetryable: Boolean, + val retryAfterMillis: @Serializable(with = NonFiniteDoubleSerializer::class) Double? = null, + ) +} + +@Serializable(with = NotificationLevel.Serializer::class) +enum class NotificationLevel(override val rawValue: String) : OpenEnum { + ALL("all"), + MENTIONS("mentions"), + NOTHING("nothing"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.NotificationLevel", entries, UNKNOWN) +} + +@Serializable +data class NotificationLevelChoice( + @EncodeDefault val level: NotificationLevel? = null, +) + +@Serializable +data class NotificationMute( + @EncodeDefault val until: Instant? = null, +) + +@Serializable(with = NotificationPlaceKind.Serializer::class) +enum class NotificationPlaceKind(override val rawValue: String) : OpenEnum { + POD("pod"), + BOT("bot"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.NotificationPlaceKind", entries, UNKNOWN) +} + +@Serializable +data class NotificationPreferences( + val level: NotificationLevel, + @EncodeDefault val pausedUntil: Instant? = null, + @EncodeDefault val quietHours: QuietHours? = null, + val turnFailures: Boolean, + val routineRuns: RoutineRunNotifications, +) + +@Serializable +data class NotificationSettings( + val level: NotificationLevel, + @EncodeDefault val pausedUntil: Instant? = null, + @EncodeDefault val quietHours: QuietHours? = null, + val turnFailures: Boolean, + val routineRuns: RoutineRunNotifications, + val pods: Map, + val bots: Map, + val mutedUntil: MutedUntil, +) { + @Serializable + data class MutedUntil( + val pods: Map, + val bots: Map, + ) +} + +@Serializable +data class OpenBotChannel( + val podId: String, + val hostAgentId: String, +) + +@Serializable +data class OwnershipTransfer( + val memberId: String, +) + +@Serializable +data class PayloadTooLargeEncoded( + @SerialName("_tag") @EncodeDefault val tag: String = "PayloadTooLarge", + val message: String, + val details: JsonElement? = null, + val error: ErrorEncoded? = null, +) { + @Serializable + data class ErrorEncoded( + @SerialName("_tag") val tag: String, + val userMessage: String, + val isRetryable: Boolean, + val retryAfterMillis: @Serializable(with = NonFiniteDoubleSerializer::class) Double? = null, + ) +} + +@Serializable +data class PersonParticipant( + @EncodeDefault val kind: String = "person", + val id: String, + val name: String, + val email: String, + val handle: String, + @EncodeDefault val image: String? = null, +) + +@Serializable(with = PersonUpdateEvent.Serializer::class) +sealed interface PersonUpdateEvent { + @Serializable + data class Notification( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "notification", + val title: String, + val body: String, + val tag: String, + val path: String, + @EncodeDefault val conversationId: String? = null, + ) : PersonUpdateEvent + + @Serializable + data class Presence( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "presence", + val clientId: String, + @EncodeDefault val conversationId: String? = null, + val sequence: Long, + ) : PersonUpdateEvent + + @Serializable + data class Reset( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "reset", + ) : PersonUpdateEvent + + /** A kind from a newer server than this app knows, by its `type`, which can't be sent. */ + data class Unknown(val tag: String) : PersonUpdateEvent + + object Serializer : JsonUnionSerializer("ai.sugabots.api.PersonUpdateEvent") { + override fun decode(element: JsonElement, json: Json): PersonUpdateEvent = + when (val tag = tagOf(element, "type")) { + "notification" -> json.decodeFromJsonElement(element) + "presence" -> json.decodeFromJsonElement(element) + "reset" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: PersonUpdateEvent, json: Json): JsonElement = + when (value) { + is Notification -> json.encodeToJsonElement(value) + is Presence -> json.encodeToJsonElement(value) + is Reset -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class Pod( + val id: String, + val workspaceId: String, + @EncodeDefault val ownerId: String? = null, + val kind: Kind, + val name: String, + val slug: String, + @EncodeDefault val color: PodColor? = null, + val permissions: PodPermissions, + val createdAt: Instant, +) { + @Serializable(with = Kind.Serializer::class) + enum class Kind(override val rawValue: String) : OpenEnum { + PERSONAL("personal"), + SHARED("shared"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.Pod.Kind", entries, UNKNOWN) + } +} + +@Serializable +data class PodChat( + @EncodeDefault val kind: String = "pod_chat", + val id: String, + val workspaceId: String, + val podId: String, + val title: String, + val createdAt: Instant, + val updatedAt: Instant, + val main: Boolean, + @EncodeDefault val archivedAt: Instant? = null, +) + +@Serializable +data class PodChatMarkers( + val pods: Map, +) { + @Serializable + data class Pod( + val unreadMessages: Long, + val needsApproval: Boolean, + val failedRoutines: Long, + ) +} + +@Serializable(with = PodColor.Serializer::class) +enum class PodColor(override val rawValue: String) : OpenEnum { + GREEN("green"), + BLUE("blue"), + PLUM("plum"), + AMBER("amber"), + TEAL("teal"), + PURPLE("purple"), + ROSE("rose"), + ORANGE("orange"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.PodColor", entries, UNKNOWN) +} + +@Serializable +data class PodMember( + val userId: String, + val name: String, + val email: String, + @EncodeDefault val image: String? = null, + val addedAt: Instant, + val removable: Boolean, +) + +@Serializable +data class PodPermissions( + val rename: Boolean, + val manageMembers: Boolean, + val leave: Boolean, + val createAgents: Boolean, + val updateAgents: Boolean, + val deleteAgents: Boolean, + val manageConnections: Boolean, + val manageSandbox: Boolean, + val useDesktops: Boolean, + val manageRoutines: Boolean, + val runRoutines: Boolean, + val deleteArtifacts: Boolean, +) + +@Serializable +data class PodSandbox( + val sandbox: PodSandboxState, + val providerEnabled: Boolean, + val canManage: Boolean, +) + +@Serializable +data class PodSandboxDisk( + val podId: String, + val disk: SandboxDisk, +) + +@Serializable +data class PodSandboxNetwork( + val mode: SandboxNetworkMode, + val blocking: Boolean, + val workspaceHosts: List, + val addedHosts: List, +) { + @Serializable + data class WorkspaceHost( + val host: String, + @EncodeDefault val blockedBy: String? = null, + ) + + @Serializable + data class AddedHost( + val host: String, + @EncodeDefault val addedByName: String? = null, + val addedAt: Instant, + @EncodeDefault val blockedBy: String? = null, + ) +} + +@Serializable(with = PodSandboxState.Serializer::class) +sealed interface PodSandboxState { + @Serializable + data class NoneState( + @EncodeDefault val kind: String = "none", + ) : PodSandboxState + + @Serializable + data class Present( + @EncodeDefault val kind: String = "present", + val state: State, + @EncodeDefault val image: String? = null, + val providerName: String, + val createdAt: Instant, + val lastUsedAt: Instant, + val turnsUsing: Long, + val peopleWatching: Long, + val upgradeAvailable: Boolean, + @EncodeDefault val disk: SandboxDisk? = null, + ) : PodSandboxState { + @Serializable(with = State.Serializer::class) + enum class State(override val rawValue: String) : OpenEnum { + RUNNING("running"), + PAUSED("paused"), + LOST("lost"), + UNREACHABLE("unreachable"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.PodSandboxState.Present.State", entries, UNKNOWN) + } + } + + /** A kind from a newer server than this app knows, by its `kind`, which can't be sent. */ + data class Unknown(val tag: String) : PodSandboxState + + object Serializer : JsonUnionSerializer("ai.sugabots.api.PodSandboxState") { + override fun decode(element: JsonElement, json: Json): PodSandboxState = + when (val tag = tagOf(element, "kind")) { + "none" -> json.decodeFromJsonElement(element) + "present" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: PodSandboxState, json: Json): JsonElement = + when (value) { + is NoneState -> json.encodeToJsonElement(value) + is Present -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class PodUpdate( + val name: String? = null, + val slug: Omittable = Omittable.Omitted, + val color: Omittable = Omittable.Omitted, +) + +@Serializable +data class PodUsage( + val podId: String, + @EncodeDefault val name: String? = null, + @EncodeDefault val color: PodColor? = null, + val botCount: Long, + val usd: Double, + val unpricedRequests: Long, +) + +@Serializable +data class Presence( + val clientId: String, + @EncodeDefault val conversationId: String? = null, + val sequence: Long, +) + +@Serializable(with = ProviderApiFormat.Serializer::class) +enum class ProviderApiFormat(override val rawValue: String) : OpenEnum { + OPENAI("openai"), + ANTHROPIC("anthropic"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ProviderApiFormat", entries, UNKNOWN) +} + +@Serializable +data class ProviderFetchResult( + val added: Long, + val updated: Long, + val unchanged: Long, +) + +@Serializable +data class ProviderHeader( + val name: String, + val value: String, +) + +@Serializable +data class ProviderModel( + val id: String, + val modelId: String, + @EncodeDefault val displayName: String? = null, + val capabilities: List, + val disabledCapabilities: List, + @EncodeDefault val contextLength: Long? = null, + val enabled: Boolean, + val source: Source, +) { + @Serializable(with = Source.Serializer::class) + enum class Source(override val rawValue: String) : OpenEnum { + FETCHED("fetched"), + MANUAL("manual"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ProviderModel.Source", entries, UNKNOWN) + } +} + +@Serializable(with = ProviderModelCapability.Serializer::class) +enum class ProviderModelCapability(override val rawValue: String) : OpenEnum { + TOOLS("tools"), + VISION("vision"), + IMAGES("images"), + AUDIO("audio"), + EMBEDDINGS("embeddings"), + REASONING("reasoning"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ProviderModelCapability", entries, UNKNOWN) +} + +@Serializable +data class ProviderModelSwitchOff( + val moveBotsTo: String? = null, + val newBotsTo: String? = null, + val summariesTo: String? = null, +) + +@Serializable +data class ProviderModelUpdate( + val enabled: Boolean? = null, + val disabledCapabilities: List? = null, + val capabilities: List? = null, +) + +@Serializable(with = ProviderPresetId.Serializer::class) +enum class ProviderPresetId(override val rawValue: String) : OpenEnum { + ANTHROPIC("anthropic"), + OPENAI("openai"), + CHATGPT("chatgpt"), + OPENROUTER("openrouter"), + GEMINI("gemini"), + GROQ("groq"), + XAI("xai"), + SUPERGROK("supergrok"), + MISTRAL("mistral"), + DEEPSEEK("deepseek"), + TOGETHER("together"), + FIREWORKS("fireworks"), + CEREBRAS("cerebras"), + OLLAMA("ollama"), + LMSTUDIO("lmstudio"), + LLAMACPP("llamacpp"), + VLLM("vllm"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ProviderPresetId", entries, UNKNOWN) +} + +@Serializable +data class ProviderSignInCompletion( + val attempt: String, +) + +@Serializable(with = ProviderSignInOutcome.Serializer::class) +sealed interface ProviderSignInOutcome { + @Serializable + data class Pending( + @EncodeDefault val status: String = "pending", + ) : ProviderSignInOutcome + + @Serializable + data class SignedIn( + @EncodeDefault val status: String = "signed_in", + val provider: ModelProvider, + ) : ProviderSignInOutcome + + /** A kind from a newer server than this app knows, by its `status`, which can't be sent. */ + data class Unknown(val tag: String) : ProviderSignInOutcome + + object Serializer : JsonUnionSerializer("ai.sugabots.api.ProviderSignInOutcome") { + override fun decode(element: JsonElement, json: Json): ProviderSignInOutcome = + when (val tag = tagOf(element, "status")) { + "pending" -> json.decodeFromJsonElement(element) + "signed_in" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: ProviderSignInOutcome, json: Json): JsonElement = + when (value) { + is Pending -> json.encodeToJsonElement(value) + is SignedIn -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class ProviderSignInStarted( + val verificationUrl: String, + val userCode: String, + val attempt: String, + val pollIntervalMs: Long, + val expiresAt: Instant, +) + +@Serializable(with = ProviderStatus.Serializer::class) +enum class ProviderStatus(override val rawValue: String) : OpenEnum { + MISSING_KEY("missing_key"), + SIGNED_OUT("signed_out"), + UNTESTED("untested"), + CONNECTED("connected"), + ERROR("error"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ProviderStatus", entries, UNKNOWN) +} + +@Serializable +data class ProviderSwitchOff( + val moveBots: List, + val newBotsTo: String? = null, + val summariesTo: String? = null, +) + +@Serializable +data class ProviderTestResult( + val reachable: Boolean, + val latencyMs: Long, + val error: String? = null, +) + +@Serializable +data class QuietHours( + val from: String, + val to: String, + val timeZone: String, +) + +@Serializable +data class ReferralLink( + @EncodeDefault val url: String? = null, +) + +@Serializable(with = RepositoryEvent.Serializer::class) +enum class RepositoryEvent(override val rawValue: String) : OpenEnum { + PULL_REQUEST_OPENED("pull_request_opened"), + PULL_REQUEST_REVIEW("pull_request_review"), + PULL_REQUEST_COMMENT("pull_request_comment"), + ISSUE_OPENED("issue_opened"), + ISSUE_COMMENT("issue_comment"), + CHECKS_FAILED("checks_failed"), + PUSH("push"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.RepositoryEvent", entries, UNKNOWN) +} + +@Serializable +data class ResetReferralLink( + val url: String, +) + +@Serializable +data class Routine( + val id: String, + val workspaceId: String, + val agentId: String, + val name: String, + val instructions: String, + val triggers: List, + val state: RoutineState, + val results: RoutineResults, + @EncodeDefault val chatId: String? = null, + @EncodeDefault val createdById: String? = null, + @EncodeDefault val createdByAgentId: String? = null, + val createdAt: Instant, + val updatedAt: Instant, +) + +@Serializable(with = RoutineCurrentSecret.Serializer::class) +sealed interface RoutineCurrentSecret { + @Serializable + data class SetSecret( + @EncodeDefault val kind: String = "set", + val secret: String, + ) : RoutineCurrentSecret + + @Serializable + data class NoneSecret( + @EncodeDefault val kind: String = "none", + ) : RoutineCurrentSecret + + @Serializable + data class Hashed( + @EncodeDefault val kind: String = "hashed", + ) : RoutineCurrentSecret + + /** A kind from a newer server than this app knows, by its `kind`, which can't be sent. */ + data class Unknown(val tag: String) : RoutineCurrentSecret + + object Serializer : JsonUnionSerializer("ai.sugabots.api.RoutineCurrentSecret") { + override fun decode(element: JsonElement, json: Json): RoutineCurrentSecret = + when (val tag = tagOf(element, "kind")) { + "set" -> json.decodeFromJsonElement(element) + "none" -> json.decodeFromJsonElement(element) + "hashed" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: RoutineCurrentSecret, json: Json): JsonElement = + when (value) { + is SetSecret -> json.encodeToJsonElement(value) + is NoneSecret -> json.encodeToJsonElement(value) + is Hashed -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class RoutineExecution( + val id: String, + val routineId: String, + val workspaceId: String, + val agentId: String, + val threadId: String, + val conversationId: String, + val routineName: String, + val instructions: String, + val trigger: RoutineExecutionTrigger, + val state: RoutineExecutionState, + @EncodeDefault val error: String? = null, + val acceptedAt: Instant, + @EncodeDefault val startedAt: Instant? = null, + @EncodeDefault val finishedAt: Instant? = null, +) + +@Serializable +data class RoutineExecutionPage( + val items: List, + @EncodeDefault val nextCursor: String? = null, +) + +@Serializable(with = RoutineExecutionState.Serializer::class) +enum class RoutineExecutionState(override val rawValue: String) : OpenEnum { + QUEUED("queued"), + RUNNING("running"), + COMPLETED("completed"), + FAILED("failed"), + CANCELLED("cancelled"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.RoutineExecutionState", entries, UNKNOWN) +} + +@Serializable +data class RoutineExecutionSummary( + val executionId: String, + val routineId: String, + val routineName: String, + val triggerKind: RoutineExecutionTriggerKind, + val triggeredAt: Instant, +) + +@Serializable(with = RoutineExecutionTrigger.Serializer::class) +sealed interface RoutineExecutionTrigger { + @Serializable + data class Cron( + @EncodeDefault val kind: String = "cron", + val scheduledAt: Instant, + val acceptedAt: Instant, + ) : RoutineExecutionTrigger + + @Serializable + data class Webhook( + @EncodeDefault val kind: String = "webhook", + val receivedAt: Instant, + @EncodeDefault val idempotencyKey: String? = null, + val payload: JsonElement, + ) : RoutineExecutionTrigger + + @Serializable + data class Github( + @EncodeDefault val kind: String = "github", + val connectionId: String, + val receivedAt: Instant, + val deliveryId: String, + val event: RepositoryEvent, + val repository: String, + val sender: String, + val url: String, + @EncodeDefault val number: Long? = null, + @EncodeDefault val title: String? = null, + @EncodeDefault val text: String? = null, + @EncodeDefault val branch: String? = null, + val comment: Comment? = null, + ) : RoutineExecutionTrigger { + @Serializable + data class Comment( + val id: Long, + val kind: Kind, + ) { + @Serializable(with = Kind.Serializer::class) + enum class Kind(override val rawValue: String) : OpenEnum { + COMMENT("comment"), + CODE_COMMENT("code_comment"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.RoutineExecutionTrigger.Github.Comment.Kind", entries, UNKNOWN) + } + } + } + + @Serializable + data class Manual( + @EncodeDefault val kind: String = "manual", + val requestedAt: Instant, + val requestedByUserId: String, + val requestId: String, + ) : RoutineExecutionTrigger + + /** A kind from a newer server than this app knows, by its `kind`, which can't be sent. */ + data class Unknown(val tag: String) : RoutineExecutionTrigger + + object Serializer : JsonUnionSerializer("ai.sugabots.api.RoutineExecutionTrigger") { + override fun decode(element: JsonElement, json: Json): RoutineExecutionTrigger = + when (val tag = tagOf(element, "kind")) { + "cron" -> json.decodeFromJsonElement(element) + "webhook" -> json.decodeFromJsonElement(element) + "github" -> json.decodeFromJsonElement(element) + "manual" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: RoutineExecutionTrigger, json: Json): JsonElement = + when (value) { + is Cron -> json.encodeToJsonElement(value) + is Webhook -> json.encodeToJsonElement(value) + is Github -> json.encodeToJsonElement(value) + is Manual -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable(with = RoutineExecutionTriggerKind.Serializer::class) +enum class RoutineExecutionTriggerKind(override val rawValue: String) : OpenEnum { + CRON("cron"), + WEBHOOK("webhook"), + GITHUB("github"), + MANUAL("manual"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.RoutineExecutionTriggerKind", entries, UNKNOWN) +} + +@Serializable +data class RoutineFeed( + @EncodeDefault val kind: String = "routine_feed", + val id: String, + val workspaceId: String, + val podId: String, + val title: String, + val createdAt: Instant, + val updatedAt: Instant, + val hostAgentId: String, + val routineId: String, +) + +@Serializable +data class RoutineResultOf( + val executionId: String, + val threadId: String, + val routineId: String, + val routineName: String, +) + +@Serializable(with = RoutineResults.Serializer::class) +enum class RoutineResults(override val rawValue: String) : OpenEnum { + KEEP_IN_RUN("keep_in_run"), + POST_TO_CHAT("post_to_chat"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.RoutineResults", entries, UNKNOWN) +} + +@Serializable(with = RoutineRunNotifications.Serializer::class) +enum class RoutineRunNotifications(override val rawValue: String) : OpenEnum { + FAILURES("failures"), + ALL("all"), + NONE("none"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.RoutineRunNotifications", entries, UNKNOWN) +} + +@Serializable(with = RoutineSchedule.Serializer::class) +sealed interface RoutineSchedule { + @Serializable + data class Daily( + @EncodeDefault val repeat: String = "daily", + val every: Long, + val times: List, + val startsOn: String, + ) : RoutineSchedule + + @Serializable + data class Weekly( + @EncodeDefault val repeat: String = "weekly", + val every: Long, + val days: List, + val times: List, + val startsOn: String, + ) : RoutineSchedule + + @Serializable + data class Monthly( + @EncodeDefault val repeat: String = "monthly", + val every: Long, + val dayOfMonth: DayOfMonth, + val times: List, + val startsOn: String, + ) : RoutineSchedule { + @Serializable(with = DayOfMonth.Serializer::class) + sealed interface DayOfMonth { + data object Last : DayOfMonth + + data class Integer(val value: Long) : DayOfMonth + + object Serializer : JsonUnionSerializer("ai.sugabots.api.RoutineSchedule.Monthly.DayOfMonth") { + override fun decode(element: JsonElement, json: Json): DayOfMonth { + if (element.isString("last")) return Last + json.decodeOrNull(element)?.let { return Integer(it) } + throw SerializationException("None of DayOfMonth's kinds.") + } + + override fun encode(value: DayOfMonth, json: Json): JsonElement = + when (value) { + is Last -> JsonPrimitive("last") + is Integer -> json.encodeToJsonElement(value.value) + } + } + } + } + + @Serializable + data class Cron( + @EncodeDefault val repeat: String = "cron", + val expression: String, + ) : RoutineSchedule + + /** A kind from a newer server than this app knows, by its `repeat`, which can't be sent. */ + data class Unknown(val tag: String) : RoutineSchedule + + object Serializer : JsonUnionSerializer("ai.sugabots.api.RoutineSchedule") { + override fun decode(element: JsonElement, json: Json): RoutineSchedule = + when (val tag = tagOf(element, "repeat")) { + "daily" -> json.decodeFromJsonElement(element) + "weekly" -> json.decodeFromJsonElement(element) + "monthly" -> json.decodeFromJsonElement(element) + "cron" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: RoutineSchedule, json: Json): JsonElement = + when (value) { + is Daily -> json.encodeToJsonElement(value) + is Weekly -> json.encodeToJsonElement(value) + is Monthly -> json.encodeToJsonElement(value) + is Cron -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +typealias RoutineScheduleOccurrences = List + +@Serializable +data class RoutineSchedulePreview( + val schedule: RoutineSchedule, + val timezone: String, +) + +@Serializable +data class RoutineSecret( + @EncodeDefault val secret: String? = null, +) + +@Serializable +data class RoutineSecretReplacement( + val secret: Omittable = Omittable.Omitted, +) + +@Serializable(with = RoutineState.Serializer::class) +enum class RoutineState(override val rawValue: String) : OpenEnum { + ENABLED("enabled"), + PAUSED("paused"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.RoutineState", entries, UNKNOWN) +} + +@Serializable(with = RoutineTrigger.Serializer::class) +sealed interface RoutineTrigger { + @Serializable + data class Cron( + val id: String, + @EncodeDefault val kind: String = "cron", + val schedule: RoutineSchedule, + val timezone: String, + @EncodeDefault val nextScheduledAt: Instant? = null, + ) : RoutineTrigger + + @Serializable + data class Webhook( + val id: String, + @EncodeDefault val kind: String = "webhook", + val auth: WebhookAuth, + val deliveryIdHeader: String? = null, + val filter: List? = null, + ) : RoutineTrigger + + @Serializable + data class Github( + val id: String, + @EncodeDefault val kind: String = "github", + val connectionId: String, + val repository: String, + val events: List, + ) : RoutineTrigger + + /** A kind from a newer server than this app knows, by its `kind`, which can't be sent. */ + data class Unknown(val tag: String) : RoutineTrigger + + object Serializer : JsonUnionSerializer("ai.sugabots.api.RoutineTrigger") { + override fun decode(element: JsonElement, json: Json): RoutineTrigger = + when (val tag = tagOf(element, "kind")) { + "cron" -> json.decodeFromJsonElement(element) + "webhook" -> json.decodeFromJsonElement(element) + "github" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: RoutineTrigger, json: Json): JsonElement = + when (value) { + is Cron -> json.encodeToJsonElement(value) + is Webhook -> json.encodeToJsonElement(value) + is Github -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class RoutineTriggerAuthor( + @EncodeDefault val kind: String = "routine_trigger", + val executionId: String, + val routineName: String, + val triggerKind: RoutineExecutionTriggerKind, +) + +@Serializable(with = RoutineTriggerInput.Serializer::class) +sealed interface RoutineTriggerInput { + @Serializable + data class Cron( + @EncodeDefault val kind: String = "cron", + val schedule: RoutineSchedule, + val timezone: String, + ) : RoutineTriggerInput + + @Serializable + data class Webhook( + @EncodeDefault val kind: String = "webhook", + val auth: WebhookAuth? = null, + val deliveryIdHeader: Omittable = Omittable.Omitted, + val filter: List? = null, + val secret: Omittable = Omittable.Omitted, + val schedule: JsonElement? = null, + val timezone: JsonElement? = null, + ) : RoutineTriggerInput + + @Serializable + data class Github( + @EncodeDefault val kind: String = "github", + val connectionId: String, + val repository: String, + val events: List, + ) : RoutineTriggerInput + + /** A kind from a newer server than this app knows, by its `kind`, which can't be sent. */ + data class Unknown(val tag: String) : RoutineTriggerInput + + object Serializer : JsonUnionSerializer("ai.sugabots.api.RoutineTriggerInput") { + override fun decode(element: JsonElement, json: Json): RoutineTriggerInput = + when (val tag = tagOf(element, "kind")) { + "cron" -> json.decodeFromJsonElement(element) + "webhook" -> json.decodeFromJsonElement(element) + "github" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: RoutineTriggerInput, json: Json): JsonElement = + when (value) { + is Cron -> json.encodeToJsonElement(value) + is Webhook -> json.encodeToJsonElement(value) + is Github -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class RoutineUpdate( + val name: String? = null, + val instructions: String? = null, + val state: RoutineState? = null, + val results: RoutineResults? = null, + val chatId: Omittable = Omittable.Omitted, +) + +@Serializable +data class RoutineWebhookChallenge( + val challenge: String, +) + +@Serializable +data class RoutineWriteResult( + val routine: Routine, + val secrets: List, +) { + @Serializable + data class Secret( + val triggerId: String, + val secret: String, + ) +} + +@Serializable +data class SandboxAccess( + val enabled: Boolean, +) + +@Serializable +data class SandboxAddedHost( + val host: String, + @EncodeDefault val addedByName: String? = null, + val addedAt: Instant, +) + +@Serializable +data class SandboxBlockedHost( + val host: String, + @EncodeDefault val blockedByName: String? = null, + val blockedAt: Instant, +) + +@Serializable +data class SandboxDisk( + val usedBytes: Long, + val totalBytes: Long, + val measuredAt: Instant, + @EncodeDefault val folders: List? = null, +) + +@Serializable(with = SandboxDiskFolder.Serializer::class) +sealed interface SandboxDiskFolder { + @Serializable + data class Home( + @EncodeDefault val kind: String = "home", + val agentId: String, + val bytes: Long, + ) : SandboxDiskFolder + + @Serializable + data class Threads( + @EncodeDefault val kind: String = "threads", + val bytes: Long, + ) : SandboxDiskFolder + + @Serializable + data class Temporary( + @EncodeDefault val kind: String = "temporary", + val bytes: Long, + ) : SandboxDiskFolder + + /** A kind from a newer server than this app knows, by its `kind`, which can't be sent. */ + data class Unknown(val tag: String) : SandboxDiskFolder + + object Serializer : JsonUnionSerializer("ai.sugabots.api.SandboxDiskFolder") { + override fun decode(element: JsonElement, json: Json): SandboxDiskFolder = + when (val tag = tagOf(element, "kind")) { + "home" -> json.decodeFromJsonElement(element) + "threads" -> json.decodeFromJsonElement(element) + "temporary" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: SandboxDiskFolder, json: Json): JsonElement = + when (value) { + is Home -> json.encodeToJsonElement(value) + is Threads -> json.encodeToJsonElement(value) + is Temporary -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable(with = SandboxNetworkMode.Serializer::class) +enum class SandboxNetworkMode(override val rawValue: String) : OpenEnum { + ALLOWLIST("allowlist"), + OPEN("open"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.SandboxNetworkMode", entries, UNKNOWN) +} + +@Serializable +data class SandboxNetworkSettings( + val mode: SandboxNetworkMode, + val blocking: Boolean, + val trustedHosts: List, + val addedHosts: List, + val blockedHosts: List, +) + +@Serializable +data class SandboxProvider( + val id: String, + val workspaceId: String, + val preset: SandboxProviderPresetId, + val name: String, + val settings: SandboxProviderSettings, + val enabled: Boolean, + val status: ProviderStatus, + val hasApiKey: Boolean, + @EncodeDefault val lastTestedAt: Instant? = null, + @EncodeDefault val lastTestError: String? = null, + val createdAt: Instant, +) + +@Serializable(with = SandboxProviderPresetId.Serializer::class) +enum class SandboxProviderPresetId(override val rawValue: String) : OpenEnum { + OPENSANDBOX("opensandbox"), + E2B("e2b"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.SandboxProviderPresetId", entries, UNKNOWN) +} + +@Serializable(with = SandboxProviderSettings.Serializer::class) +sealed interface SandboxProviderSettings { + @Serializable + data class Opensandbox( + @EncodeDefault val preset: String = "opensandbox", + val serverUrl: String? = null, + val image: String? = null, + val cpuCount: Long? = null, + val memoryGiB: Long? = null, + val networkMode: SandboxNetworkMode? = null, + ) : SandboxProviderSettings + + @Serializable + data class E2b( + @EncodeDefault val preset: String = "e2b", + val apiUrl: String? = null, + val sandboxUrl: String? = null, + val template: String? = null, + val cpuCount: Long? = null, + val memoryGiB: Long? = null, + val networkMode: SandboxNetworkMode? = null, + ) : SandboxProviderSettings + + /** A kind from a newer server than this app knows, by its `preset`, which can't be sent. */ + data class Unknown(val tag: String) : SandboxProviderSettings + + object Serializer : JsonUnionSerializer("ai.sugabots.api.SandboxProviderSettings") { + override fun decode(element: JsonElement, json: Json): SandboxProviderSettings = + when (val tag = tagOf(element, "preset")) { + "opensandbox" -> json.decodeFromJsonElement(element) + "e2b" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: SandboxProviderSettings, json: Json): JsonElement = + when (value) { + is Opensandbox -> json.encodeToJsonElement(value) + is E2b -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class SandboxProviderTestResult( + val reachable: Boolean, + val latencyMs: Long, + val error: String? = null, +) + +@Serializable +data class SandboxProviderUpdate( + val enabled: Boolean? = null, + val apiKey: Omittable = Omittable.Omitted, + val settings: SandboxProviderSettings? = null, +) + +@Serializable +data class SandboxTemplate( + @EncodeDefault val state: State? = null, +) { + @Serializable(with = State.Serializer::class) + enum class State(override val rawValue: String) : OpenEnum { + MISSING("missing"), + BUILDING("building"), + READY("ready"), + FAILED("failed"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.SandboxTemplate.State", entries, UNKNOWN) + } +} + +@Serializable +data class SearchProvider( + val id: String, + val workspaceId: String, + val preset: SearchProviderPresetId, + val name: String, + val baseUrl: String, + val enabled: Boolean, + val status: ProviderStatus, + val hasApiKey: Boolean, + @EncodeDefault val lastTestedAt: Instant? = null, + @EncodeDefault val lastTestError: String? = null, + val createdAt: Instant, +) + +@Serializable(with = SearchProviderPresetId.Serializer::class) +enum class SearchProviderPresetId(override val rawValue: String) : OpenEnum { + BRAVE("brave"), + EXA("exa"), + TAVILY("tavily"), + SEARXNG("searxng"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.SearchProviderPresetId", entries, UNKNOWN) +} + +@Serializable +data class SearchProviderResponse( + @EncodeDefault val provider: SearchProvider? = null, +) + +@Serializable +data class SearchProviderTestResult( + val reachable: Boolean, + val latencyMs: Long, + val results: Long? = null, + val error: String? = null, +) + +@Serializable +data class SearchProviderUpdate( + val enabled: Boolean? = null, + val baseUrl: String? = null, + val apiKey: Omittable = Omittable.Omitted, +) + +@Serializable +data class SessionUser( + val id: String, + val email: String, + val name: String, + @EncodeDefault val image: String? = null, +) + +@Serializable +data class StartedThread( + val conversation: ConversationThread, + val message: Message, +) + +@Serializable +data class SystemAgent( + val key: SystemAgentKey, + val name: String, + @EncodeDefault val description: String? = null, + val color: AgentColor, + val face: AgentFace, + val shape: AgentShape, + @EncodeDefault val model: String? = null, +) + +@Serializable(with = SystemAgentKey.Serializer::class) +enum class SystemAgentKey(override val rawValue: String) : OpenEnum { + SUMMARISE("summarise"), + COMPACT("compact"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.SystemAgentKey", entries, UNKNOWN) +} + +@Serializable +data class SystemAgentUpdate( + val model: String, +) + +@Serializable +data class TextPart( + @EncodeDefault val type: String = "text", + val text: String, +) + +@Serializable +data class Thread( + val id: String, + val workspaceId: String, + val podId: String, + @EncodeDefault val hostAgentId: String? = null, + @EncodeDefault val conversationId: String? = null, + val type: ThreadType, + val title: String, + val status: Status, + @EncodeDefault val parentThreadId: String? = null, + @EncodeDefault val doneAt: Instant? = null, + @EncodeDefault val initiatorUserId: String? = null, + val createdAt: Instant, + val updatedAt: Instant, +) { + @Serializable(with = Status.Serializer::class) + enum class Status(override val rawValue: String) : OpenEnum { + RUNNING("running"), + DONE("done"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.Thread.Status", entries, UNKNOWN) + } +} + +@Serializable +data class ThreadActivity( + @EncodeDefault val summary: ThreadSummary? = null, + @EncodeDefault val context: ThreadContext? = null, + val recentParticipants: List, +) + +@Serializable +data class ThreadContext( + val usedTokens: Long, + val measuredAt: Instant, + val windowTokens: Long, + val compactionLineTokens: Long, + @EncodeDefault val compactedAt: Instant? = null, +) + +@Serializable +data class ThreadDetails( + val thread: Thread, + val capabilities: Capabilities? = null, + @EncodeDefault val routineExecution: RoutineExecution? = null, + val routine: Routine? = null, + @EncodeDefault val startedFrom: Message? = null, + val participants: List, + val crew: List, + val members: List, + val messages: List, + @EncodeDefault val olderMessagesCursor: String? = null, + @EncodeDefault val queuedSince: Instant? = null, + val reads: List, +) { + @Serializable + data class Capabilities( + val approveToolCalls: Boolean, + val approveSandboxRequests: Boolean? = null, + ) + + @Serializable + data class Routine( + val id: String, + val agentId: String, + val state: RoutineState, + val failed: Boolean, + val pausedAfterFailures: Boolean, + ) +} + +@Serializable(with = ThreadParticipant.Serializer::class) +sealed interface ThreadParticipant { + data class Person(val value: PersonParticipant) : ThreadParticipant + + data class Agent(val value: AgentParticipant) : ThreadParticipant + + /** A kind from a newer server than this app knows, by its `kind`, which can't be sent. */ + data class Unknown(val tag: String) : ThreadParticipant + + object Serializer : JsonUnionSerializer("ai.sugabots.api.ThreadParticipant") { + override fun decode(element: JsonElement, json: Json): ThreadParticipant = + when (val tag = tagOf(element, "kind")) { + "person" -> Person(json.decodeFromJsonElement(element)) + "agent" -> Agent(json.decodeFromJsonElement(element)) + else -> Unknown(tag) + } + + override fun encode(value: ThreadParticipant, json: Json): JsonElement = + when (value) { + is Person -> json.encodeToJsonElement(value.value) + is Agent -> json.encodeToJsonElement(value.value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class ThreadRead( + val person: PersonParticipant, + val readThrough: Instant, + val readAt: Instant, +) + +@Serializable +data class ThreadSummary( + val content: String, + val sourceMessageId: String, + val updatedAt: Instant, +) + +@Serializable(with = ThreadType.Serializer::class) +enum class ThreadType(override val rawValue: String) : OpenEnum { + CONVERSATION("conversation"), + POD_CHAT("pod_chat"), + BOT_CHANNEL("bot_channel"), + COLLABORATION("collaboration"), + ROUTINE("routine"), + ROUTINE_FEED("routine_feed"), + SYSTEM_AGENT("system_agent"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ThreadType", entries, UNKNOWN) +} + +@Serializable(with = ThreadUpdateEvent.Serializer::class) +sealed interface ThreadUpdateEvent { + @Serializable + data class MessageCreated( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "message.created", + val threadId: String, + val message: Message, + ) : ThreadUpdateEvent + + @Serializable + data class MessageDelta( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "message.delta", + val threadId: String, + val messageId: String, + val offset: Long, + val text: String, + ) : ThreadUpdateEvent + + @Serializable + data class MessageCompleted( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "message.completed", + val threadId: String, + val messageId: String, + val content: String, + val status: MessageStatus, + ) : ThreadUpdateEvent + + @Serializable + data class MessageFailed( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "message.failed", + val threadId: String, + val messageId: String, + val turnId: String, + val willRetry: Boolean, + val error: String, + ) : ThreadUpdateEvent + + @Serializable + data class MessageReactionsChanged( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "message.reactions_changed", + val threadId: String, + val messageId: String, + val reactions: MessageReactions, + ) : ThreadUpdateEvent + + @Serializable + data class MessageFilesChanged( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "message.files_changed", + val threadId: String, + val messageId: String, + val files: List, + ) : ThreadUpdateEvent + + @Serializable + data class ToolCallStarted( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "tool_call.started", + val threadId: String, + val messageId: String, + val toolCall: ToolCallPart, + ) : ThreadUpdateEvent + + @Serializable + data class ToolCallCompleted( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "tool_call.completed", + val threadId: String, + val messageId: String, + val toolCall: ToolCallPart, + ) : ThreadUpdateEvent + + @Serializable + data class ToolCallUpdated( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "tool_call.updated", + val threadId: String, + val messageId: String, + val toolCall: ToolCallPart, + ) : ThreadUpdateEvent + + @Serializable + data class TurnStarted( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "turn.started", + val threadId: String, + val turnId: String, + val agentId: String, + ) : ThreadUpdateEvent + + @Serializable + data class TurnCancelRequested( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "turn.cancel_requested", + val threadId: String, + val turnId: String, + ) : ThreadUpdateEvent + + @Serializable + data class TurnCompleted( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "turn.completed", + val threadId: String, + val turnId: String, + val status: Status, + ) : ThreadUpdateEvent { + @Serializable(with = Status.Serializer::class) + enum class Status(override val rawValue: String) : OpenEnum { + DONE("done"), + CANCELLED("cancelled"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ThreadUpdateEvent.TurnCompleted.Status", entries, UNKNOWN) + } + } + + @Serializable + data class ThreadChanged( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "thread.changed", + val threadId: String, + ) : ThreadUpdateEvent + + @Serializable + data class ThreadNotice( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "thread.notice", + val threadId: String, + val notice: String, + ) : ThreadUpdateEvent + + @Serializable + data class ThreadRead( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "thread.read", + val threadId: String, + val person: PersonParticipant, + val readThrough: Instant, + val readAt: Instant, + ) : ThreadUpdateEvent + + @Serializable + data class PersonTyping( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "person.typing", + val threadId: String, + val person: PersonParticipant, + ) : ThreadUpdateEvent + + @Serializable + data class ConversationThreadChanged( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "conversation.thread_changed", + val conversationId: String, + val threadId: String, + ) : ThreadUpdateEvent + + @Serializable + data class CollaborationUpdated( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "collaboration.updated", + val threadId: String, + val messageId: String, + val collaboration: CollaborationPart, + ) : ThreadUpdateEvent + + @Serializable + data class Reset( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "reset", + ) : ThreadUpdateEvent + + /** A kind from a newer server than this app knows, by its `type`, which can't be sent. */ + data class Unknown(val tag: String) : ThreadUpdateEvent + + object Serializer : JsonUnionSerializer("ai.sugabots.api.ThreadUpdateEvent") { + override fun decode(element: JsonElement, json: Json): ThreadUpdateEvent = + when (val tag = tagOf(element, "type")) { + "message.created" -> json.decodeFromJsonElement(element) + "message.delta" -> json.decodeFromJsonElement(element) + "message.completed" -> json.decodeFromJsonElement(element) + "message.failed" -> json.decodeFromJsonElement(element) + "message.reactions_changed" -> json.decodeFromJsonElement(element) + "message.files_changed" -> json.decodeFromJsonElement(element) + "tool_call.started" -> json.decodeFromJsonElement(element) + "tool_call.completed" -> json.decodeFromJsonElement(element) + "tool_call.updated" -> json.decodeFromJsonElement(element) + "turn.started" -> json.decodeFromJsonElement(element) + "turn.cancel_requested" -> json.decodeFromJsonElement(element) + "turn.completed" -> json.decodeFromJsonElement(element) + "thread.changed" -> json.decodeFromJsonElement(element) + "thread.notice" -> json.decodeFromJsonElement(element) + "thread.read" -> json.decodeFromJsonElement(element) + "person.typing" -> json.decodeFromJsonElement(element) + "conversation.thread_changed" -> json.decodeFromJsonElement(element) + "collaboration.updated" -> json.decodeFromJsonElement(element) + "reset" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: ThreadUpdateEvent, json: Json): JsonElement = + when (value) { + is MessageCreated -> json.encodeToJsonElement(value) + is MessageDelta -> json.encodeToJsonElement(value) + is MessageCompleted -> json.encodeToJsonElement(value) + is MessageFailed -> json.encodeToJsonElement(value) + is MessageReactionsChanged -> json.encodeToJsonElement(value) + is MessageFilesChanged -> json.encodeToJsonElement(value) + is ToolCallStarted -> json.encodeToJsonElement(value) + is ToolCallCompleted -> json.encodeToJsonElement(value) + is ToolCallUpdated -> json.encodeToJsonElement(value) + is TurnStarted -> json.encodeToJsonElement(value) + is TurnCancelRequested -> json.encodeToJsonElement(value) + is TurnCompleted -> json.encodeToJsonElement(value) + is ThreadChanged -> json.encodeToJsonElement(value) + is ThreadNotice -> json.encodeToJsonElement(value) + is ThreadRead -> json.encodeToJsonElement(value) + is PersonTyping -> json.encodeToJsonElement(value) + is ConversationThreadChanged -> json.encodeToJsonElement(value) + is CollaborationUpdated -> json.encodeToJsonElement(value) + is Reset -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class ToolAccessCounts( + val allow: Long, + val ask: Long, + val off: Long, +) + +@Serializable(with = ToolApprovalDeciders.Serializer::class) +enum class ToolApprovalDeciders(override val rawValue: String) : OpenEnum { + POD("pod"), + SANDBOX_MANAGERS("sandbox-managers"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ToolApprovalDeciders", entries, UNKNOWN) +} + +@Serializable +data class ToolApprovalDecision( + val decision: Decision, +) { + @Serializable(with = Decision.Serializer::class) + enum class Decision(override val rawValue: String) : OpenEnum { + ALLOW_ONCE("allow_once"), + DENY("deny"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ToolApprovalDecision.Decision", entries, UNKNOWN) + } +} + +@Serializable(with = ToolApprovalStatus.Serializer::class) +enum class ToolApprovalStatus(override val rawValue: String) : OpenEnum { + PENDING("pending"), + ALLOWED("allowed"), + DENIED("denied"), + AUTOMATIC("automatic"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ToolApprovalStatus", entries, UNKNOWN) +} + +@Serializable +data class ToolCallPart( + @EncodeDefault val type: String = "tool_call", + val id: String, + val tool: String, + val input: JsonElement, + @EncodeDefault val output: JsonElement? = null, + val status: ToolCallStatus, + val approval: Approval? = null, + @EncodeDefault val error: String? = null, + val mutating: Boolean, + val atOffset: Long, + val startedAt: Instant, + @EncodeDefault val finishedAt: Instant? = null, +) { + @Serializable + data class Approval( + val status: ToolApprovalStatus, + val deciders: ToolApprovalDeciders? = null, + @EncodeDefault val decidedByName: String? = null, + @EncodeDefault val decidedAt: Instant? = null, + ) +} + +@Serializable(with = ToolCallStatus.Serializer::class) +enum class ToolCallStatus(override val rawValue: String) : OpenEnum { + AWAITING_APPROVAL("awaiting_approval"), + RUNNING("running"), + COMPLETED("completed"), + FAILED("failed"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.ToolCallStatus", entries, UNKNOWN) +} + +@Serializable +data class TrialAccuracy( + val passed: Long, + val attempts: Long, + val share: Double, + val needed: Double, + val rating: TrialRating, +) + +@Serializable +data class TrialCaseResult( + val name: String, + val passed: Long, + val attempts: Long, + val example: String? = null, +) + +@Serializable(with = TrialRating.Serializer::class) +enum class TrialRating(override val rawValue: String) : OpenEnum { + EXCELLENT("excellent"), + GOOD("good"), + POOR("poor"), + TERRIBLE("terrible"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.TrialRating", entries, UNKNOWN) +} + +@Serializable +data class TrialSpeed( + val typicalMs: Double, + val slowestMs: Double, + val budgetMs: Double, + val rating: TrialRating, +) + +@Serializable +data class UnauthorizedEncoded( + @SerialName("_tag") @EncodeDefault val tag: String = "Unauthorized", + val message: String, + val details: JsonElement? = null, + val error: ErrorEncoded? = null, +) { + @Serializable + data class ErrorEncoded( + @SerialName("_tag") val tag: String, + val userMessage: String, + val isRetryable: Boolean, + val retryAfterMillis: @Serializable(with = NonFiniteDoubleSerializer::class) Double? = null, + ) +} + +@Serializable +data class UnsavedConnection( + val url: String, + val secretHeader: String? = null, + val secret: String? = null, +) + +@Serializable +data class UploadedAttachment( + val id: String, + val name: String, + val contentType: String, + val size: Long, +) + +@Serializable +data class UsageDay( + val date: String, + val usd: Double, +) + +@Serializable +data class WebAccess( + val enabled: Boolean, +) + +@Serializable(with = WebhookAuth.Serializer::class) +sealed interface WebhookAuth { + @Serializable + data class GithubOrStripeOrSlackOrLinear( + val kind: Kind, + ) : WebhookAuth { + @Serializable(with = Kind.Serializer::class) + enum class Kind(override val rawValue: String) : OpenEnum { + GITHUB("github"), + STRIPE("stripe"), + SLACK("slack"), + LINEAR("linear"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.WebhookAuth.GithubOrStripeOrSlackOrLinear.Kind", entries, UNKNOWN) + } + } + + @Serializable + data class Hmac( + @EncodeDefault val kind: String = "hmac", + val header: String, + val algorithm: WebhookHmacAlgorithm, + val encoding: WebhookSignatureEncoding, + ) : WebhookAuth + + @Serializable + data class ApiKey( + @EncodeDefault val kind: String = "api_key", + val header: String, + ) : WebhookAuth + + @Serializable + data class Bearer( + @EncodeDefault val kind: String = "bearer", + ) : WebhookAuth + + @Serializable + data class Basic( + @EncodeDefault val kind: String = "basic", + val username: String, + ) : WebhookAuth + + /** A kind from a newer server than this app knows, by its `kind`, which can't be sent. */ + data class Unknown(val tag: String) : WebhookAuth + + object Serializer : JsonUnionSerializer("ai.sugabots.api.WebhookAuth") { + override fun decode(element: JsonElement, json: Json): WebhookAuth = + when (val tag = tagOf(element, "kind")) { + "github", "stripe", "slack", "linear" -> json.decodeFromJsonElement(element) + "hmac" -> json.decodeFromJsonElement(element) + "api_key" -> json.decodeFromJsonElement(element) + "bearer" -> json.decodeFromJsonElement(element) + "basic" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: WebhookAuth, json: Json): JsonElement = + when (value) { + is GithubOrStripeOrSlackOrLinear -> json.encodeToJsonElement(value) + is Hmac -> json.encodeToJsonElement(value) + is ApiKey -> json.encodeToJsonElement(value) + is Bearer -> json.encodeToJsonElement(value) + is Basic -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class WebhookCondition( + val path: String, + val oneOf: List, +) + +@Serializable(with = WebhookHmacAlgorithm.Serializer::class) +enum class WebhookHmacAlgorithm(override val rawValue: String) : OpenEnum { + SHA1("sha1"), + SHA256("sha256"), + SHA512("sha512"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.WebhookHmacAlgorithm", entries, UNKNOWN) +} + +@Serializable(with = WebhookSignatureEncoding.Serializer::class) +enum class WebhookSignatureEncoding(override val rawValue: String) : OpenEnum { + HEX("hex"), + BASE64("base64"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.WebhookSignatureEncoding", entries, UNKNOWN) +} + +@Serializable(with = Weekday.Serializer::class) +enum class Weekday(override val rawValue: String) : OpenEnum { + MON("mon"), + TUE("tue"), + WED("wed"), + THU("thu"), + FRI("fri"), + SAT("sat"), + SUN("sun"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.Weekday", entries, UNKNOWN) +} + +@Serializable +data class Workspace( + val id: String, + val name: String, + val slug: String, + val timeZone: String, + @EncodeDefault val setupCompletedAt: Instant? = null, +) + +@Serializable +data class WorkspaceDetails( + val name: String, + val slug: String, +) + +@Serializable +data class WorkspaceInvitation( + val id: String, + val email: String, + val role: AssignableWorkspaceRole, + val expiresAt: Instant, + val sentAt: Instant, +) + +@Serializable +data class WorkspaceMember( + val id: String, + val role: WorkspaceRole, + val user: SessionUser, + val joinedAt: Instant, +) + +@Serializable +data class WorkspaceMemberUpdate( + val role: AssignableWorkspaceRole, +) + +@Serializable +data class WorkspaceModel( + val providerId: String, + val providerName: String, + @EncodeDefault val providerPreset: ProviderPresetId? = null, + val providerActive: Boolean, + val modelId: String, + @EncodeDefault val displayName: String? = null, + val capabilities: List, +) + +@Serializable +data class WorkspaceModelsResponse( + val models: List, + @EncodeDefault val defaultModel: String? = null, +) + +@Serializable +data class WorkspacePermissions( + val createPods: Boolean, + val updateWorkspace: Boolean, + val manageProviders: Boolean, + val manageMembers: Boolean, + val configureBuiltInAgents: Boolean, + val manageUsage: Boolean, + val manageAdmins: Boolean, + val transferOwnership: Boolean, + val deleteWorkspace: Boolean, +) + +@Serializable(with = WorkspaceRole.Serializer::class) +enum class WorkspaceRole(override val rawValue: String) : OpenEnum { + OWNER("owner"), + ADMIN("admin"), + MEMBER("member"), + VIEWER("viewer"), + + /** A value from a newer server than this app knows, which can't be sent. */ + UNKNOWN(""); + + object Serializer : OpenEnumSerializer("ai.sugabots.api.WorkspaceRole", entries, UNKNOWN) +} + +@Serializable +data class WorkspaceRoutine( + val routine: Routine, + val agent: Agent, + val pod: Pod, +) { + @Serializable + data class Pod( + val id: String, + val slug: String, + ) +} + +@Serializable +data class WorkspaceRoutineList( + val items: List, +) + +@Serializable +data class WorkspaceTimeZone( + val timeZone: String, + val scheduledRoutines: @Serializable(with = NonFiniteDoubleSerializer::class) Double, +) + +@Serializable +data class WorkspaceTimeZoneChange( + val timeZone: String, +) + +@Serializable(with = WorkspaceUpdateEvent.Serializer::class) +sealed interface WorkspaceUpdateEvent { + @Serializable + data class ThreadChanged( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "thread.changed", + val threadId: String, + ) : WorkspaceUpdateEvent + + @Serializable + data class ConversationThreadChanged( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "conversation.thread_changed", + val conversationId: String, + val threadId: String, + ) : WorkspaceUpdateEvent + + @Serializable + data class Reset( + @EncodeDefault val v: Long = 1L, + @EncodeDefault val type: String = "reset", + ) : WorkspaceUpdateEvent + + /** A kind from a newer server than this app knows, by its `type`, which can't be sent. */ + data class Unknown(val tag: String) : WorkspaceUpdateEvent + + object Serializer : JsonUnionSerializer("ai.sugabots.api.WorkspaceUpdateEvent") { + override fun decode(element: JsonElement, json: Json): WorkspaceUpdateEvent = + when (val tag = tagOf(element, "type")) { + "thread.changed" -> json.decodeFromJsonElement(element) + "conversation.thread_changed" -> json.decodeFromJsonElement(element) + "reset" -> json.decodeFromJsonElement(element) + else -> Unknown(tag) + } + + override fun encode(value: WorkspaceUpdateEvent, json: Json): JsonElement = + when (value) { + is ThreadChanged -> json.encodeToJsonElement(value) + is ConversationThreadChanged -> json.encodeToJsonElement(value) + is Reset -> json.encodeToJsonElement(value) + is Unknown -> throw SerializationException("A kind this app doesn't know can't be sent.") + } + } +} + +@Serializable +data class WorkspaceUsage( + val month: String, + val timeZone: String, + val usd: Double, + val unpricedRequests: Long, + val days: List, + val bots: List, + val models: List, + val pods: List, + val systemAgents: SystemAgents, +) { + @Serializable + data class SystemAgents( + val usd: Double, + val unpricedRequests: Long, + ) +} + +// MARK: Requests + +/** + * The API's routes, grouped as the web's client groups them: `api.threads.get(...)` + * there is `client.threads.get(...)` here. + */ +class ApiClient(transport: ApiTransport) { + private val caller = ApiCaller(transport, ApiJson) + + /** The `agents` routes, as `api.agents` in the web's client. */ + val agents: AgentsRoutes = AgentsRoutes(caller) + + /** The `artifacts` routes, as `api.artifacts` in the web's client. */ + val artifacts: ArtifactsRoutes = ArtifactsRoutes(caller) + + /** The `chats` routes, as `api.chats` in the web's client. */ + val chats: ChatsRoutes = ChatsRoutes(caller) + + /** The `connections` routes, as `api.connections` in the web's client. */ + val connections: ConnectionsRoutes = ConnectionsRoutes(caller) + + /** The `events` routes, as `api.events` in the web's client. */ + val events: EventsRoutes = EventsRoutes(caller) + + /** The `gitHubConnections` routes, as `api.gitHubConnections` in the web's client. */ + val gitHubConnections: GitHubConnectionsRoutes = GitHubConnectionsRoutes(caller) + + /** The `gitHubWebhooks` routes, as `api.gitHubWebhooks` in the web's client. */ + val gitHubWebhooks: GitHubWebhooksRoutes = GitHubWebhooksRoutes(caller) + + /** The `modelProviders` routes, as `api.modelProviders` in the web's client. */ + val modelProviders: ModelProvidersRoutes = ModelProvidersRoutes(caller) + + /** The `modelTrials` routes, as `api.modelTrials` in the web's client. */ + val modelTrials: ModelTrialsRoutes = ModelTrialsRoutes(caller) + + /** The `notifications` routes, as `api.notifications` in the web's client. */ + val notifications: NotificationsRoutes = NotificationsRoutes(caller) + + /** The `onboarding` routes, as `api.onboarding` in the web's client. */ + val onboarding: OnboardingRoutes = OnboardingRoutes(caller) + + /** The `pods` routes, as `api.pods` in the web's client. */ + val pods: PodsRoutes = PodsRoutes(caller) + + /** The `podSandbox` routes, as `api.podSandbox` in the web's client. */ + val podSandbox: PodSandboxRoutes = PodSandboxRoutes(caller) + + /** The `referrals` routes, as `api.referrals` in the web's client. */ + val referrals: ReferralsRoutes = ReferralsRoutes(caller) + + /** The `routines` routes, as `api.routines` in the web's client. */ + val routines: RoutinesRoutes = RoutinesRoutes(caller) + + /** The `sandboxProviders` routes, as `api.sandboxProviders` in the web's client. */ + val sandboxProviders: SandboxProvidersRoutes = SandboxProvidersRoutes(caller) + + /** The `searchProviders` routes, as `api.searchProviders` in the web's client. */ + val searchProviders: SearchProvidersRoutes = SearchProvidersRoutes(caller) + + /** The `systemAgents` routes, as `api.systemAgents` in the web's client. */ + val systemAgents: SystemAgentsRoutes = SystemAgentsRoutes(caller) + + /** The `threads` routes, as `api.threads` in the web's client. */ + val threads: ThreadsRoutes = ThreadsRoutes(caller) + + /** The `toolApprovals` routes, as `api.toolApprovals` in the web's client. */ + val toolApprovals: ToolApprovalsRoutes = ToolApprovalsRoutes(caller) + + /** The `usage` routes, as `api.usage` in the web's client. */ + val usage: UsageRoutes = UsageRoutes(caller) + + /** The `workspaces` routes, as `api.workspaces` in the web's client. */ + val workspaces: WorkspacesRoutes = WorkspacesRoutes(caller) + + suspend fun health(): HealthResponse { + return caller.call("GET", "health") + } + + suspend fun me(): Me { + return caller.call("GET", "me") + } + + suspend fun workspaceAccess(workspace: String): WorkspaceAccessResponse { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/me") + } + + @Serializable + data class WorkspaceAccessResponse( + val role: WorkspaceRole? = null, + val permissions: WorkspacePermissions, + ) +} + +/** The `agents` routes, as `api.agents` in the web's client. */ +class AgentsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun list(workspace: String): List { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/agents") + } + + suspend fun create(podId: String, name: String, handle: String? = null, description: Omittable = Omittable.Omitted, color: AgentColor? = null, face: AgentFace? = null, shape: AgentShape? = null, model: String, prompt: String? = null, disabledTools: List? = null, usesSandbox: Boolean? = null, naturalBrowsing: Boolean? = null): Agent { + return caller.call("POST", "pods/${pathSegment(podId)}/agents", body = caller.jsonBody(NewAgentInPod(name = name, handle = handle, description = description, color = color, face = face, shape = shape, model = model, prompt = prompt, disabledTools = disabledTools, usesSandbox = usesSandbox, naturalBrowsing = naturalBrowsing))) + } + + suspend fun get(agentId: String): Agent { + return caller.call("GET", "agents/${pathSegment(agentId)}") + } + + suspend fun update(agentId: String, name: String? = null, handle: Omittable = Omittable.Omitted, description: Omittable = Omittable.Omitted, color: Omittable = Omittable.Omitted, face: Omittable = Omittable.Omitted, shape: Omittable = Omittable.Omitted, model: Omittable = Omittable.Omitted, prompt: Omittable = Omittable.Omitted, disabledTools: Omittable?> = Omittable.Omitted, usesSandbox: Omittable = Omittable.Omitted, naturalBrowsing: Omittable = Omittable.Omitted): Agent { + return caller.call("PATCH", "agents/${pathSegment(agentId)}", body = caller.jsonBody(AgentUpdate(name = name, handle = handle, description = description, color = color, face = face, shape = shape, model = model, prompt = prompt, disabledTools = disabledTools, usesSandbox = usesSandbox, naturalBrowsing = naturalBrowsing))) + } + + suspend fun remove(agentId: String) { + caller.callForData("DELETE", "agents/${pathSegment(agentId)}") + } +} + +/** The `artifacts` routes, as `api.artifacts` in the web's client. */ +class ArtifactsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun list(podId: String): List { + return caller.call("GET", "pods/${pathSegment(podId)}/artifacts") + } + + suspend fun get(podId: String, artifactId: String): Artifact { + return caller.call("GET", "pods/${pathSegment(podId)}/artifacts/${pathSegment(artifactId)}") + } + + suspend fun remove(podId: String, artifactId: String) { + caller.callForData("DELETE", "pods/${pathSegment(podId)}/artifacts/${pathSegment(artifactId)}") + } + + suspend fun versions(podId: String, artifactId: String): List { + return caller.call("GET", "pods/${pathSegment(podId)}/artifacts/${pathSegment(artifactId)}/versions") + } + + suspend fun getVersion(podId: String, artifactId: String, version: String): Artifact { + return caller.call("GET", "pods/${pathSegment(podId)}/artifacts/${pathSegment(artifactId)}/versions/${pathSegment(version)}") + } + + suspend fun pageAddress(podId: String, artifactId: String, version: String): PageAddressResponse { + return caller.call("GET", "pods/${pathSegment(podId)}/artifacts/${pathSegment(artifactId)}/versions/${pathSegment(version)}/page") + } + + @Serializable + data class PageAddressResponse( + @EncodeDefault val url: String? = null, + ) +} + +/** The `chats` routes, as `api.chats` in the web's client. */ +class ChatsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun list(workspace: String, pod: String): ChatList { + val query = QueryItems() + query.add("pod", pod) + return caller.call("GET", "workspaces/${pathSegment(workspace)}/chats", query) + } + + suspend fun podMarkers(workspace: String): PodChatMarkers { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/chats/pod-markers") + } + + suspend fun activity(workspace: String): ActivityFeed { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/chats/activity") + } + + suspend fun approvals(workspace: String): ApprovalInbox { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/chats/approvals") + } + + suspend fun openBotChannel(workspace: String, podId: String, hostAgentId: String): BotChannel { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/bot-channels", body = caller.jsonBody(OpenBotChannel(podId = podId, hostAgentId = hostAgentId))) + } + + suspend fun openRoutineFeed(workspace: String, routineId: String): RoutineFeed { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/routines/${pathSegment(routineId)}/thread") + } + + suspend fun openPodChat(workspace: String, podId: String): PodChat { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/pods/${pathSegment(podId)}/chat") + } + + suspend fun startChat(podId: String, name: String): PodChat { + return caller.call("POST", "pods/${pathSegment(podId)}/chats", body = caller.jsonBody(NewChat(name = name))) + } + + suspend fun renameChat(conversationId: String, name: String) { + caller.callForData("PUT", "conversations/${pathSegment(conversationId)}/name", body = caller.jsonBody(NewChat(name = name))) + } + + suspend fun archiveChat(conversationId: String) { + caller.callForData("PUT", "conversations/${pathSegment(conversationId)}/archived") + } + + suspend fun startThread(conversationId: String, id: String, message: String, attachments: List? = null, hostAgentId: String? = null, replyTo: String? = null): StartedThread { + return caller.call("POST", "conversations/${pathSegment(conversationId)}/threads", body = caller.jsonBody(NewThread(id = id, message = message, attachments = attachments, hostAgentId = hostAgentId, replyTo = replyTo))) + } + + suspend fun threadFrom(messageId: String): ConversationThread { + return caller.call("POST", "messages/${pathSegment(messageId)}/thread") + } + + suspend fun messages(conversationId: String, cursor: String? = null, limit: Long? = null): ChatMessagesPage { + val query = QueryItems() + query.add("cursor", cursor) + query.add("limit", limit?.let { it.toString() }) + return caller.call("GET", "conversations/${pathSegment(conversationId)}/messages", query) + } + + suspend fun send(conversationId: String, id: String, message: String, attachments: List? = null, replyTo: String? = null): Message { + return caller.call("POST", "conversations/${pathSegment(conversationId)}/messages", body = caller.jsonBody(NewMessage(id = id, message = message, attachments = attachments, replyTo = replyTo))) + } + + suspend fun history(conversationId: String, cursor: String? = null, limit: Long? = null): ChatHistoryPage { + val query = QueryItems() + query.add("cursor", cursor) + query.add("limit", limit?.let { it.toString() }) + return caller.call("GET", "conversations/${pathSegment(conversationId)}/history", query) + } + + suspend fun markDone(conversationId: String) { + caller.callForData("PUT", "conversations/${pathSegment(conversationId)}/done") + } + + suspend fun reopen(conversationId: String) { + caller.callForData("DELETE", "conversations/${pathSegment(conversationId)}/done") + } + + suspend fun markRead(conversationId: String) { + caller.callForData("POST", "conversations/${pathSegment(conversationId)}/read") + } + + suspend fun uploadFile(conversationId: String, name: String, type: String? = null, data: ByteArray): UploadedAttachment { + val query = QueryItems() + query.add("name", name) + query.add("type", type) + return caller.call("POST", "conversations/${pathSegment(conversationId)}/files", query, body = ApiRequestBody.Bytes(data)) + } + + suspend fun removeFile(conversationId: String, fileId: String) { + caller.callForData("DELETE", "conversations/${pathSegment(conversationId)}/files/${pathSegment(fileId)}") + } + + suspend fun file(conversationId: String, fileId: String): ByteArray { + return caller.callForData("GET", "conversations/${pathSegment(conversationId)}/files/${pathSegment(fileId)}") + } +} + +/** The `connections` routes, as `api.connections` in the web's client. */ +class ConnectionsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun list(podId: String): List { + return caller.call("GET", "pods/${pathSegment(podId)}/connections") + } + + suspend fun create(podId: String, body: NewConnection): Connection { + return caller.call("POST", "pods/${pathSegment(podId)}/connections", body = caller.jsonBody(body)) + } + + suspend fun testUnsaved(podId: String, url: String, secretHeader: String? = null, secret: String? = null): ConnectionTestResult { + return caller.call("POST", "pods/${pathSegment(podId)}/connections/test", body = caller.jsonBody(UnsavedConnection(url = url, secretHeader = secretHeader, secret = secret))) + } + + suspend fun get(podId: String, connectionId: String): ConnectionWithTools { + return caller.call("GET", "pods/${pathSegment(podId)}/connections/${pathSegment(connectionId)}") + } + + suspend fun update(podId: String, connectionId: String, name: String? = null, url: String? = null, secretHeader: Omittable = Omittable.Omitted, secret: Omittable = Omittable.Omitted, access: ConnectionAccess? = null, toolAccess: Map? = null): Connection { + return caller.call("PATCH", "pods/${pathSegment(podId)}/connections/${pathSegment(connectionId)}", body = caller.jsonBody(ConnectionUpdate(name = name, url = url, secretHeader = secretHeader, secret = secret, access = access, toolAccess = toolAccess))) + } + + suspend fun remove(podId: String, connectionId: String) { + caller.callForData("DELETE", "pods/${pathSegment(podId)}/connections/${pathSegment(connectionId)}") + } + + suspend fun test(podId: String, connectionId: String): ConnectionTestResult { + return caller.call("POST", "pods/${pathSegment(podId)}/connections/${pathSegment(connectionId)}/test") + } + + suspend fun connectFromCatalog(podId: String, name: String, url: String): ConnectFromCatalogResult { + return caller.call("POST", "pods/${pathSegment(podId)}/connections/connect", body = caller.jsonBody(ConnectFromCatalog(name = name, url = url))) + } + + suspend fun startOAuth(podId: String, connectionId: String): ConnectionOauthStart { + return caller.call("POST", "pods/${pathSegment(podId)}/connections/${pathSegment(connectionId)}/oauth/start") + } + + suspend fun oauthCallback(code: String? = null, state: String? = null, error: String? = null, errorDescription: String? = null) { + val query = QueryItems() + query.add("code", code) + query.add("state", state) + query.add("error", error) + query.add("error_description", errorDescription) + caller.callForData("GET", "connections/oauth/callback", query) + } +} + +/** The `events` routes, as `api.events` in the web's client. */ +class EventsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun typing(threadId: String) { + caller.callForData("POST", "threads/${pathSegment(threadId)}/typing") + } +} + +/** The `gitHubConnections` routes, as `api.gitHubConnections` in the web's client. */ +class GitHubConnectionsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun start(podId: String, organization: String? = null): GitHubAppForm { + return caller.call("POST", "pods/${pathSegment(podId)}/github", body = caller.jsonBody(NewGitHubApp(organization = organization))) + } + + suspend fun installUrl(podId: String, connectionId: String): GitHubAppInstall { + return caller.call("POST", "pods/${pathSegment(podId)}/connections/${pathSegment(connectionId)}/github/install") + } + + suspend fun reachableRepositories(podId: String, connectionId: String): List { + return caller.call("GET", "pods/${pathSegment(podId)}/connections/${pathSegment(connectionId)}/github/reachable") + } + + suspend fun repositories(podId: String, connectionId: String): ConnectionRepositories { + return caller.call("GET", "pods/${pathSegment(podId)}/connections/${pathSegment(connectionId)}/repositories") + } + + suspend fun addRepository(podId: String, connectionId: String, repository: String): ConnectionRepositories { + return caller.call("POST", "pods/${pathSegment(podId)}/connections/${pathSegment(connectionId)}/repositories", body = caller.jsonBody(ConnectionRepositoryChange(repository = repository))) + } + + suspend fun removeRepository(podId: String, connectionId: String, repository: String): ConnectionRepositories { + return caller.call("POST", "pods/${pathSegment(podId)}/connections/${pathSegment(connectionId)}/repositories/remove", body = caller.jsonBody(ConnectionRepositoryChange(repository = repository))) + } + + suspend fun gitHubAppMade(code: String? = null, state: String? = null) { + val query = QueryItems() + query.add("code", code) + query.add("state", state) + caller.callForData("GET", "connections/github/made", query) + } + + suspend fun gitHubAppInstalled(installationId: String? = null, state: String? = null) { + val query = QueryItems() + query.add("installation_id", installationId) + query.add("state", state) + caller.callForData("GET", "connections/github/installed", query) + } +} + +/** The `gitHubWebhooks` routes, as `api.gitHubWebhooks` in the web's client. */ +class GitHubWebhooksRoutes internal constructor(private val caller: ApiCaller) { + suspend fun delivery(connectionId: String, body: JsonElement) { + caller.callForData("POST", "hooks/connections/${pathSegment(connectionId)}", body = caller.jsonBody(body)) + } +} + +/** The `modelProviders` routes, as `api.modelProviders` in the web's client. */ +class ModelProvidersRoutes internal constructor(private val caller: ApiCaller) { + suspend fun list(workspace: String): List { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/model-providers") + } + + suspend fun create(workspace: String, body: NewModelProvider): ModelProvider { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/model-providers", body = caller.jsonBody(body)) + } + + suspend fun listEnabledModels(workspace: String): WorkspaceModelsResponse { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/model-providers/models") + } + + suspend fun setDefaultModel(workspace: String, model: String): WorkspaceModelsResponse { + return caller.call("PUT", "workspaces/${pathSegment(workspace)}/model-providers/models/default", body = caller.jsonBody(DefaultModelUpdate(model = model))) + } + + suspend fun get(workspace: String, providerId: String): ModelProvider { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}") + } + + suspend fun update(workspace: String, providerId: String, active: Boolean? = null, baseUrl: String? = null, apiFormat: ProviderApiFormat? = null, apiKey: Omittable = Omittable.Omitted, customHeaders: List? = null): ModelProvider { + return caller.call("PATCH", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}", body = caller.jsonBody(ModelProviderUpdate(active = active, baseUrl = baseUrl, apiFormat = apiFormat, apiKey = apiKey, customHeaders = customHeaders))) + } + + suspend fun remove(workspace: String, providerId: String) { + caller.callForData("DELETE", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}") + } + + suspend fun switchOff(workspace: String, providerId: String, moveBots: List, newBotsTo: String? = null, summariesTo: String? = null): SwitchOffResponse { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}/switch-off", body = caller.jsonBody(ProviderSwitchOff(moveBots = moveBots, newBotsTo = newBotsTo, summariesTo = summariesTo))) + } + + suspend fun test(workspace: String, providerId: String): ProviderTestResult { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}/test") + } + + suspend fun startSignIn(workspace: String, providerId: String): ProviderSignInStarted { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}/sign-in") + } + + suspend fun signOut(workspace: String, providerId: String): ModelProvider { + return caller.call("DELETE", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}/sign-in") + } + + suspend fun completeSignIn(workspace: String, providerId: String, attempt: String): ProviderSignInOutcome { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}/sign-in/complete", body = caller.jsonBody(ProviderSignInCompletion(attempt = attempt))) + } + + suspend fun fetchModels(workspace: String, providerId: String): ProviderFetchResult { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}/fetch-models") + } + + suspend fun addModel(workspace: String, providerId: String, modelId: String, displayName: Omittable = Omittable.Omitted, capabilities: List? = null, contextLength: Omittable = Omittable.Omitted): ModelProvider { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}/models", body = caller.jsonBody(NewProviderModel(modelId = modelId, displayName = displayName, capabilities = capabilities, contextLength = contextLength))) + } + + suspend fun setModelsEnabled(workspace: String, providerId: String, modelIds: List, enabled: Boolean): SetModelsEnabledResponse { + return caller.call("PATCH", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}/models", body = caller.jsonBody(BulkProviderModelUpdate(modelIds = modelIds, enabled = enabled))) + } + + suspend fun updateModel(workspace: String, providerId: String, modelId: String, enabled: Boolean? = null, disabledCapabilities: List? = null, capabilities: List? = null): UpdateModelResponse { + return caller.call("PATCH", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}/models/${pathSegment(modelId)}", body = caller.jsonBody(ProviderModelUpdate(enabled = enabled, disabledCapabilities = disabledCapabilities, capabilities = capabilities))) + } + + suspend fun removeModel(workspace: String, providerId: String, modelId: String) { + caller.callForData("DELETE", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}/models/${pathSegment(modelId)}") + } + + suspend fun switchOffModel(workspace: String, providerId: String, modelId: String, moveBotsTo: String? = null, newBotsTo: String? = null, summariesTo: String? = null): SwitchOffModelResponse { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/model-providers/${pathSegment(providerId)}/models/${pathSegment(modelId)}/switch-off", body = caller.jsonBody(ProviderModelSwitchOff(moveBotsTo = moveBotsTo, newBotsTo = newBotsTo, summariesTo = summariesTo))) + } + + @Serializable + data class SwitchOffResponse( + val moved: Long, + ) + + @Serializable + data class SetModelsEnabledResponse( + val updated: Long, + ) + + @Serializable + data class UpdateModelResponse( + val updated: Long, + ) + + @Serializable + data class SwitchOffModelResponse( + val moved: Long, + ) +} + +/** The `modelTrials` routes, as `api.modelTrials` in the web's client. */ +class ModelTrialsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun run(workspace: String, systemAgentKey: SystemAgentKey, model: String): ModelTrial { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/model-trials", body = caller.jsonBody(NewModelTrial(systemAgentKey = systemAgentKey, model = model))) + } +} + +/** The `notifications` routes, as `api.notifications` in the web's client. */ +class NotificationsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun settings(): NotificationSettings { + return caller.call("GET", "notifications") + } + + suspend fun updatePreferences(level: NotificationLevel, pausedUntil: Instant? = null, quietHours: QuietHours? = null, turnFailures: Boolean, routineRuns: RoutineRunNotifications): NotificationSettings { + return caller.call("PUT", "notifications", body = caller.jsonBody(NotificationPreferences(level = level, pausedUntil = pausedUntil, quietHours = quietHours, turnFailures = turnFailures, routineRuns = routineRuns))) + } + + suspend fun setLevel(kind: NotificationPlaceKind, id: String, level: NotificationLevel? = null) { + caller.callForData("PUT", "notifications/${pathSegment(kind.rawValue)}/${pathSegment(id)}/level", body = caller.jsonBody(NotificationLevelChoice(level = level))) + } + + suspend fun mute(kind: NotificationPlaceKind, id: String, until: Instant? = null) { + caller.callForData("PUT", "notifications/${pathSegment(kind.rawValue)}/${pathSegment(id)}/mute", body = caller.jsonBody(NotificationMute(until = until))) + } + + suspend fun sendTest() { + caller.callForData("POST", "notifications/test") + } + + suspend fun reportPresence(clientId: String, conversationId: String? = null, sequence: Long) { + caller.callForData("PUT", "notifications/presence", body = caller.jsonBody(Presence(clientId = clientId, conversationId = conversationId, sequence = sequence))) + } +} + +/** The `onboarding` routes, as `api.onboarding` in the web's client. */ +class OnboardingRoutes internal constructor(private val caller: ApiCaller) { + suspend fun complete(workspaceId: String, podId: String, agentId: String) { + caller.callForData("POST", "onboarding/complete", body = caller.jsonBody(CompleteOnboarding(workspaceId = workspaceId, podId = podId, agentId = agentId))) + } +} + +/** The `pods` routes, as `api.pods` in the web's client. */ +class PodsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun list(workspace: String): List { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/pods") + } + + suspend fun create(workspace: String, name: String, slug: String? = null, color: PodColor? = null): Pod { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/pods", body = caller.jsonBody(NewPod(name = name, slug = slug, color = color))) + } + + suspend fun ensurePersonal(workspace: String, model: String): Pod { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/personal-pod", body = caller.jsonBody(EnsurePersonalBody(model = model))) + } + + suspend fun update(podId: String, name: String? = null, slug: Omittable = Omittable.Omitted, color: Omittable = Omittable.Omitted): Pod { + return caller.call("PATCH", "pods/${pathSegment(podId)}", body = caller.jsonBody(PodUpdate(name = name, slug = slug, color = color))) + } + + suspend fun remove(podId: String) { + caller.callForData("DELETE", "pods/${pathSegment(podId)}") + } + + suspend fun listMembers(podId: String): List { + return caller.call("GET", "pods/${pathSegment(podId)}/members") + } + + suspend fun addMember(podId: String, userId: String) { + caller.callForData("POST", "pods/${pathSegment(podId)}/members", body = caller.jsonBody(NewPodMember(userId = userId))) + } + + suspend fun removeMember(podId: String, userId: String) { + caller.callForData("DELETE", "pods/${pathSegment(podId)}/members/${pathSegment(userId)}") + } + + suspend fun leave(podId: String) { + caller.callForData("DELETE", "pods/${pathSegment(podId)}/membership") + } + + @Serializable + data class EnsurePersonalBody( + val model: String, + ) +} + +/** The `podSandbox` routes, as `api.podSandbox` in the web's client. */ +class PodSandboxRoutes internal constructor(private val caller: ApiCaller) { + suspend fun get(podId: String): PodSandbox { + return caller.call("GET", "pods/${pathSegment(podId)}/sandbox") + } + + suspend fun reset(podId: String): PodSandbox { + return caller.call("POST", "pods/${pathSegment(podId)}/sandbox/reset") + } + + suspend fun upgrade(podId: String): PodSandbox { + return caller.call("POST", "pods/${pathSegment(podId)}/sandbox/upgrade") + } + + suspend fun network(podId: String): PodSandboxNetwork { + return caller.call("GET", "pods/${pathSegment(podId)}/sandbox/network") + } + + suspend fun addHost(podId: String, host: String): PodSandboxNetwork { + return caller.call("POST", "pods/${pathSegment(podId)}/sandbox/network/hosts", body = caller.jsonBody(NewSandboxHost(host = host))) + } + + suspend fun removeHost(podId: String, host: String): PodSandboxNetwork { + return caller.call("DELETE", "pods/${pathSegment(podId)}/sandbox/network/hosts/${pathSegment(host)}") + } +} + +/** The `referrals` routes, as `api.referrals` in the web's client. */ +class ReferralsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun link(): ReferralLink { + return caller.call("GET", "referral-link") + } + + suspend fun resetLink(): ResetReferralLink { + return caller.call("POST", "referral-link/reset") + } +} + +/** The `routines` routes, as `api.routines` in the web's client. */ +class RoutinesRoutes internal constructor(private val caller: ApiCaller) { + suspend fun listInWorkspace(workspace: String): WorkspaceRoutineList { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/routines") + } + + suspend fun list(agentId: String): List { + return caller.call("GET", "agents/${pathSegment(agentId)}/routines") + } + + suspend fun create(agentId: String, name: String, instructions: String, state: RoutineState? = null, results: RoutineResults? = null, chatId: Omittable = Omittable.Omitted, triggers: List): RoutineWriteResult { + return caller.call("POST", "agents/${pathSegment(agentId)}/routines", body = caller.jsonBody(NewRoutine(name = name, instructions = instructions, state = state, results = results, chatId = chatId, triggers = triggers))) + } + + suspend fun previewSchedule(agentId: String, schedule: RoutineSchedule, timezone: String): RoutineScheduleOccurrences { + return caller.call("POST", "agents/${pathSegment(agentId)}/routines/schedule-preview", body = caller.jsonBody(RoutineSchedulePreview(schedule = schedule, timezone = timezone))) + } + + suspend fun get(agentId: String, routineId: String): Routine { + return caller.call("GET", "agents/${pathSegment(agentId)}/routines/${pathSegment(routineId)}") + } + + suspend fun update(agentId: String, routineId: String, name: String? = null, instructions: String? = null, state: RoutineState? = null, results: RoutineResults? = null, chatId: Omittable = Omittable.Omitted): RoutineWriteResult { + return caller.call("PATCH", "agents/${pathSegment(agentId)}/routines/${pathSegment(routineId)}", body = caller.jsonBody(RoutineUpdate(name = name, instructions = instructions, state = state, results = results, chatId = chatId))) + } + + suspend fun remove(agentId: String, routineId: String) { + caller.callForData("DELETE", "agents/${pathSegment(agentId)}/routines/${pathSegment(routineId)}") + } + + suspend fun run(agentId: String, routineId: String, requestId: String): AcceptedRoutineExecution { + return caller.call("POST", "agents/${pathSegment(agentId)}/routines/${pathSegment(routineId)}/run", body = caller.jsonBody(ManualRoutineRun(requestId = requestId))) + } + + suspend fun addTrigger(agentId: String, routineId: String, body: RoutineTriggerInput): RoutineWriteResult { + return caller.call("POST", "agents/${pathSegment(agentId)}/routines/${pathSegment(routineId)}/triggers", body = caller.jsonBody(body)) + } + + suspend fun updateTrigger(agentId: String, routineId: String, triggerId: String, body: RoutineTriggerInput): RoutineWriteResult { + return caller.call("PUT", "agents/${pathSegment(agentId)}/routines/${pathSegment(routineId)}/triggers/${pathSegment(triggerId)}", body = caller.jsonBody(body)) + } + + suspend fun removeTrigger(agentId: String, routineId: String, triggerId: String): Routine { + return caller.call("DELETE", "agents/${pathSegment(agentId)}/routines/${pathSegment(routineId)}/triggers/${pathSegment(triggerId)}") + } + + suspend fun getSecret(agentId: String, routineId: String, triggerId: String): RoutineCurrentSecret { + return caller.call("GET", "agents/${pathSegment(agentId)}/routines/${pathSegment(routineId)}/triggers/${pathSegment(triggerId)}/secret") + } + + suspend fun rotateSecret(agentId: String, routineId: String, triggerId: String, secret: Omittable = Omittable.Omitted): RoutineSecret { + return caller.call("POST", "agents/${pathSegment(agentId)}/routines/${pathSegment(routineId)}/triggers/${pathSegment(triggerId)}/secret", body = caller.jsonBody(RoutineSecretReplacement(secret = secret))) + } + + suspend fun executions(agentId: String, routineId: String, cursor: String? = null, limit: Long? = null): RoutineExecutionPage { + val query = QueryItems() + query.add("cursor", cursor) + query.add("limit", limit?.let { it.toString() }) + return caller.call("GET", "agents/${pathSegment(agentId)}/routines/${pathSegment(routineId)}/executions", query) + } + + suspend fun webhook(triggerId: String, body: JsonElement): WebhookResponse { + return caller.call("POST", "hooks/triggers/${pathSegment(triggerId)}", body = caller.jsonBody(body)) + } + + suspend fun routineWebhook(routineId: String, body: JsonElement): RoutineWebhookResponse { + return caller.call("POST", "hooks/routines/${pathSegment(routineId)}", body = caller.jsonBody(body)) + } + + @Serializable(with = WebhookResponse.Serializer::class) + sealed interface WebhookResponse { + data class IgnoredRoutineWebhookResponse(val value: IgnoredRoutineWebhook) : WebhookResponse + + data class RoutineWebhookChallengeResponse(val value: RoutineWebhookChallenge) : WebhookResponse + + object Serializer : JsonUnionSerializer("ai.sugabots.api.RoutinesRoutes.WebhookResponse") { + override fun decode(element: JsonElement, json: Json): WebhookResponse { + json.decodeOrNull(element)?.let { return IgnoredRoutineWebhookResponse(it) } + json.decodeOrNull(element)?.let { return RoutineWebhookChallengeResponse(it) } + throw SerializationException("None of WebhookResponse's kinds.") + } + + override fun encode(value: WebhookResponse, json: Json): JsonElement = + when (value) { + is IgnoredRoutineWebhookResponse -> json.encodeToJsonElement(value.value) + is RoutineWebhookChallengeResponse -> json.encodeToJsonElement(value.value) + } + } + } + + @Serializable(with = RoutineWebhookResponse.Serializer::class) + sealed interface RoutineWebhookResponse { + data class IgnoredRoutineWebhookResponse(val value: IgnoredRoutineWebhook) : RoutineWebhookResponse + + data class RoutineWebhookChallengeResponse(val value: RoutineWebhookChallenge) : RoutineWebhookResponse + + object Serializer : JsonUnionSerializer("ai.sugabots.api.RoutinesRoutes.RoutineWebhookResponse") { + override fun decode(element: JsonElement, json: Json): RoutineWebhookResponse { + json.decodeOrNull(element)?.let { return IgnoredRoutineWebhookResponse(it) } + json.decodeOrNull(element)?.let { return RoutineWebhookChallengeResponse(it) } + throw SerializationException("None of RoutineWebhookResponse's kinds.") + } + + override fun encode(value: RoutineWebhookResponse, json: Json): JsonElement = + when (value) { + is IgnoredRoutineWebhookResponse -> json.encodeToJsonElement(value.value) + is RoutineWebhookChallengeResponse -> json.encodeToJsonElement(value.value) + } + } + } +} + +/** The `sandboxProviders` routes, as `api.sandboxProviders` in the web's client. */ +class SandboxProvidersRoutes internal constructor(private val caller: ApiCaller) { + suspend fun list(workspace: String): List { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/sandbox-providers") + } + + suspend fun create(workspace: String, settings: SandboxProviderSettings, enabled: Boolean? = null, apiKey: String? = null): SandboxProvider { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/sandbox-providers", body = caller.jsonBody(NewSandboxProvider(settings = settings, enabled = enabled, apiKey = apiKey))) + } + + suspend fun access(workspace: String): SandboxAccess { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/sandbox-providers/access") + } + + suspend fun update(workspace: String, providerId: String, enabled: Boolean? = null, apiKey: Omittable = Omittable.Omitted, settings: SandboxProviderSettings? = null): SandboxProvider { + return caller.call("PATCH", "workspaces/${pathSegment(workspace)}/sandbox-providers/${pathSegment(providerId)}", body = caller.jsonBody(SandboxProviderUpdate(enabled = enabled, apiKey = apiKey, settings = settings))) + } + + suspend fun remove(workspace: String, providerId: String) { + caller.callForData("DELETE", "workspaces/${pathSegment(workspace)}/sandbox-providers/${pathSegment(providerId)}") + } + + suspend fun template(workspace: String, providerId: String): SandboxTemplate { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/sandbox-providers/${pathSegment(providerId)}/template") + } + + suspend fun prepareTemplate(workspace: String, providerId: String): SandboxTemplate { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/sandbox-providers/${pathSegment(providerId)}/template") + } + + suspend fun test(workspace: String, providerId: String): SandboxProviderTestResult { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/sandbox-providers/${pathSegment(providerId)}/test") + } + + suspend fun disks(workspace: String): List { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/sandbox-disks") + } + + suspend fun network(workspace: String): SandboxNetworkSettings { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/sandbox-network") + } + + suspend fun addHost(workspace: String, host: String): SandboxNetworkSettings { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/sandbox-network/hosts", body = caller.jsonBody(NewSandboxHost(host = host))) + } + + suspend fun removeHost(workspace: String, host: String): SandboxNetworkSettings { + return caller.call("DELETE", "workspaces/${pathSegment(workspace)}/sandbox-network/hosts/${pathSegment(host)}") + } + + suspend fun blockHost(workspace: String, host: String): SandboxNetworkSettings { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/sandbox-network/blocked-hosts", body = caller.jsonBody(NewSandboxHost(host = host))) + } + + suspend fun unblockHost(workspace: String, host: String): SandboxNetworkSettings { + return caller.call("DELETE", "workspaces/${pathSegment(workspace)}/sandbox-network/blocked-hosts/${pathSegment(host)}") + } +} + +/** The `searchProviders` routes, as `api.searchProviders` in the web's client. */ +class SearchProvidersRoutes internal constructor(private val caller: ApiCaller) { + suspend fun get(workspace: String): SearchProviderResponse { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/search-provider") + } + + suspend fun replace(workspace: String, preset: SearchProviderPresetId, enabled: Boolean? = null, apiKey: String? = null, baseUrl: String? = null): SearchProvider { + return caller.call("PUT", "workspaces/${pathSegment(workspace)}/search-provider", body = caller.jsonBody(NewSearchProvider(preset = preset, enabled = enabled, apiKey = apiKey, baseUrl = baseUrl))) + } + + suspend fun update(workspace: String, enabled: Boolean? = null, baseUrl: String? = null, apiKey: Omittable = Omittable.Omitted): SearchProvider { + return caller.call("PATCH", "workspaces/${pathSegment(workspace)}/search-provider", body = caller.jsonBody(SearchProviderUpdate(enabled = enabled, baseUrl = baseUrl, apiKey = apiKey))) + } + + suspend fun remove(workspace: String) { + caller.callForData("DELETE", "workspaces/${pathSegment(workspace)}/search-provider") + } + + suspend fun webAccess(workspace: String): WebAccess { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/search-provider/web-access") + } + + suspend fun test(workspace: String): SearchProviderTestResult { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/search-provider/test") + } +} + +/** The `systemAgents` routes, as `api.systemAgents` in the web's client. */ +class SystemAgentsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun list(workspace: String): List { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/system-agents") + } + + suspend fun update(workspace: String, key: String, model: String): SystemAgent { + return caller.call("PATCH", "workspaces/${pathSegment(workspace)}/system-agents/${pathSegment(key)}", body = caller.jsonBody(SystemAgentUpdate(model = model))) + } +} + +/** The `threads` routes, as `api.threads` in the web's client. */ +class ThreadsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun list(workspace: String): List { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/threads") + } + + suspend fun get(threadId: String, cursor: String? = null, limit: Long? = null): ThreadDetails { + val query = QueryItems() + query.add("cursor", cursor) + query.add("limit", limit?.let { it.toString() }) + return caller.call("GET", "threads/${pathSegment(threadId)}", query) + } + + suspend fun activity(threadId: String): ThreadActivity { + return caller.call("GET", "threads/${pathSegment(threadId)}/activity") + } + + suspend fun react(messageId: String, emoji: String): MessageReactions { + return caller.call("PUT", "messages/${pathSegment(messageId)}/reactions/${pathSegment(emoji)}") + } + + suspend fun unreact(messageId: String, emoji: String): MessageReactions { + return caller.call("DELETE", "messages/${pathSegment(messageId)}/reactions/${pathSegment(emoji)}") + } + + suspend fun cancelTurn(turnId: String) { + caller.callForData("POST", "turns/${pathSegment(turnId)}/cancel") + } +} + +/** The `toolApprovals` routes, as `api.toolApprovals` in the web's client. */ +class ToolApprovalsRoutes internal constructor(private val caller: ApiCaller) { + suspend fun decide(podId: String, toolCallId: String, decision: ToolApprovalDecision.Decision) { + caller.callForData("POST", "pods/${pathSegment(podId)}/tool-calls/${pathSegment(toolCallId)}/approval", body = caller.jsonBody(ToolApprovalDecision(decision = decision))) + } +} + +/** The `usage` routes, as `api.usage` in the web's client. */ +class UsageRoutes internal constructor(private val caller: ApiCaller) { + suspend fun month(workspace: String, month: String): WorkspaceUsage { + val query = QueryItems() + query.add("month", month) + return caller.call("GET", "workspaces/${pathSegment(workspace)}/usage", query) + } +} + +/** The `workspaces` routes, as `api.workspaces` in the web's client. */ +class WorkspacesRoutes internal constructor(private val caller: ApiCaller) { + suspend fun list(): List { + return caller.call("GET", "workspaces") + } + + suspend fun create(name: String, slug: String, timeZone: String? = null): Workspace { + return caller.call("POST", "workspaces", body = caller.jsonBody(NewWorkspace(name = name, slug = slug, timeZone = timeZone))) + } + + suspend fun update(workspace: String, name: String, slug: String): Workspace { + return caller.call("PATCH", "workspaces/${pathSegment(workspace)}", body = caller.jsonBody(WorkspaceDetails(name = name, slug = slug))) + } + + suspend fun delete(workspace: String) { + caller.callForData("DELETE", "workspaces/${pathSegment(workspace)}") + } + + suspend fun timeZone(workspace: String): WorkspaceTimeZone { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/time-zone") + } + + suspend fun changeTimeZone(workspace: String, timeZone: String) { + caller.callForData("PUT", "workspaces/${pathSegment(workspace)}/time-zone", body = caller.jsonBody(WorkspaceTimeZoneChange(timeZone = timeZone))) + } + + suspend fun members(workspace: String): List { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/members") + } + + suspend fun updateMember(workspace: String, memberId: String, role: AssignableWorkspaceRole) { + caller.callForData("PATCH", "workspaces/${pathSegment(workspace)}/members/${pathSegment(memberId)}", body = caller.jsonBody(WorkspaceMemberUpdate(role = role))) + } + + suspend fun removeMember(workspace: String, memberId: String) { + caller.callForData("DELETE", "workspaces/${pathSegment(workspace)}/members/${pathSegment(memberId)}") + } + + suspend fun transferOwnership(workspace: String, memberId: String) { + caller.callForData("PUT", "workspaces/${pathSegment(workspace)}/owner", body = caller.jsonBody(OwnershipTransfer(memberId = memberId))) + } + + suspend fun leave(workspace: String) { + caller.callForData("POST", "workspaces/${pathSegment(workspace)}/leave") + } + + suspend fun invitations(workspace: String): List { + return caller.call("GET", "workspaces/${pathSegment(workspace)}/invitations") + } + + suspend fun invite(workspace: String, email: String, role: AssignableWorkspaceRole, resend: Boolean? = null): WorkspaceInvitation { + return caller.call("POST", "workspaces/${pathSegment(workspace)}/invitations", body = caller.jsonBody(NewWorkspaceInvitation(email = email, role = role, resend = resend))) + } + + suspend fun cancelInvitation(invitationId: String) { + caller.callForData("DELETE", "invitations/${pathSegment(invitationId)}") + } + + suspend fun invitation(invitationId: String): InvitationPreview { + return caller.call("GET", "invitations/${pathSegment(invitationId)}") + } + + suspend fun acceptInvitation(invitationId: String): AcceptedInvitation { + return caller.call("POST", "invitations/${pathSegment(invitationId)}/accept") + } +} diff --git a/apps/android/api/src/main/kotlin/ai/sugabots/api/ApiSupport.kt b/apps/android/api/src/main/kotlin/ai/sugabots/api/ApiSupport.kt new file mode 100644 index 000000000..16c510d96 --- /dev/null +++ b/apps/android/api/src/main/kotlin/ai/sugabots/api/ApiSupport.kt @@ -0,0 +1,277 @@ +// What `Api.generated.kt` is written against: how a request is sent, and how +// the API's JSON is read and written. + +package ai.sugabots.api + +import java.net.URLEncoder +import java.time.Instant +import java.time.ZoneOffset +import java.time.format.DateTimeFormatter +import kotlinx.serialization.ExperimentalSerializationApi +import kotlinx.serialization.KSerializer +import kotlinx.serialization.Serializable +import kotlinx.serialization.SerializationException +import kotlinx.serialization.encodeToString +import kotlinx.serialization.descriptors.PrimitiveKind +import kotlinx.serialization.descriptors.PrimitiveSerialDescriptor +import kotlinx.serialization.descriptors.SerialDescriptor +import kotlinx.serialization.encoding.Decoder +import kotlinx.serialization.encoding.Encoder +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonDecoder +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonEncoder +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.decodeFromJsonElement +import kotlinx.serialization.modules.SerializersModule + +// MARK: Sending requests + +/** A request to the API. `path` is relative to the API's mount, such as `workspaces/acme/chats`. */ +class ApiRequest( + val method: String, + val path: String, + val query: List>, + val body: ApiRequestBody?, +) + +/** What a request sends: JSON, or bytes as they are, as an upload. */ +sealed interface ApiRequestBody { + val contentType: String + + class Json(val text: String) : ApiRequestBody { + override val contentType: String get() = "application/json" + } + + class Bytes(val bytes: ByteArray) : ApiRequestBody { + override val contentType: String get() = "application/octet-stream" + } +} + +/** What the API answered, whatever its status. */ +class ApiResponse(val status: Int, val body: ByteArray) + +/** + * Sends requests to the API over HTTP. An implementation, over OkHttp or Ktor, + * resolves a request's path against the API's address + * (`https://sugabots.example.com/api/`), adds the bearer token, and answers + * with the response as it came, whatever its status. + */ +fun interface ApiTransport { + suspend fun send(request: ApiRequest): ApiResponse +} + +/** A refusal or failure the API answered with, in its own words. */ +class ApiFailure(val status: Int, override val message: String) : Exception(message) + +/** How the API's JSON is read and written: fields this app doesn't know are ignored, and a field left at its default is left out. */ +val ApiJson: Json = Json { + ignoreUnknownKeys = true + encodeDefaults = false + serializersModule = SerializersModule { contextual(Instant::class, InstantSerializer) } +} + +/** + * Sends the generated routes' requests through a transport, and reads their + * answers. `ApiClient` makes its own with `ApiJson`, whose left-out defaults + * an `Omittable` relies on. + */ +internal class ApiCaller( + private val transport: ApiTransport, + @PublishedApi internal val json: Json, +) { + /** Sends a request and answers with its body as it came, or throws the API's failure. */ + suspend fun callForData( + method: String, + path: String, + query: QueryItems = QueryItems(), + body: ApiRequestBody? = null, + ): ByteArray { + val response = transport.send(ApiRequest(method, path, query.items, body)) + if (response.status !in 200..299) throw failure(response) + return response.body + } + + /** Sends a request and decodes its answer. */ + suspend inline fun call( + method: String, + path: String, + query: QueryItems = QueryItems(), + body: ApiRequestBody? = null, + ): Response = json.decodeFromString(callForData(method, path, query, body).decodeToString()) + + /** `body` as a request's JSON. */ + inline fun jsonBody(body: Body): ApiRequestBody = + ApiRequestBody.Json(json.encodeToString(body)) + + /** The API answers failures as `{ "_tag": "NotFound", "message": "…" }`. */ + private fun failure(response: ApiResponse): ApiFailure { + val message = runCatching { + (json.parseToJsonElement(response.body.decodeToString()) as? JsonObject) + ?.get("message") + ?.let { (it as? JsonPrimitive)?.contentOrNull } + }.getOrNull() + return ApiFailure(response.status, message ?: "The server answered ${response.status}.") + } +} + +/** A request's query, built a parameter at a time; one left out is not sent. */ +class QueryItems { + private val added = mutableListOf>() + val items: List> get() = added.toList() + + fun add(name: String, value: String?) { + if (value != null) added += name to value + } + + /** Sends `name` once for each of `values`. */ + fun addAll(name: String, values: List?) { + values?.forEach { add(name, it) } + } +} + +/** `value` as one segment of a path, its reserved characters escaped. */ +fun pathSegment(value: String): String = URLEncoder.encode(value, Charsets.UTF_8).replace("+", "%20") + +// MARK: Reading and writing values + +/** As the API writes a timestamp: `2026-10-30T09:00:00.000Z`. */ +private val timestampFormat: DateTimeFormatter = + DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC) + +fun formatTimestamp(instant: Instant): String = timestampFormat.format(instant) + +/** Timestamps as the API writes them, read with or without their fraction of a second. */ +object InstantSerializer : KSerializer { + override val descriptor = PrimitiveSerialDescriptor("ai.sugabots.api.Instant", PrimitiveKind.STRING) + + override fun deserialize(decoder: Decoder): Instant { + val text = decoder.decodeString() + return runCatching { Instant.parse(text) }.getOrElse { + throw SerializationException("Not an ISO 8601 timestamp: $text") + } + } + + override fun serialize(encoder: Encoder, value: Instant) { + encoder.encodeString(formatTimestamp(value)) + } +} + +/** A number, which Effect writes as the string `Infinity`, `-Infinity` or `NaN` where JSON can't hold it. */ +object NonFiniteDoubleSerializer : KSerializer { + override val descriptor = PrimitiveSerialDescriptor("ai.sugabots.api.NonFiniteDouble", PrimitiveKind.DOUBLE) + + override fun deserialize(decoder: Decoder): Double { + val element = (decoder as? JsonDecoder)?.decodeJsonElement() as? JsonPrimitive + ?: return decoder.decodeDouble() + if (!element.isString) return element.content.toDouble() + return when (element.content) { + "Infinity" -> Double.POSITIVE_INFINITY + "-Infinity" -> Double.NEGATIVE_INFINITY + "NaN" -> Double.NaN + else -> throw SerializationException("Not a number: ${element.content}") + } + } + + override fun serialize(encoder: Encoder, value: Double) { + when { + value.isNaN() -> encoder.encodeString("NaN") + value == Double.POSITIVE_INFINITY -> encoder.encodeString("Infinity") + value == Double.NEGATIVE_INFINITY -> encoder.encodeString("-Infinity") + else -> encoder.encodeDouble(value) + } + } +} + +/** + * A field a request may leave out, to keep what the server has, or send, even + * as null, to change it: `Omitted`, or `Present(null)` to clear it. Its field + * defaults to `Omitted`, which `ApiJson` leaves out as it does any default. + */ +@Serializable(with = OmittableSerializer::class) +sealed interface Omittable { + data object Omitted : Omittable + + data class Present(val value: T) : Omittable +} + +class OmittableSerializer(private val valueSerializer: KSerializer) : KSerializer> { + override val descriptor: SerialDescriptor = valueSerializer.descriptor + + /** A field that's there is present, even as null; one left out is never read, and keeps its default. */ + override fun deserialize(decoder: Decoder): Omittable = + Omittable.Present(valueSerializer.deserialize(decoder)) + + override fun serialize(encoder: Encoder, value: Omittable) { + when (value) { + is Omittable.Present -> valueSerializer.serialize(encoder, value.value) + Omittable.Omitted -> throw SerializationException("An omitted field is left out, so ApiJson must not encode defaults.") + } + } +} + +/** A string enum's value, as the API writes it. */ +interface OpenEnum { + val rawValue: String +} + +/** A string enum that reads a value from a newer server than this app knows as `unknown`, which can't be sent. */ +open class OpenEnumSerializer( + serialName: String, + private val entries: List, + private val unknown: E, +) : KSerializer where E : Enum, E : OpenEnum { + override val descriptor = PrimitiveSerialDescriptor(serialName, PrimitiveKind.STRING) + + override fun deserialize(decoder: Decoder): E { + val rawValue = decoder.decodeString() + return entries.firstOrNull { it != unknown && it.rawValue == rawValue } ?: unknown + } + + override fun serialize(encoder: Encoder, value: E) { + if (value == unknown) throw SerializationException("A value this app doesn't know can't be sent.") + encoder.encodeString(value.rawValue) + } +} + +/** A union, read and written as JSON by what its members' JSON holds. */ +@OptIn(ExperimentalSerializationApi::class) +abstract class JsonUnionSerializer(serialName: String) : KSerializer { + final override val descriptor: SerialDescriptor = + SerialDescriptor(serialName, JsonElement.serializer().descriptor) + + protected abstract fun decode(element: JsonElement, json: Json): T + + protected abstract fun encode(value: T, json: Json): JsonElement + + final override fun deserialize(decoder: Decoder): T { + val input = decoder as? JsonDecoder + ?: throw SerializationException("${descriptor.serialName} is read from JSON only.") + return decode(input.decodeJsonElement(), input.json) + } + + final override fun serialize(encoder: Encoder, value: T) { + val output = encoder as? JsonEncoder + ?: throw SerializationException("${descriptor.serialName} is written as JSON only.") + output.encodeJsonElement(encode(value, output.json)) + } + + /** The string an object's `property` holds, which tells a tagged union's members apart. */ + protected fun tagOf(element: JsonElement, property: String): String = + ((element as? JsonObject)?.get(property) as? JsonPrimitive)?.takeIf { it.isString }?.content + ?: throw SerializationException("${descriptor.serialName} has no `$property` to tell its kind by.") + + /** Whether `element` is exactly the string `value`. */ + protected fun JsonElement.isString(value: String): Boolean = + this is JsonPrimitive && isString && content == value + + /** `element` as a `T`, or null when it isn't one, to try an untagged union's next member. */ + protected inline fun Json.decodeOrNull(element: JsonElement): T? = + try { + decodeFromJsonElement(element) + } catch (_: IllegalArgumentException) { + null + } +} diff --git a/apps/android/api/src/test/kotlin/ai/sugabots/api/ApiSerializationTest.kt b/apps/android/api/src/test/kotlin/ai/sugabots/api/ApiSerializationTest.kt new file mode 100644 index 000000000..b82efe95c --- /dev/null +++ b/apps/android/api/src/test/kotlin/ai/sugabots/api/ApiSerializationTest.kt @@ -0,0 +1,97 @@ +package ai.sugabots.api + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertIs +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.SerializationException +import kotlinx.serialization.encodeToString +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive + +class ApiSerializationTest { + private val json = ApiJson + + @Test + fun `an enum reads a value it doesn't know as unknown, and won't send it`() { + assertEquals(AgentColor.RED, json.decodeFromString("\"red\"")) + assertEquals(AgentColor.UNKNOWN, json.decodeFromString("\"chartreuse\"")) + assertEquals("\"red\"", json.encodeToString(AgentColor.RED)) + assertFailsWith { json.encodeToString(AgentColor.UNKNOWN) } + } + + @Test + fun `a tagged union reads a tag it doesn't know as unknown, and its members by their tag`() { + val schedule = json.decodeFromString( + """{"repeat":"monthly","every":1,"dayOfMonth":"last","times":[540],"startsOn":"2026-11-01","extra":true}""", + ) + assertEquals( + RoutineSchedule.Monthly(every = 1, dayOfMonth = RoutineSchedule.Monthly.DayOfMonth.Last, times = listOf(540), startsOn = "2026-11-01"), + schedule, + ) + assertEquals(RoutineSchedule.Unknown("fortnightly"), json.decodeFromString("""{"repeat":"fortnightly"}""")) + assertFailsWith { json.encodeToString(RoutineSchedule.Unknown("fortnightly")) } + } + + @Test + fun `a member's tag is sent though it's the default`() { + val sent = json.parseToJsonElement(json.encodeToString(RoutineSchedule.Cron(expression = "0 9 * * 1"))) + assertEquals(JsonObject(mapOf("repeat" to JsonPrimitive("cron"), "expression" to JsonPrimitive("0 9 * * 1"))), sent) + } + + @Test + fun `an untagged union tries each member`() { + val day = { text: String -> json.decodeFromString(text) } + assertEquals(RoutineSchedule.Monthly.DayOfMonth.Last, day("\"last\"")) + assertEquals(RoutineSchedule.Monthly.DayOfMonth.Integer(15), day("15")) + assertFailsWith { day("\"first\"") } + assertEquals("15", json.encodeToString(RoutineSchedule.Monthly.DayOfMonth.Integer(15))) + } + + @Test + fun `a clearable field is left out to keep its value, and sent as null to clear it`() { + assertEquals("{}", json.encodeToString(PodUpdate())) + assertEquals("""{"name":"Ops","slug":null}""", json.encodeToString(PodUpdate(name = "Ops", slug = Omittable.Present(null)))) + assertEquals("""{"color":"green"}""", json.encodeToString(PodUpdate(color = Omittable.Present(PodColor.GREEN)))) + + assertEquals(PodUpdate(), json.decodeFromString("{}")) + assertEquals(PodUpdate(slug = Omittable.Present(null)), json.decodeFromString("""{"slug":null}""")) + } + + @Test + fun `a required field that may be null is sent as null, and read as null when left out`() { + assertEquals("""{"items":[],"nextCursor":null}""", json.encodeToString(ChatMessagesPage(items = emptyList()))) + assertEquals(ChatMessagesPage(items = emptyList()), json.decodeFromString("""{"items":[]}""")) + } + + /** Stops a request once the transport has it, to look at what was sent. */ + private class Sent(val request: ApiRequest) : Exception() + + private val recordingClient = ApiClient({ request -> throw Sent(request) }) + + @Test + fun `a route sends its body's fields, and its path's values escaped`() = runTest { + val request = assertFailsWith { + recordingClient.pods.update("pod 1", name = "Ops", slug = Omittable.Present(null)) + }.request + assertEquals("PATCH", request.method) + assertEquals("pods/pod%201", request.path) + assertEquals("""{"name":"Ops","slug":null}""", assertIs(request.body).text) + } + + @Test + fun `a route sends the query parameters it's given, and leaves out the rest`() = runTest { + val request = assertFailsWith { recordingClient.chats.messages("c1", limit = 20) }.request + assertEquals("conversations/c1/messages", request.path) + assertEquals(listOf("limit" to "20"), request.query) + } + + @Test + fun `a failure is thrown in the API's words`() = runTest { + val client = ApiClient({ ApiResponse(404, """{"_tag":"NotFound","message":"No such pod."}""".encodeToByteArray()) }) + val failure = assertFailsWith { client.pods.remove("pod-1") } + assertEquals(404, failure.status) + assertEquals("No such pod.", failure.message) + } +} diff --git a/apps/codegen/api/kotlin.ts b/apps/codegen/api/kotlin.ts new file mode 100644 index 000000000..ba8e90385 --- /dev/null +++ b/apps/codegen/api/kotlin.ts @@ -0,0 +1,624 @@ +/** + * Writes the API model as Kotlin, in package `ai.sugabots.api`: a + * kotlinx.serialization type for each of the API's types, and a `suspend` + * function for each route, grouped as the web's client groups them, so + * `api.threads.get(...)` in TypeScript is `client.threads.get(...)` in Kotlin. + * + * It is written against `ApiSupport.kt` beside it: `ApiCaller`, `QueryItems`, + * `Omittable`, `OpenEnum` and the serializers there. + * + * - A struct is a `data class`. A field that may be left out defaults to null, + * and a clearable one is an `Omittable`, which tells left out from null. + * - An enum is an `enum class` that reads a value it doesn't know as `UNKNOWN`. + * - A union is a `sealed interface`. A member defined inline implements it; any + * other is wrapped in a case of its own. A tagged union reads a tag it doesn't + * know as `Unknown`. + */ +import { + type ApiModel, + type Definition, + type Operation, + type OperationGroup, + operationTypes, + type Presence, + type Property, + routesClassName, + type StringEnum, + type Struct, + type TaggedCase, + type TaggedUnion, + type TypeRef, + type UntaggedCase, + type UntaggedUnion, +} from "./model.ts"; +import { camelCase, words } from "./naming.ts"; + +const packageName = "ai.sugabots.api"; +const indentUnit = " "; + +const kotlinKeywords = new Set( + "as break class continue do else false for fun if in interface is null object package return super this throw true try typealias typeof val var when while".split( + " ", + ), +); + +/** A name as Kotlin will take it: backquoted when it's a keyword. */ +function identifier(name: string): string { + return kotlinKeywords.has(name) ? `\`${name}\`` : name; +} + +/** A Kotlin string literal: JSON's, with `$` escaped so it isn't a template. */ +function kotlinString(value: string): string { + return JSON.stringify(value).replaceAll("$", "\\$"); +} + +function docComment(text: string | undefined): string[] { + if (text === undefined || text.trim() === "") return []; + // Kotlin comments nest, so a `/*` or `*/` in the text would end the comment early or never. + const lines = text + .trim() + .split("\n") + .map((line) => line.trim().replaceAll("/*", "/ *").replaceAll("*/", "* /")); + if (lines.length === 1) return [`/** ${lines[0]} */`]; + return ["/**", ...lines.map((line) => ` * ${line}`.trimEnd()), " */"]; +} + +function indented(lines: string[], depth = 1): string[] { + const prefix = indentUnit.repeat(depth); + return lines.map((line) => (line ? prefix + line : line)); +} + +/** An enum case's label as a constant's name: `inProgress` → `IN_PROGRESS`. */ +function constantName(label: string): string { + const name = words(label) + .map((word) => word.toUpperCase()) + .join("_"); + return /^[0-9]/.test(name) ? `_${name}` : name; +} + +function isInlineStruct(type: TypeRef): type is { kind: "inline"; definition: Struct } { + return type.kind === "inline" && type.definition.kind === "struct"; +} + +/** A Kotlin number literal for `value`, a field's one allowed value, as a `Long` or a `Double`. */ +function numberLiteral(value: number, type: TypeRef): string { + if (type.kind === "integer") { + if (!Number.isInteger(value)) + throw new Error(`The integer field's fixed value ${value} isn't an integer.`); + return `${value}L`; + } + return Number.isInteger(value) ? `${value}.0` : `${value}`; +} + +/** + * Writes each definition where the model nests it. `enclosing` is how a type + * nested at that point is reached from the top of the file: `Outer.`, or `` at + * the top. + */ +class KotlinWriter { + private readonly model: ApiModel; + + constructor(model: ApiModel) { + this.model = model; + } + + // MARK: Types + + /** The Kotlin type for `type`, with `inlinePrefix` before an inline type's name. */ + private typeOf(type: TypeRef, inlinePrefix = ""): string { + switch (type.kind) { + case "reference": + return type.name; + case "nullable": + return `${this.typeOf(type.type, inlinePrefix)}?`; + case "inline": + return inlinePrefix + type.definition.name; + case "array": + return `List<${this.typeOf(type.items, inlinePrefix)}>`; + case "map": + return `Map`; + case "string": + return "String"; + case "integer": + return "Long"; + case "number": + return type.acceptsNonFiniteStrings + ? "@Serializable(with = NonFiniteDoubleSerializer::class) Double" + : "Double"; + case "boolean": + return "Boolean"; + case "dateTime": + return "Instant"; + case "binary": + return "ByteArray"; + case "json": + return "JsonElement"; + } + } + + /** The definition a reference names, looking through aliases. */ + private resolve(type: TypeRef): TypeRef { + if (type.kind !== "reference") return type; + const definition = this.model.components.find( + (component) => component.name === type.name, + )?.definition; + if (!definition) return type; + return definition.kind === "alias" + ? this.resolve(definition.type) + : { kind: "inline", definition }; + } + + /** A path's or query's value as the string the API reads. */ + private text(type: TypeRef, value: string): string { + const resolved = this.resolve(type); + switch (resolved.kind) { + case "string": + return value; + case "integer": + case "number": + case "boolean": + return `${value}.toString()`; + case "dateTime": + return `formatTimestamp(${value})`; + case "inline": + if (resolved.definition.kind === "enum") return `${value}.rawValue`; + break; + default: + break; + } + throw new Error(`A ${resolved.kind} can't be sent in a path or query.`); + } + + // MARK: Definitions + + /** + * `definition`'s declaration, and those of the types nested in it, with + * `parent` the sealed interface it implements. + */ + private definition(definition: Definition, enclosing: string, parent?: string): string[] { + switch (definition.kind) { + case "struct": + return this.struct(definition, enclosing, parent); + case "enum": + return this.stringEnum(definition, enclosing); + case "taggedUnion": + return this.taggedUnion(definition, enclosing); + case "untaggedUnion": + return this.untaggedUnion(definition, enclosing); + case "alias": + // A type alias can't hold types, so what it names sits beside it, at the top of the file. + return [ + ...docComment(definition.description), + `typealias ${definition.name} = ${this.typeOf(definition.type)}`, + ...this.nestedIn(definition.type, "").flatMap((lines) => ["", ...lines]), + ]; + } + } + + /** The declarations of the inline types `type` uses. */ + private nestedIn(type: TypeRef, enclosing: string): string[][] { + switch (type.kind) { + case "inline": + return [this.definition(type.definition, enclosing)]; + case "nullable": + return this.nestedIn(type.type, enclosing); + case "array": + return this.nestedIn(type.items, enclosing); + case "map": + return this.nestedIn(type.values, enclosing); + default: + return []; + } + } + + /** A class's body: its nested declarations, blank lines between. */ + private body(blocks: string[][]): string[] { + return blocks.flatMap((lines, index) => (index === 0 ? lines : ["", ...lines])); + } + + /** The name kotlinx.serialization knows a type by: its path from the package. */ + private serialName(definition: Definition, enclosing: string): string { + return `${packageName}.${enclosing}${definition.name}`; + } + + private struct(struct: Struct, enclosing: string, parent?: string): string[] { + const name = struct.name; + const inside = `${enclosing}${name}.`; + const supertype = parent ? ` : ${parent}` : ""; + const nested = this.body( + struct.properties.flatMap((property) => this.nestedIn(property.type, inside)), + ); + // A data class needs a field, so one without is a plain class. + const header = + struct.properties.length === 0 + ? [`class ${name}${supertype}`] + : [ + `data class ${name}(`, + ...indented(struct.properties.flatMap((property) => this.field(property))), + `)${supertype}`, + ]; + if (nested.length > 0) header.push(`${header.pop()} {`, ...indented(nested), "}"); + return [...docComment(struct.description), "@Serializable", ...header]; + } + + /** A struct's field, as a constructor's parameter. */ + private field(property: Property): string[] { + const annotations = + property.name === property.jsonName + ? [] + : [`@SerialName(${kotlinString(property.jsonName)})`]; + const declaration = `${identifier(property.name)}: ${fieldType(property.presence, this.typeOf(property.type))}`; + return [ + ...docComment(property.description), + `${[...annotations, this.parameter(property, declaration)].join(" ")},`, + ]; + } + + /** `declaration`, a field's name and type, as a constructor's parameter with its default. */ + private parameter(property: Property, declaration: string): string { + const presence = property.presence; + switch (presence.kind) { + case "clearable": + return `val ${declaration} = Omittable.Omitted`; + case "fixed": { + const fixed = + typeof presence.value === "string" + ? kotlinString(presence.value) + : numberLiteral(presence.value, property.type); + // A field with one allowed value is sent though it's the default. + return `@EncodeDefault val ${declaration} = ${fixed}`; + } + case "requiredOrNull": + // A required field that may be null is sent as null, where a default is otherwise left out. + return `@EncodeDefault val ${declaration} = null`; + case "optional": + return `val ${declaration} = null`; + case "required": + return `val ${declaration}`; + } + } + + private stringEnum(stringEnum: StringEnum, enclosing: string): string[] { + const name = stringEnum.name; + const unknown = constantName(stringEnum.unknownLabel); + return [ + ...docComment(stringEnum.description), + `@Serializable(with = ${name}.Serializer::class)`, + `enum class ${name}(override val rawValue: String) : OpenEnum {`, + ...indented([ + ...stringEnum.cases.map( + (entry) => `${constantName(entry.label)}(${kotlinString(entry.value)}),`, + ), + "", + "/** A value from a newer server than this app knows, which can't be sent. */", + `${unknown}("");`, + "", + `object Serializer : OpenEnumSerializer<${name}>(${kotlinString(this.serialName(stringEnum, enclosing))}, entries, ${unknown})`, + ]), + "}", + ]; + } + + // MARK: Unions + + /** A union's cases: each inline member, which implements it, or a wrapper of a member's value and the types it uses. */ + private unionCases(union: TaggedUnion | UntaggedUnion, enclosing: string): string[][] { + const inside = `${enclosing}${union.name}.`; + const cases: (TaggedCase | UntaggedCase)[] = union.cases; + return cases.flatMap((entry) => { + if (!entry.type) return [[`data object ${entry.className} : ${union.name}`]]; + if (isInlineStruct(entry.type)) + return [this.struct(entry.type.definition, inside, union.name)]; + return [ + [`data class ${entry.className}(val value: ${this.typeOf(entry.type)}) : ${union.name}`], + ...this.nestedIn(entry.type, inside), + ]; + }); + } + + private taggedUnion(union: TaggedUnion, enclosing: string): string[] { + const name = union.name; + const unknown = union.unknownCase.className; + const decode = union.cases.map((entry) => { + const tags = entry.tagValues.map(kotlinString).join(", "); + if (isInlineStruct(entry.type)) + return `${tags} -> json.decodeFromJsonElement<${entry.className}>(element)`; + return `${tags} -> ${entry.className}(json.decodeFromJsonElement<${this.typeOf(entry.type)}>(element))`; + }); + const encode = union.cases.map((entry) => { + if (isInlineStruct(entry.type)) + return `is ${entry.className} -> json.encodeToJsonElement<${entry.className}>(value)`; + return `is ${entry.className} -> json.encodeToJsonElement<${this.typeOf(entry.type)}>(value.value)`; + }); + return [ + ...docComment(union.description), + `@Serializable(with = ${name}.Serializer::class)`, + `sealed interface ${name} {`, + ...indented([ + ...this.body(this.unionCases(union, enclosing)), + "", + `/** A kind from a newer server than this app knows, by its \`${union.tag}\`, which can't be sent. */`, + `data class ${unknown}(val tag: String) : ${name}`, + "", + `object Serializer : JsonUnionSerializer<${name}>(${kotlinString(this.serialName(union, enclosing))}) {`, + ...indented([ + `override fun decode(element: JsonElement, json: Json): ${name} =`, + ...indented([`when (val tag = tagOf(element, ${kotlinString(union.tag)})) {`]), + ...indented([...decode, `else -> ${unknown}(tag)`], 2), + ...indented(["}"]), + "", + `override fun encode(value: ${name}, json: Json): JsonElement =`, + ...indented(["when (value) {"]), + ...indented( + [ + ...encode, + `is ${unknown} -> throw SerializationException("A kind this app doesn't know can't be sent.")`, + ], + 2, + ), + ...indented(["}"]), + ]), + "}", + ]), + "}", + ]; + } + + /** A union whose members share no tag: each is tried in turn, in the order the model lists them. */ + private untaggedUnion(union: UntaggedUnion, enclosing: string): string[] { + const name = union.name; + const decode = union.cases.map((entry) => { + if (!entry.type) + return `if (element.isString(${kotlinString(entry.literal)})) return ${entry.className}`; + if (isInlineStruct(entry.type)) + return `json.decodeOrNull<${entry.className}>(element)?.let { return it }`; + return `json.decodeOrNull<${this.typeOf(entry.type)}>(element)?.let { return ${entry.className}(it) }`; + }); + const encode = union.cases.map((entry) => { + if (!entry.type) + return `is ${entry.className} -> JsonPrimitive(${kotlinString(entry.literal)})`; + if (isInlineStruct(entry.type)) + return `is ${entry.className} -> json.encodeToJsonElement<${entry.className}>(value)`; + return `is ${entry.className} -> json.encodeToJsonElement<${this.typeOf(entry.type)}>(value.value)`; + }); + return [ + ...docComment(union.description), + `@Serializable(with = ${name}.Serializer::class)`, + `sealed interface ${name} {`, + ...indented([ + ...this.body(this.unionCases(union, enclosing)), + "", + `object Serializer : JsonUnionSerializer<${name}>(${kotlinString(this.serialName(union, enclosing))}) {`, + ...indented([ + `override fun decode(element: JsonElement, json: Json): ${name} {`, + ...indented([ + ...decode, + `throw SerializationException(${kotlinString(`None of ${name}'s kinds.`)})`, + ]), + "}", + "", + `override fun encode(value: ${name}, json: Json): JsonElement =`, + ...indented(["when (value) {"]), + ...indented(encode, 2), + ...indented(["}"]), + ]), + "}", + ]), + "}", + ]; + } + + /** The declaration for one of the API's named types. */ + component(definition: Definition): string[] { + return this.definition(definition, ""); + } + + // MARK: Requests + + /** + * `ApiClient`, with a property for each group of routes, and a class for + * each group. The client sends through an `ApiCaller` of its own, which + * writes JSON with `ApiJson`, so an `Omittable` left out is never written. + */ + client(groups: OperationGroup[]): string[] { + const named = groups.filter((group) => group.name); + const ungrouped = groups.find((group) => !group.name); + const client = [ + "/**", + " * The API's routes, grouped as the web's client groups them: `api.threads.get(...)`", + " * there is `client.threads.get(...)` here.", + " */", + "class ApiClient(transport: ApiTransport) {", + ...indented( + this.body([ + ["private val caller = ApiCaller(transport, ApiJson)"], + ...named.map((group) => [ + `/** The \`${group.name}\` routes, as \`api.${group.name}\` in the web's client. */`, + `val ${identifier(camelCase(group.name))}: ${routesClassName(group.name)} = ${routesClassName(group.name)}(caller)`, + ]), + ...(ungrouped ? this.routes(ungrouped, "ApiClient.") : []), + ]), + ), + "}", + ]; + const routeClasses = named.map((group) => { + const className = routesClassName(group.name); + return [ + `/** The \`${group.name}\` routes, as \`api.${group.name}\` in the web's client. */`, + `class ${className} internal constructor(private val caller: ApiCaller) {`, + ...indented(this.body(this.routes(group, `${className}.`))), + "}", + ]; + }); + return this.body([client, ...routeClasses]); + } + + /** A group's functions, then the types they use defined inline. */ + private routes(group: OperationGroup, enclosing: string): string[][] { + return [ + ...group.operations.map((operation) => this.request(operation)), + ...group.operations.flatMap((operation) => + operationTypes(operation).flatMap((type) => this.nestedIn(type, enclosing)), + ), + ]; + } + + private request(operation: Operation): string[] { + const parameters: string[] = []; + for (const parameter of operation.pathParameters) { + parameters.push(`${identifier(parameter.argumentName)}: ${this.typeOf(parameter.type)}`); + } + const query: string[] = []; + for (const parameter of operation.query) { + const base = this.typeOf(parameter.type); + const name = identifier(parameter.argumentName); + parameters.push(parameter.optional ? `${name}: ${base}? = null` : `${name}: ${base}`); + query.push( + this.queryLine( + parameter.name, + name, + parameter.type, + parameter.optional, + parameter.encoding, + ), + ); + } + const body = this.requestBody(operation); + parameters.push(...body.parameters); + + const returns = + operation.response.kind === "json" + ? this.typeOf(operation.response.type) + : operation.response.kind === "binary" + ? "ByteArray" + : undefined; + const path = operation.path.replace(/^\//, "").replace(/\{([^}]+)\}/g, (_, name: string) => { + const parameter = operation.pathParameters.find((candidate) => candidate.name === name); + if (!parameter) + throw new Error(`${operation.path} names {${name}}, which isn't one of its parameters.`); + return `\${pathSegment(${this.text(parameter.type, identifier(parameter.argumentName))})}`; + }); + const callArguments = [ + kotlinString(operation.method), + `"${path}"`, + ...(query.length > 0 ? ["query"] : []), + ...(body.argument ? [`body = ${body.argument}`] : []), + ].join(", "); + const call = + operation.response.kind === "json" + ? `return caller.call(${callArguments})` + : operation.response.kind === "binary" + ? `return caller.callForData(${callArguments})` + : `caller.callForData(${callArguments})`; + return [ + ...docComment(operation.description), + `suspend fun ${identifier(camelCase(operation.name))}(${parameters.join(", ")})${returns ? `: ${returns}` : ""} {`, + ...indented([...(query.length > 0 ? ["val query = QueryItems()", ...query] : []), call]), + "}", + ]; + } + + private queryLine( + jsonName: string, + value: string, + type: TypeRef, + optional: boolean, + encoding: "single" | "repeated", + ): string { + const name = kotlinString(jsonName); + if (encoding === "repeated") { + const items = type.kind === "array" ? type.items : type; + const each = this.text(items, "it"); + const values = each === "it" ? value : `${value}${optional ? "?" : ""}.map { ${each} }`; + return `query.addAll(${name}, ${values})`; + } + const text = this.text(type, "it"); + if (text === "it") return `query.add(${name}, ${value})`; + return optional + ? `query.add(${name}, ${value}?.let { ${text} })` + : `query.add(${name}, ${this.text(type, value)})`; + } + + /** How a request's body is taken: the fields the model gives as arguments, so a call reads `update(podId, name = ...)`, or whole. */ + private requestBody(operation: Operation): { parameters: string[]; argument?: string } { + if (operation.body.kind === "binary") { + return { parameters: ["data: ByteArray"], argument: "ApiRequestBody.Bytes(data)" }; + } + if (operation.body.kind === "none") return { parameters: [] }; + const type = this.typeOf(operation.body.type); + const fields = operation.body.fields; + if (!fields) return { parameters: [`body: ${type}`], argument: "caller.jsonBody(body)" }; + // The body's own nested types, named from outside it. + const parameters = fields.map((field) => { + const declared = `${identifier(field.name)}: ${fieldType(field.presence, this.typeOf(field.type, `${type}.`))}`; + return `${declared}${argumentDefault(field.presence)}`; + }); + const values = fields + .map((field) => identifier(field.name)) + .map((name) => `${name} = ${name}`) + .join(", "); + return { parameters, argument: `caller.jsonBody(${type}(${values}))` }; + } +} + +/** A field's type as a parameter declares it, given its type without null, `base`. */ +function fieldType(presence: Presence, base: string): string { + switch (presence.kind) { + case "clearable": + return `Omittable<${base}?>`; + case "required": + case "fixed": + return base; + case "requiredOrNull": + case "optional": + return `${base}?`; + } +} + +/** What a call's argument for a field of a body defaults to, as Kotlin writes it after the type. */ +function argumentDefault(presence: Presence): string { + switch (presence.kind) { + case "clearable": + return " = Omittable.Omitted"; + case "required": + case "fixed": + return ""; + case "requiredOrNull": + case "optional": + return " = null"; + } +} + +/** `Api.generated.kt`'s contents. */ +export function kotlinApi(model: ApiModel): string { + const writer = new KotlinWriter(model); + const declarations = model.components.map((component) => writer.component(component.definition)); + return [ + "// Generated by apps/codegen/generate-api.ts from packages/contracts/openapi.json. Don't edit it by hand.", + "@file:OptIn(ExperimentalSerializationApi::class)", + "@file:UseSerializers(InstantSerializer::class)", + "", + `package ${packageName}`, + "", + "import java.time.Instant", + "import kotlinx.serialization.EncodeDefault", + "import kotlinx.serialization.ExperimentalSerializationApi", + "import kotlinx.serialization.SerialName", + "import kotlinx.serialization.Serializable", + "import kotlinx.serialization.SerializationException", + "import kotlinx.serialization.UseSerializers", + "import kotlinx.serialization.json.Json", + "import kotlinx.serialization.json.JsonElement", + "import kotlinx.serialization.json.JsonPrimitive", + "import kotlinx.serialization.json.decodeFromJsonElement", + "import kotlinx.serialization.json.encodeToJsonElement", + "", + "// MARK: Schemas", + ...declarations.flatMap((lines) => ["", ...lines]), + "", + "// MARK: Requests", + "", + ...writer.client(model.groups), + "", + ].join("\n"); +} diff --git a/apps/codegen/api/model.ts b/apps/codegen/api/model.ts new file mode 100644 index 000000000..0caa6ea82 --- /dev/null +++ b/apps/codegen/api/model.ts @@ -0,0 +1,943 @@ +/** + * The API as the apps see it, read from `packages/contracts/openapi.json`: its + * named types and its routes, in terms no one language owns. Each emitter + * writes it out in its own language. + * + * What Effect's OpenAPI means is settled here, so every language reads it + * alike: + * + * - The apps are often older than the server they talk to, so an enum or a + * tagged union decodes a value it has never heard of as unknown rather than + * failing the whole response, and a field it doesn't know is ignored. + * - Effect writes a field that may be left out as "it, or null", so a field + * that may also be null is that twice over. In what a request sends, such a + * field is clearable: left out, it keeps its value; sent as null, it clears it. + * - A union whose members share a property with values of their own is told + * apart by it; any other is decoded by trying each member in turn. + * - Numbers JSON can't hold are written as strings beside a number. + * - A query carries only strings, so Effect writes a number in one as a string + * of digits. It is an integer here, which each app writes out as text. + * + * Every name is settled here too: each inline type's, kept apart from the types + * nested beside and around it and from the API's types it would hide, and each + * field's and case's, kept apart from the others in its type. + */ +import { + camelCase, + MemberNames, + pascalCase, + reservedTypeNames, + singular, + TypeScope, +} from "./naming.ts"; + +// MARK: The model + +/** What a value is: a type of its own, defined inline or named, or one built from others. */ +export type TypeRef = + | { kind: "string" | "integer" | "boolean" | "dateTime" | "binary" | "json" } + /** A number, which may also come as the strings `Infinity`, `-Infinity` or `NaN`. */ + | { kind: "number"; acceptsNonFiniteStrings: boolean } + /** One of the API's named types, by its name. */ + | { kind: "reference"; name: string } + /** A type defined where it's used, which an emitter nests in the type that uses it. */ + | { kind: "inline"; definition: Definition } + | { kind: "array"; items: TypeRef } + /** An object whose keys are any strings, and whose values are all one type. */ + | { kind: "map"; values: TypeRef } + | { kind: "nullable"; type: NonNullableTypeRef }; + +export type NonNullableTypeRef = Exclude; + +export type Definition = Struct | StringEnum | TaggedUnion | UntaggedUnion | Alias; + +/** + * Every definition has a `name`, in PascalCase: a named type's own, or an + * inline one's, unique among the types nested beside it, different from the + * types it is nested in, and never one of the API's types that the type it is + * nested in refers to, which it would hide there. An inline type in an alias + * sits beside the alias, at the top of the file, where its name is unique too. + */ +export interface Struct { + kind: "struct"; + name: string; + description?: string; + properties: Property[]; +} + +export interface Property { + jsonName: string; + /** Its name as a field or an argument, in camelCase, unique among its struct's. */ + name: string; + /** Its type, without the null `presence` may allow. */ + type: NonNullableTypeRef; + presence: Presence; + description?: string; +} + +/** Whether a field must be there, and whether it may be null. */ +export type Presence = + /** Always there, and never null. */ + | { kind: "required" } + /** Always there, maybe as null, which is written out rather than left out. */ + | { kind: "requiredOrNull" } + /** May be left out; where it's read, null means the same. */ + | { kind: "optional" } + /** Only in what a request sends: left out, it keeps its value; sent as null, it clears it. */ + | { kind: "clearable" } + /** Always there with the one value it allows, such as a union member's `kind`, filled in so a caller needn't write it. */ + | { kind: "fixed"; value: string | number }; + +/** A string with a few known values, which decodes any other as unknown. */ +export interface StringEnum { + kind: "enum"; + name: string; + description?: string; + cases: EnumCase[]; + /** The case a value it doesn't know is, in camelCase, unique among `cases`' labels. */ + unknownLabel: string; +} + +export interface EnumCase { + value: string; + /** The case's name, in camelCase, unique among its enum's. */ + label: string; +} + +/** A union told apart by `tag`, which decodes a tag it doesn't know as unknown. */ +export interface TaggedUnion { + kind: "taggedUnion"; + name: string; + description?: string; + tag: string; + cases: TaggedCase[]; + /** The case a tag it doesn't know is, holding that tag. */ + unknownCase: { label: string; className: string }; +} + +export interface TaggedCase { + /** The case's name, in camelCase, unique among its union's. */ + label: string; + /** + * The name of the type nested in the union that this case is, for a + * language whose union cases are types: an inline struct's own, or another + * that wraps the case's value. + */ + className: string; + /** The values of the tag that mean this case. */ + tagValues: string[]; + type: TypeRef; +} + +/** + * A union whose members share no tag, decoded by trying each case in the order + * `cases` lists them: exact strings first, then objects, those requiring the + * most fields first, then anything else. + */ +export interface UntaggedUnion { + kind: "untaggedUnion"; + name: string; + description?: string; + cases: UntaggedCase[]; +} + +/** A case that is a value of a type, or exactly one string. `label` and `className` are as a tagged case's. */ +export type UntaggedCase = + | { label: string; className: string; type: TypeRef; literal?: undefined } + | { label: string; className: string; type?: undefined; literal: string }; + +/** Another name for a type, for a named schema that isn't a struct, enum or union of its own. */ +export interface Alias { + kind: "alias"; + name: string; + description?: string; + type: TypeRef; +} + +/** A named type and its definition. A reference to it is nullable where its schema allows null. */ +export interface Component { + name: string; + definition: Definition; +} + +/** The routes the web's client groups as `api.`. */ +export interface OperationGroup { + /** The group's name, or `""` for the routes outside any group. */ + name: string; + operations: Operation[]; +} + +export interface Operation { + /** The route's name within its group, as the web's client calls it. */ + name: string; + method: string; + /** The route's path, with `{parameter}` placeholders. */ + path: string; + description?: string; + pathParameters: PathParameter[]; + query: QueryParameter[]; + body: RequestBody; + response: Payload; +} + +export interface PathParameter { + name: string; + /** Its name as an argument, in camelCase, unique among the route's parameters. */ + argumentName: string; + type: NonNullableTypeRef; +} + +export interface QueryParameter { + name: string; + /** Its name as an argument, in camelCase, unique among the route's parameters. */ + argumentName: string; + type: NonNullableTypeRef; + /** May be left out of the query. */ + optional: boolean; + /** `single` sends one `name=value`; `repeated` sends one for each of a list's items. */ + encoding: "single" | "repeated"; +} + +/** A response's body: none, bytes as they are, or JSON of a type. */ +export type Payload = { kind: "none" } | { kind: "binary" } | { kind: "json"; type: TypeRef }; + +/** A request's body: none, bytes as they are, or JSON of a type. */ +export type RequestBody = + | { kind: "none" } + | { kind: "binary" } + | { + kind: "json"; + type: TypeRef; + /** + * The fields a call takes as its own arguments, so a call reads + * `update(podId:name:)`: a struct body's fields but its fixed ones, + * unless one shares a name with a path or query parameter, when the + * call takes the body whole. + */ + fields?: Property[]; + }; + +export interface ApiModel { + /** The API's named types, by name. */ + components: Component[]; + /** The routes, by group, groups by name. Routes answered with an event stream are left out. */ + groups: OperationGroup[]; +} + +/** The types an operation names, in the order it names them. */ +export function operationTypes(operation: Operation): TypeRef[] { + return [ + ...operation.pathParameters.map((parameter) => parameter.type), + ...operation.query.map((parameter) => parameter.type), + ...(operation.body.kind === "json" ? [operation.body.type] : []), + ...(operation.response.kind === "json" ? [operation.response.type] : []), + ]; +} + +// MARK: OpenAPI + +type Json = null | boolean | number | string | Json[] | { [key: string]: Json }; +type Schema = { [key: string]: Json }; + +interface OpenApiOperation { + operationId: string; + summary?: string; + description?: string; + parameters?: OpenApiParameter[]; + requestBody?: { content: Record }; + responses: Record }>; +} + +interface OpenApiParameter { + name: string; + in: "path" | "query"; + required?: boolean; + description?: string; + schema: Schema; +} + +export interface OpenApiDocument { + paths: Record>; + components: { schemas: Record }; +} + +/** The routes whose answer is a stream, which each app reads itself. */ +const streamContentType = "text/event-stream"; + +const componentPrefix = "#/components/schemas/"; + +/** Numbers JSON can't hold, which Effect writes as strings beside a number. */ +const nonFiniteNumbers = ["Infinity", "-Infinity", "NaN"]; + +const isNull = (schema: Json) => isObject(schema) && schema.type === "null"; + +function isObject(value: Json | undefined): value is Schema { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +function list(value: Json | undefined): Schema[] { + return Array.isArray(value) ? value.filter(isObject) : []; +} + +function descriptionOf(schema: Schema): string | undefined { + return typeof schema.description === "string" ? schema.description : undefined; +} + +/** `type`, allowing null too. */ +function nullable(type: TypeRef): TypeRef { + return type.kind === "nullable" ? type : { kind: "nullable", type }; +} + +function withoutNull(type: TypeRef): NonNullableTypeRef { + return type.kind === "nullable" ? type.type : type; +} + +/** The members of a union, nested unions flattened, and whether `null` is one of them. */ +function unionMembers(schema: Schema): { members: Schema[]; nullable: boolean } { + const members: Schema[] = []; + let nullable = false; + for (const member of list(schema.anyOf ?? schema.oneOf)) { + if (isNull(member)) { + nullable = true; + } else if (member.anyOf || member.oneOf) { + const inner = unionMembers(member); + members.push(...inner.members); + nullable ||= inner.nullable; + } else { + members.push(member); + } + } + return { members, nullable }; +} + +/** + * Whether a field that may be left out may also be sent as null, to clear it. + * Effect writes a field that may be left out as "it, or null", so one that may + * also be null is that twice over: `optional(NullOr(...))`. + */ +function isClearable(schema: Schema): boolean { + const members = list(schema.anyOf ?? schema.oneOf); + return ( + members.some(isNull) && + members.some((member) => list(member.anyOf ?? member.oneOf).some(isNull)) + ); +} + +/** The string values a schema allows, when it allows only a few. */ +function stringValues(schema: Schema): string[] | undefined { + if (!Array.isArray(schema.enum)) return undefined; + if (!schema.enum.every((value) => typeof value === "string")) return undefined; + return schema.enum as string[]; +} + +/** What a schema that is one thing or null is, when that thing is a type of its own. */ +function nullableMember(schema: Schema): Schema | undefined { + if (!schema.anyOf && !schema.oneOf) return undefined; + const { members, nullable } = unionMembers(schema); + const [only] = members; + if (!nullable || members.length !== 1 || !only || only.$ref) return undefined; + const isOwnType = + (only.type === "object" && isObject(only.properties)) || (stringValues(only)?.length ?? 0) > 1; + return isOwnType ? only : undefined; +} + +/** The one value an object's field allows, such as the `http` of `kind: "http"`, to name the object by. */ +function literalField(schema: Schema): string | undefined { + const properties = isObject(schema.properties) ? Object.values(schema.properties) : []; + for (const property of properties) { + if (!isObject(property)) continue; + const [only] = property.anyOf || property.oneOf ? unionMembers(property).members : [property]; + const values = only ? stringValues(only) : undefined; + if (values?.length === 1 && values[0]) return camelCase(values[0]); + } + return undefined; +} + +/** The one value a field allows. */ +function fixedValueOf(schema: Schema): string | number | undefined { + if (!Array.isArray(schema.enum) || schema.enum.length !== 1) return undefined; + const [value] = schema.enum; + return typeof value === "string" || typeof value === "number" ? value : undefined; +} + +/** The name of the component a `$ref` names, if it names one. */ +function referencedComponent(schema: Schema): string | undefined { + const reference = schema.$ref; + if (typeof reference !== "string" || !reference.startsWith(componentPrefix)) return undefined; + return reference.slice(componentPrefix.length); +} + +/** The names of the API's types that `value` refers to anywhere within it, without following them. */ +function referencedNames(value: Json | undefined, names = new Set()): Set { + if (Array.isArray(value)) { + for (const item of value) referencedNames(item, names); + return names; + } + if (!isObject(value)) return names; + const name = referencedComponent(value); + if (name !== undefined) names.add(pascalCase(name)); + for (const child of Object.values(value)) referencedNames(child, names); + return names; +} + +/** + * The scope of the types nested in a type at the top of the file called + * `name`, defined by `schemas`: their names mustn't hide one of the API's types + * that `schemas` refers to. + */ +function outermostScope( + name: string, + schemas: Json, + alsoReserved: ReadonlySet = new Set(), +): TypeScope { + const referenced = referencedNames(schemas); + return new TypeScope( + name, + (candidate) => + reservedTypeNames.has(candidate) || referenced.has(candidate) || alsoReserved.has(candidate), + ); +} + +/** The pattern of a query's number, which Effect writes as a string of digits. */ +const digitsPattern = "^\\d+$"; + +/** Whether `schema`, perhaps or null, is a number written as a string of digits. */ +function isDigitString(schema: Schema): boolean { + const members = schema.anyOf || schema.oneOf ? unionMembers(schema).members : [schema]; + const [only] = members; + return members.length === 1 && only?.type === "string" && only.pattern === digitsPattern; +} + +/** The class a group's routes are functions of. */ +export function routesClassName(groupName: string): string { + return `${pascalCase(groupName)}Routes`; +} + +/** The name of the scope the routes outside any group, and the types they define inline, are in. */ +const ungroupedScopeName = "ApiClient"; + +/** The order an untagged union's cases are tried in, by what each matches. */ +const decodingTiers = ["exactString", "object", "other"] as const; + +interface UntaggedCaseRead { + entry: UntaggedCase; + tier: (typeof decodingTiers)[number]; + /** How many fields an object requires: of two objects, the one requiring more is tried first. */ + requiredFields: number; +} + +function byDecodingOrder(a: UntaggedCaseRead, b: UntaggedCaseRead): number { + const tierOrder = decodingTiers.indexOf(a.tier) - decodingTiers.indexOf(b.tier); + return tierOrder !== 0 ? tierOrder : b.requiredFields - a.requiredFields; +} + +function isInlineStruct(type: TypeRef): type is { kind: "inline"; definition: Struct } { + return type.kind === "inline" && type.definition.kind === "struct"; +} + +/** + * Reads the model from an OpenAPI document. `sent` says whether the type being + * read is one a request sends, where a field left out and a field sent as null + * differ; inline types inherit it from where they're used. `scope` is where an + * inline type being read is nested, which names it. + */ +class ModelReader { + private readonly components: Record; + /** Named schemas that are something or null: each is defined as the something, and referred to as nullable. */ + private readonly nullableComponents: Set; + /** The named schemas some request sends. */ + private readonly sentComponents: Set; + private readonly document: OpenApiDocument; + /** The routes by the name of their group, groups by name. */ + private readonly routesByGroup: Map; + /** The top of the file, where the inline types an alias uses sit beside it, since an alias can't hold them. */ + private readonly topLevel: TypeScope; + /** The API's named types read so far, by name. */ + private readonly definitions = new Map(); + + constructor(document: OpenApiDocument) { + this.document = document; + this.components = document.components.schemas; + this.nullableComponents = new Set( + Object.entries(this.components) + .filter(([, schema]) => nullableMember(schema) !== undefined) + .map(([name]) => name), + ); + this.sentComponents = this.componentsSent(); + this.routesByGroup = this.routesGrouped(); + const topLevelNames = new Set([ + ...Object.keys(this.components).map(pascalCase), + ...[...this.routesByGroup.keys()].filter(Boolean).map(routesClassName), + ]); + this.topLevel = new TypeScope( + "", + (name) => reservedTypeNames.has(name) || topLevelNames.has(name), + ); + } + + read(): ApiModel { + const components = Object.entries(this.components) + .sort(([a], [b]) => a.localeCompare(b)) + .map(([key, schema]): Component => { + const definition = this.component(key, schema); + this.definitions.set(definition.name, definition); + return { name: definition.name, definition }; + }); + return { components, groups: this.groups() }; + } + + private componentsSent(): Set { + const sent = new Set(); + const visit = (value: Json | undefined): void => { + if (Array.isArray(value)) { + for (const item of value) visit(item); + return; + } + if (!isObject(value)) return; + const name = referencedComponent(value); + if (name !== undefined) { + if (sent.has(name)) return; + sent.add(name); + visit(this.components[name]); + } + for (const child of Object.values(value)) visit(child); + }; + for (const operations of Object.values(this.document.paths)) { + for (const operation of Object.values(operations)) visit(operation.requestBody as Json); + } + return sent; + } + + private resolve(schema: Schema): Schema { + const name = referencedComponent(schema); + const target = name === undefined ? undefined : this.components[name]; + return target ? this.resolve(target) : schema; + } + + // MARK: Types + + /** The type of `schema`. One that needs a type of its own, written inline, is named from `hint`. */ + private typeOf(schema: Schema, hint: string, sent: boolean, scope: TypeScope): TypeRef { + const component = referencedComponent(schema); + if (component !== undefined) { + const reference: TypeRef = { kind: "reference", name: pascalCase(component) }; + return this.nullableComponents.has(component) ? nullable(reference) : reference; + } + if (schema.anyOf || schema.oneOf) { + const members = unionMembers(schema); + const type = this.unionType(members.members, hint, sent, scope); + return members.nullable ? nullable(type) : type; + } + const values = stringValues(schema); + if (values && values.length > 1) { + return inline(stringEnum(scope.claim(pascalCase(hint)), values, descriptionOf(schema))); + } + if (Array.isArray(schema.enum) && schema.enum.every((value) => typeof value === "number")) { + return schema.enum.every(Number.isInteger) + ? { kind: "integer" } + : { kind: "number", acceptsNonFiniteStrings: false }; + } + switch (schema.type) { + case "string": + if (schema.format === "date-time") return { kind: "dateTime" }; + if (schema.format === "binary") return { kind: "binary" }; + return { kind: "string" }; + case "integer": + return { kind: "integer" }; + case "number": + return { kind: "number", acceptsNonFiniteStrings: false }; + case "boolean": + return { kind: "boolean" }; + case "array": { + const items = isObject(schema.items) ? schema.items : {}; + return { kind: "array", items: this.typeOf(items, singular(hint), sent, scope) }; + } + case "object": + return this.objectType(schema, hint, sent, scope); + default: + return { kind: "json" }; + } + } + + private objectType(schema: Schema, hint: string, sent: boolean, scope: TypeScope): TypeRef { + if (isObject(schema.properties) && Object.keys(schema.properties).length > 0) { + const name = scope.claim(pascalCase(hint)); + return inline(this.struct(name, schema, sent, scope.nested(name))); + } + if (isObject(schema.additionalProperties)) { + return { + kind: "map", + values: this.typeOf(schema.additionalProperties, singular(hint), sent, scope), + }; + } + const patterns = isObject(schema.patternProperties) + ? Object.values(schema.patternProperties) + : []; + const [pattern] = patterns.filter(isObject); + if (patterns.length === 1 && pattern) { + return { kind: "map", values: this.typeOf(pattern, singular(hint), sent, scope) }; + } + return { kind: "map", values: { kind: "json" } }; + } + + private unionType(members: Schema[], hint: string, sent: boolean, scope: TypeScope): TypeRef { + if (members.length === 0) return nullable({ kind: "json" }); + const [only] = members; + if (members.length === 1 && only) return this.typeOf(only, hint, sent, scope); + const kinds = members.map((member) => this.resolve(member)); + const isNonFiniteNumber = (member: Schema) => + stringValues(member)?.every((value) => nonFiniteNumbers.includes(value)) ?? false; + if ( + kinds.some((member) => member.type === "number") && + kinds.every((member) => member.type === "number" || isNonFiniteNumber(member)) + ) { + return { kind: "number", acceptsNonFiniteStrings: true }; + } + const strings = kinds.map(stringValues); + const hasReference = members.some((member) => member.$ref); + if (strings.every((values) => values !== undefined) && !hasReference) { + const name = scope.claim(pascalCase(hint)); + return inline(stringEnum(name, [...new Set(strings.flat())], undefined)); + } + const primitives = kinds.map((member) => + member.type === "object" || member.type === "array" || stringValues(member) + ? undefined + : member.type, + ); + const [firstPrimitive] = primitives; + if (firstPrimitive && primitives.every((type) => type === firstPrimitive) && !hasReference) { + // Differently checked strings, such as an id or a slug, are one string here. + return this.typeOf(kinds[0] ?? {}, hint, sent, scope); + } + const name = scope.claim(pascalCase(hint)); + return inline(this.union(name, members, undefined, sent, scope.nested(name))); + } + + // MARK: Definitions + + /** A struct called `name`, whose inline types are nested in `scope`. */ + private struct(name: string, schema: Schema, sent: boolean, scope: TypeScope): Struct { + const required = new Set(Array.isArray(schema.required) ? schema.required : []); + const properties = isObject(schema.properties) ? schema.properties : {}; + const names = new MemberNames(); + return { + kind: "struct", + name, + description: descriptionOf(schema), + properties: Object.entries(properties).flatMap(([jsonName, value]): Property[] => { + if (!isObject(value)) return []; + const memberName = names.claim(camelCase(jsonName) || "value"); + const type = this.typeOf(value, memberName, sent, scope); + return [ + { + jsonName, + name: memberName, + type: withoutNull(type), + presence: presenceOf(value, type, required.has(jsonName), sent), + description: descriptionOf(value), + }, + ]; + }), + }; + } + + /** The property every member of a union carries with values of its own, which tells them apart. */ + private discriminator( + members: Schema[], + ): { property: string; valuesByMember: string[][] } | undefined { + const resolved = members.map((member) => this.resolve(member)); + if (!resolved.every((member) => member.type === "object" && isObject(member.properties))) { + return undefined; + } + const [first] = resolved; + const candidates = Object.keys(isObject(first?.properties) ? first.properties : {}); + for (const property of candidates) { + const valuesByMember = resolved.map((member) => { + const value = isObject(member.properties) ? member.properties[property] : undefined; + return isObject(value) ? stringValues(this.resolve(value)) : undefined; + }); + if (!valuesByMember.every((values) => values !== undefined && values.length > 0)) continue; + const all = (valuesByMember as string[][]).flat(); + if (new Set(all).size === all.length) + return { property, valuesByMember: valuesByMember as string[][] }; + } + return undefined; + } + + /** A union called `name`, whose case types and inline types are nested in `scope`. */ + private union( + name: string, + members: Schema[], + description: string | undefined, + sent: boolean, + scope: TypeScope, + ): TaggedUnion | UntaggedUnion { + const tagged = this.discriminator(members); + if (!tagged) return this.untaggedUnion(name, members, description, sent, scope); + const labels = new MemberNames(); + const cases = members.map((member, index): TaggedCase => { + const tagValues = tagged.valuesByMember[index] ?? []; + const label = labels.claim(camelCase(tagValues.join(" or ")) || `case${index}`); + const type = this.typeOf(member, pascalCase(label), sent, scope); + return { label, className: caseClassName(type, label, scope), tagValues, type }; + }); + return { + kind: "taggedUnion", + name, + description, + tag: tagged.property, + cases, + unknownCase: { label: labels.claim("unknown"), className: scope.claim("Unknown") }, + }; + } + + private untaggedUnion( + name: string, + members: Schema[], + description: string | undefined, + sent: boolean, + scope: TypeScope, + ): UntaggedUnion { + const labels = new MemberNames(); + const cases = members.map((member, index): UntaggedCaseRead => { + const resolved = this.resolve(member); + const values = stringValues(resolved); + const [onlyValue] = values ?? []; + if (values?.length === 1 && onlyValue !== undefined && !member.$ref) { + const label = labels.claim(camelCase(onlyValue) || `case${index}`); + const entry = { label, className: scope.claim(pascalCase(label)), literal: onlyValue }; + return { entry, tier: "exactString", requiredFields: 0 }; + } + const reference = referencedComponent(member); + const label = labels.claim( + reference + ? camelCase(reference) + : (primitiveLabels[String(resolved.type)] ?? + literalField(resolved) ?? + `variant${index + 1}`), + ); + const type = this.typeOf(member, pascalCase(label), sent, scope); + const entry = { label, className: caseClassName(type, label, scope), type }; + if (resolved.type !== "object") return { entry, tier: "other", requiredFields: 0 }; + const requiredFields = Array.isArray(resolved.required) ? resolved.required.length : 0; + return { entry, tier: "object", requiredFields }; + }); + return { + kind: "untaggedUnion", + name, + description, + cases: cases.sort(byDecodingOrder).map(({ entry }) => entry), + }; + } + + private component(key: string, givenSchema: Schema): Definition { + const schema = nullableMember(givenSchema) ?? givenSchema; + const sent = this.sentComponents.has(key); + const name = pascalCase(key); + const description = descriptionOf(schema); + const scope = outermostScope(name, givenSchema); + if (schema.anyOf || schema.oneOf) { + const { members, nullable } = unionMembers(schema); + if (!nullable) { + const strings = members.map(stringValues); + if ( + strings.every((values) => values !== undefined) && + members.every((member) => !member.$ref) + ) { + return stringEnum(name, [...new Set(strings.flat())], description); + } + return this.union(name, members, description, sent, scope); + } + } + const values = stringValues(schema); + if (values && values.length > 1) return stringEnum(name, values, description); + if (schema.type === "object" && isObject(schema.properties)) + return this.struct(name, schema, sent, scope); + // Anything else, such as a nullable union, is another name for the type it spells. + const type = this.typeOf(schema, `${name}Value`, sent, this.topLevel); + return { kind: "alias", name, description, type }; + } + + // MARK: Operations + + private routesGrouped(): Map { + const groups = new Map(); + for (const [path, operations] of Object.entries(this.document.paths)) { + for (const [method, operation] of Object.entries(operations)) { + const group = operation.operationId.includes(".") + ? (operation.operationId.split(".")[0] ?? "") + : ""; + groups.set(group, [...(groups.get(group) ?? []), { path, method, operation }]); + } + } + return new Map([...groups].sort(([a], [b]) => a.localeCompare(b))); + } + + private groups(): OperationGroup[] { + const routesClassNames = new Set( + [...this.routesByGroup.keys()].filter(Boolean).map(routesClassName), + ); + return [...this.routesByGroup] + .map(([name, routes]) => { + const schemas = routes.map(({ operation }) => operation as unknown as Json); + // The client holds each group of routes, so a type nested in it mustn't hide their classes. + const scope = name + ? outermostScope(routesClassName(name), schemas) + : outermostScope(ungroupedScopeName, schemas, routesClassNames); + const operations = routes.flatMap(({ path, method, operation }) => { + const read = this.operation(path, method, operation, scope); + return read ? [read] : []; + }); + return { name, operations }; + }) + .filter(({ operations }) => operations.length > 0); + } + + /** A route, or nothing for one answered with an event stream. Its inline types are nested in `scope`. */ + private operation( + path: string, + method: string, + operation: OpenApiOperation, + scope: TypeScope, + ): Operation | undefined { + const success = Object.entries(operation.responses) + .filter(([status]) => status.startsWith("2")) + .sort(([a], [b]) => a.localeCompare(b))[0]?.[1]; + if (success?.content?.[streamContentType]) return undefined; + const name = operation.operationId.split(".").pop() ?? operation.operationId; + const hint = pascalCase(name); + const parameters = operation.parameters ?? []; + const argumentNames = new MemberNames(); + const pathParameters = parameters + .filter((parameter) => parameter.in === "path") + .map((parameter): PathParameter => { + const type = this.typeOf( + parameter.schema, + `${hint}${pascalCase(parameter.name)}`, + false, + scope, + ); + return { + name: parameter.name, + argumentName: argumentNames.claim(camelCase(parameter.name)), + type: withoutNull(type), + }; + }); + const query = parameters + .filter((parameter) => parameter.in === "query") + .map((parameter): QueryParameter => { + const type = this.typeOf( + parameter.schema, + `${hint}${pascalCase(parameter.name)}`, + false, + scope, + ); + const base: NonNullableTypeRef = isDigitString(parameter.schema) + ? { kind: "integer" } + : withoutNull(type); + return { + name: parameter.name, + argumentName: argumentNames.claim(camelCase(parameter.name)), + type: base, + optional: !parameter.required || type.kind === "nullable", + encoding: base.kind === "array" ? "repeated" : "single", + }; + }); + const parameterNames = new Set( + [...pathParameters, ...query].map((parameter) => parameter.argumentName), + ); + const body = this.requestBody(operation, hint, scope, parameterNames); + const json = success?.content?.["application/json"]?.schema; + const response: Payload = json + ? { kind: "json", type: this.typeOf(json, `${hint}Response`, false, scope) } + : success?.content?.["application/octet-stream"] + ? { kind: "binary" } + : { kind: "none" }; + return { + name, + method: method.toUpperCase(), + path, + description: operation.description ?? operation.summary, + pathParameters, + query, + body, + response, + }; + } + + private requestBody( + operation: OpenApiOperation, + hint: string, + scope: TypeScope, + parameterNames: Set, + ): RequestBody { + const content = operation.requestBody?.content ?? {}; + if (content["application/octet-stream"]) return { kind: "binary" }; + const schema = content["application/json"]?.schema; + if (!schema) return { kind: "none" }; + const type = this.typeOf(schema, `${hint}Body`, true, scope); + const fields = this.structOf(type)?.properties.filter( + (property) => property.presence.kind !== "fixed", + ); + if (!fields || fields.some((field) => parameterNames.has(field.name))) { + return { kind: "json", type }; + } + return { kind: "json", type, fields }; + } + + /** The struct `type` is, defined inline or named. */ + private structOf(type: TypeRef): Struct | undefined { + if (isInlineStruct(type)) return type.definition; + if (type.kind !== "reference") return undefined; + const definition = this.definitions.get(type.name); + return definition?.kind === "struct" ? definition : undefined; + } +} + +/** One route as the document lists it. */ +interface Route { + path: string; + method: string; + operation: OpenApiOperation; +} + +/** Whether a field of `schema`, read as `type`, must be there, and whether it may be null. */ +function presenceOf(schema: Schema, type: TypeRef, required: boolean, sent: boolean): Presence { + if (!required) return sent && isClearable(schema) ? { kind: "clearable" } : { kind: "optional" }; + const fixedValue = fixedValueOf(schema); + if (fixedValue !== undefined) return { kind: "fixed", value: fixedValue }; + return type.kind === "nullable" ? { kind: "requiredOrNull" } : { kind: "required" }; +} + +/** The class a union's case of `type` is: an inline struct itself, or a wrapper claimed in `scope`. */ +function caseClassName(type: TypeRef, label: string, scope: TypeScope): string { + return isInlineStruct(type) ? type.definition.name : scope.claim(pascalCase(label)); +} + +/** What an untagged union's case of a plain type is called. */ +const primitiveLabels: Record = { + integer: "integer", + number: "number", + string: "string", + boolean: "bool", + array: "array", +}; + +function inline(definition: Definition): TypeRef { + return { kind: "inline", definition }; +} + +function stringEnum(name: string, values: string[], description: string | undefined): StringEnum { + const labels = new MemberNames(); + return { + kind: "enum", + name, + description, + cases: values.map((value) => ({ value, label: labels.claim(camelCase(value) || "empty") })), + unknownLabel: labels.claim("unknown"), + }; +} + +export function readModel(document: OpenApiDocument): ApiModel { + return new ModelReader(document).read(); +} diff --git a/apps/codegen/api/naming.ts b/apps/codegen/api/naming.ts new file mode 100644 index 000000000..7ab273800 --- /dev/null +++ b/apps/codegen/api/naming.ts @@ -0,0 +1,108 @@ +/** + * Casing the API's names into the names a type, a field or a case is given, + * and keeping those names apart. Swift and Kotlin case alike, so the model + * settles every name once, and each emitter spells its own identifiers with them. + */ + +export function words(text: string): string[] { + return text + .replace(/([a-z0-9])([A-Z])/g, "$1 $2") + .split(/[^A-Za-z0-9]+/) + .filter(Boolean); +} + +export function pascalCase(text: string): string { + const result = words(text) + .map((word) => word.charAt(0).toUpperCase() + word.slice(1)) + .join(""); + return /^[0-9]/.test(result) ? `_${result}` : result; +} + +export function camelCase(text: string): string { + const pascal = pascalCase(text); + if (pascal.startsWith("_")) return pascal; + // `URLs` → `urls`, `ID` → `id`, `HTTPHeader` → `httpHeader`. + const leadingCapitals = pascal.match(/^[A-Z]+(?=[A-Z][a-z]|[0-9]|$)/)?.[0]; + if (leadingCapitals) return leadingCapitals.toLowerCase() + pascal.slice(leadingCapitals.length); + return pascal.charAt(0).toLowerCase() + pascal.slice(1); +} + +/** What one item of a list called `name` is called: `threads` → `thread`. */ +export function singular(name: string): string { + if (/ies$/.test(name)) return `${name.slice(0, -3)}y`; + if (/(ss|us|is)$/.test(name)) return `${name}Item`; + if (/s$/.test(name)) return name.slice(0, -1); + return `${name}Item`; +} + +/** + * Type names the generated Swift or Kotlin writes without qualifying them, from + * the language, Foundation, kotlinx.serialization and each app's API support + * file. A nested type of the same name would hide them from the code around it. + */ +export const reservedTypeNames: ReadonlySet = new Set( + [ + // Swift and Foundation + "Any Array Bool Data Date Decoder Dictionary Double Encoder Error Int None Optional Result Set Some String Type URL UUID Void", + // Kotlin and kotlinx.serialization + "Boolean Byte ByteArray Char Companion EncodeDefault Float Instant Json JsonElement JsonPrimitive List Long Map Nothing Number Serializable SerialName SerializationException Serializer Short Unit", + // `APISupport.swift` and `ApiSupport.kt` + "APIClient AnyCodingKey ApiCaller ApiClient Empty JSONValue Omittable OpenEnum ParameterValue QueryItems", + ] + .join(" ") + .split(" "), +); + +/** + * The names of the types nested in one type, which must differ from each other, + * from the type's own name, from the names of the types it is nested in, and + * from any name `isReserved` keeps for something a nested type would hide. + */ +export class TypeScope { + readonly name: string; + private readonly taken = new Set(); + private readonly isReserved: (name: string) => boolean; + + constructor(name: string, isReserved: (name: string) => boolean) { + this.name = name; + this.isReserved = isReserved; + } + + /** + * `wanted` when it's free; otherwise `wanted` and this scope's last word, so + * a `Routine` inside `ActivityItem` that would hide the API's own `Routine` is + * `RoutineItem`; then that numbered. + */ + claim(wanted: string): string { + const isFree = (name: string) => + !this.taken.has(name) && !this.isReserved(name) && name !== this.name; + const ownerWord = words(this.name).pop() ?? ""; + let name = isFree(wanted) ? wanted : `${wanted}${ownerWord}`; + for (let attempt = 2; !isFree(name); attempt += 1) name = `${wanted}${ownerWord}${attempt}`; + this.taken.add(name); + return name; + } + + /** The scope of the types nested in `name`, a type nested in this scope. */ + nested(name: string): TypeScope { + return new TypeScope( + name, + (candidate) => this.isReserved(candidate) || candidate === this.name, + ); + } +} + +/** + * The names of the members of one type, such as a struct's fields or an enum's + * cases: `wanted` when it's free, otherwise `wanted` numbered. + */ +export class MemberNames { + private readonly taken = new Set(); + + claim(wanted: string): string { + let name = wanted; + for (let attempt = 2; this.taken.has(name); attempt += 1) name = `${wanted}${attempt}`; + this.taken.add(name); + return name; + } +} diff --git a/apps/codegen/generate-api.ts b/apps/codegen/generate-api.ts new file mode 100644 index 000000000..69d2b3ac8 --- /dev/null +++ b/apps/codegen/generate-api.ts @@ -0,0 +1,31 @@ +/** + * Writes each app's API client from `packages/contracts/openapi.json`: a type + * for each schema the API names, and a typed request for each route, grouped as + * the web's client groups them. + * + * - Android: `api/src/main/kotlin/ai/sugabots/api/Api.generated.kt`, written by + * `api/kotlin.ts`. + * + * `api/model.ts` reads the document into a model no one language owns, and + * settles there what Effect's OpenAPI means and what every type, field and + * case is called; each emitter only spells that model in its language. + */ +import document from "../../packages/contracts/openapi.json" with { type: "json" }; +import { kotlinApi } from "./api/kotlin.ts"; +import { type OpenApiDocument, readModel } from "./api/model.ts"; +import type { Generator } from "./generated-files.ts"; + +export const generator: Generator = { + targets: ["android"], + generate(target) { + const model = readModel(document as unknown as OpenApiDocument); + switch (target) { + case "android": + return { + files: new Map([ + ["api/src/main/kotlin/ai/sugabots/api/Api.generated.kt", kotlinApi(model)], + ]), + }; + } + }, +}; diff --git a/apps/codegen/generate.test.ts b/apps/codegen/generate.test.ts new file mode 100644 index 000000000..78449f6d8 --- /dev/null +++ b/apps/codegen/generate.test.ts @@ -0,0 +1,45 @@ +import { readdirSync, readFileSync, statSync } from "node:fs"; +import { dirname, join, relative } from "node:path"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { generators } from "./generate.ts"; +import { targetRoots, targets } from "./generated-files.ts"; + +/** Every file under `folder`, relative to `root`. */ +function filesUnder(root: string, folder: string): string[] { + return readdirSync(root + folder).flatMap((name) => { + const path = join(root, folder, name); + if (statSync(path).isDirectory()) return filesUnder(root, relative(root, path)); + return name === ".DS_Store" ? [] : [relative(root, path)]; + }); +} + +it("runs every generate-*.ts script", () => { + const folder = dirname(fileURLToPath(import.meta.url)); + const scripts = readdirSync(folder).filter( + (name) => /^generate-.*\.ts$/.test(name) && !name.endsWith(".test.ts"), + ); + expect(Object.keys(generators).sort()).toEqual(scripts.sort()); +}); + +for (const target of targets) { + const root = targetRoots[target]; + const serving = Object.entries(generators).filter(([, generator]) => + generator.targets.includes(target), + ); + if (serving.length === 0) continue; + describe(`${target}'s generated files (run \`node apps/codegen/generate.ts\`)`, () => { + for (const [script, generator] of serving) { + it(`are what ${script} makes now`, () => { + const { files, folder } = generator.generate(target); + for (const [path, contents] of files) { + expect(readFileSync(root + path, "utf8"), path).toBe(contents); + } + if (folder) + expect(filesUnder(root, folder).sort()).toEqual( + [...files.keys()].filter((path) => path.startsWith(folder)).sort(), + ); + }); + } + }); +} diff --git a/apps/codegen/generate.ts b/apps/codegen/generate.ts new file mode 100644 index 000000000..66bd9f4de --- /dev/null +++ b/apps/codegen/generate.ts @@ -0,0 +1,34 @@ +/** + * Regenerates every file the apps copy from the web's packages and the API: + * + * node apps/codegen/generate.ts + * + * The apps keep the files they last took until someone runs it, so the web and + * the API can move on without them. Run it before changing an app: the Native + * apps workflow's `codegen` tests fail on a change to an app until it has been, + * and the apps then fail to build wherever they relied on what changed. + */ +import { mkdirSync, rmSync, writeFileSync } from "node:fs"; +import { dirname } from "node:path"; +import * as api from "./generate-api.ts"; +import { type Generator, targetRoots } from "./generated-files.ts"; + +/** Every generator, by the script that holds it; a test checks each `generate-*.ts` is here. */ +export const generators: Record = { + "generate-api.ts": api.generator, +}; + +if (import.meta.main) { + for (const [script, generator] of Object.entries(generators)) { + for (const target of generator.targets) { + const root = targetRoots[target]; + const { files, folder } = generator.generate(target); + if (folder) rmSync(root + folder, { recursive: true, force: true }); + for (const [path, contents] of files) { + mkdirSync(dirname(root + path), { recursive: true }); + writeFileSync(root + path, contents); + } + console.log(`${script} (${target}): ${files.size} ${files.size === 1 ? "file" : "files"}`); + } + } +} diff --git a/apps/codegen/generated-files.ts b/apps/codegen/generated-files.ts new file mode 100644 index 000000000..09c9900f7 --- /dev/null +++ b/apps/codegen/generated-files.ts @@ -0,0 +1,26 @@ +import { fileURLToPath } from "node:url"; + +/** The apps generated files are written for, by the folder each one's paths are relative to. */ +export const targetRoots = { + android: fileURLToPath(new URL("../android/", import.meta.url)), +}; + +export type Target = keyof typeof targetRoots; + +export const targets = Object.keys(targetRoots) as Target[]; + +/** + * What a generator produces for one app: each file's contents by its path under + * the app's root, and the folder it owns outright, if any, where a file it no + * longer produces is stale and removed. + */ +export interface GeneratedFiles { + files: Map; + folder?: string; +} + +/** A generator: the apps it writes files for, and the files it writes for each. */ +export interface Generator { + targets: readonly Target[]; + generate: (target: Target) => GeneratedFiles; +} diff --git a/apps/codegen/vitest.config.ts b/apps/codegen/vitest.config.ts new file mode 100644 index 000000000..e05364476 --- /dev/null +++ b/apps/codegen/vitest.config.ts @@ -0,0 +1,13 @@ +import { defineConfig } from "vitest/config"; + +// Run on their own, by the Native apps workflow, rather than as one of the +// repo's projects: the apps keep the generated files they last took, so a +// change to the web or the API doesn't wait on regenerating them. +export default defineConfig({ + test: { + name: "codegen", + root: import.meta.dirname, + environment: "node", + include: ["**/*.test.ts"], + }, +});