← All proposals

Context: AgentTree

A tree of agent cards: the lead on top, its sub-agents side by side below, their helpers under them, joined by thin connectors.

Net-new componentOpen in Storybook

proposals/AgentTree/agent-tree-utils.ts326 lines · View on GitHub
import { type ReactNode, useEffect, useState } from 'react';

import type { PDSIcon } from '@pantheon-systems/pds-toolkit-react';

export type AgentTreeStatus =
	'active' | 'done' | 'failed' | 'idle' | 'paused' | 'waiting';

export type AgentTreeSteer =
	'approve' | 'decline' | 'message' | 'pause' | 'resume' | 'retry' | 'stop';

export interface AgentTreeTool {
	/**
	 * The PDS icon that stands for the tool.
	 */
	iconName: PDSIcon;
	/**
	 * The tool's name: the tooltip of its icon on the card, and its label in
	 * the agent's details.
	 */
	name: string;
}

export interface AgentTreeAgent {
	/**
	 * What the agent does right now, or when it rests, the last thing it did.
	 */
	activity?: string;
	/**
	 * Sub-agents of the lead, or helpers of a sub-agent.
	 */
	children?: AgentTreeAgent[];
	/**
	 * How full its context window is, from 0 to 1.
	 */
	context?: number;
	/**
	 * The size of its context window in tokens. The card then reads
	 * "136k / 200k" instead of a percentage.
	 */
	contextLimit?: number;
	/**
	 * What it cost so far, in the unit `formatCost` expects.
	 */
	cost?: number;
	/**
	 * When it stopped, in milliseconds. Leave out while it runs.
	 */
	ended?: number;
	/**
	 * The icon in the agent's avatar. `zappy` (the bolt) is only for Pantheon's
	 * own agent, Zappy; leave it out for Zappy. `sparklesSolid` is for
	 * third-party agents.
	 */
	iconName?: 'sparklesSolid' | 'zappy';
	/**
	 * Unique id of the agent.
	 */
	id: string;
	/**
	 * The last thing it was handed, for example "Lead: Guard empty carts".
	 */
	last?: { from: string; text: string };
	/**
	 * The model, under the name.
	 */
	model?: string;
	/**
	 * The model maker's logo, before the model in the details.
	 */
	modelLogo?: ReactNode;
	/**
	 * Name of the agent.
	 */
	name: string;
	/**
	 * When it started, in milliseconds. The details count the time from it.
	 */
	started?: number;
	/**
	 * `active` works, `idle`, `paused` and `done` rest, `waiting` needs you and
	 * `failed` stopped with an error.
	 */
	status: AgentTreeStatus;
	/**
	 * What it was asked to do, shown in the details.
	 */
	task?: string;
	/**
	 * The tools it works with: small icon buttons on the card, named in the details.
	 */
	tools?: AgentTreeTool[];
}

export interface AgentTreeHandoff {
	/**
	 * Id of the agent that handed the work over.
	 */
	from: string;
	/**
	 * Unique id. Each new id runs once; the ones there on first render do not.
	 */
	id: string;
	/**
	 * What was handed over, added to the announcement.
	 */
	label?: string;
	/**
	 * Id of the agent that received the work.
	 */
	to: string;
}

export interface AgentTreeProject {
	/**
	 * Unique id of the project.
	 */
	id: string;
	/**
	 * Name of the project.
	 */
	name: string;
	/**
	 * Agents in the project that need you. Shown next to the name.
	 */
	needsYou?: number;
	/**
	 * Agents in the project that are working. Shown next to the name when none
	 * needs you.
	 */
	working?: number;
}

export interface AgentTreeLabelStrings {
	agent: string;
	agentThirdParty: string;
	agentZappy: string;
	approve: string;
	context: string;
	contextValue: string;
	cost: string;
	decline: string;
	details: string;
	handoffSaid: string;
	handoffSaidWithLabel: string;
	messageLabel: string;
	messagePlaceholder: string;
	pause: string;
	projectNeedsYou: string;
	projects: string;
	projectWorking: string;
	resume: string;
	retry: string;
	running: string;
	saidApprove: string;
	saidDecline: string;
	saidMessage: string;
	saidPause: string;
	saidResume: string;
	saidRetry: string;
	saidStop: string;
	send: string;
	statusActive: string;
	statusDone: string;
	statusFailed: string;
	statusIdle: string;
	statusIndicator: string;
	statusPaused: string;
	statusWaiting: string;
	stop: string;
	time: string;
	tokens: string;
}

export const defaultLabelStrings: AgentTreeLabelStrings = {
	agent: 'Agent',
	agentThirdParty: 'Third-party agent',
	agentZappy: 'Zappy agent',
	approve: 'Approve',
	context: 'Context window',
	contextValue: 'context {count}%',
	cost: 'Cost',
	decline: 'Decline',
	details: '{name}: details',
	handoffSaid: '{from} handed to {to}',
	handoffSaidWithLabel: '{from} handed to {to}: {label}',
	messageLabel: 'Message to {name}',
	messagePlaceholder: 'Tell {name}…',
	pause: 'Pause',
	projectNeedsYou: '{count} needs you',
	projects: 'Project',
	projectWorking: '{count} working',
	resume: 'Resume',
	retry: 'Retry',
	running: 'Running',
	saidApprove: 'Approved for {name}',
	saidDecline: 'Declined for {name}',
	saidMessage: 'Sent to {name}: {message}',
	saidPause: 'Paused {name}',
	saidResume: 'Resumed {name}',
	saidRetry: 'Retrying {name}',
	saidStop: 'Stopped {name}',
	send: 'Send',
	statusActive: 'Working',
	statusDone: 'Done',
	statusFailed: 'Failed',
	statusIdle: 'Idle',
	statusIndicator: 'Status: ',
	statusPaused: 'Paused',
	statusWaiting: 'Needs you',
	stop: 'Stop',
	time: 'Time',
	tokens: 'Tokens',
};

/**
 * Fills `{name}`-style placeholders in a translated string.
 */
export const fill = (
	template: string,
	values: Record<string, number | string | undefined>,
) =>
	template.replace(/\{(\w+)\}/g, (match, key: string) => {
		const value = values[key];
		return value === undefined ? match : String(value);
	});

export const isResting = (status: AgentTreeStatus) =>
	status === 'idle' || status === 'done' || status === 'paused';

export const walk = (agent: AgentTreeAgent): AgentTreeAgent[] => [
	agent,
	...(agent.children ?? []).flatMap(walk),
];

export const depthOf = (agent: AgentTreeAgent): number =>
	Math.max(0, ...(agent.children ?? []).map((child) => depthOf(child) + 1));

/**
 * The share of the context window as a whole percent, clamped to 0-100.
 */
export const percent = (value?: number) =>
	Math.round(
		Math.min(1, Math.max(0, Number.isFinite(value) ? (value as number) : 0)) *
			100,
	);

/**
 * Tokens read so far, from the share of the window (not the rounded percent,
 * so 80 tokens of 200k read "80", not "0").
 */
export const tokensUsed = (agent: {
	context?: number;
	contextLimit?: number;
}) =>
	Math.min(
		1,
		Math.max(0, Number.isFinite(agent.context) ? (agent.context as number) : 0),
	) * (agent.contextLimit ?? 0);

/**
 * A cost that is a real number. A broken one (NaN, Infinity) is left out
 * instead of reading "$NaN".
 */
export const realCost = (amount?: number) =>
	amount !== undefined && Number.isFinite(amount) ? amount : undefined;

export const formatTokens = (count: number) =>
	new Intl.NumberFormat(undefined, {
		maximumFractionDigits: 1,
		notation: 'compact',
	}).format(count);

export const defaultFormatCost = (amount: number) =>
	amount > 0 && amount < 0.005
		? '<$0.01'
		: new Intl.NumberFormat(undefined, {
				currency: 'USD',
				maximumFractionDigits: amount < 10 ? 2 : 0,
				minimumFractionDigits: amount < 10 ? 2 : 0,
				style: 'currency',
			}).format(amount);

export const defaultFormatDuration = (milliseconds: number) => {
	const seconds = Math.max(0, Math.round(milliseconds / 1000));
	if (seconds < 60) return `${seconds}s`;
	const minutes = Math.floor(seconds / 60);
	if (minutes < 60)
		return `${minutes}m ${String(seconds % 60).padStart(2, '0')}s`;
	const hours = Math.floor(minutes / 60);
	return hours < 24
		? `${hours}h ${String(minutes % 60).padStart(2, '0')}m`
		: `${Math.floor(hours / 24)}d ${hours % 24}h`;
};

export const prefersReducedMotion = () =>
	typeof window !== 'undefined' &&
	window.matchMedia('(prefers-reduced-motion: reduce)').matches;

/**
 * How long an agent has run, formatted. It ticks every second while the agent
 * is running; `isRunning` says whether it does. Both are `undefined` and
 * `false` when the agent has no `started` time.
 */
export const useElapsed = (
	agent: AgentTreeAgent,
	formatDuration: (milliseconds: number) => string,
) => {
	const isRunning =
		agent.started !== undefined &&
		agent.ended === undefined &&
		!isResting(agent.status);
	const [now, setNow] = useState(() => Date.now());
	useEffect(() => {
		if (!isRunning) return;
		const timer = window.setInterval(() => setNow(Date.now()), 1000);
		return () => window.clearInterval(timer);
	}, [isRunning]);
	const time =
		agent.started !== undefined
			? formatDuration(
					(agent.ended ?? (isRunning ? now : agent.started)) - agent.started,
				)
			: undefined;
	return { isRunning, time };
};