Skip to content
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
4 changes: 4 additions & 0 deletions convex/_generated/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ import type * as privacy from "../privacy.js";
import type * as projects from "../projects.js";
import type * as providers_asana from "../providers/asana.js";
import type * as providers_canvas from "../providers/canvas.js";
import type * as providers_firecrawl from "../providers/firecrawl.js";
import type * as providers_google from "../providers/google.js";
import type * as providers_index from "../providers/index.js";
import type * as providers_mcp from "../providers/mcp.js";
Expand All @@ -73,6 +74,7 @@ import type * as toolSources from "../toolSources.js";
import type * as undo from "../undo.js";
import type * as validators from "../validators.js";
import type * as voice from "../voice.js";
import type * as webSearch from "../webSearch.js";

import type {
ApiFromModules,
Expand Down Expand Up @@ -125,6 +127,7 @@ declare const fullApi: ApiFromModules<{
projects: typeof projects;
"providers/asana": typeof providers_asana;
"providers/canvas": typeof providers_canvas;
"providers/firecrawl": typeof providers_firecrawl;
"providers/google": typeof providers_google;
"providers/index": typeof providers_index;
"providers/mcp": typeof providers_mcp;
Expand All @@ -146,6 +149,7 @@ declare const fullApi: ApiFromModules<{
undo: typeof undo;
validators: typeof validators;
voice: typeof voice;
webSearch: typeof webSearch;
}>;

/**
Expand Down
11 changes: 9 additions & 2 deletions convex/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { agentSources, openServer, type AgentSources } from './toolSources';
import { capyAdapter, capyConn, capyConnected } from './adapters/capy';
import { CANVAS } from '../src/shared/canvasAgent';
import { makePick } from './models';
import { withoutToolCalls } from '../src/shared/toolCallText';

/** A model the composer picked: a connected provider's id, or the house model's, and the model on it. */
const chatModel = v.object({ provider: v.string(), model: v.string() });
Expand Down Expand Up @@ -497,12 +498,17 @@ export const commit = internalMutation({
},
});

/**
* Ends a reply, yoji Agent's or a plain chat's, on every route. Tool-call markup a model wrote as text never lands in it
* (shared/toolCallText.ts); a reply that was only markup says it got no answer instead.
*/
export const finish = internalMutation({
args: { messageId: v.id('agentMessages'), text: v.string(), status: v.union(v.literal('done'), v.literal('error')), choices: v.optional(v.array(v.string())), sources: v.optional(v.array(sourceLink)), applied: v.optional(agentApplied) },
handler: async (ctx, { messageId, ...rest }) => {
const m = await ctx.db.get(messageId);
if (!m || m.status !== 'working') return null;
await ctx.db.patch(messageId, { ...rest, doneAt: Date.now() });
const text = withoutToolCalls(rest.text), empty = !text && !!rest.text.trim();
await ctx.db.patch(messageId, { ...rest, ...(empty ? { text: 'I didn’t get an answer back. Try again?', status: 'error' as const } : { text }), doneAt: Date.now() });
await ctx.db.patch(m.chatId, { updatedAt: Date.now() });
return null;
},
Expand Down Expand Up @@ -727,13 +733,14 @@ export const run = internalAction({
if (!(await ctx.runQuery(internal.agent.live, { messageId }))) return;
const r = await generate(ctx, [...msgs], {}, { chat: t.reply.chatId });
if (!r) return void (await end('yoji Agent needs a model. Connect one in Settings › Chats, then ask again.', 'error'));
const text = r.text ?? '', step = parseStep(text);
const text = r.text ?? '', step = parseStep(text, (name) => !!specOf(name));
if (!step) {
if (retried || !text.trim()) return void (await end(text.trim() || 'I didn’t get an answer back. Try again?', text.trim() ? 'done' : 'error'));
retried = true;
msgs.push({ role: 'assistant', content: text }, { role: 'user', content: 'That wasn’t one JSON object. Answer again with only the JSON object.' });
continue;
}
retried = false;
msgs.push({ role: 'assistant', content: JSON.stringify(step) });
if (!step.calls) return void (await end(step.reply!, 'done', step));
const batch = step.calls.slice(0, MAX_CALLS - calls);
Expand Down
132 changes: 132 additions & 0 deletions convex/agentToolText.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
// @vitest-environment edge-runtime
/// <reference types="vite/client" />
import { convexTest } from 'convex-test';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { api } from './_generated/api';
import type { Id } from './_generated/dataModel';
import schema from './schema';
import { canvasAgent } from './canvasAgent.fixture';
import { sealedBefore } from './sealed.fixture';
import { CANVAS, CANVAS_NAME } from '../src/shared/canvasAgent';

// yoji Agent on every route a chat can run on (your Anthropic key, your OpenAI key, an OpenAI-compatible server, the
// house model), with each model mocked at the HTTP or overlay edge: a model that writes its own tool-call markup
// instead of a JSON step gets those calls run, and markup never lands in a reply.

const overlay = vi.hoisted(() => ({ replies: [] as string[], messages: [] as { role: string; content: string }[][] }));
vi.mock('@private/convex', () => ({ default: { model: { id: 'brain', name: 'Brain', model: 'house', generate: async (_token: string, messages: { role: string; content: string }[]) => (overlay.messages.push(messages), { text: overlay.replies.shift() ?? '{"reply": "From the brain."}', claude: true, finish: 'stop', cost: null }) } } }));

const modules = import.meta.glob('./**/*.ts');
const ENC = btoa(String.fromCharCode(...new Uint8Array(32).fill(5)));
const ANTHROPIC = 'https://api.anthropic.com/v1/messages';
const OPENAI = 'https://api.openai.com/v1/responses';
const LOCAL = 'http://localhost:11434/v1/chat/completions';
const MARKUP = '<invoke name="getTask">\n<parameter name="task">YJ-1</parameter>\n</invoke>';
const ANSWER = '{"reply": "Orbit launch is on Oct 20.", "sources": ["YJ-1"]}';
const BROKEN = '<invoke>\n<parameter name="task">YJ-1</parameter>\n</invoke>';

type Route = 'anthropic' | 'openai' | 'compatible' | 'house';
let sent: { url: string; body: any }[] = [];
let replies: string[] = [];
const wrap: Record<Exclude<Route, 'house'>, (text: string) => unknown> = {
anthropic: (text) => ({ content: [{ type: 'text', text }], stop_reason: 'end_turn' }),
openai: (text) => ({ status: 'completed', output: [{ type: 'message', content: [{ type: 'output_text', text }] }] }),
compatible: (text) => ({ choices: [{ message: { content: text }, finish_reason: 'stop' }] }),
};
const routeOf = (url: string): Exclude<Route, 'house'> | null => (url === ANTHROPIC ? 'anthropic' : url === OPENAI ? 'openai' : url === LOCAL ? 'compatible' : null);
const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });

beforeEach(() => {
sent = [];
replies = [];
overlay.replies = [];
overlay.messages = [];
vi.stubEnv('YOJI_ENCRYPTION_KEY', ENC);
vi.stubEnv('YOJI_ALLOW_PRIVATE_URLS', '1');
vi.stubGlobal('fetch', vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
const url = String(input), body = init?.body ? JSON.parse(String(init.body)) : undefined;
if (url.endsWith('/models') || url.endsWith('/models?limit=100')) return json({ data: [{ id: 'claude-sonnet-9' }, { id: 'gpt-5.2' }, { id: 'llama' }] });
const route = routeOf(url);
if (!route) return json({}, 404);
sent.push({ url, body });
return json(wrap[route](replies.shift() ?? '{"reply": "Done."}'));
}));
});

afterEach(() => {
vi.unstubAllEnvs();
vi.unstubAllGlobals();
vi.useRealTimers();
});

async function setup(route: Route) {
const t = convexTest(schema, modules);
await t.mutation(api.data.init, {});
await t.mutation(api.tasks.create, { task: { status: 'todo', priority: 0, tags: [], length: 60, notes: '', link: '', title: 'Orbit launch' }, day: '2026-10-20' });
const ids = {
anthropic: (await t.action(api.models.connect, { kind: 'anthropic', apiKey: 'sk-ant', model: 'claude-sonnet-9' })) as string,
openai: (await t.action(api.models.connect, { kind: 'openai', apiKey: 'sk-o', model: 'gpt-5.2' })) as string,
compatible: (await t.action(api.models.connect, { kind: 'openaiCompatible', apiKey: '', baseUrl: 'http://localhost:11434/v1', model: 'llama' })) as string,
};
const model = { anthropic: { provider: ids.anthropic, model: 'claude-sonnet-9' }, openai: { provider: ids.openai, model: 'gpt-5.2' }, compatible: { provider: ids.compatible, model: 'llama' } };
if (route === 'house') {
for (const id of Object.values(ids)) await t.mutation(api.models.remove, { id: id as Id<'modelProviders'> });
await t.run(async (ctx) => ctx.db.insert('connections', { provider: CANVAS, agent: canvasAgent(), accountId: 'u1', label: CANVAS_NAME, status: 'active', accessToken: await sealedBefore('agent-token'), createdAt: 1 }));
}
sent = [];
return { t, model: route === 'house' ? undefined : model[route] };
}

/** The model's replies in order, on that route. */
const script = (route: Route, ...texts: string[]) => (route === 'house' ? overlay.replies.push(...texts) : replies.push(...texts));
/** What the model was sent on each call, as plain text. */
const asked = (route: Route): string[] => (route === 'house' ? overlay.messages.map((m) => JSON.stringify(m)) : sent.map((s) => JSON.stringify(s.body)));

async function ask(t: ReturnType<typeof convexTest>, text: string, model?: { provider: string; model: string }) {
vi.useFakeTimers();
const s = await t.mutation(api.agent.send, { text, today: '2026-10-21', timezone: 'America/New_York', ...(model ? { model } : {}) });
await t.finishAllScheduledFunctions(vi.runAllTimers);
vi.useRealTimers();
return (await t.query(api.agent.messages, { chatId: s.chatId })).find((m) => m._id === s.messageId)!;
}

describe('yoji Agent: tool calls written as markup, per route', () => {
for (const route of ['anthropic', 'openai', 'compatible', 'house'] as const) {
it(route + ': runs <invoke> calls as tools and answers, with no markup in the reply', async () => {
const { t, model } = await setup(route);
script(route, MARKUP, ANSWER);
const reply = await ask(t, 'when is the orbit launch?', model);
expect(reply).toMatchObject({ status: 'done', text: 'Orbit launch is on Oct 20.', steps: ['Read YJ-1'] });
const calls = asked(route);
expect(calls).toHaveLength(2);
expect(calls[1]).toContain('[getTask] YJ-1');
expect(calls[1]).toContain('\\"calls\\":[{\\"tool\\":\\"getTask\\",\\"args\\":{\\"task\\":\\"YJ-1\\"}}]');
expect(calls[0]).toContain('never as <invoke> or other tool-call tags');
});

it(route + ': markup it can’t run never shows, the reply says it got no answer', async () => {
const { t, model } = await setup(route);
script(route, BROKEN, BROKEN);
const reply = await ask(t, 'when is the orbit launch?', model);
expect(asked(route)).toHaveLength(2);
expect(reply).toMatchObject({ status: 'error', text: 'I didn’t get an answer back. Try again?' });
expect(reply.text).not.toMatch(/<\/?(invoke|parameter)/);
});
}

it('one slip early in a turn doesn’t use up the retry for a later one', async () => {
const { t } = await setup('house');
script('house', 'Let me look.', '{"calls": [{"tool": "findTasks", "args": {"text": "orbit"}}]}', 'Found it, one moment.', ANSWER);
const reply = await ask(t, 'when is the orbit launch?');
expect(overlay.messages).toHaveLength(4);
expect(overlay.messages[3]!.at(-1)!.content).toContain('wasn’t one JSON object');
expect(reply).toMatchObject({ status: 'done', text: 'Orbit launch is on Oct 20.', steps: ['Found YJ-1'] });
});

it('keeps the words of a reply and drops markup that came with them', async () => {
const { t, model } = await setup('anthropic');
script('anthropic', '{"reply": "Orbit launch is on Oct 20.\\n<invoke name=\\"getTask\\"><parameter name=\\"task\\">YJ-1</parameter></invoke>"}');
const reply = await ask(t, 'when is the orbit launch?', model);
expect(reply).toMatchObject({ status: 'done', text: 'Orbit launch is on Oct 20.' });
});
});
22 changes: 17 additions & 5 deletions convex/ai.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import { HOUSE, openEndpoint } from './models';
import { convexOverlay } from './overlay';
import { slack } from './providers';
import * as models from './providers/models';
import type { ChatTurn, GenerateOptions, Generated } from './providers/models';
import type { ChatTurn, GenerateOptions, Generated, ToolKit } from './providers/models';
import type { SlackMeta } from './providers/slack';
import { CANVAS } from '../src/shared/canvasAgent';

Expand Down Expand Up @@ -53,16 +53,28 @@ export type { ChatTurn };
* One reply from the active model provider: its text, whether a Claude model wrote it, and its cost when known. With
* no provider active it is the overlay's model on the agent connection's token, and null without either. `use: 'agent'`
* runs on yoji Agent's model for that chat (its own pick, else Settings › Chats' default); everything else, task drafts
* and Captain summaries, on Settings › Chats' default too.
* and Captain summaries, on Settings › Chats' default too. `tools` (a plain chat's web tools) run as the provider's own
* tool calls, or on the text protocol (models.textTools) for the house model and a server that refuses tool calls.
*/
export async function generate(ctx: ActionCtx, messages: ChatTurn[], options: GenerateOptions = {}, use?: 'agent' | { chat: Id<'agentChats'> }): Promise<Generated | null> {
export async function generate(ctx: ActionCtx, messages: ChatTurn[], options: GenerateOptions = {}, use?: 'agent' | { chat: Id<'agentChats'> }, tools?: ToolKit): Promise<Generated | null> {
const pick = use ? await ctx.runQuery(internal.models.agentEndpoint, typeof use === 'object' ? { chatId: use.chat } : {}) : await ctx.runQuery(internal.models.backgroundEndpoint, {});
const house = pick?.kind === HOUSE ? pick : null;
const row = pick?.kind === HOUSE ? null : pick ?? (await ctx.runQuery(internal.models.activeEndpoint, {}));
if (row) return models.generate(await openEndpoint(row), messages, options);
if (row) {
const e = await openEndpoint(row);
try {
return await models.generate(e, messages, options, tools);
} catch (err) {
if (!(err instanceof models.ToolsRefused) || !tools) throw err;
return (await models.textTools((m) => models.generate(e, m, options), messages, tools))!;
}
}
const fallback = convexOverlay.model;
const c = fallback && (await ctx.runQuery(internal.ai.canvasConnection, {}));
return c ? fallback.generate(await accessToken(ctx, c), models.textOnly(messages), house ? { ...options, model: house.model } : options) : null;
if (!c) return null;
const token = await accessToken(ctx, c), opts = house ? { ...options, model: house.model } : options;
const ask = (m: ChatTurn[]) => fallback.generate(token, models.textOnly(m), opts);
return tools ? models.textTools(ask, messages, tools) : ask(messages);
}

/** A task draft's prompt with its language line: the sending device's language, from an app that sends one. */
Expand Down
13 changes: 13 additions & 0 deletions convex/overlay.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// Settings → Models, yoji Agent has no built-in docs tools, and voice runs on the keys set in Settings or the env.
import values from '@private/convex';
import type { McpAgentConfig } from './adapters/mcpClient';
import type { Found, Page } from './providers/firecrawl';
import type { ChatTurn, GenerateOptions, Generated } from './providers/models';
import type { ReasoningMode } from '../src/shared/capyModels';
import type { ActionCtx, QueryCtx } from './_generated/server';
Expand Down Expand Up @@ -37,6 +38,17 @@ export interface DocsOverlay {
run(token: string, call: AgentCall): Promise<{ text: string; docs: DocRef[]; step: string }>;
}

/**
* Web search for plain Chats run by the workspace on the agent connection's token, used while no Firecrawl key is set
* (convex/webSearch.ts). `refused` says whether an error means the workspace doesn't serve it (yet), as opposed to one
* search or page failing.
*/
export interface WebOverlay {
search(token: string, query: string, limit: number): Promise<Found[]>;
scrape(token: string, url: string): Promise<Page>;
refused(e: unknown): boolean;
}

/** One of the house model's choices: its id (naming its company), its name, an older id a saved pick may hold, and the efforts it takes when known. */
export interface HouseModel { id: string; label: string; alias?: string; efforts?: ReasoningMode[] }

Expand All @@ -58,6 +70,7 @@ export interface ConvexOverlay {
/** Whether transcribe can answer now, and the name Settings › Integrations shows for it. */
transcribeStatus?: (ctx: QueryCtx) => Promise<{ name: string } | null>;
docs?: DocsOverlay;
web?: WebOverlay;
/** Tool sources it holds to asking first, and calls it refuses (src/shared/toolTrust.ts). */
guard?: SourceGuard;
}
Expand Down
Loading