Skip to content

An open-source, faster Devin alternative

TypeScript

feat: complete agent invocation product surfaces

Igor Zalutski50482bf84dcd
diff --git a/sdks/typescript/src/agents/normalize.test.ts b/sdks/typescript/src/agents/normalize.test.ts
index 6624232c..71224c43 100644
--- a/sdks/typescript/src/agents/normalize.test.ts
+++ b/sdks/typescript/src/agents/normalize.test.ts
@@ -17,6 +17,31 @@ describe("normalize (API response → idiomatic TS)", () => {
expect(out.head).toBe(3);
});
+ it("normalizes the canonical nested usage shape", () => {
+ const out = normalize<{
+ usage?: {
+ activeSeconds?: number;
+ reportedTurns?: number;
+ totalCostUsd?: number;
+ cacheReadInputTokens?: number;
+ };
+ }>({
+ usage: {
+ active_seconds: 12,
+ reported_turns: 2,
+ total_cost_usd: 0.42,
+ cache_read_input_tokens: 17,
+ },
+ });
+
+ expect(out.usage).toEqual({
+ activeSeconds: 12,
+ reportedTurns: 2,
+ totalCostUsd: 0.42,
+ cacheReadInputTokens: 17,
+ });
+ });
+
it("passes `metadata` through verbatim — opaque, inner keys untouched", () => {
const out = normalize<{ metadata?: Record<string, unknown> }>({
metadata: { pull_number: 42, owner_repo: "acme/widgets", nested: { keep_me: true } },
diff --git a/sdks/typescript/src/agents/sessions.ts b/sdks/typescript/src/agents/sessions.ts
index 46041d7e..7eb68ce1 100644
--- a/sdks/typescript/src/agents/sessions.ts
+++ b/sdks/typescript/src/agents/sessions.ts
@@ -260,6 +260,8 @@ export class Session extends ClientSession {
get status(): SessionStatus { return this.data.status; }
get lastTurn(): LastTurn | undefined { return this.data.lastTurn; }
+ /** Durable rollup of terminal-turn usage; absent cost is unknown, not zero. */
+ get usage(): SessionData["usage"] { return this.data.usage; }
/** Source checkout status from the create response — `{ name, status, path, sha, ... }[]`
* (empty when none). For **live** status, call {@link Session.listSources}. */
get sources(): SourceSummary[] { return this._sources; }
diff --git a/sdks/typescript/src/agents/types.ts b/sdks/typescript/src/agents/types.ts
index aabce0e5..5eabd18b 100644
--- a/sdks/typescript/src/agents/types.ts
+++ b/sdks/typescript/src/agents/types.ts
@@ -9,6 +9,49 @@ export type YieldReason =
export interface Limits { tokens?: number; turnSeconds?: number; turns?: number; }
+export type UsageAttribution = "exact" | "best_effort";
+
+/** A terminal turn whose runtime reported a complete normalized token total. */
+export interface ReportedTurnUsage {
+ reported: true;
+ inputTokens: number;
+ outputTokens: number;
+ cacheCreationInputTokens: number;
+ cacheReadInputTokens: number;
+ tokens: number;
+ /** Runtime/provider-reported visibility; absent means unknown, not zero. */
+ totalCostUsd?: number;
+ attribution?: UsageAttribution;
+}
+
+/** A terminal turn for which no trustworthy usage observation was available. */
+export interface UnreportedTurnUsage {
+ reported: false;
+ attribution?: UsageAttribution;
+}
+
+/** Historical rows created before usage rollups were populated remain empty. */
+export type HistoricalUsage = { [key: string]: never };
+export type TurnUsage = ReportedTurnUsage | UnreportedTurnUsage | HistoricalUsage;
+
+export interface SessionUsageSummary {
+ activeSeconds: number;
+ reportedTurns: number;
+ unreportedTurns: number;
+ /** False means any token/cost totals present are lower bounds. */
+ complete: boolean;
+ inputTokens?: number;
+ outputTokens?: number;
+ cacheCreationInputTokens?: number;
+ cacheReadInputTokens?: number;
+ tokens?: number;
+ /** Runtime/provider-reported visibility; absent means unknown, not zero. */
+ totalCostUsd?: number;
+ attribution?: UsageAttribution;
+}
+
+export type SessionUsage = SessionUsageSummary | HistoricalUsage;
+
// The runtime an agent runs on. `claude` and `pi` run `anthropic/…` models today and
// `codex` runs `openai/…`. `pi` is built provider-agnostic (the provider comes from the
// model's `provider/` prefix, not the runtime) — more providers land next. The union
@@ -65,6 +108,8 @@ export interface Turn {
error?: unknown;
startedAt?: string;
completedAt?: string;
+ activeSeconds?: number;
+ usage?: TurnUsage | null;
}
export interface SessionData {
@@ -76,6 +121,7 @@ export interface SessionData {
agentId?: string;
credentialId?: string;
lastTurn?: LastTurn;
+ usage?: SessionUsage | null;
limits?: Limits;
/** Opaque app routing state set at create (`null` when unset). See {@link CreateSessionParams.metadata}. */
metadata?: Record<string, unknown> | null;
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
index c6febcef..a332bd0b 100644
--- a/web/src/api/client.ts
+++ b/web/src/api/client.ts
@@ -58,6 +58,11 @@ export type {
SandboxWebhookDelivery,
Credential,
AgentSecurityNotification,
+ AgentHook,
+ AgentHookCreate,
+ AgentInvokeReceipt,
+ SessionUsage,
+ TurnUsage,
} from './schemas'
const API_BASE = '/api/dashboard'
@@ -530,6 +535,47 @@ export const updateAgent = (
S.AgentSchema,
)
+export const invokeAgent = (
+ agentId: string,
+ payload: unknown,
+ idempotencyKey: string,
+) =>
+ apiFetch(
+ `/v3/agents/${encodeURIComponent(agentId)}/sessions`,
+ {
+ method: 'POST',
+ headers: { 'Idempotency-Key': idempotencyKey },
+ body: JSON.stringify(payload),
+ },
+ S.AgentInvokeReceiptSchema,
+ )
+
+export const getAgentHooks = (agentId: string, cursor?: string) => {
+ const query = new URLSearchParams({ include_revoked: 'true', limit: '100' })
+ if (cursor) query.set('cursor', cursor)
+ return apiFetch(
+ `/v3/agents/${encodeURIComponent(agentId)}/hooks?${query.toString()}`,
+ {},
+ S.AgentHookListSchema,
+ )
+}
+
+export const createAgentHook = (
+ agentId: string,
+ body: { name: string; expires_at?: string | null },
+) =>
+ apiFetch(
+ `/v3/agents/${encodeURIComponent(agentId)}/hooks`,
+ { method: 'POST', body: JSON.stringify(body) },
+ S.AgentHookCreateSchema,
+ )
+
+export const revokeAgentHook = (agentId: string, hookId: string) =>
+ apiFetch<void>(
+ `/v3/agents/${encodeURIComponent(agentId)}/hooks/${encodeURIComponent(hookId)}`,
+ { method: 'DELETE' },
+ )
+
// Agent Revisions (design 009) — the deploy history of an agent's behavior. List
// endpoints wrap rows in { data: [...] }; callers want the array. Rollback = activate
// an earlier revision (by id or number); it moves the production pointer.
diff --git a/web/src/api/deployment-schemas.test.ts b/web/src/api/deployment-schemas.test.ts
index 5f5893c5..bd4fae2d 100644
--- a/web/src/api/deployment-schemas.test.ts
+++ b/web/src/api/deployment-schemas.test.ts
@@ -92,6 +92,7 @@ describe('repository deployment API schemas', () => {
it('preserves the legacy Flue admission proof without inventing live status', () => {
const parsed = AgentSchema.parse({
id: 'agt_legacy',
+ invoke_url: 'https://agt-legacy.agents.opencomputer.dev',
name: 'Legacy Flue agent',
prompt: null,
model: 'anthropic/claude-haiku-4-5',
diff --git a/web/src/api/mock-contracts.test.ts b/web/src/api/mock-contracts.test.ts
index f9835640..6e2684b5 100644
--- a/web/src/api/mock-contracts.test.ts
+++ b/web/src/api/mock-contracts.test.ts
@@ -1,9 +1,12 @@
import { describe, expect, it } from 'vitest'
import { mockFetch } from './mock'
import {
+ AgentListSchema,
RepositoryAccessSchema,
RepositorySourceInspectionSchema,
+ SessionListSchema,
SessionSourceListSchema,
+ SessionTurnListSchema,
} from './schemas'
describe('preview API contracts', () => {
@@ -18,7 +21,7 @@ describe('preview API contracts', () => {
it('keeps repository access and source-detail fixtures valid', () => {
expect(() =>
RepositoryAccessSchema.parse(
- mockFetch('/v3/agents/agt_flue_import/repository-access'),
+ mockFetch('/v3/agents/agt_fedcba9876543210fedcba98/repository-access'),
),
).not.toThrow()
expect(() =>
@@ -27,4 +30,14 @@ describe('preview API contracts', () => {
),
).not.toThrow()
})
+
+ it('keeps agent and canonical usage fixtures valid', () => {
+ expect(() => AgentListSchema.parse(mockFetch('/v3/agents'))).not.toThrow()
+ expect(() =>
+ SessionListSchema.parse(mockFetch('/v3/sessions')),
+ ).not.toThrow()
+ expect(() =>
+ SessionTurnListSchema.parse(mockFetch('/v3/sessions/ses_a1b2c3/turns')),
+ ).not.toThrow()
+ })
})
diff --git a/web/src/api/mock.ts b/web/src/api/mock.ts
index 70889879..23ccaac1 100644
--- a/web/src/api/mock.ts
+++ b/web/src/api/mock.ts
@@ -460,7 +460,8 @@ const orgInvitations = [
// ── Durable Agent Sessions ─────────────────────────────────────────────
const agents = [
{
- id: 'agt_3kf9xz',
+ id: 'agt_0123456789abcdef01234567',
+ invoke_url: 'https://agt-0123456789abcdef01234567.agents.opencomputer.dev',
name: 'PR Reviewer',
prompt:
'You are a meticulous code reviewer. Flag correctness, security, and clarity issues; be concise and cite line numbers.',
@@ -472,7 +473,8 @@ const agents = [
created_at: at(20),
},
{
- id: 'agt_7mq2aa',
+ id: 'agt_89abcdef0123456789abcdef',
+ invoke_url: 'https://agt-89abcdef0123456789abcdef.agents.opencomputer.dev',
name: 'Docs Writer',
prompt:
'You write clear, friendly developer documentation. Prefer short sentences and runnable examples.',
@@ -569,7 +571,7 @@ const repositoryAccess = {
// The linked source for the 'connected' preview (echoed for any agent id).
const deploymentSource = {
- agent_id: 'agt_3kf9xz',
+ agent_id: 'agt_0123456789abcdef01234567',
repo_id: 'repo_acme_agents',
path: 'agents/pr-reviewer',
production_ref: 'main',
@@ -627,7 +629,8 @@ const flueInspection = {
}
const importedAgent = {
- id: 'agt_flue_import',
+ id: 'agt_fedcba9876543210fedcba98',
+ invoke_url: 'https://agt-fedcba9876543210fedcba98.agents.opencomputer.dev',
name: 'Support triage',
prompt: null,
prompt_hash: null,
@@ -861,7 +864,7 @@ const agentSkills = {
// A connected Slack app for the first agent (the AgentDetail Slack panel).
const slackConnection = {
id: 'sla_5p6q7r',
- agent_id: 'agt_3kf9xz',
+ agent_id: 'agt_0123456789abcdef01234567',
handle: 'PR Reviewer',
slack_app_id: 'A0123ABCDEF',
team_id: 'T0123ABCDEF',
@@ -919,14 +922,25 @@ const credentials = [
const sessions = [
{
- // A flue (CF-native) session — meters at the gateway, so its `usage` is empty here
- // (spend renders "—"); the runtime badge is accented to set it apart from brain-box.
+ // Flue reports best-effort per-session attribution; its gateway remains the
+ // monetary authority.
id: 'ses_a1b2c3',
status: 'running',
- agent_id: 'agt_3kf9xz',
+ agent_id: 'agt_0123456789abcdef01234567',
agent_snapshot: { runtime: 'flue', model: 'anthropic/claude-haiku-4-5' },
head: 24,
- usage: {},
+ usage: {
+ active_seconds: 18,
+ reported_turns: 1,
+ unreported_turns: 0,
+ complete: true,
+ input_tokens: 1240,
+ output_tokens: 185,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 620,
+ tokens: 2045,
+ attribution: 'best_effort',
+ },
created_at: at(0, 1),
last_turn: { state: 'running' },
sandboxes: { brain: 'sbx_a1b2c3d4e5', hands: 'sbx_f6g7h8i9j0' },
@@ -934,41 +948,52 @@ const sessions = [
{
id: 'ses_d4e5f6',
status: 'awaiting_input',
- agent_id: 'agt_3kf9xz',
+ agent_id: 'agt_0123456789abcdef01234567',
agent_snapshot: { runtime: 'claude', model: 'anthropic/claude-sonnet-5' },
head: 12,
- usage: { cost_usd: 0.0231, input_tokens: 8200, output_tokens: 640 },
+ usage: {
+ active_seconds: 42,
+ reported_turns: 2,
+ unreported_turns: 0,
+ complete: true,
+ input_tokens: 8200,
+ output_tokens: 640,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ tokens: 8840,
+ total_cost_usd: 0.0231,
+ attribution: 'exact',
+ },
created_at: at(0, 3),
last_turn: { state: 'ok', yield_reason: 'needs_input' },
},
{
id: 'ses_g7h8i9',
status: 'idle',
- agent_id: 'agt_7mq2aa',
+ agent_id: 'agt_89abcdef0123456789abcdef',
agent_snapshot: { runtime: 'pi', model: 'anthropic/claude-sonnet-5' },
head: 41,
- // No cost reported → the spend column falls back to a token total.
- usage: { input_tokens: 15000, output_tokens: 2200 },
+ usage: {},
created_at: at(1, 2),
last_turn: { state: 'ok', yield_reason: 'completed' },
},
{
id: 'ses_j1k2l3',
status: 'failed',
- agent_id: 'agt_3kf9xz',
+ agent_id: 'agt_0123456789abcdef01234567',
agent_snapshot: { runtime: 'codex', model: 'openai/gpt-5.3-codex' },
head: 8,
- usage: { cost_usd: 0.11 },
+ usage: {},
created_at: at(2, 5),
last_turn: { state: 'error', yield_reason: 'error' },
},
{
id: 'ses_m4n5o6',
status: 'archived',
- agent_id: 'agt_7mq2aa',
+ agent_id: 'agt_89abcdef0123456789abcdef',
agent_snapshot: { runtime: 'claude', model: 'anthropic/claude-opus-4-8' },
head: 60,
- usage: { cost_usd: 1.42, input_tokens: 320000, output_tokens: 18400 },
+ usage: {},
created_at: at(4, 1),
last_turn: { state: 'ok', yield_reason: 'completed' },
},
@@ -1070,8 +1095,16 @@ const sessionTurns = [
yield_reason: 'needs_input',
started_at: at(0, 1),
completed_at: at(0, 1),
- active_seconds: 6.4,
- usage: { cost_usd: 0.0121, input_tokens: 4200, output_tokens: 310 },
+ active_seconds: 7,
+ usage: {
+ reported: true,
+ input_tokens: 4200,
+ output_tokens: 310,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ tokens: 4510,
+ total_cost_usd: 0.0121,
+ },
},
{
id: 'trn_1',
@@ -1079,8 +1112,8 @@ const sessionTurns = [
yield_reason: 'error',
started_at: at(0, 2),
completed_at: at(0, 2),
- active_seconds: 2.1,
- usage: {},
+ active_seconds: 3,
+ usage: { reported: false },
error: {
code: 'provision_infra',
message: 'brain sandbox failed to start',
@@ -1218,7 +1251,7 @@ const ROUTES: Array<[RegExp, Handler]> = [
() => failedFlueDeployment,
],
[
- /^\/v3\/agents\/agt_flue_import\/deployments(?:\?.*)?$/,
+ /^\/v3\/agents\/agt_fedcba9876543210fedcba98\/deployments(?:\?.*)?$/,
() => ({
data: [flueDeployment, failedFlueDeployment],
next_cursor: null,
@@ -1230,7 +1263,7 @@ const ROUTES: Array<[RegExp, Handler]> = [
],
[/^\/v3\/agents\/[^/]+\/deployments\/[^/]+$/, () => flueDeployment],
[
- /^\/v3\/agents\/agt_flue_import\/deployment-source$/,
+ /^\/v3\/agents\/agt_fedcba9876543210fedcba98\/deployment-source$/,
() => ({ source: importedSource }),
],
[
@@ -1241,7 +1274,11 @@ const ROUTES: Array<[RegExp, Handler]> = [
[/^\/v3\/agents\/[^/]+\/deploys$/, () => ({ data: agentDeploys })],
[/^\/v3\/agents\/[^/]+\/revisions$/, () => ({ data: agentRevisions })],
[/^\/v3\/agents\/[^/]+\/skills$/, () => agentSkills],
- [/^\/v3\/agents\/agt_flue_import$/, () => importedAgent],
+ [
+ /^\/v3\/agents\/[^/]+\/hooks(?:\?.*)?$/,
+ () => ({ data: [], next_cursor: null }),
+ ],
+ [/^\/v3\/agents\/agt_fedcba9876543210fedcba98$/, () => importedAgent],
[/^\/v3\/agents\/[^/]+$/, () => agents[0]],
[/^\/v3\/agents$/, () => ({ data: [...agents, importedAgent] })],
[/^\/v3\/credentials$/, () => ({ data: credentials })],
diff --git a/web/src/api/schemas.ts b/web/src/api/schemas.ts
index 784f825f..b957a309 100644
--- a/web/src/api/schemas.ts
+++ b/web/src/api/schemas.ts
@@ -340,6 +340,7 @@ export const SandboxWebhookDeliveryListSchema = z.object({
export const AgentSchema = z.object({
id: z.string(),
name: z.string(),
+ invoke_url: z.string(),
prompt: z.string().nullish(),
prompt_hash: z.string().nullish(),
model: z.string(),
@@ -904,6 +905,44 @@ export const AgentSnapshotSchema = z.object({
skill_bundle_digest: z.string().nullish(),
})
+const UsageAttributionSchema = z.enum(['exact', 'best_effort'])
+const ReportedTurnUsageSchema = z.object({
+ reported: z.literal(true),
+ input_tokens: z.number().int().nonnegative(),
+ output_tokens: z.number().int().nonnegative(),
+ cache_creation_input_tokens: z.number().int().nonnegative(),
+ cache_read_input_tokens: z.number().int().nonnegative(),
+ tokens: z.number().int().nonnegative(),
+ total_cost_usd: z.number().nonnegative().optional(),
+ attribution: UsageAttributionSchema.optional(),
+})
+const UnreportedTurnUsageSchema = z.object({
+ reported: z.literal(false),
+ attribution: UsageAttributionSchema.optional(),
+})
+const HistoricalEmptyUsageSchema = z.object({}).strict()
+export const TurnUsageSchema = z.union([
+ ReportedTurnUsageSchema,
+ UnreportedTurnUsageSchema,
+ HistoricalEmptyUsageSchema,
+])
+export const SessionUsageSchema = z.union([
+ z.object({
+ active_seconds: z.number().int().nonnegative(),
+ reported_turns: z.number().int().nonnegative(),
+ unreported_turns: z.number().int().nonnegative(),
+ complete: z.boolean(),
+ input_tokens: z.number().int().nonnegative().optional(),
+ output_tokens: z.number().int().nonnegative().optional(),
+ cache_creation_input_tokens: z.number().int().nonnegative().optional(),
+ cache_read_input_tokens: z.number().int().nonnegative().optional(),
+ tokens: z.number().int().nonnegative().optional(),
+ total_cost_usd: z.number().nonnegative().optional(),
+ attribution: UsageAttributionSchema.optional(),
+ }),
+ HistoricalEmptyUsageSchema,
+])
+
export const SessionSchema = z.object({
id: z.string(),
status: z.string(),
@@ -912,7 +951,7 @@ export const SessionSchema = z.object({
credential_id: z.string().nullable().optional(),
head: z.coerce.number().optional(), // current event seq; API returns it as a string ("0")
last_turn: record.nullish(),
- usage: record.nullish(),
+ usage: SessionUsageSchema.nullish(),
limits: record.nullish(),
metadata: record.nullish(),
// The OC sandboxes this session runs on (agent-sandbox-ownership Phase 1).
@@ -992,7 +1031,7 @@ export const TurnSchema = z.object({
completed_at: z.string().nullable().optional(),
active_seconds: z.number().nullish(),
result_event_id: z.string().nullish(),
- usage: record.nullish(),
+ usage: TurnUsageSchema.nullish(),
error: z.unknown().nullish(), // server serializes the error as an opaque object, not a string
})
export const SessionTurnListSchema = z.object({
@@ -1005,6 +1044,37 @@ export const SessionResultSchema = z.object({
result: SessionEventSchema.nullable(),
})
+export const AgentHookSchema = z.object({
+ id: z.string(),
+ agent_id: z.string(),
+ name: z.string(),
+ status: z.enum(['active', 'expired', 'revoked']),
+ secret_last4: z.string(),
+ revoked_reason: z.enum(['manual', 'secret_exposure']).nullable(),
+ expires_at: z.string().nullable(),
+ created_at: z.string(),
+})
+export const AgentHookListSchema = z.object({
+ data: z.array(AgentHookSchema),
+ next_cursor: z.string().nullable(),
+})
+export const AgentHookCreateSchema = z.object({
+ hook: AgentHookSchema,
+ hook_url: z.string(),
+})
+
+export const AgentInvokeReceiptSchema = z.object({
+ request_id: z.string(),
+ session: z.object({
+ id: z.string(),
+ status: z.string(),
+ head: z.coerce.number(),
+ }),
+ client_token: z.string(),
+ links: z.object({ events: z.string(), messages: z.string() }),
+ replayed: z.boolean(),
+})
+
export const AgentSecurityNotificationSchema = z.object({
id: z.string(),
agentId: z.string(),
@@ -1085,6 +1155,11 @@ export type AgentSnapshot = z.infer<typeof AgentSnapshotSchema>
export type SessionEvent = z.infer<typeof SessionEventSchema>
export type Turn = z.infer<typeof TurnSchema>
export type SessionResult = z.infer<typeof SessionResultSchema>
+export type TurnUsage = z.infer<typeof TurnUsageSchema>
+export type SessionUsage = z.infer<typeof SessionUsageSchema>
+export type AgentHook = z.infer<typeof AgentHookSchema>
+export type AgentHookCreate = z.infer<typeof AgentHookCreateSchema>
+export type AgentInvokeReceipt = z.infer<typeof AgentInvokeReceiptSchema>
export type AgentSecurityNotification = z.infer<
typeof AgentSecurityNotificationSchema
>
diff --git a/web/src/components/agent-hooks-panel.tsx b/web/src/components/agent-hooks-panel.tsx
new file mode 100644
index 00000000..b7a470ff
--- /dev/null
+++ b/web/src/components/agent-hooks-panel.tsx
@@ -0,0 +1,292 @@
+import { useState } from 'react'
+import {
+ useInfiniteQuery,
+ useMutation,
+ useQueryClient,
+} from '@tanstack/react-query'
+import { KeyRound, Plus, Trash2 } from 'lucide-react'
+import {
+ createAgentHook,
+ getAgentHooks,
+ revokeAgentHook,
+ type AgentHook,
+ type AgentHookCreate,
+} from '@/api/client'
+import { notifyError } from '@/lib/errors'
+import {
+ Panel,
+ PanelContent,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
+import { Button } from '@/components/ui/button'
+import { Field, Input } from '@/components/form'
+import { CopyRow } from '@/components/copy-row'
+import { StatusBadge } from '@/components/status-badge'
+import { ConfirmDialog } from '@/components/confirm-dialog'
+import { ApiHint } from '@/components/api-hint'
+
+function revokedReason(reason: AgentHook['revoked_reason']): string | null {
+ if (reason === 'secret_exposure') return 'Secret exposure detected'
+ if (reason === 'manual') return 'Revoked manually'
+ return null
+}
+
+function expiryLabel(value: string | null): string {
+ return value ? `Expires ${new Date(value).toLocaleString()}` : 'No expiry'
+}
+
+export function AgentHooksPanel({ agentId }: { agentId: string }) {
+ const queryClient = useQueryClient()
+ const [creating, setCreating] = useState(false)
+ const [createPending, setCreatePending] = useState(false)
+ const [name, setName] = useState('')
+ const [expiresAt, setExpiresAt] = useState('')
+ const [created, setCreated] = useState<AgentHookCreate | null>(null)
+ const [revoke, setRevoke] = useState<AgentHook | null>(null)
+ const query = useInfiniteQuery({
+ queryKey: ['agent-hooks', agentId],
+ queryFn: ({ pageParam }) => getAgentHooks(agentId, pageParam),
+ initialPageParam: undefined as string | undefined,
+ getNextPageParam: (page) => page.next_cursor ?? undefined,
+ })
+ const hooks = query.data?.pages.flatMap((page) => page.data) ?? []
+
+ const invalidate = () =>
+ queryClient.invalidateQueries({ queryKey: ['agent-hooks', agentId] })
+ const submitCreate = async () => {
+ setCreatePending(true)
+ try {
+ const result = await createAgentHook(agentId, {
+ name: name.trim(),
+ ...(expiresAt ? { expires_at: new Date(expiresAt).toISOString() } : {}),
+ })
+ // The complete Hook URL stays only in this component until dismissed.
+ setCreated(result)
+ setCreating(false)
+ setName('')
+ setExpiresAt('')
+ void invalidate()
+ } catch (error) {
+ notifyError("Couldn't create the Hook URL.", error)
+ } finally {
+ setCreatePending(false)
+ }
+ }
+ const revokeMutation = useMutation({
+ mutationFn: (hook: AgentHook) => revokeAgentHook(agentId, hook.id),
+ onSuccess: () => {
+ setRevoke(null)
+ void invalidate()
+ },
+ onError: (error) => notifyError("Couldn't revoke the Hook URL.", error),
+ })
+
+ return (
+ <Panel id="hooks" className="scroll-mt-36">
+ <PanelHeader>
+ <div>
+ <PanelTitle>Hook URLs</PanelTitle>
+ <p className="text-muted-foreground mt-1 text-xs">
+ One named, revocable URL per external sender.
+ </p>
+ </div>
+ <ApiHint
+ method="POST"
+ path={`/v3/agents/${agentId}/hooks`}
+ sdk="oc.agents.hooks.create(id, …)"
+ docs="https://docs.opencomputer.dev/agent-sessions/hooks"
+ />
+ </PanelHeader>
+
+ {created ? (
+ <PanelContent className="border-b">
+ <div className="border-status-warning/40 bg-status-warning-bg rounded-md border p-3">
+ <p className="text-foreground text-sm font-medium">
+ Copy {created.hook.name}&apos;s complete URL now
+ </p>
+ <p className="text-muted-foreground mt-1 text-xs">
+ It cannot be retrieved after you close this notice.
+ </p>
+ <CopyRow
+ value={created.hook_url}
+ maskable
+ className="bg-background mt-3"
+ />
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ className="mt-2"
+ onClick={() => setCreated(null)}
+ >
+ I&apos;ve copied it
+ </Button>
+ </div>
+ </PanelContent>
+ ) : null}
+
+ {creating ? (
+ <PanelContent className="border-b">
+ <form
+ className="space-y-3"
+ onSubmit={(event) => {
+ event.preventDefault()
+ if (name.trim()) void submitCreate()
+ }}
+ >
+ <Field label="Name" htmlFor="hook-name">
+ <Input
+ id="hook-name"
+ value={name}
+ onChange={(event) => setName(event.target.value)}
+ placeholder="grafana-prod"
+ pattern="[a-z0-9][a-z0-9-]{0,63}"
+ required
+ />
+ </Field>
+ <Field
+ label="Expires"
+ htmlFor="hook-expiry"
+ description="Optional. Leave empty for no expiry."
+ >
+ <Input
+ id="hook-expiry"
+ type="datetime-local"
+ value={expiresAt}
+ onChange={(event) => setExpiresAt(event.target.value)}
+ />
+ </Field>
+ <div className="flex justify-end gap-2">
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ disabled={createPending}
+ onClick={() => setCreating(false)}
+ >
+ Cancel
+ </Button>
+ <Button
+ type="submit"
+ size="sm"
+ disabled={!name.trim() || createPending}
+ >
+ {createPending ? 'Creating…' : 'Create Hook URL'}
+ </Button>
+ </div>
+ </form>
+ </PanelContent>
+ ) : null}
+
+ <div className="divide-y">
+ {query.isLoading ? (
+ <p className="text-muted-foreground px-5 py-4 text-xs">Loading…</p>
+ ) : query.isError ? (
+ <div className="px-5 py-5 text-center">
+ <p className="text-sm font-medium">Hook URLs unavailable</p>
+ <p className="text-muted-foreground mt-1 text-xs">
+ Could not load this agent&apos;s Hooks.
+ </p>
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ className="mt-3"
+ onClick={() => void query.refetch()}
+ >
+ Try again
+ </Button>
+ </div>
+ ) : hooks.length === 0 ? (
+ <div className="px-5 py-5 text-center">
+ <KeyRound className="text-muted-foreground mx-auto size-5" />
+ <p className="mt-2 text-sm font-medium">No Hook URLs</p>
+ <p className="text-muted-foreground mt-1 text-xs">
+ Create one when an external system needs to start this agent.
+ </p>
+ </div>
+ ) : (
+ hooks.map((hook) => {
+ const reason = revokedReason(hook.revoked_reason)
+ return (
+ <div key={hook.id} className="px-5 py-3">
+ <div className="flex items-start justify-between gap-3">
+ <div className="min-w-0">
+ <div className="flex flex-wrap items-center gap-2">
+ <span className="text-sm font-medium">{hook.name}</span>
+ <StatusBadge status={hook.status} />
+ </div>
+ <p className="text-muted-foreground mt-1 font-mono text-[11px]">
+ {hook.id} · ends in {hook.secret_last4}
+ </p>
+ <p className="text-muted-foreground mt-1 text-xs">
+ Created {new Date(hook.created_at).toLocaleString()} ·{' '}
+ {expiryLabel(hook.expires_at)}
+ </p>
+ {reason ? (
+ <p className="text-status-error mt-0.5 text-xs">
+ {reason}
+ </p>
+ ) : null}
+ </div>
+ {hook.status !== 'revoked' ? (
+ <Button
+ type="button"
+ size="icon-xs"
+ variant="ghost"
+ aria-label={`Revoke ${hook.name}`}
+ onClick={() => setRevoke(hook)}
+ >
+ <Trash2 className="size-3.5" />
+ </Button>
+ ) : null}
+ </div>
+ </div>
+ )
+ })
+ )}
+ </div>
+
+ <div className="flex items-center justify-between border-t px-5 py-3">
+ {query.hasNextPage ? (
+ <Button
+ type="button"
+ size="sm"
+ variant="ghost"
+ disabled={query.isFetchingNextPage}
+ onClick={() => void query.fetchNextPage()}
+ >
+ {query.isFetchingNextPage ? 'Loading…' : 'Load older'}
+ </Button>
+ ) : (
+ <span />
+ )}
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={creating || !!created}
+ onClick={() => setCreating(true)}
+ >
+ <Plus className="size-3.5" /> New Hook URL
+ </Button>
+ </div>
+
+ <ConfirmDialog
+ open={!!revoke}
+ onOpenChange={(open) => {
+ if (!open) setRevoke(null)
+ }}
+ title={`Revoke ${revoke?.name ?? 'this Hook'}?`}
+ description="The sender will immediately lose access. This cannot be undone. Create a replacement before revoking if the integration must stay live."
+ confirmLabel="Revoke Hook"
+ destructive
+ pending={revokeMutation.isPending}
+ onConfirm={() => {
+ if (revoke) revokeMutation.mutate(revoke)
+ }}
+ />
+ </Panel>
+ )
+}
diff --git a/web/src/components/agent-invocation-panels.test.tsx b/web/src/components/agent-invocation-panels.test.tsx
new file mode 100644
index 00000000..02d38d7b
--- /dev/null
+++ b/web/src/components/agent-invocation-panels.test.tsx
@@ -0,0 +1,69 @@
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
+import { renderToStaticMarkup } from 'react-dom/server'
+import { MemoryRouter } from 'react-router-dom'
+import { describe, expect, it } from 'vitest'
+import type { Agent } from '@/api/client'
+import { AgentHooksPanel } from './agent-hooks-panel'
+import { AgentUrlPanel } from './agent-url-panel'
+
+const agent: Agent = {
+ id: 'agt_0123456789abcdef01234567',
+ name: 'Reviewer',
+ invoke_url: 'https://agt-0123456789abcdef01234567.agents.opencomputer.dev',
+ model: 'anthropic/claude-opus-4-8',
+ runtime: 'claude',
+ credential_id: 'managed',
+ revision: 1,
+ created_at: '2026-07-22T00:00:00.000Z',
+}
+
+function renderPanels() {
+ const queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false, staleTime: Infinity } },
+ })
+ queryClient.setQueryData(['agent-hooks', agent.id], {
+ pages: [
+ {
+ data: [
+ {
+ id: 'hk_0123456789abcdef01234567',
+ agent_id: agent.id,
+ name: 'grafana-prod',
+ status: 'revoked',
+ secret_last4: 'xYz0',
+ revoked_reason: 'secret_exposure',
+ expires_at: null,
+ created_at: '2026-07-22T00:00:00.000Z',
+ },
+ ],
+ next_cursor: null,
+ },
+ ],
+ pageParams: [undefined],
+ })
+
+ return renderToStaticMarkup(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter>
+ <AgentUrlPanel agent={agent} />
+ <AgentHooksPanel agentId={agent.id} />
+ </MemoryRouter>
+ </QueryClientProvider>,
+ )
+}
+
+describe('Agent invocation panels', () => {
+ it('keeps root invocation server-only and renders Hook audit metadata', () => {
+ const markup = renderPanels()
+
+ expect(markup).toContain(agent.invoke_url)
+ expect(markup).toContain('Server-side only')
+ expect(markup).toContain('Run test')
+ expect(markup).toContain('View sessions')
+ expect(markup).toContain(`/agents/${agent.id}/sessions`)
+ expect(markup).toContain('grafana-prod')
+ expect(markup).toContain('Secret exposure detected')
+ expect(markup).toContain('ends in xYz0')
+ expect(markup).not.toContain('/hooks/secret')
+ })
+})
diff --git a/web/src/components/agent-url-panel.tsx b/web/src/components/agent-url-panel.tsx
new file mode 100644
index 00000000..c8d0560a
--- /dev/null
+++ b/web/src/components/agent-url-panel.tsx
@@ -0,0 +1,114 @@
+import { useState } from 'react'
+import { Link } from 'react-router-dom'
+import { ExternalLink, Play } from 'lucide-react'
+import { invokeAgent, type Agent } from '@/api/client'
+import { notifyError } from '@/lib/errors'
+import {
+ Panel,
+ PanelContent,
+ PanelHeader,
+ PanelTitle,
+} from '@/components/panel'
+import { Button } from '@/components/ui/button'
+import { Textarea } from '@/components/form'
+import { CopyRow } from '@/components/copy-row'
+import { ApiHint } from '@/components/api-hint'
+
+const DEFAULT_PAYLOAD = `{
+ "task": "Summarize the latest support request"
+}`
+
+export function AgentUrlPanel({ agent }: { agent: Agent }) {
+ const [payload, setPayload] = useState(DEFAULT_PAYLOAD)
+ const [parseError, setParseError] = useState<string | null>(null)
+ const [pending, setPending] = useState(false)
+ const [sessionId, setSessionId] = useState<string | null>(null)
+
+ const run = async () => {
+ let body: unknown
+ try {
+ body = JSON.parse(payload)
+ } catch {
+ setParseError('Enter a valid JSON value.')
+ return
+ }
+ setParseError(null)
+ setPending(true)
+ try {
+ const receipt = await invokeAgent(agent.id, body, crypto.randomUUID())
+ // Do not retain the returned client token in component or query state.
+ setSessionId(receipt.session.id)
+ } catch (error) {
+ notifyError("Couldn't invoke the agent.", error)
+ } finally {
+ setPending(false)
+ }
+ }
+
+ return (
+ <Panel>
+ <PanelHeader>
+ <div>
+ <PanelTitle>Agent URL</PanelTitle>
+ <p className="text-muted-foreground mt-1 text-xs">
+ Root invocation requires an OpenComputer API key. Server-side only.
+ </p>
+ </div>
+ <ApiHint
+ method="POST"
+ path="/"
+ docs="https://docs.opencomputer.dev/agent-sessions/agent-urls"
+ />
+ </PanelHeader>
+ <PanelContent className="space-y-4">
+ <CopyRow value={agent.invoke_url} />
+ <pre className="bg-panel-2 text-muted-foreground overflow-x-auto rounded-md border p-3 font-mono text-[11px] leading-relaxed">{`curl "$AGENT_URL/" \\
+ -H "Authorization: Bearer $OPENCOMPUTER_API_KEY" \\
+ -H "Content-Type: application/json" \\
+ -d '{"task":"Summarize the latest support request"}'`}</pre>
+ <div className="space-y-2">
+ <Textarea
+ aria-label="Test JSON payload"
+ value={payload}
+ onChange={(event) => setPayload(event.target.value)}
+ className="min-h-24 font-mono text-xs"
+ />
+ {parseError ? (
+ <p className="text-status-error text-xs font-medium" role="alert">
+ {parseError}
+ </p>
+ ) : null}
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <Button
+ type="button"
+ size="sm"
+ variant="outline"
+ disabled={pending}
+ onClick={() => void run()}
+ >
+ <Play className="size-3.5" />
+ {pending ? 'Starting…' : 'Run test'}
+ </Button>
+ <div className="flex flex-wrap items-center gap-3">
+ <Link
+ to={`/agents/${agent.id}/sessions`}
+ className="text-muted-foreground text-xs font-medium underline underline-offset-4"
+ >
+ View sessions
+ </Link>
+ {sessionId ? (
+ <Link
+ to={`/sessions/${sessionId}`}
+ className="text-foreground inline-flex items-center gap-1 text-xs font-medium underline underline-offset-4"
+ >
+ Session {sessionId}
+ <ExternalLink className="size-3" aria-hidden />
+ </Link>
+ ) : null}
+ </div>
+ </div>
+ </div>
+ </PanelContent>
+ </Panel>
+ )
+}
diff --git a/web/src/components/session-conversation.test.tsx b/web/src/components/session-conversation.test.tsx
new file mode 100644
index 00000000..0751ea35
--- /dev/null
+++ b/web/src/components/session-conversation.test.tsx
@@ -0,0 +1,32 @@
+import { renderToStaticMarkup } from 'react-dom/server'
+import { describe, expect, it } from 'vitest'
+import type { SessionEvent } from '@/api/client'
+import { HttpRequestCard } from './session-conversation'
+
+describe('HttpRequestCard', () => {
+ it('renders the attributed payload as structured, escaped JSON', () => {
+ const event: SessionEvent = {
+ id: 'evt_http',
+ seq: 1,
+ type: 'http.request',
+ level: 'user',
+ source: 'http',
+ actor: {
+ id: 'hk_0123456789abcdef01234567',
+ type: 'trigger',
+ display: 'grafana-prod',
+ },
+ body: { payload: { title: '<script>alert(1)</script>', count: 2 } },
+ }
+
+ const markup = renderToStaticMarkup(
+ <HttpRequestCard event={event} seq={event.seq} />,
+ )
+
+ expect(markup).toContain('grafana-prod')
+ expect(markup).toContain('HTTP input')
+ expect(markup).toContain('&lt;script&gt;alert(1)&lt;/script&gt;')
+ expect(markup).not.toContain('<script>')
+ expect(markup).toContain('&quot;count&quot;: 2')
+ })
+})
diff --git a/web/src/components/session-conversation.tsx b/web/src/components/session-conversation.tsx
index 53d95972..0dbb41d8 100644
--- a/web/src/components/session-conversation.tsx
+++ b/web/src/components/session-conversation.tsx
@@ -1,9 +1,11 @@
import type { ReactNode } from 'react'
import { Link } from 'react-router-dom'
import { Hourglass } from 'lucide-react'
+import type { SessionEvent } from '@/api/client'
import { Button } from '@/components/ui/button'
import {
bodyText,
+ httpRequestPayloadText,
isOutOfCredits,
isTerminalSessionStatus,
isTurnInput,
@@ -11,6 +13,38 @@ import {
type TurnState,
} from '@/lib/session-turns'
+export function HttpRequestCard({
+ event,
+ seq,
+ meta,
+}: {
+ event: SessionEvent
+ seq?: number
+ meta?: ReactNode
+}) {
+ return (
+ <div>
+ <div className="mb-1 flex items-center gap-2">
+ <span className="text-foreground text-xs font-semibold">
+ {event.actor?.display ?? 'HTTP'}
+ </span>
+ {seq != null ? (
+ <span className="text-muted-foreground/70 font-mono text-[10px]">
+ #{seq}
+ </span>
+ ) : null}
+ <span className="text-muted-foreground bg-muted rounded-sm px-1.5 py-0.5 text-[10px] font-medium">
+ HTTP input
+ </span>
+ {meta}
+ </div>
+ <pre className="bg-panel-2 text-foreground/90 overflow-x-auto rounded-md border p-3 font-mono text-xs leading-relaxed whitespace-pre-wrap">
+ {httpRequestPayloadText(event) ?? 'Payload unavailable'}
+ </pre>
+ </div>
+ )
+}
+
// A single chat bubble (You / Agent). Shared between the grouped Conversation
// view and the flat All log so both render identical message markup.
export function MessageBubble({
@@ -112,6 +146,21 @@ export function TurnConversation({
return (
<li key={group.turnId} className="space-y-3 px-4 py-3">
{group.events.map((ev) => {
+ if (ev.type === 'http.request') {
+ return (
+ <HttpRequestCard
+ key={ev.id}
+ event={ev}
+ meta={
+ showActiveState &&
+ ev.id === activeInputId &&
+ group.state === 'queued' ? (
+ <TurnStateChip state="queued" />
+ ) : undefined
+ }
+ />
+ )
+ }
if (ev.type === 'user.message') {
return (
<MessageBubble
@@ -153,15 +202,26 @@ export function TurnConversation({
})}
{grouped.pending.map((ev) => (
<li key={ev.id} className="px-4 py-3">
- <MessageBubble
- label={ev.actor?.display ?? 'You'}
- text={bodyText(ev)}
- meta={
- !halted && !sessionTerminal ? (
- <TurnStateChip state="queued" />
- ) : undefined
- }
- />
+ {ev.type === 'http.request' ? (
+ <HttpRequestCard
+ event={ev}
+ meta={
+ !halted && !sessionTerminal ? (
+ <TurnStateChip state="queued" />
+ ) : undefined
+ }
+ />
+ ) : (
+ <MessageBubble
+ label={ev.actor?.display ?? 'You'}
+ text={bodyText(ev)}
+ meta={
+ !halted && !sessionTerminal ? (
+ <TurnStateChip state="queued" />
+ ) : undefined
+ }
+ />
+ )}
</li>
))}
</ul>
diff --git a/web/src/components/session-turns.tsx b/web/src/components/session-turns.tsx
index 7ba91ffd..e802957c 100644
--- a/web/src/components/session-turns.tsx
+++ b/web/src/components/session-turns.tsx
@@ -3,7 +3,11 @@ import { getSessionTurns, type Turn } from '@/api/client'
import { Panel } from '@/components/panel'
import { StatusBadge } from '@/components/status-badge'
import { ApiHint } from '@/components/api-hint'
-import { formatSpend } from '@/lib/usage'
+import {
+ formatUsageCost,
+ formatUsageTokens,
+ usageAttribution,
+} from '@/lib/usage'
// A turn's `error` is an opaque object (or a string); pull a one-line message defensively.
function errorMessage(error: unknown): string | null {
@@ -78,7 +82,16 @@ export function SessionTurns({
{(turns ?? []).map((t) => {
const err = t.state === 'error' ? errorMessage(t.error) : null
const dur = duration(t)
- const spend = formatSpend(t.usage)
+ const tokens = formatUsageTokens(t.usage)
+ const cost = formatUsageCost(t.usage)
+ const usage =
+ tokens === 'Unknown'
+ ? 'Usage unknown'
+ : `${tokens} tok · ${cost === 'Unknown' ? 'cost unknown' : cost}${
+ usageAttribution(t.usage) === 'best_effort'
+ ? ' · best-effort'
+ : ''
+ }`
return (
<li key={t.id} className="px-4 py-2.5">
<div className="flex flex-wrap items-center gap-x-3 gap-y-1">
@@ -96,7 +109,7 @@ export function SessionTurns({
) : null}
<span className="text-muted-foreground/70 ml-auto flex items-center gap-3 font-mono text-[11px] tabular-nums">
{dur ? <span title="active compute">{dur}</span> : null}
- {spend !== '—' ? <span title="turn usage">{spend}</span> : null}
+ <span title="turn usage">{usage}</span>
</span>
</div>
{err ? (
diff --git a/web/src/lib/session-turns.test.ts b/web/src/lib/session-turns.test.ts
index db1d84db..a3801937 100644
--- a/web/src/lib/session-turns.test.ts
+++ b/web/src/lib/session-turns.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest'
import type { SessionEvent } from '@/api/client'
-import { groupIntoTurns } from './session-turns'
+import { groupIntoTurns, httpRequestPayloadText } from './session-turns'
function event(
seq: number,
@@ -187,6 +187,26 @@ describe('groupIntoTurns', () => {
})
})
+ it('groups and preserves structured HTTP input', () => {
+ const input = event(1, 'http.request', {
+ source: 'http',
+ turn_id: 'trn_http',
+ actor: { id: 'hk_test', type: 'trigger', display: 'grafana-prod' },
+ body: { payload: { severity: 'critical', count: 2 } },
+ })
+ const timeline = groupIntoTurns([input])
+
+ expect(timeline.pending).toEqual([])
+ expect(timeline.groups[0]).toMatchObject({
+ turnId: 'trn_http',
+ state: 'queued',
+ events: [input],
+ })
+ expect(httpRequestPayloadText(input)).toBe(
+ '{\n "severity": "critical",\n "count": 2\n}',
+ )
+ })
+
it('deduplicates history and SSE copies and cannot regress on arrival order', () => {
const input = event(1, 'user.message', {
source: 'client',
diff --git a/web/src/lib/session-turns.ts b/web/src/lib/session-turns.ts
index 94f82dbe..b5b469f7 100644
--- a/web/src/lib/session-turns.ts
+++ b/web/src/lib/session-turns.ts
@@ -62,6 +62,19 @@ export function bodyText(ev: SessionEvent): string | null {
return typeof text === 'string' ? text : null
}
+// HTTP invocation bodies stay structured in the durable event log. Render the
+// authoritative payload rather than the adapter's derived model-input string.
+export function httpRequestPayloadText(ev: SessionEvent): string | null {
+ if (ev.type !== 'http.request') return null
+ const body = record(ev.body)
+ if (!Object.prototype.hasOwnProperty.call(body, 'payload')) return null
+ try {
+ return JSON.stringify(body.payload, null, 2) ?? null
+ } catch {
+ return null
+ }
+}
+
// The runtime's failPreExec emits an agent.message tagged with an
// insufficient_credits code so the UI can offer a "top up" affordance.
export function isOutOfCredits(ev: SessionEvent): boolean {
@@ -73,6 +86,7 @@ export function isOutOfCredits(ev: SessionEvent): boolean {
export function isTurnInput(ev: SessionEvent): boolean {
return (
+ ev.type === 'http.request' ||
ev.type === 'user.message' ||
ev.source === 'client' ||
ev.source === 'github'
diff --git a/web/src/lib/usage.test.ts b/web/src/lib/usage.test.ts
new file mode 100644
index 00000000..b177a5da
--- /dev/null
+++ b/web/src/lib/usage.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest'
+import {
+ formatDuration,
+ formatUsageCost,
+ formatUsageDuration,
+ formatUsageTokens,
+ usageDisclosure,
+} from './usage'
+
+describe('canonical usage presentation', () => {
+ it('renders complete session usage as exact values', () => {
+ const usage = {
+ active_seconds: 65,
+ reported_turns: 1,
+ unreported_turns: 0,
+ complete: true,
+ input_tokens: 10,
+ output_tokens: 5,
+ cache_creation_input_tokens: 0,
+ cache_read_input_tokens: 0,
+ tokens: 15,
+ total_cost_usd: 0.0042,
+ attribution: 'exact' as const,
+ }
+
+ expect(formatUsageTokens(usage)).toBe('15')
+ expect(formatUsageCost(usage)).toBe('$0.0042')
+ expect(formatUsageDuration(usage)).toBe('1m 05s')
+ expect(usageDisclosure(usage)).toBeNull()
+ })
+
+ it('marks incomplete totals and best-effort attribution', () => {
+ const usage = {
+ active_seconds: 4,
+ reported_turns: 2,
+ unreported_turns: 1,
+ complete: false,
+ tokens: 1234,
+ total_cost_usd: 0.12,
+ attribution: 'best_effort' as const,
+ }
+
+ expect(formatUsageTokens(usage)).toBe('≥1,234')
+ expect(formatUsageCost(usage)).toBe('≥$0.120')
+ expect(usageDisclosure(usage)).toBe(
+ 'Lower bound · 1 turn did not report usage · Best-effort session attribution',
+ )
+ })
+
+ it('keeps missing and historical usage unknown', () => {
+ expect(formatUsageTokens({})).toBe('Unknown')
+ expect(formatUsageCost({ reported: false })).toBe('Unknown')
+ expect(formatUsageDuration(null)).toBe('Unknown')
+ })
+
+ it('formats long active durations compactly', () => {
+ expect(formatDuration(0)).toBe('0s')
+ expect(formatDuration(59)).toBe('59s')
+ expect(formatDuration(3661)).toBe('1h 01m')
+ })
+})
diff --git a/web/src/lib/usage.ts b/web/src/lib/usage.ts
index b1ab36bd..009190b0 100644
--- a/web/src/lib/usage.ts
+++ b/web/src/lib/usage.ts
@@ -1,54 +1,99 @@
-// A session's / turn's `usage` is an opaque, runtime-authored object — its shape
-// varies by runtime (brain-box runtimes report token counts + sometimes a cost;
-// flue currently emits `{}`, with spend metered authoritatively at the gateway).
-// Extract the human-meaningful bits defensively — never assume a field is present.
+import type { SessionUsage, TurnUsage } from '@/api/schemas'
-export type UsageLike = Record<string, unknown> | null | undefined
+export type UsageLike = SessionUsage | TurnUsage | null | undefined
-function num(v: unknown): number | null {
- return typeof v === 'number' && Number.isFinite(v) ? v : null
+function asRecord(value: UsageLike): Record<string, unknown> | null {
+ return value !== null && typeof value === 'object' ? value : null
}
export function hasUsage(usage: UsageLike): boolean {
- return !!usage && Object.keys(usage).length > 0
+ const record = asRecord(usage)
+ return record !== null && Object.keys(record).length > 0
}
-// Cost in USD if the runtime reported one — several field spellings appear across runtimes.
export function usageCostUsd(usage: UsageLike): number | null {
- if (!usage) return null
- const u = usage
- for (const k of ['cost_usd', 'total_cost_usd', 'cost', 'total_cost', 'usd']) {
- const n = num(u[k])
- if (n !== null) return n
- }
- return null
+ const record = asRecord(usage)
+ if (!record) return null
+ const value = record.total_cost_usd
+ return typeof value === 'number' && Number.isFinite(value) ? value : null
}
-// Total tokens, summing input/output when a direct total isn't given.
export function usageTokens(usage: UsageLike): number | null {
- if (!usage) return null
- const u = usage
- const total = num(u.total_tokens) ?? num(u.tokens)
- if (total !== null) return total
- const inp = num(u.input_tokens) ?? num(u.prompt_tokens)
- const out = num(u.output_tokens) ?? num(u.completion_tokens)
- if (inp !== null || out !== null) return (inp ?? 0) + (out ?? 0)
- return null
-}
-
-// Sub-cent per-session spend is common; show enough precision to stay non-zero.
-export function formatUsd(n: number): string {
- if (n === 0) return '$0'
- if (n < 0.01) return `$${n.toFixed(4)}`
- if (n < 1) return `$${n.toFixed(3)}`
- return `$${n.toFixed(2)}`
-}
-
-// A compact one-line spend label for a table cell / metric: "$0.0230", "1,240 tok", or "—".
-export function formatSpend(usage: UsageLike): string {
- const cost = usageCostUsd(usage)
- if (cost !== null) return formatUsd(cost)
- const tok = usageTokens(usage)
- if (tok !== null) return `${tok.toLocaleString()} tok`
- return '—'
+ const record = asRecord(usage)
+ if (!record) return null
+ const value = record.tokens
+ return typeof value === 'number' && Number.isSafeInteger(value) ? value : null
+}
+
+export function usageActiveSeconds(usage: UsageLike): number | null {
+ const record = asRecord(usage)
+ if (!record) return null
+ const value = record.active_seconds
+ return typeof value === 'number' && Number.isSafeInteger(value) ? value : null
+}
+
+export function usageIsIncomplete(usage: UsageLike): boolean {
+ return asRecord(usage)?.complete === false
+}
+
+export function usageAttribution(
+ usage: UsageLike,
+): 'exact' | 'best_effort' | null {
+ const record = asRecord(usage)
+ if (!record) return null
+ return record.attribution === 'exact' || record.attribution === 'best_effort'
+ ? record.attribution
+ : null
+}
+
+export function formatUsd(value: number): string {
+ if (value === 0) return '$0'
+ if (value < 0.01) return `$${value.toFixed(4)}`
+ if (value < 1) return `$${value.toFixed(3)}`
+ return `$${value.toFixed(2)}`
+}
+
+export function formatUsageTokens(usage: UsageLike): string {
+ const value = usageTokens(usage)
+ if (value === null) return 'Unknown'
+ return `${usageIsIncomplete(usage) ? '≥' : ''}${value.toLocaleString()}`
+}
+
+export function formatUsageCost(usage: UsageLike): string {
+ const value = usageCostUsd(usage)
+ if (value === null) return 'Unknown'
+ return `${usageIsIncomplete(usage) ? '≥' : ''}${formatUsd(value)}`
+}
+
+export function formatDuration(seconds: number): string {
+ if (seconds < 60) return `${seconds}s`
+ const minutes = Math.floor(seconds / 60)
+ const remainder = seconds % 60
+ if (minutes < 60) return `${minutes}m ${String(remainder).padStart(2, '0')}s`
+ const hours = Math.floor(minutes / 60)
+ const minuteRemainder = minutes % 60
+ return `${hours}h ${String(minuteRemainder).padStart(2, '0')}m`
+}
+
+export function formatUsageDuration(usage: UsageLike): string {
+ const seconds = usageActiveSeconds(usage)
+ return seconds === null ? 'Unknown' : formatDuration(seconds)
+}
+
+export function usageDisclosure(usage: UsageLike): string | null {
+ const record = asRecord(usage)
+ if (!record) return null
+ const notes: string[] = []
+ if (record.complete === false) {
+ const missing = record.unreported_turns
+ notes.push(
+ typeof missing === 'number' && missing > 0
+ ? `Lower bound · ${missing} turn${missing === 1 ? '' : 's'} did not report usage`
+ : 'Lower-bound usage',
+ )
+ }
+ if (record.attribution === 'best_effort') {
+ notes.push('Best-effort session attribution')
+ }
+ return notes.length > 0 ? notes.join(' · ') : null
}
diff --git a/web/src/pages/AgentDetail.tsx b/web/src/pages/AgentDetail.tsx
index 08575775..f1c600dc 100644
--- a/web/src/pages/AgentDetail.tsx
+++ b/web/src/pages/AgentDetail.tsx
@@ -40,6 +40,8 @@ import { AgentDeploySource } from '@/components/agent-deploy-source'
import { AgentSchedulesTab } from '@/components/agent-schedules'
import { AgentRevisions } from '@/components/agent-revisions'
import { AgentDeployments } from '@/components/agent-deployments'
+import { AgentUrlPanel } from '@/components/agent-url-panel'
+import { AgentHooksPanel } from '@/components/agent-hooks-panel'
import {
RepositoryAccessPanel,
RepositoryAccessSummary,
@@ -601,8 +603,10 @@ export default function AgentDetail() {
</Panel>
<AgentSkills agentId={agent.id} />
</div>
- {/* Right rail: deployment source, working-repo scope, and Slack. */}
+ {/* Right rail: invocation surfaces, deployment source, working-repo scope, and Slack. */}
<div className="space-y-4">
+ <AgentUrlPanel key={`url-${agent.id}`} agent={agent} />
+ <AgentHooksPanel key={`hooks-${agent.id}`} agentId={agent.id} />
<AgentDeploySource
agentId={agent.id}
profilePinned={agent.runtime === 'flue'}
diff --git a/web/src/pages/SessionDetail.tsx b/web/src/pages/SessionDetail.tsx
index d4a0b3ae..ab60e4b3 100644
--- a/web/src/pages/SessionDetail.tsx
+++ b/web/src/pages/SessionDetail.tsx
@@ -41,14 +41,21 @@ import { ApiHint } from '@/components/api-hint'
import { MessagesSquare } from 'lucide-react'
import { cn } from '@/lib/utils'
import { GithubMark } from '@/components/github-mark'
-import { formatSpend, usageTokens } from '@/lib/usage'
import {
+ formatUsageCost,
+ formatUsageDuration,
+ formatUsageTokens,
+ usageDisclosure,
+} from '@/lib/usage'
+import {
+ HttpRequestCard,
MessageBubble,
TurnConversation,
} from '@/components/session-conversation'
import {
bodyText,
groupIntoTurns,
+ httpRequestPayloadText,
isOutOfCredits,
isTurnInput,
} from '@/lib/session-turns'
@@ -397,9 +404,12 @@ for await (const event of session.events()) {
const m = new Map<string, TurnStartInfo>()
for (const g of grouped.groups) {
const firstInput = g.events.find(isTurnInput)
- const raw = firstInput ? bodyText(firstInput) : null
+ const raw = firstInput
+ ? (bodyText(firstInput) ?? httpRequestPayloadText(firstInput))
+ : null
+ const compact = raw?.replace(/\s+/g, ' ') ?? null
const preview =
- raw && raw.length > 40 ? `${raw.slice(0, 40)}…` : (raw ?? null)
+ compact && compact.length > 40 ? `${compact.slice(0, 40)}…` : compact
m.set(g.turnId, { from: g.fromSeq, to: g.toSeq, preview })
}
return m
@@ -530,14 +540,22 @@ for await (const event of session.events()) {
onRetry={() => void sourcesQuery.refetch()}
/>
- {/* Spend / usage — derived from the session's opaque usage object (no dedicated
- spend endpoint). Tokens shown only when the runtime reports them (flue meters
- at the gateway and reports none here). */}
- <div className="mb-4 grid grid-cols-2 gap-4 sm:grid-cols-3">
- <MetricCard label="Spend" value={formatSpend(session?.usage)} />
+ {/* Usage is the durable rollup of terminal turns. Missing turn observations stay
+ unknown, and incomplete totals are visibly lower bounds. */}
+ <div className="mb-4 grid grid-cols-2 gap-4 sm:grid-cols-4">
<MetricCard
label="Tokens"
- value={usageTokens(session?.usage)?.toLocaleString() ?? '—'}
+ value={formatUsageTokens(session?.usage)}
+ hint={usageDisclosure(session?.usage)}
+ />
+ <MetricCard
+ label="Active time"
+ value={formatUsageDuration(session?.usage)}
+ />
+ <MetricCard
+ label="Cost"
+ value={formatUsageCost(session?.usage)}
+ hint="Runtime-reported"
/>
<MetricCard
label="Events"
@@ -812,6 +830,24 @@ function EventRow({
)
}
+ if (ev.type === 'http.request') {
+ return (
+ <li className="px-4 py-3">
+ <HttpRequestCard
+ event={ev}
+ seq={ev.seq}
+ meta={
+ pending.has(ev.seq) ? (
+ <span className="text-muted-foreground text-[10px]">
+ · queued
+ </span>
+ ) : undefined
+ }
+ />
+ </li>
+ )
+ }
+
// Conversation messages — the signal.
if (ev.type === 'user.message' || ev.type === 'agent.message') {
const isUser = ev.type === 'user.message'
diff --git a/web/src/pages/Sessions.tsx b/web/src/pages/Sessions.tsx
index 43eda75d..0f40a206 100644
--- a/web/src/pages/Sessions.tsx
+++ b/web/src/pages/Sessions.tsx
@@ -28,7 +28,12 @@ import { StatusBadge } from '@/components/status-badge'
import { RuntimeBadge } from '@/components/runtime-badge'
import { EmptyState } from '@/components/empty-state'
import { ResourceTable, type Column } from '@/components/resource-table'
-import { formatSpend } from '@/lib/usage'
+import {
+ formatUsageCost,
+ formatUsageDuration,
+ formatUsageTokens,
+ usageDisclosure,
+} from '@/lib/usage'
export default function Sessions() {
const navigate = useNavigate()
@@ -139,12 +144,38 @@ export default function Sessions() {
),
},
{
- key: 'spend',
- header: 'Spend',
+ key: 'tokens',
+ header: 'Tokens',
+ align: 'right',
+ cell: (s) => (
+ <span
+ className="text-muted-foreground font-mono text-xs tabular-nums"
+ title={usageDisclosure(s.usage) ?? undefined}
+ >
+ {formatUsageTokens(s.usage)}
+ </span>
+ ),
+ },
+ {
+ key: 'active',
+ header: 'Active',
align: 'right',
cell: (s) => (
<span className="text-muted-foreground font-mono text-xs tabular-nums">
- {formatSpend(s.usage)}
+ {formatUsageDuration(s.usage)}
+ </span>
+ ),
+ },
+ {
+ key: 'cost',
+ header: 'Cost',
+ align: 'right',
+ cell: (s) => (
+ <span
+ className="text-muted-foreground font-mono text-xs tabular-nums"
+ title={usageDisclosure(s.usage) ?? 'Runtime-reported when available'}
+ >
+ {formatUsageCost(s.usage)}
</span>
),
},