feat(hub): persist agent turns and report them through hapi usage

Whether a session's agent is thinking lived only in the session cache,
so once a turn ended nothing could say how long the agent had worked,
and a hub restart forgot even the turn in progress. Tools that track
time (Weft, for one) had no way to see when agents on other machines
were busy.

Schema v28 adds session_turns: a row opens when a session starts
thinking (a prompt queued through the hub, the agent reporting it,
or a patch) and closes when it stops, the session ends, or its
keepalives expire, at the last keepalive. Rows are only written on
those transitions, never per keepalive. Turns move with a session
when it is merged away.

At startup the hub closes turns left open by the previous process at
the session's newest message. If the agent carries on thinking within
10 minutes of the restart, the same turn continues, so the work between
that message and the restart isn't lost. The deadline counts from the
restart, and a keepalive or patch reporting idle, the session ending,
or a new prompt ends the chance: those start a new turn.

GET /api/activity returns, for the caller's namespace, each session's
turns in a window (default 24 h, at most 31 days) with what identifies
it (flavor, agent session id, machine, path, title) and the permission
prompts and questions it waited on, taken from agent_state.

`hapi usage [--since] [--until] [--json]` prints a summary or a
hapi.activity.v1 report for other tools, with distinct exit codes for
bad arguments (2), missing or refused credentials (3) and a hub too
old to answer (4). The summary counts only the part of each turn
inside the window and subtracts overlapping waits once. It reuses the
peer commands' token exchange.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
weishu
2026-10-29 08:48:06 +08:00
co-authored by Claude Opus 5.5
parent b4be7c2d93
commit 23122ccbc0
33 changed files with 1465 additions and 23 deletions
+159
View File
@@ -0,0 +1,159 @@
import { describe, expect, it, vi } from 'vitest'
import type { AxiosInstance } from 'axios'
import type { AgentActivitySession } from '@hapi/protocol/apiTypes'
import {
ACTIVITY_REPORT_SCHEMA,
ActivityError,
exitCodeForActivityError,
fetchActivity,
formatActivityReport,
parseTimeArg,
workedMs
} from './activity'
vi.mock('@/persistence', () => ({
readSettings: vi.fn(async () => ({ machineId: 'local-machine' }))
}))
type MockResponse = { status: number; data: unknown }
function createHttp(activity: MockResponse, auth: MockResponse = { status: 200, data: { token: 'jwt' } }) {
return {
post: vi.fn(async () => auth),
get: vi.fn(async (_url: string, _config?: { params?: Record<string, unknown>; headers?: Record<string, string> }) => activity)
}
}
const session: AgentActivitySession = {
id: 'session-1',
flavor: 'codex',
agentSessionId: 'thread-1',
machineId: 'remote-machine',
host: 'build-box',
machineName: 'Build box',
path: '/srv/project',
title: 'Port the runner',
turns: [
{ start: 0, end: 600_000, endReason: 'idle', startedBy: 'hub_prompt' },
{ start: 900_000, end: null, endReason: null, startedBy: 'agent' }
],
waits: [{ start: 100_000, end: 160_000, kind: 'permission', tool: 'Bash' }]
}
describe('parseTimeArg', () => {
const now = Date.UTC(2026, 9, 29, 12)
it('reads relative times, ISO dates and epoch milliseconds', () => {
expect(parseTimeArg('30m', now)).toBe(now - 30 * 60_000)
expect(parseTimeArg('24h', now)).toBe(now - 24 * 3_600_000)
expect(parseTimeArg('7d', now)).toBe(now - 7 * 86_400_000)
expect(parseTimeArg('2026-10-01T00:00:00Z', now)).toBe(Date.UTC(2026, 9, 1))
expect(parseTimeArg('1793000000000', now)).toBe(1_793_000_000_000)
})
it('rejects anything else', () => {
expect(() => parseTimeArg('yesterday', now)).toThrow(ActivityError)
})
})
describe('fetchActivity', () => {
it('wraps the hub response in a versioned report', async () => {
const http = createHttp({ status: 200, data: { since: 1, until: 2, generatedAt: 3, sessions: [session] } })
const report = await fetchActivity({
since: 1, until: 2, apiUrl: 'https://hub.example', accessToken: 'token',
http: http as unknown as AxiosInstance, now: () => 42
})
expect(report).toEqual({
schema: ACTIVITY_REPORT_SCHEMA,
generatedAt: 42,
hubUrl: 'https://hub.example',
localMachineId: 'local-machine',
since: 1,
until: 2,
sessions: [session]
})
const [url, config] = http.get.mock.calls[0]!
expect(url).toBe('https://hub.example/api/activity')
expect(config?.params).toEqual({ since: 1, until: 2 })
expect(config?.headers?.Authorization).toBe('Bearer jwt')
})
it('says when the hub is too old, the token is refused, or the request fails', async () => {
const run = (activity: MockResponse, auth?: MockResponse) => fetchActivity({
since: 1, until: 2, apiUrl: 'https://hub.example', accessToken: 'token',
http: createHttp(activity, auth) as unknown as AxiosInstance
}).catch((error: ActivityError) => error.code)
expect(await run({ status: 404, data: 'Not Found' })).toBe('hub_too_old')
expect(await run({ status: 200, data: {} }, { status: 401, data: { error: 'Invalid token' } })).toBe('auth_failed')
expect(await run({ status: 400, data: { error: 'The window can be at most 31 days' } })).toBe('request_failed')
})
it('rejects an empty window before asking the hub', async () => {
const http = createHttp({ status: 200, data: { sessions: [] } })
await expect(fetchActivity({ since: 5, until: 5, http: http as unknown as AxiosInstance })).rejects.toThrow(ActivityError)
expect(http.post).not.toHaveBeenCalled()
})
it('maps errors to documented exit codes', () => {
expect(exitCodeForActivityError(new ActivityError('bad_args', ''))).toBe(2)
expect(exitCodeForActivityError(new ActivityError('auth_failed', ''))).toBe(3)
expect(exitCodeForActivityError(new ActivityError('hub_too_old', ''))).toBe(4)
expect(exitCodeForActivityError(new ActivityError('request_failed', ''))).toBe(1)
})
})
describe('reporting', () => {
it('counts turns minus waits, open turns up to the end of the window', () => {
// 600s turn minus a 60s wait, plus an open turn from 900s to 1000s.
expect(workedMs(session, { since: 0, until: 1_000_000 })).toBe(540_000 + 100_000)
})
it('only counts the part of a turn inside the window', () => {
const long: AgentActivitySession = {
...session,
turns: [{ start: 0, end: 3 * 3_600_000, endReason: 'idle', startedBy: 'agent' }],
waits: [{ start: 3_600_000 - 600_000, end: 3_600_000 + 600_000, kind: 'permission', tool: 'Bash' }]
}
// One hour out of a three-hour turn, minus the ten minutes of the wait inside it.
expect(workedMs(long, { since: 3_600_000, until: 2 * 3_600_000 })).toBe(3_600_000 - 600_000)
// An open turn in an earlier window stops at that window's end.
const open: AgentActivitySession = { ...session, turns: [{ start: 0, end: null, endReason: null, startedBy: 'agent' }], waits: [] }
expect(workedMs(open, { since: 0, until: 60_000 })).toBe(60_000)
})
it('subtracts overlapping waits once', () => {
const minute = 60_000
const parallel: AgentActivitySession = {
...session,
turns: [{ start: 0, end: 10 * minute, endReason: 'idle', startedBy: 'agent' }],
waits: [
{ start: 2 * minute, end: 6 * minute, kind: 'permission', tool: 'Bash' },
{ start: 4 * minute, end: 8 * minute, kind: 'input', tool: 'AskUserQuestion' }
]
}
expect(workedMs(parallel, { since: 0, until: 20 * minute })).toBe(4 * minute)
})
it('lists sessions busiest first, saying where they ran', () => {
const local: AgentActivitySession = {
...session, id: 'session-2', machineId: 'local-machine', title: 'Short one',
turns: [{ start: 0, end: 60_000, endReason: 'idle', startedBy: 'agent' }], waits: []
}
const text = formatActivityReport({
schema: ACTIVITY_REPORT_SCHEMA, generatedAt: 1_000_000, hubUrl: 'https://hub.example',
localMachineId: 'local-machine', since: 0, until: 1_000_000, sessions: [local, session]
})
const lines = text.split('\n')
expect(lines[0]).toBe('Agents worked 12m across 2 sessions:')
expect(lines[1]).toContain('Port the runner · codex · Build box · 2 turns (working now)')
expect(lines[2]).toContain('Short one · codex · this machine · 1 turn')
})
it('says so when nothing happened', () => {
expect(formatActivityReport({
schema: ACTIVITY_REPORT_SCHEMA, generatedAt: 0, hubUrl: '', localMachineId: null, since: 0, until: 1, sessions: []
})).toBe('No agent activity in this period.')
})
})
+199
View File
@@ -0,0 +1,199 @@
/**
* When agents were working, from the hub's GET /api/activity, for
* `hapi usage`. Other tools (e.g. time trackers) read the `--json` output, so
* its shape is versioned by `ACTIVITY_REPORT_SCHEMA`.
*/
import axios, { type AxiosInstance } from 'axios'
import type { AgentActivitySession } from '@hapi/protocol/apiTypes'
import { readSettings } from '@/persistence'
import {
PingPeerError,
authHeaders,
exchangeJwt,
resolveAccessToken,
resolveApiUrl
} from '@/modules/pingPeer/pingPeer'
/** Bump when the JSON output changes incompatibly. */
export const ACTIVITY_REPORT_SCHEMA = 'hapi.activity.v1'
export type ActivityReport = {
schema: typeof ACTIVITY_REPORT_SCHEMA
generatedAt: number
hubUrl: string
/** This machine's id, so a reader can tell local sessions from remote ones. */
localMachineId: string | null
since: number
until: number
sessions: AgentActivitySession[]
}
export type ActivityErrorCode = 'bad_args' | 'auth_failed' | 'hub_too_old' | 'request_failed'
export class ActivityError extends Error {
readonly code: ActivityErrorCode
constructor(code: ActivityErrorCode, message: string) {
super(message)
this.name = 'ActivityError'
this.code = code
}
}
export function exitCodeForActivityError(error: ActivityError): number {
switch (error.code) {
case 'bad_args': return 2
case 'auth_failed': return 3
case 'hub_too_old': return 4
default: return 1
}
}
const UNIT_MS: Record<string, number> = { m: 60_000, h: 3_600_000, d: 86_400_000 }
/** `30m`, `24h`, `7d` (before `now`), an ISO date, or epoch milliseconds. */
export function parseTimeArg(value: string, now: number): number {
const trimmed = value.trim()
const relative = /^(\d+)([mhd])$/.exec(trimmed)
if (relative) {
return now - Number(relative[1]) * UNIT_MS[relative[2]!]!
}
if (/^\d{10,15}$/.test(trimmed)) {
return Number(trimmed)
}
const parsed = Date.parse(trimmed)
if (Number.isNaN(parsed)) {
throw new ActivityError('bad_args', `can't read '${value}' as a time; use 24h, 7d, an ISO date or epoch milliseconds`)
}
return parsed
}
export type FetchActivityOptions = {
since: number
until: number
apiUrl?: string
accessToken?: string
http?: AxiosInstance
now?: () => number
}
export async function fetchActivity(options: FetchActivityOptions): Promise<ActivityReport> {
if (options.since >= options.until) {
throw new ActivityError('bad_args', '--since must be before --until')
}
const http = options.http ?? axios
let apiUrl: string
let jwt: string
try {
apiUrl = resolveApiUrl(options.apiUrl)
jwt = await exchangeJwt(apiUrl, resolveAccessToken(options.accessToken), http)
} catch (error) {
if (error instanceof PingPeerError) {
throw new ActivityError(error.code === 'auth_failed' ? 'auth_failed' : 'bad_args', error.message)
}
throw error
}
let response
try {
response = await http.get(`${apiUrl}/api/activity`, {
params: { since: options.since, until: options.until },
headers: authHeaders(jwt),
timeout: 30_000,
validateStatus: () => true
})
} catch (error) {
throw new ActivityError('request_failed', `could not reach ${apiUrl}: ${error instanceof Error ? error.message : String(error)}`)
}
if (response.status === 404) {
throw new ActivityError('hub_too_old', `the hub at ${apiUrl} doesn't report agent activity yet; update it`)
}
if (response.status === 401 || response.status === 403) {
throw new ActivityError('auth_failed', `the hub at ${apiUrl} refused the request (HTTP ${response.status})`)
}
const body = response.data as { error?: unknown; sessions?: unknown; since?: unknown; until?: unknown } | undefined
if (response.status < 200 || response.status >= 300 || !Array.isArray(body?.sessions)) {
const detail = typeof body?.error === 'string' ? body.error : `HTTP ${response.status}`
throw new ActivityError('request_failed', `the hub at ${apiUrl} could not report activity: ${detail}`)
}
const settings = await readSettings()
return {
schema: ACTIVITY_REPORT_SCHEMA,
generatedAt: (options.now ?? Date.now)(),
hubUrl: apiUrl,
localMachineId: settings.machineId ?? null,
since: typeof body.since === 'number' ? body.since : options.since,
until: typeof body.until === 'number' ? body.until : options.until,
sessions: body.sessions as AgentActivitySession[]
}
}
type Interval = { start: number; end: number }
/** Sorted, non-overlapping intervals covering the same time. */
function mergeIntervals(intervals: Interval[]): Interval[] {
const merged: Interval[] = []
for (const interval of [...intervals].sort((a, b) => a.start - b.start)) {
const last = merged[merged.length - 1]
if (last && interval.start <= last.end) {
last.end = Math.max(last.end, interval.end)
} else {
merged.push({ ...interval })
}
}
return merged
}
/**
* Time a session's agent spent working within `window`: its turns, minus
* the time it waited on the user. The hub returns whole turns that overlap
* the window, so turns and waits are cut to it first; a turn still open
* runs to the end of the window.
*/
export function workedMs(session: AgentActivitySession, window: { since: number; until: number }): number {
const clamp = (start: number, end: number | null): Interval | null => {
const clamped = { start: Math.max(start, window.since), end: Math.min(end ?? window.until, window.until) }
return clamped.end > clamped.start ? clamped : null
}
const turns = mergeIntervals(session.turns.flatMap((turn) => clamp(turn.start, turn.end) ?? []))
const waits = mergeIntervals(session.waits.flatMap((wait) => clamp(wait.start, wait.end) ?? []))
let total = 0
for (const turn of turns) {
let waited = 0
for (const wait of waits) {
const overlap = Math.min(turn.end, wait.end) - Math.max(turn.start, wait.start)
if (overlap > 0) waited += overlap
}
total += turn.end - turn.start - waited
}
return total
}
function formatDuration(ms: number): string {
const minutes = Math.round(ms / 60_000)
if (minutes < 60) return `${minutes}m`
return minutes % 60 === 0 ? `${minutes / 60}h` : `${Math.floor(minutes / 60)}h ${minutes % 60}m`
}
/** One line per session, busiest first. */
export function formatActivityReport(report: ActivityReport): string {
if (report.sessions.length === 0) {
return 'No agent activity in this period.'
}
const window = { since: report.since, until: Math.min(report.until, report.generatedAt) }
const rows = report.sessions
.map((session) => ({ session, worked: workedMs(session, window) }))
.sort((a, b) => b.worked - a.worked)
const total = rows.reduce((sum, row) => sum + row.worked, 0)
const lines = rows.map(({ session, worked }) => {
const title = session.title ?? session.path ?? session.id.slice(0, 8)
const where = session.machineId && session.machineId === report.localMachineId ? 'this machine' : (session.machineName ?? session.host ?? 'unknown machine')
const live = session.turns.some((turn) => turn.end === null) ? ' (working now)' : ''
const turns = `${session.turns.length} turn${session.turns.length === 1 ? '' : 's'}`
return ` ${formatDuration(worked).padStart(7)} ${title} · ${session.flavor ?? 'agent'} · ${where} · ${turns}${live}`
})
return [`Agents worked ${formatDuration(total)} across ${rows.length} session${rows.length === 1 ? '' : 's'}:`, ...lines].join('\n')
}
+4 -4
View File
@@ -125,7 +125,7 @@ const AUTH_RECOVERY_HINT =
'or run `hapi auth login` to save the token. Inside a HAPI session prefer MCP ' +
'`list_peers` / `ping_peer` / `inspect_peer`, which use the session CLI credentials.'
function resolveApiUrl(apiUrl?: string): string {
export function resolveApiUrl(apiUrl?: string): string {
const raw = (apiUrl ?? configuration.apiUrl).trim().replace(/\/+$/, '')
if (!raw) {
throw new PingPeerError(
@@ -138,7 +138,7 @@ function resolveApiUrl(apiUrl?: string): string {
return raw
}
function resolveAccessToken(accessToken?: string): string {
export function resolveAccessToken(accessToken?: string): string {
let token = ''
try {
token = (accessToken ?? getAuthToken()).trim()
@@ -158,7 +158,7 @@ function authFailedMessage(apiUrl: string, detail: string): string {
return `failed to exchange access token for JWT (${detail}). Hub URL: ${apiUrl}. ${AUTH_RECOVERY_HINT}`
}
async function exchangeJwt(
export async function exchangeJwt(
apiUrl: string,
accessToken: string,
http: AxiosInstance
@@ -192,7 +192,7 @@ async function exchangeJwt(
}
}
function authHeaders(jwt: string): Record<string, string> {
export function authHeaders(jwt: string): Record<string, string> {
return buildHubRequestHeaders({
Authorization: `Bearer ${jwt}`,
'Content-Type': 'application/json'