Skip to content
This repository was archived by the owner on Oct 27, 2026. It is now read-only.
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions apps/api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -430,6 +430,7 @@ export async function createApp(
sandbox,
memory,
home,
runtime,
secrets,
oauthLogins,
integrationSettings,
Expand Down
44 changes: 44 additions & 0 deletions apps/api/src/bot-refine.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { ScriptedAgentRuntime } from "@milo/adapters";
import { describe, expect, it } from "vitest";
import {
buildRefinePrompt,
fallbackRefine,
parseRefineReply,
refineBotProfile,
} from "./bot-refine.js";

describe("bot refine", () => {
it("builds a prompt the scripted runtime can match", () => {
expect(buildRefinePrompt("Scout", "Find travel deals")).toContain("milo refine bot profile");
expect(buildRefinePrompt("Scout", "Find travel deals")).toContain("Name: Scout");
});

it("falls back when the reply is not JSON", () => {
expect(parseRefineReply("sorry", "Scout", "Find travel deals.")).toEqual(
fallbackRefine("Scout", "Find travel deals."),
);
});

it("parses a JSON reply", () => {
expect(
parseRefineReply(
'Here you go:\n{"title":"Travel finder","instructions":"Hunt deals daily."}\n',
"Scout",
"Find travel deals",
),
).toEqual({
title: "Travel finder",
instructions: "Hunt deals daily.",
});
});

it("runs through the scripted runtime", async () => {
const refined = await refineBotProfile(
new ScriptedAgentRuntime(),
{ name: "Scout", description: "Find travel deals every morning." },
{ provider: "scripted", id: "scripted" },
);
expect(refined.title.length).toBeGreaterThan(0);
expect(refined.instructions).toContain("Find travel deals");
});
});
77 changes: 77 additions & 0 deletions apps/api/src/bot-refine.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { randomUUID } from "node:crypto";
import type { AgentRuntime } from "@milo/adapter-kit";
import {
BOT_INSTRUCTIONS_MAX_LENGTH,
BOT_TITLE_MAX_LENGTH,
type RefineBotOutput,
} from "@milo/contracts";

/** Marker the scripted runtime matches so offline tests stay deterministic. */
export const REFINE_PROMPT_MARKER = "milo refine bot profile";

/**
* One place for the refine prompt. The model returns JSON only:
* `{"title":"…","instructions":"…"}`.
*/
export function buildRefinePrompt(name: string, description: string): string {
return `${REFINE_PROMPT_MARKER}
Name: ${name}
Description: ${description || "(none)"}
---
Reply with JSON only, no markdown: {"title":"<short role title>","instructions":"<system instructions for this bot>"}.
Keep title under 80 characters. Instructions should be concrete and actionable.`;
}

export function fallbackRefine(name: string, description: string): RefineBotOutput {
const trimmed = description.trim();
const title = (trimmed.split(/[.!\n]/)[0] ?? "").trim().slice(0, 80) || name;
return {
title: title.slice(0, BOT_TITLE_MAX_LENGTH),
instructions: (trimmed || `You are ${name}. Help with whatever is asked.`).slice(
0,
BOT_INSTRUCTIONS_MAX_LENGTH,
),
};
}

export function parseRefineReply(text: string, name: string, description: string): RefineBotOutput {
const match = text.match(/\{[\s\S]*\}/);
if (!match) return fallbackRefine(name, description);
try {
const parsed = JSON.parse(match[0]) as { title?: unknown; instructions?: unknown };
const title =
typeof parsed.title === "string" ? parsed.title.trim().slice(0, BOT_TITLE_MAX_LENGTH) : "";
const instructions =
typeof parsed.instructions === "string"
? parsed.instructions.trim().slice(0, BOT_INSTRUCTIONS_MAX_LENGTH)
: "";
if (!title || !instructions) return fallbackRefine(name, description);
return { title, instructions };
} catch {
return fallbackRefine(name, description);
}
}

/** Run the refine prompt through the agent runtime and parse the reply. */
export async function refineBotProfile(
runtime: AgentRuntime,
input: { name: string; description: string },
model: { provider: string; id: string },
): Promise<RefineBotOutput> {
const prompt = buildRefinePrompt(input.name, input.description);
let text = "";
for await (const event of runtime.run({
botId: "refine",
threadId: "refine",
runId: randomUUID(),
prompt,
instructions: "You refine bot profiles. Reply with JSON only.",
history: [],
tools: [],
model,
})) {
if (event.type === "text" && event.text) text += event.text;
if (event.type === "done" && event.text) text = event.text;
}
return parseRefineReply(text, input.name, input.description);
}
24 changes: 22 additions & 2 deletions apps/api/src/router.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { createHash, randomBytes, randomUUID } from "node:crypto";
import type {
AdapterContext,
AgentHomeStore,
AgentRuntime,
ArtifactStore,
ConnectorCatalogItem,
JobPublisher,
Expand Down Expand Up @@ -210,6 +211,7 @@ import {
listArtifactVersions,
listSpaceArtifacts,
} from "./artifacts.js";
import { refineBotProfile } from "./bot-refine.js";
import { botProfileLabelsChanged, commitBotUpdate } from "./bot-update.js";
import {
executionBlocksUserTakeover,
Expand Down Expand Up @@ -542,6 +544,8 @@ export interface RouterDeps {
sandbox: SandboxProvider;
memory: MemoryStore;
home: AgentHomeStore;
/** Used by bots.refine for a short profile pass before create. */
runtime: AgentRuntime;
secrets: EncryptedSecretStore;
oauthLogins: PiOAuthLogins;
/** Live Codex catalog seam; defaults to the shared per-process cache. */
Expand Down Expand Up @@ -1406,11 +1410,27 @@ export function createRouter(deps: RouterDeps) {
} catch (error) {
throw mapSpaceLifecycleError(error);
}
await enqueueBotIntroRun(deps, context.actor, bot).catch((error) => {
getLogger().error("bot intro run enqueue", error);
// Fixed intro with idea chips; the model-driven intro run is unused since v0.
await introduce(onboardingDeps, context.actor, bot.id).catch((error) => {
getLogger().error("bot intro", error);
});
return bot;
}),
refine: authed.bots.refine.handler(async ({ context, input }) => {
const managed = await selectRuntimeModel(
deps.prisma,
context.actor,
runtimeModel(deps.env.agentRuntime),
);
const model = managed
? { provider: managed.provider, id: managed.id }
: { provider: "scripted", id: "scripted" };
return refineBotProfile(
deps.runtime,
{ name: input.name, description: input.description },
model,
);
}),
duplicate: authed.bots.duplicate.handler(async ({ context, input }) => {
const source = await repos.getBot(context.actor, input.botId);
const duplicate = await repos
Expand Down
138 changes: 104 additions & 34 deletions apps/mobile/app/new.tsx
Original file line number Diff line number Diff line change
@@ -1,28 +1,36 @@
import {
BOT_DESCRIPTION_MAX_LENGTH,
BOT_NAME_MAX_LENGTH,
BOT_TITLE_MAX_LENGTH,
type ComputerMode,
normalizeCreateBotProfile,
} from "@milo/contracts";
import { type AgentStatus, BOT_DESCRIPTION_MAX_LENGTH, BOT_NAME_MAX_LENGTH } from "@milo/contracts";
import { BOT_PALETTE_COLORS } from "@milo/core";
import { Stack, useRouter } from "expo-router";
import { useState } from "react";
import { Pressable, ScrollView, Text, TextInput } from "react-native";
import { ComputerModePicker } from "../components/computer-mode-picker";
import { useEffect, useState } from "react";
import { Pressable, ScrollView, Text, TextInput, View } from "react-native";
import { type MobileBot, rpc } from "../lib/api";
import { useI18n } from "../lib/i18n";
import { useMobileTokens } from "../lib/native";

type RunsOn = "chatgpt" | "claude";

function claudeReady(status: AgentStatus | null): boolean {
return Boolean(status?.installed && status.loggedIn);
}

export default function NewBot() {
const { t } = useI18n();
const tokens = useMobileTokens();
const router = useRouter();
const [name, setName] = useState("");
const [title, setTitle] = useState("");
const [description, setDescription] = useState("");
const [computerMode, setComputerMode] = useState<ComputerMode>("team");
const [color, setColor] = useState(BOT_PALETTE_COLORS[0]!);
const [provider, setProvider] = useState<RunsOn>("chatgpt");
const [agentStatus, setAgentStatus] = useState<AgentStatus | null>(null);
const [error, setError] = useState<string | null>(null);
const [pending, setPending] = useState(false);
const showRunsOn = claudeReady(agentStatus);

useEffect(() => {
void rpc<AgentStatus | null>("agent/status")
.then(setAgentStatus)
.catch(() => setAgentStatus(null));
}, []);

function close() {
if (router.canDismiss()) {
Expand All @@ -40,11 +48,30 @@ export default function NewBot() {
if (!name.trim() || pending) return;
setPending(true);
setError(null);
const trimmedName = name.trim();
const trimmedDescription = description.trim();
try {
let title = "";
let instructions = trimmedDescription;
try {
const refined = await rpc<{ title: string; instructions: string }>("bots/refine", {
name: trimmedName,
description: trimmedDescription,
});
title = refined.title;
instructions = refined.instructions;
} catch {
// Create still works with the raw description when refine fails.
}
const usesClaude = showRunsOn && provider === "claude";
const bot = await rpc<MobileBot>("bots/create", {
...normalizeCreateBotProfile({ name, title, description }),
name: trimmedName,
title,
description: trimmedDescription,
instructions,
notifyOnFinish: true,
computerMode,
color: `${color}::shape_0`,
...(usesClaude ? { modelProvider: "claude-code", modelId: "sonnet" } : {}),
});
router.replace({ pathname: "/thread", params: { botId: bot.id, name: bot.name } });
} catch (err) {
Expand Down Expand Up @@ -93,30 +120,13 @@ export default function NewBot() {
}}
/>
<Text style={{ color: tokens.mutedForeground, marginTop: 16, fontSize: 14 }}>
{t("Title")}
</Text>
<TextInput
value={title}
maxLength={BOT_TITLE_MAX_LENGTH}
onChangeText={setTitle}
placeholder={t("Describe what this bot does")}
placeholderTextColor={tokens.mutedForeground}
style={{
marginTop: 8,
backgroundColor: tokens.muted,
borderRadius: 11,
padding: 16,
color: tokens.foreground,
}}
/>
<Text style={{ color: tokens.mutedForeground, marginTop: 16, fontSize: 14 }}>
{t("Description")}
{t("What should it do?")}
</Text>
<TextInput
value={description}
maxLength={BOT_DESCRIPTION_MAX_LENGTH}
onChangeText={setDescription}
placeholder={t("What this bot is for")}
placeholder={t("Describe what this bot does")}
placeholderTextColor={tokens.mutedForeground}
multiline
style={{
Expand All @@ -129,7 +139,67 @@ export default function NewBot() {
textAlignVertical: "top",
}}
/>
<ComputerModePicker value={computerMode} onChange={setComputerMode} />
<Text style={{ color: tokens.mutedForeground, marginTop: 16, fontSize: 14 }}>
{t("Color")}
</Text>
<View style={{ flexDirection: "row", flexWrap: "wrap", gap: 10, marginTop: 8 }}>
{BOT_PALETTE_COLORS.map((swatch) => {
const selected = color.toLowerCase() === swatch.toLowerCase();
return (
<Pressable
key={swatch}
onPress={() => setColor(swatch)}
accessibilityRole="button"
accessibilityState={{ selected }}
accessibilityLabel={swatch}
style={{
width: 32,
height: 32,
borderRadius: 16,
backgroundColor: swatch,
borderWidth: selected ? 2 : 1,
borderColor: selected ? tokens.foreground : tokens.border,
}}
/>
);
})}
</View>
{showRunsOn ? (
<>
<Text style={{ color: tokens.mutedForeground, marginTop: 16, fontSize: 14 }}>
{t("Runs on")}
</Text>
<View style={{ flexDirection: "row", gap: 8, marginTop: 8 }}>
{(
[
{ id: "chatgpt", label: t("ChatGPT") },
{ id: "claude", label: t("Claude") },
] as const
).map((option) => {
const selected = provider === option.id;
return (
<Pressable
key={option.id}
onPress={() => setProvider(option.id)}
accessibilityRole="button"
accessibilityState={{ selected }}
style={{
flex: 1,
padding: 12,
borderRadius: 11,
borderWidth: 1,
borderColor: selected ? tokens.foreground : tokens.border,
backgroundColor: selected ? tokens.muted : tokens.card,
alignItems: "center",
}}
>
<Text style={{ color: tokens.foreground }}>{option.label}</Text>
</Pressable>
);
})}
</View>
</>
) : null}
{error ? <Text style={{ color: tokens.destructive, marginTop: 16 }}>{error}</Text> : null}
<Pressable
onPress={() => void create()}
Expand Down
Loading
Loading