Files
hapi/cli/src/commands/usage.ts
T
weishuandClaude Opus 5.5 23122ccbc0 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>
2026-10-29 08:48:06 +08:00

104 lines
3.5 KiB
TypeScript

import chalk from 'chalk'
import { initializeToken } from '@/ui/tokenInit'
import {
ActivityError,
exitCodeForActivityError,
fetchActivity,
formatActivityReport,
parseTimeArg
} from '@/modules/activity/activity'
import type { CommandDefinition } from './types'
type ParsedUsageArgs = {
help: boolean
json: boolean
since?: string
until?: string
}
function showHelp(): void {
console.log(`
${chalk.bold('hapi usage')} - When agents were working, across every machine on this hub
${chalk.bold('Usage:')}
hapi usage Last 24 hours
hapi usage --since 7d
hapi usage --since 2026-10-01 --until 2026-10-08
hapi usage --json Machine-readable (schema hapi.activity.v1)
${chalk.bold('Notes:')}
A turn runs from the agent starting to think until it stops; waits for
permission or answers are listed separately. Windows are at most 31 days.
--since/--until take 30m, 24h, 7d, an ISO date or epoch milliseconds.
${chalk.bold('Exit codes:')}
2 bad arguments · 3 not signed in or refused · 4 hub too old · 1 other
${chalk.bold('Env:')}
HAPI_API_URL / CLI_API_TOKEN (or ~/.hapi/settings.json via \`hapi auth login\`)
`)
}
export function parseUsageArgs(args: string[]): ParsedUsageArgs {
const result: ParsedUsageArgs = { help: false, json: false }
for (let i = 0; i < args.length; i++) {
const arg = args[i]!
if (arg === '--help' || arg === '-h') {
result.help = true
} else if (arg === '--json') {
result.json = true
} else if (arg === '--since' || arg === '--until') {
const value = args[++i]
if (!value) throw new ActivityError('bad_args', `${arg} requires a value`)
result[arg === '--since' ? 'since' : 'until'] = value
} else if (arg.startsWith('--since=')) {
result.since = arg.slice('--since='.length)
} else if (arg.startsWith('--until=')) {
result.until = arg.slice('--until='.length)
} else {
throw new ActivityError('bad_args', `unexpected argument: ${arg}`)
}
}
return result
}
export async function handleUsageCommand(args: string[]): Promise<void> {
const parsed = parseUsageArgs(args)
if (parsed.help) {
showHelp()
return
}
const now = Date.now()
const until = parsed.until ? parseTimeArg(parsed.until, now) : now
const since = parsed.since ? parseTimeArg(parsed.since, now) : until - 24 * 60 * 60 * 1000
try {
await initializeToken()
} catch (error) {
throw new ActivityError('auth_failed', error instanceof Error ? error.message : String(error))
}
const report = await fetchActivity({ since, until })
console.log(parsed.json ? JSON.stringify(report) : formatActivityReport(report))
}
export const usageCommand: CommandDefinition = {
name: 'usage',
requiresRuntimeAssets: false,
run: async ({ commandArgs }) => {
try {
await handleUsageCommand(commandArgs)
} catch (error) {
// Errors go to stderr so --json output on stdout stays parseable.
if (error instanceof ActivityError) {
console.error(chalk.red('hapi usage:'), error.message)
process.exit(exitCodeForActivityError(error))
}
console.error(chalk.red('hapi usage:'), error instanceof Error ? error.message : 'Unknown error')
if (process.env.DEBUG) {
console.error(error)
}
process.exit(1)
}
}
}