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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ yoji Agent (⌘J) and AI task drafts run on the model you connect in Settings
| Google Calendar | Shows your calendars, and edits events you change in yoji | A Google OAuth client | [google.md](docs/google.md) |
| Slack | Mentions and DMs in the Inbox, with threads, replies, reactions and files | Your own Slack app | [slack.md](docs/slack.md) |
| Asana | Tasks and comments in the Inbox, with replies | An Asana OAuth app | [asana.md](docs/asana.md) |
| Capy | Captains in Agents, cards, and In flight | A Capy API key | [agents.md](docs/agents.md) |
| Capy | Captains in Agents, cards, and In flight | A Capy API key. A non-production Capy can be set under Advanced; empty, yoji uses capy.ai | [agents.md](docs/agents.md#a-non-production-capy-server) |
| MCP servers | Tools that yoji Agent can call | A streamable HTTP URL, in Settings → MCP servers | [self-hosting.md](docs/self-hosting.md#mcp-servers-for-yoji-agent) |
| Model providers (Anthropic, OpenAI, OpenAI-compatible) | yoji Agent and AI task drafts | An API key, in Settings → Models | [agents.md](docs/agents.md#model-providers) |

Expand Down
51 changes: 39 additions & 12 deletions convex/adapters/capy.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { ConvexError } from 'convex/values';
import type { AgentAdapter, AgentCapabilities, AgentConn, AgentEvent, AgentThreadState, AgentThreadStatus } from '../../src/shared/agentAdapter';
import type { CapyAsk } from '../../src/shared/captains';
import { CAPY_WEB } from '../../src/shared/config';
import type { CapyServer } from '../../src/shared/capyServer';
import { UPLOAD_MAX, uploadType } from '../../src/shared/uploads';
import { capyApi } from '../config';
import { fetchText, MB } from '../net';
Expand All @@ -12,7 +13,8 @@ import { internal } from '../_generated/api';
import type { ActionCtx, QueryCtx } from '../_generated/server';
import { openToken } from '../tokens';

export type CapyConfig = Record<string, never>;
/** The Capy server the key was saved for (src/shared/capyServer.ts); absent, Capy's own (capyApi, CAPY_WEB). */
export type CapyConfig = { server?: CapyServer };

export type CapyConn = AgentConn<CapyConfig>;

Expand All @@ -23,30 +25,54 @@ export async function capyConnected(ctx: QueryCtx): Promise<boolean> {
return !!(await capyRowOf(ctx))?.secret;
}

/** Capy's row with its sealed key, as actions read it; null before Capy was ever connected. */
export type CapyRow = { _id: string; secret?: string } | null;
/** Capy's row with its sealed key and its Capy server if one is set, as actions read it; null before Capy was ever connected. */
export type CapyRow = { _id: string; secret?: string; server?: CapyServer } | null;

export async function capyRowData(ctx: QueryCtx): Promise<CapyRow> {
const row = await capyRowOf(ctx);
return row ? (row.secret ? { _id: row._id, secret: row.secret } : { _id: row._id }) : null;
return row ? { _id: row._id, ...(row.secret ? { secret: row.secret } : {}), ...(row.server ? { server: row.server } : {}) } : null;
}

/** The Capy connection from its row, key opened: the key you saved in Settings → Agents. */
/**
* What yoji seals for a key: the key alone for Capy's own servers, as it always has, or the Capy server's API address,
* a newline and the key when one is set. A key has no whitespace (agents:connectCapy), so the two never mix up.
*/
export const capyKeyToSeal = (key: string, server?: CapyServer): string => (server ? `${server.api}\n${key}` : key);

export const CAPY_SERVER_MOVED = 'The Capy server changed after this key was saved. Add the key again in Settings → Agents.';

/**
* The Capy connection from its row, key opened: the key you saved in Settings → Agents. A key sealed with a Capy server
* goes only to that server's API: the row's plain server must name the same API, or the key isn't used at all, so a
* changed row can't send it anywhere else without the key being entered again.
*/
export async function capyConnOf(row: CapyRow): Promise<CapyConn> {
const secret = row?.secret ? await openToken(row.secret, { table: 'agentConnections', field: 'secret', id: row._id }) : undefined;
return { id: 'capy', kind: 'capy', label: 'Capy', config: {}, ...(secret ? { secret } : {}) };
const opened = row?.secret ? await openToken(row.secret, { table: 'agentConnections', field: 'secret', id: row._id }) : undefined;
const cut = opened?.indexOf('\n') ?? -1, sealedApi = cut < 0 ? undefined : opened!.slice(0, cut), secret = cut < 0 ? opened : opened!.slice(cut + 1);
if (opened && sealedApi !== row?.server?.api) throw new ConvexError(CAPY_SERVER_MOVED);
return { id: 'capy', kind: 'capy', label: 'Capy', config: row?.server ? { server: row.server } : {}, ...(secret ? { secret } : {}) };
}

/** The Capy connection for an internal action, which reads the row itself; a userAction gets it from capy.ts capyAction. */
export const capyConn = async (ctx: Pick<ActionCtx, 'runQuery'>): Promise<CapyConn> => capyConnOf(await ctx.runQuery(internal.agents.capyRow, {}));

/**
* The Capy API a connection's calls go to: its Capy server's, set in Settings → Agents; else CAPY_API_URL on the
* deployment; else Capy's own (convex/config.ts capyApi).
*/
export const capyApiOf = (conn: Pick<AgentConn<CapyConfig>, 'config'>): string => conn.config.server?.api ?? capyApi();

/** The Capy web app a connection's Captain avatars come from: its Capy server's, else CAPY_WEB. */
export const capyWebOf = (conn: Pick<AgentConn<CapyConfig>, 'config'>): string => conn.config.server?.web ?? CAPY_WEB;

/**
* One Capy REST call with the connection's key, within net.ts's limits: a redirect is an error, so the key never follows
* one. Capy's refusals become errors the apps show as they are.
* one. A Capy server set in Settings is a URL a user gave, so it's checked as one too (public and https). Capy's
* refusals become errors the apps show as they are.
*/
export async function capyRequest<T>(conn: AgentConn<CapyConfig>, path: string, init: RequestInit = {}): Promise<T> {
if (!conn.secret) throw new ConvexError('Capy isn’t connected yet');
const { res, text } = await fetchText(`${capyApi()}${path}`, { ...init, headers: { Authorization: `Bearer ${conn.secret}`, 'Content-Type': 'application/json', ...(init.headers as Record<string, string> | undefined) } }, { name: 'Capy', timeoutMs: 30_000, maxBytes: 16 * MB }).catch((e: unknown) => {
const { res, text } = await fetchText(`${capyApiOf(conn)}${path}`, { ...init, headers: { Authorization: `Bearer ${conn.secret}`, 'Content-Type': 'application/json', ...(init.headers as Record<string, string> | undefined) } }, { name: 'Capy', timeoutMs: 30_000, maxBytes: 16 * MB, ...(conn.config.server ? { userUrl: true } : {}) }).catch((e: unknown) => {
throw e instanceof ProviderError ? new ConvexError(e.message) : e;
});
if (res.status === 401) throw new ConvexError('Capy turned the API key down; add a new one');
Expand All @@ -65,8 +91,9 @@ const STATUSES: AgentThreadStatus[] = ['working', 'waiting', 'idle', 'failed', '

export const captainStatus = (c: Pick<RawCaptain, 'archived' | 'status'>): AgentThreadStatus => (c.archived ? 'archived' : STATUSES.includes(c.status as AgentThreadStatus) ? (c.status as AgentThreadStatus) : 'idle');

export const captainAvatar = (c: Pick<RawCaptain, 'avatar'>): { image: string } | { emoji: string } =>
c.avatar?.image ? { image: c.avatar.image } : c.avatar?.kind === 'emoji' && c.avatar.value ? { emoji: c.avatar.value } : { image: `${CAPY_WEB}/avatars/${/^[\w-]+$/.test(c.avatar?.value ?? '') ? c.avatar!.value : 'capy-avatar-1'}.png` };
/** A Captain's face: its own image or emoji, else one of Capy's stock avatars on `web`, the connection's Capy web app (capyWebOf). */
export const captainAvatar = (c: Pick<RawCaptain, 'avatar'>, web = CAPY_WEB): { image: string } | { emoji: string } =>
c.avatar?.image ? { image: c.avatar.image } : c.avatar?.kind === 'emoji' && c.avatar.value ? { emoji: c.avatar.value } : { image: `${web}/avatars/${/^[\w-]+$/.test(c.avatar?.value ?? '') ? c.avatar!.value : 'capy-avatar-1'}.png` };

export const captainName = (c: Pick<RawCaptain, 'name' | 'title'>): string => c.name || c.title || 'Captain';

Expand Down Expand Up @@ -110,7 +137,7 @@ export const capyAdapter: AgentAdapter<CapyConfig> = {
...(c.needsYou && c.ask?.text ? { ask: c.ask.text } : {}),
unread: c.hasUnreads,
lastActivityAt: Date.parse(c.lastActivityAt) || 0,
avatar: captainAvatar(c),
avatar: captainAvatar(c, capyWebOf(conn)),
color: c.avatar?.background ?? '#5AAB6B',
}));
return { threads, events: [] };
Expand Down
50 changes: 36 additions & 14 deletions convex/agents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ import { CAPY_CONNECTION, issueTruths, itemIssue, mirrorCanvasChats, mirrorCanva
import { sortCaptains, type Captain } from '../src/shared/captains';
import type { FlightIssue, FlightThread } from '../src/shared/inFlight';
import { convexOverlay } from './overlay';
import { capyAdapter, capyRequest, capyRowData, capyRowOf, type CapyRow } from './adapters/capy';
import { capyAdapter, capyApiOf, capyKeyToSeal, capyRequest, capyRowData, capyRowOf, type CapyRow } from './adapters/capy';
import { CAPY_SERVER_PROBLEMS, capyHost, capyServerOf } from '../src/shared/capyServer';
import { urlRefusal } from './net';
import { mcpAdapter } from './adapters/mcp';
import type { AgentConnection } from '../src/shared/agentAdapter';
import { CANVAS } from '../src/shared/canvasAgent';
Expand Down Expand Up @@ -116,7 +118,7 @@ export const connections = userQuery({
args: {},
handler: async (ctx): Promise<AgentConnection[]> => {
const row = await capyRowOf(ctx), caps = capyAdapter.capabilities({});
const capy: AgentConnection[] = row?.secret ? [{ id: row._id, kind: 'capy', label: row.label, status: row.status, capabilities: caps }] : [];
const capy: AgentConnection[] = row?.secret ? [{ id: row._id, kind: 'capy', label: row.label, status: row.status, capabilities: caps, ...(row.server ? { server: row.server } : {}) }] : [];
const mcp = (await ctx.db.query('connections').withIndex('by_provider', (q) => q.eq('provider', CANVAS)).collect()).flatMap((c): AgentConnection[] =>
c.agent ? [{ id: c._id, kind: 'mcp', label: c.agent.label, status: c.status, capabilities: mcpAdapter.capabilities(c.agent) }] : []);
return [...capy, ...mcp];
Expand All @@ -135,28 +137,48 @@ export const capyLoad = internalQuery({
handler: async (ctx): Promise<Loaded<CapyRow>> => ({ owner: await isOwner(ctx), data: await capyRowData(ctx) }),
});

/** Writes Capy's row: a sealed key, or none to disconnect. With onlyNew, a row that's already there stays as it is. */
/**
* Writes Capy's row: a sealed key, or none to disconnect, with the Capy server it was sealed for (none for Capy's own,
* which leaves the row as it always was). With onlyNew, a row that's already there stays as it is.
*/
export const saveCapy = internalMutation({
args: { secret: v.optional(v.string()), onlyNew: v.optional(v.boolean()) },
handler: async (ctx, { secret, onlyNew }): Promise<boolean> => {
args: { secret: v.optional(v.string()), server: v.optional(v.object({ web: v.string(), api: v.string() })), onlyNew: v.optional(v.boolean()) },
handler: async (ctx, { secret, server, onlyNew }): Promise<boolean> => {
const row = await capyRowOf(ctx), now = Date.now();
if (row && onlyNew) return false;
if (row) await ctx.db.patch(row._id, { secret, status: 'active', error: undefined, updatedAt: now });
else await ctx.db.insert('agentConnections', { kind: 'capy', label: 'Capy', secret, status: 'active', createdAt: now, updatedAt: now });
if (row) await ctx.db.patch(row._id, { secret, server, status: 'active', error: undefined, updatedAt: now });
else await ctx.db.insert('agentConnections', { kind: 'capy', label: 'Capy', secret, ...(server ? { server } : {}), status: 'active', createdAt: now, updatedAt: now });
if (secret) await ensurePolling(ctx);
return true;
},
});

/** Connects Capy with an API key from Capy's settings: checked against Capy first, then stored sealed. */
/**
* Connects Capy with an API key from Capy's settings: checked against Capy first, then stored sealed. `server` is the
* optional Capy server from Settings → Agents → Capy → Advanced (src/shared/capyServer.ts); left out, or empty, the key
* goes to Capy's own as it always has. Set, the key is checked on that server and sealed together with its API address
* (adapters/capy.ts capyKeyToSeal), so it's only ever sent there. A refusal names the server that refused, because a key
* made on one Capy is turned down by any other.
*/
export const connectCapy = userAction({
args: { apiKey: v.string() },
handler: async (ctx, { apiKey }): Promise<null> => {
args: { apiKey: v.string(), server: v.optional(v.object({ web: v.string(), api: v.string() })) },
handler: async (ctx, { apiKey, server: typed }): Promise<null> => {
const key = apiKey.trim();
if (!/^\S{8,512}$/.test(key)) throw new ConvexError('That doesn’t look like a Capy API key');
const secret = await sealInput(key, { table: 'agentConnections', field: 'secret', id: '' });
await capyRequest({ id: 'capy', kind: 'capy', label: 'Capy', config: {}, secret: key }, '/captains');
await ctx.runMutation(internal.agents.saveCapy, { secret });
const checked = typed ? capyServerOf(typed.web, typed.api) : { server: null };
if ('problem' in checked) throw new ConvexError(CAPY_SERVER_PROBLEMS[checked.problem]);
const server = checked.server ?? undefined;
for (const url of server ? [server.web, server.api] : []) {
const why = urlRefusal(url);
if (why) throw new ConvexError(why);
}
const at = { table: 'agentConnections', field: 'secret', id: '' } as const;
const sealed = await sealInput(key, at), secret = server ? await sealInput(capyKeyToSeal(key, server), at) : sealed;
const conn = { id: 'capy', kind: 'capy' as const, label: 'Capy', config: server ? { server } : {}, secret: key };
await capyRequest(conn, '/captains').catch((e: unknown) => {
throw e instanceof ConvexError && String(e.data).startsWith('Capy turned the API key down') ? new ConvexError(`Capy turned the API key down at ${capyHost(capyApiOf(conn))}. A key works only on the Capy server it was made on.`) : e;
});
await ctx.runMutation(internal.agents.saveCapy, { secret, ...(server ? { server } : {}) });
const row = await ctx.runQuery(internal.agents.capyRow, {});
if (row) await bindRow(ctx, 'agentConnections', row._id);
return null;
Expand All @@ -168,7 +190,7 @@ export const disconnectCapy = userMutation({
args: {},
handler: async (ctx): Promise<null> => {
const row = await capyRowOf(ctx);
if (row) await ctx.db.patch(row._id, { secret: undefined, updatedAt: Date.now() });
if (row) await ctx.db.patch(row._id, { secret: undefined, server: undefined, updatedAt: Date.now() });
return null;
},
});
Expand Down
Loading