typeclaw 0.46.2 → 0.47.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -5,6 +5,7 @@ import {
5
5
  composeLogs,
6
6
  composeRestart,
7
7
  composeStart,
8
+ composeStats,
8
9
  composeStatus,
9
10
  composeStop,
10
11
  composeUsage,
@@ -15,6 +16,7 @@ import { config } from '@/config'
15
16
  import { parseTailValue } from '@/container'
16
17
  import { formatJson, formatReport } from '@/doctor'
17
18
 
19
+ import { formatComposeStats } from './compose-stats'
18
20
  import { formatComposeStatus } from './compose-status'
19
21
  import { formatComposeUsage, formatComposeUsageJson } from './compose-usage'
20
22
  import { preflightDocker, printDockerGuidance } from './docker-preflight'
@@ -154,6 +156,16 @@ const statusSub = defineCommand({
154
156
  },
155
157
  })
156
158
 
159
+ const statsSub = defineCommand({
160
+ meta: { name: 'stats', description: 'show cpu, memory, and pids for every agent in immediate subdirectories of cwd' },
161
+ async run() {
162
+ await requireDockerOrExit()
163
+ const result = await composeStats(process.cwd())
164
+ const useColor = Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined
165
+ process.stdout.write(`${formatComposeStats(result, { useColor })}\n`)
166
+ },
167
+ })
168
+
157
169
  const logsSub = defineCommand({
158
170
  meta: { name: 'logs', description: 'multiplex docker logs for every running agent in immediate subdirectories' },
159
171
  args: {
@@ -284,6 +296,7 @@ export const composeCommand = defineCommand({
284
296
  stop: stopSub,
285
297
  restart: restartSub,
286
298
  status: statusSub,
299
+ stats: statsSub,
287
300
  logs: logsSub,
288
301
  usage: usageSub,
289
302
  doctor: doctorSub,
package/src/cli/index.ts CHANGED
@@ -22,6 +22,7 @@ const main = defineCommand({
22
22
  stop: () => import('./stop').then((m) => m.stopCommand),
23
23
  restart: () => import('./restart').then((m) => m.restartCommand),
24
24
  status: () => import('./status').then((m) => m.statusCommand),
25
+ stats: () => import('./stats').then((m) => m.statsCommand),
25
26
  reload: () => import('./reload').then((m) => m.reload),
26
27
  logs: () => import('./logs').then((m) => m.logsCommand),
27
28
  inspect: () => import('./inspect').then((m) => m.inspectCommand),
@@ -0,0 +1,134 @@
1
+ import { styleText } from 'node:util'
2
+
3
+ import { defineCommand } from 'citty'
4
+
5
+ import { type ContainerStats, type DockerExec, resolveController } from '@/container'
6
+ import { findAgentDir } from '@/init'
7
+
8
+ import { type DockerPreflightResult, preflightDocker, printDockerGuidance } from './docker-preflight'
9
+
10
+ export const statsCommand = defineCommand({
11
+ meta: {
12
+ name: 'stats',
13
+ description: 'show the agent container resource usage: cpu, memory, pids (host stage)',
14
+ },
15
+ async run() {
16
+ await runStats()
17
+ },
18
+ })
19
+
20
+ export type RunStatsDeps = {
21
+ cwd?: string
22
+ preflight?: () => Promise<DockerPreflightResult>
23
+ exec?: DockerExec
24
+ write?: (text: string) => void
25
+ onDockerUnavailable?: (failure: Extract<DockerPreflightResult, { ok: false }>) => void
26
+ }
27
+
28
+ export async function runStats(deps: RunStatsDeps = {}): Promise<void> {
29
+ const cwd = deps.cwd ?? findAgentDir(process.cwd()) ?? process.cwd()
30
+
31
+ const preflight = await (deps.preflight ?? preflightDocker)()
32
+ if (!preflight.ok) {
33
+ ;(deps.onDockerUnavailable ?? defaultOnDockerUnavailable)(preflight)
34
+ return
35
+ }
36
+
37
+ const container = await resolveController().stats({ cwd, exec: deps.exec })
38
+
39
+ const useColor = Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined
40
+ const write = deps.write ?? ((text: string) => process.stdout.write(text))
41
+ write(`${formatStats({ cwd, container }, { useColor })}\n`)
42
+ }
43
+
44
+ function defaultOnDockerUnavailable(failure: Extract<DockerPreflightResult, { ok: false }>): never {
45
+ printDockerGuidance(failure)
46
+ process.exit(1)
47
+ }
48
+
49
+ export type StatsReport = {
50
+ cwd: string
51
+ container: ContainerStats
52
+ }
53
+
54
+ export type FormatOptions = { useColor?: boolean }
55
+
56
+ type ColorFn = (s: string) => string
57
+ type Palette = {
58
+ bold: ColorFn
59
+ dim: ColorFn
60
+ green: ColorFn
61
+ yellow: ColorFn
62
+ cyan: ColorFn
63
+ }
64
+
65
+ const identity: ColorFn = (s) => s
66
+ const NO_PALETTE: Palette = {
67
+ bold: identity,
68
+ dim: identity,
69
+ green: identity,
70
+ yellow: identity,
71
+ cyan: identity,
72
+ }
73
+
74
+ const COLOR_PALETTE: Palette = {
75
+ bold: (s) => styleText('bold', s),
76
+ dim: (s) => styleText('dim', s),
77
+ green: (s) => styleText('green', s),
78
+ yellow: (s) => styleText('yellow', s),
79
+ cyan: (s) => styleText('cyan', s),
80
+ }
81
+
82
+ export function formatStats(report: StatsReport, opts: FormatOptions = {}): string {
83
+ const useColor = opts.useColor ?? false
84
+ const p: Palette = useColor ? COLOR_PALETTE : NO_PALETTE
85
+
86
+ const container = report.container
87
+ const lines: string[] = []
88
+ lines.push(`${p.bold('Container')} ${container.containerName}`)
89
+ lines.push(row('cwd', report.cwd))
90
+ lines.push(row('image', container.imageTag))
91
+
92
+ if (container.kind === 'missing') {
93
+ lines.push(row('state', p.dim('missing')))
94
+ return lines.join('\n')
95
+ }
96
+
97
+ if (container.kind === 'stopped') {
98
+ lines.push(row('state', p.yellow('stopped')))
99
+ return lines.join('\n')
100
+ }
101
+
102
+ lines.push(row('state', `${p.green('running')}${formatUptime(container.startedAt, p)}`))
103
+ lines.push('')
104
+ lines.push(row('cpu', p.cyan(container.cpuPercent)))
105
+ lines.push(row('memory', `${p.cyan(container.memUsage)} ${p.dim(`(${container.memPercent})`)}`))
106
+ lines.push(row('pids', p.cyan(container.pids)))
107
+ return lines.join('\n')
108
+ }
109
+
110
+ function formatUptime(startedAt: string | null, p: Palette): string {
111
+ if (startedAt === null) return ''
112
+ const started = Date.parse(startedAt)
113
+ if (Number.isNaN(started)) return ''
114
+ const elapsedMs = Date.now() - started
115
+ if (elapsedMs < 0) return ''
116
+ return ` ${p.dim(`up ${formatDuration(elapsedMs)}`)}`
117
+ }
118
+
119
+ export function formatDuration(ms: number): string {
120
+ const totalSeconds = Math.floor(ms / 1000)
121
+ const days = Math.floor(totalSeconds / 86400)
122
+ const hours = Math.floor((totalSeconds % 86400) / 3600)
123
+ const minutes = Math.floor((totalSeconds % 3600) / 60)
124
+ const seconds = totalSeconds % 60
125
+
126
+ if (days > 0) return `${days}d ${hours}h`
127
+ if (hours > 0) return `${hours}h ${minutes}m`
128
+ if (minutes > 0) return `${minutes}m ${seconds}s`
129
+ return `${seconds}s`
130
+ }
131
+
132
+ function row(label: string, value: string): string {
133
+ return ` ${label.padEnd(8)}${value}`
134
+ }
@@ -8,6 +8,7 @@ export {
8
8
  type ComposeDoctorReport,
9
9
  } from './doctor'
10
10
  export { colorFor, composeLogs, makeLinePrefixer, type ComposeLogsOptions, type ComposeLogsResult } from './logs'
11
+ export { composeStats, type AgentStatsEntry, type AgentStatsState, type ComposeStatsResult } from './stats'
11
12
  export { composeStatus, type AgentRuntimeState, type AgentStatusEntry, type ComposeStatusResult } from './status'
12
13
  export {
13
14
  composeRestart,
@@ -0,0 +1,51 @@
1
+ import { type ContainerStats, resolveController } from '@/container'
2
+
3
+ import { discoverAgents, type AgentEntry } from './discover'
4
+
5
+ export type AgentStatsState = 'running' | 'stopped' | 'absent'
6
+
7
+ export type AgentStatsEntry = AgentEntry & {
8
+ state: AgentStatsState
9
+ cpuPercent: string | null
10
+ memUsage: string | null
11
+ memPercent: string | null
12
+ pids: string | null
13
+ }
14
+
15
+ export type ComposeStatsResult = {
16
+ rootCwd: string
17
+ entries: AgentStatsEntry[]
18
+ }
19
+
20
+ export type StatsProbe = (cwd: string) => Promise<ContainerStats>
21
+
22
+ export type ComposeStatsDeps = {
23
+ discover?: (rootCwd: string) => AgentEntry[]
24
+ probe?: StatsProbe
25
+ }
26
+
27
+ export async function composeStats(rootCwd: string, deps: ComposeStatsDeps = {}): Promise<ComposeStatsResult> {
28
+ const discover = deps.discover ?? discoverAgents
29
+ const probe = deps.probe ?? ((cwd) => resolveController().stats({ cwd }))
30
+
31
+ const agents = discover(rootCwd)
32
+ const entries = await Promise.all(agents.map(async (agent) => classify(agent, await probe(agent.cwd))))
33
+ return { rootCwd, entries }
34
+ }
35
+
36
+ function classify(agent: AgentEntry, container: ContainerStats): AgentStatsEntry {
37
+ if (container.kind === 'missing') {
38
+ return { ...agent, state: 'absent', cpuPercent: null, memUsage: null, memPercent: null, pids: null }
39
+ }
40
+ if (container.kind === 'stopped') {
41
+ return { ...agent, state: 'stopped', cpuPercent: null, memUsage: null, memPercent: null, pids: null }
42
+ }
43
+ return {
44
+ ...agent,
45
+ state: 'running',
46
+ cpuPercent: container.cpuPercent,
47
+ memUsage: container.memUsage,
48
+ memPercent: container.memPercent,
49
+ pids: container.pids,
50
+ }
51
+ }
@@ -287,6 +287,17 @@ export const gitSchema = z
287
287
 
288
288
  export type GitConfig = z.infer<typeof gitSchema>
289
289
 
290
+ export const DEFAULT_LOG_RETENTION_DAYS = 14
291
+ export const MAX_LOG_RETENTION_DAYS = 3650
292
+
293
+ const logsObjectSchema = z.object({
294
+ retentionDays: z.number().int().min(1).max(MAX_LOG_RETENTION_DAYS).default(DEFAULT_LOG_RETENTION_DAYS),
295
+ })
296
+
297
+ export const logsSchema = logsObjectSchema.default(() => logsObjectSchema.parse({}))
298
+
299
+ export type LogsConfig = z.infer<typeof logsSchema>
300
+
290
301
  const IPV4_CIDR_PATTERN = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})(?:\/(\d{1,2}))?$/
291
302
 
292
303
  const ipv4CidrSchema = z.string().refine(
@@ -784,6 +795,7 @@ export const configSchema = z
784
795
  sandbox: sandboxSchema,
785
796
  docker: dockerSchema,
786
797
  git: gitSchema,
798
+ logs: logsSchema,
787
799
  roles: rolesConfigSchema.optional(),
788
800
  tunnels: tunnelsArraySchema,
789
801
  // When `true` (default), the system prompt tells the agent it runs on
@@ -1010,6 +1022,7 @@ export const FIELD_EFFECTS: Record<string, FieldEffect> = {
1010
1022
  tunnels: 'restart-required',
1011
1023
  'docker.file': 'restart-required',
1012
1024
  'git.ignore': 'restart-required',
1025
+ logs: 'ignored',
1013
1026
  // Split: `match` lists are reload-safe (typeclaw role claim, hand-edits
1014
1027
  // adding/removing match rules apply without a container restart);
1015
1028
  // `permissions` lists are restart-required (changing what a role can DO
@@ -1104,6 +1117,7 @@ export function extractPluginConfigs(raw: unknown): Record<string, unknown> {
1104
1117
  'network',
1105
1118
  'docker',
1106
1119
  'git',
1120
+ 'logs',
1107
1121
  'roles',
1108
1122
  'permissions',
1109
1123
  'tunnels',
@@ -4,6 +4,7 @@ export {
4
4
  configSchema,
5
5
  customModelMetaSchema,
6
6
  customModelsSchema,
7
+ DEFAULT_LOG_RETENTION_DAYS,
7
8
  DEFAULT_PLUGINS,
8
9
  dockerSchema,
9
10
  dockerfileSchema,
@@ -19,6 +20,8 @@ export {
19
20
  loadConfigSync,
20
21
  loadConfigSyncOrDefaults,
21
22
  loadPluginConfigsSync,
23
+ logsSchema,
24
+ MAX_LOG_RETENTION_DAYS,
22
25
  migrateLegacyConfigShape,
23
26
  modelsSchema,
24
27
  mountSchema,
@@ -39,6 +42,7 @@ export {
39
42
  type DockerfileConfig,
40
43
  type GitConfig,
41
44
  type GitignoreConfig,
45
+ type LogsConfig,
42
46
  type MigrationResult,
43
47
  type MigrationStep,
44
48
  type Models,
@@ -2,6 +2,7 @@ import { logs, type LogsOptions, type LogsResult } from './logs'
2
2
  import { containerNameFromCwd, imageTagFromCwd } from './shared'
3
3
  import { shell, type ShellResult } from './shell'
4
4
  import { start, type StartOptions, type StartResult } from './start'
5
+ import { stats, type ContainerStats, type StatsOptions } from './stats'
5
6
  import { status, type ContainerStatus, type StatusOptions } from './status'
6
7
  import { stop, type StopOptions, type StopResult } from './stop'
7
8
 
@@ -17,6 +18,7 @@ export interface Controller {
17
18
  start(options: StartOptions): Promise<StartResult>
18
19
  stop(options: StopOptions): Promise<StopResult>
19
20
  status(options: StatusOptions): Promise<ContainerStatus>
21
+ stats(options: StatsOptions): Promise<ContainerStats>
20
22
  logs(options: LogsOptions): Promise<LogsResult>
21
23
  shell(options: { cwd: string; shell?: string }): Promise<ShellResult>
22
24
  }
@@ -30,6 +32,7 @@ export function createLocalDockerController(): Controller {
30
32
  start: (options) => start(options),
31
33
  stop: (options) => stop(options),
32
34
  status: (options) => status(options),
35
+ stats: (options) => stats(options),
33
36
  logs: (options) => logs(options),
34
37
  shell: (options) => shell(options),
35
38
  }
@@ -53,6 +56,9 @@ export function createNoopController(): Controller {
53
56
  async status({ cwd }) {
54
57
  return { kind: 'missing', containerName: containerNameFromCwd(cwd), imageTag: imageTagFromCwd(cwd) }
55
58
  },
59
+ async stats({ cwd }) {
60
+ return { kind: 'missing', containerName: containerNameFromCwd(cwd), imageTag: imageTagFromCwd(cwd) }
61
+ },
56
62
  async logs({ cwd }) {
57
63
  return { ok: false, reason: unsupported('logs', cwd) }
58
64
  },
@@ -24,6 +24,7 @@ export {
24
24
  type RequireContainerRunningResult,
25
25
  } from './require-running'
26
26
  export { planShell, shell, type ShellPlan, type ShellResult } from './shell'
27
+ export { parseStatsLine, stats, type ContainerStats, type StatsOptions, type StatsSnapshot } from './stats'
27
28
  export { status, type ContainerStatus, type StatusOptions } from './status'
28
29
  export {
29
30
  checkDockerAvailable,