typeclaw 0.46.1 → 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.
Files changed (57) hide show
  1. package/README.md +2 -1
  2. package/package.json +2 -2
  3. package/src/agent/tool-file-safety.ts +18 -9
  4. package/src/agent/tools/webfetch/strategies/jq.ts +1 -2
  5. package/src/agent/tools/webfetch/strategies/readability.ts +39 -16
  6. package/src/agent/tools/webfetch/strategies/selector.ts +4 -2
  7. package/src/agent/tools/webfetch/strategies/snapshot.ts +3 -2
  8. package/src/agent/tools/webfetch/tool.ts +3 -3
  9. package/src/bundled-plugins/backup/index.ts +21 -4
  10. package/src/bundled-plugins/backup/runner.ts +19 -5
  11. package/src/bundled-plugins/memory/dreaming.ts +2 -1
  12. package/src/bundled-plugins/memory/load-shards.ts +31 -3
  13. package/src/bundled-plugins/memory/memory-logger.ts +2 -1
  14. package/src/bundled-plugins/memory/memory-snapshot.ts +8 -0
  15. package/src/bundled-plugins/memory/vector/embedder.ts +28 -9
  16. package/src/bundled-plugins/memory/vector/hybrid.ts +10 -2
  17. package/src/bundled-plugins/memory/vector/store.ts +21 -9
  18. package/src/bundled-plugins/security/policies/git-exfil.ts +45 -27
  19. package/src/bundled-plugins/security/policies/outbound-secret-scan.ts +8 -3
  20. package/src/bundled-plugins/security/policies/private-surface-read.ts +6 -0
  21. package/src/channels/adapters/telegram-bot-classify.ts +29 -0
  22. package/src/channels/router.ts +98 -0
  23. package/src/channels/types.ts +7 -0
  24. package/src/cli/command-meta.ts +2 -0
  25. package/src/cli/compose-stats.ts +103 -0
  26. package/src/cli/compose.ts +13 -0
  27. package/src/cli/index.ts +1 -0
  28. package/src/cli/inspect.ts +16 -0
  29. package/src/cli/stats.ts +134 -0
  30. package/src/compose/index.ts +1 -0
  31. package/src/compose/stats.ts +51 -0
  32. package/src/config/config.ts +14 -0
  33. package/src/config/index.ts +4 -0
  34. package/src/container/controller.ts +6 -0
  35. package/src/container/index.ts +1 -0
  36. package/src/container/log-archive.ts +448 -0
  37. package/src/container/shared.ts +49 -19
  38. package/src/container/start.ts +78 -63
  39. package/src/container/stats.ts +86 -0
  40. package/src/container/stop.ts +63 -36
  41. package/src/init/checkpoint.ts +4 -4
  42. package/src/init/dockerfile.ts +87 -88
  43. package/src/init/gitignore.ts +5 -6
  44. package/src/init/restart-deps-preflight.ts +2 -2
  45. package/src/init/run-bun-install.ts +16 -2
  46. package/src/init/validate-api-key.ts +1 -0
  47. package/src/inspect/item-list.ts +12 -6
  48. package/src/permissions/permissions.ts +93 -2
  49. package/src/role-claim/code.ts +9 -5
  50. package/src/run/index.ts +50 -36
  51. package/src/run/resource-report.ts +226 -0
  52. package/src/sandbox/canonical-secrets.ts +7 -0
  53. package/src/sandbox/index.ts +1 -0
  54. package/src/sandbox/symlinks.ts +1 -1
  55. package/src/secrets/export-claude-credentials-file.ts +13 -22
  56. package/src/secrets/export-codex-auth-file.ts +12 -28
  57. package/typeclaw.schema.json +14 -0
@@ -88,6 +88,12 @@ const ENV_KEY_RECON_TARGETS: ReadonlyArray<string> = [
88
88
 
89
89
  const ENV_KEY_RECON_THRESHOLD = 3
90
90
 
91
+ // Names are fixed literals, so these boundary regexes are constant. Compile
92
+ // once at module load, not ~30 RegExps per outbound message (guard is per-send).
93
+ const ENV_KEY_RECON_MATCHERS: ReadonlyArray<readonly [name: string, pattern: RegExp]> = ENV_KEY_RECON_TARGETS.map(
94
+ (name) => [name, new RegExp(`\\b${name}\\b`)] as const,
95
+ )
96
+
91
97
  const TEXT_KEYS = ['text', 'message', 'content', 'body']
92
98
 
93
99
  export type OutboundSecretMatch = {
@@ -137,9 +143,8 @@ export function findOutboundSecrets(text: string, env: NodeJS.ProcessEnv = proce
137
143
 
138
144
  function findReconEnvKeys(text: string): string[] {
139
145
  const out: string[] = []
140
- for (const name of ENV_KEY_RECON_TARGETS) {
141
- const re = new RegExp(`\\b${name}\\b`)
142
- if (re.test(text)) out.push(name)
146
+ for (const [name, pattern] of ENV_KEY_RECON_MATCHERS) {
147
+ if (pattern.test(text)) out.push(name)
143
148
  }
144
149
  return out
145
150
  }
@@ -22,6 +22,7 @@ import {
22
22
  CANONICAL_AGENT_SECRET_FILES,
23
23
  CANONICAL_HOME_SECRET_DIRS,
24
24
  CANONICAL_HOME_SECRET_FILES,
25
+ CONTAINER_RUNTIME_HOME,
25
26
  type HiddenPaths,
26
27
  } from '@/sandbox'
27
28
 
@@ -166,7 +167,11 @@ function deniedSurface(agentDir: string, hidden: HiddenPaths): { deniedDirs: str
166
167
  ...new Set([
167
168
  ...hidden.dirs,
168
169
  ...CANONICAL_AGENT_SECRET_DIRS.map((dir) => path.join(agentDir, dir)),
170
+ // homedir() follows the live container HOME; the fixed runtime path
171
+ // keeps the same denial deterministic in host-stage tests and any
172
+ // partially-initialized caller whose environment has not switched yet.
169
173
  ...CANONICAL_HOME_SECRET_DIRS.map((dir) => path.join(homedir(), dir)),
174
+ ...CANONICAL_HOME_SECRET_DIRS.map((dir) => path.join(CONTAINER_RUNTIME_HOME, dir)),
170
175
  ]),
171
176
  ],
172
177
  // Keep runtime-owned credential stores independent of role-derived
@@ -176,6 +181,7 @@ function deniedSurface(agentDir: string, hidden: HiddenPaths): { deniedDirs: str
176
181
  ...hidden.files,
177
182
  ...CANONICAL_AGENT_SECRET_FILES.map((file) => path.join(agentDir, file)),
178
183
  ...CANONICAL_HOME_SECRET_FILES.map((file) => path.join(homedir(), file)),
184
+ ...CANONICAL_HOME_SECRET_FILES.map((file) => path.join(CONTAINER_RUNTIME_HOME, file)),
179
185
  ]),
180
186
  ],
181
187
  }
@@ -62,6 +62,8 @@ export function classifyInbound(
62
62
 
63
63
  const thread = event.message_thread_id !== undefined ? String(event.message_thread_id) : null
64
64
 
65
+ const isBotMentionOnly = attachments.length === 0 && isOnlyBotMention(entities, fullText, bot.id, botUsername)
66
+
65
67
  return {
66
68
  kind: 'route',
67
69
  payload: {
@@ -76,6 +78,7 @@ export function classifyInbound(
76
78
  authorName: formatAuthorName(author),
77
79
  authorIsBot: author.is_bot === true,
78
80
  isBotMention,
81
+ isBotMentionOnly,
79
82
  replyToBotMessageId,
80
83
  mentionsOthers,
81
84
  replyToOtherMessageId,
@@ -85,6 +88,32 @@ export function classifyInbound(
85
88
  }
86
89
  }
87
90
 
91
+ // A "bare ping" is a message whose entire body (ignoring surrounding
92
+ // whitespace) is a SINGLE mention of the bot. The router cannot detect this
93
+ // from `text` because a `text_mention` renders as the target's display name,
94
+ // not `<@id>` markup, so the adapter must decide it here where the structured
95
+ // entities are still available. Offsets are UTF-16 code units in both Telegram
96
+ // entities and JS strings, so slicing lines up. Multiple mentions, any extra
97
+ // words, or a mention that does not span the whole trimmed text are not bare.
98
+ function isOnlyBotMention(
99
+ entities: readonly TelegramMessageEntity[],
100
+ fullText: string,
101
+ botId: number,
102
+ botUsername: string | undefined,
103
+ ): boolean {
104
+ const userMentions = entities.filter(isUserMentionEntity)
105
+ if (userMentions.length !== 1) return false
106
+ const entity = userMentions[0]!
107
+ const start = fullText.length - fullText.trimStart().length
108
+ const end = fullText.trimEnd().length
109
+ return (
110
+ start < end &&
111
+ entity.offset === start &&
112
+ entity.offset + entity.length === end &&
113
+ isUserMentionForBot(entity, fullText, botId, botUsername)
114
+ )
115
+ }
116
+
88
117
  function formatAuthorName(user: TelegramBotUser): string {
89
118
  if (user.username !== undefined && user.username !== '') return user.username
90
119
  const last = user.last_name ?? ''
@@ -137,6 +137,13 @@ export const CONTEXT_BUFFER_SIZE = 20
137
137
  // subsequent turn until it ages out. Cap each observed message's text; the
138
138
  // addressed current message is never capped (it's the actual request).
139
139
  export const OBSERVED_MESSAGE_MAX_CHARS = 800
140
+ // A bare @mention (no text of its own) is a "wake up and look" ping, not a
141
+ // question — the user is signalling that a recent un-responded message is what
142
+ // they want a reply to. The wake-request nudge only fires when such a ping
143
+ // lands within this window of a recent observed message, so a mention that
144
+ // arrives long after the channel went quiet does not misread stale scrollback
145
+ // as the thing to answer.
146
+ export const WAKE_REQUEST_LOOKBACK_MS = 60_000
140
147
  // Discord's typing indicator expires after ~10s; an 8s heartbeat keeps it
141
148
  // continuously visible while we debounce + generate without spamming the API.
142
149
  // This is the default; an adapter whose platform expires the indicator sooner
@@ -705,6 +712,7 @@ type QueuedInbound = {
705
712
  reactionRef?: ReactionRef
706
713
  engageReaction?: Promise<ReactionRef | null>
707
714
  isBotMention: boolean
715
+ isBotMentionOnly?: boolean
708
716
  replyToBotMessageId: string | null
709
717
  isDm: boolean
710
718
  typingThread?: string
@@ -3637,6 +3645,7 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
3637
3645
  ...(event.reactionRef !== undefined ? { reactionRef: event.reactionRef } : {}),
3638
3646
  ...(engageReaction !== null ? { engageReaction } : {}),
3639
3647
  isBotMention: event.isBotMention,
3648
+ ...(event.isBotMentionOnly !== undefined ? { isBotMentionOnly: event.isBotMentionOnly } : {}),
3640
3649
  replyToBotMessageId: event.replyToBotMessageId,
3641
3650
  isDm: event.isDm,
3642
3651
  ...(event.typingThread !== undefined ? { typingThread: event.typingThread } : {}),
@@ -5967,6 +5976,56 @@ function findAttachmentById(attachments: readonly InboundAttachment[], id: numbe
5967
5976
  return null
5968
5977
  }
5969
5978
 
5979
+ // Strips the platform's user/group-mention markup so a bare ping can be told
5980
+ // from a mention that also carries real text. Slack and Discord both encode
5981
+ // mentions as `<@id>` / `<@id|name>` (users) and `<!subteam^ID>` / `<!channel>`
5982
+ // (groups); GitHub and the plain-name adapters have no wrapping syntax to strip,
5983
+ // so their text is returned as-is and a mention there is never classified thin.
5984
+ // Content-blind and script-agnostic: it removes only fixed markup, never words,
5985
+ // so it works identically for Korean, CJK, Arabic, or any other input.
5986
+ function stripMentionMarkup(text: string, adapter: AdapterId): string {
5987
+ switch (adapter) {
5988
+ case 'slack':
5989
+ case 'slack-bot':
5990
+ case 'discord':
5991
+ case 'discord-bot':
5992
+ return text.replace(/<[@!][^>]*>/g, ' ')
5993
+ default:
5994
+ return text
5995
+ }
5996
+ }
5997
+
5998
+ // A "wake request" is a mention whose only payload IS the mention: once the
5999
+ // markup is stripped the remainder is empty. That shape means "wake up and look
6000
+ // at what was just said", not a self-contained question, so the caller nudges
6001
+ // the model toward the recent conversation instead of asking "what do you need?".
6002
+ function isThinMention(trigger: QueuedInbound, adapter: AdapterId): boolean {
6003
+ if (!trigger.isBotMention) return false
6004
+ if (trigger.attachments !== undefined && trigger.attachments.length > 0) return false
6005
+ // Adapters whose visible text cannot reveal a bare ping (Telegram text_mention
6006
+ // renders as a display name) carry the authoritative signal; trust it. Others
6007
+ // fall back to stripping the platform's mention markup from the text.
6008
+ if (trigger.isBotMentionOnly !== undefined) return trigger.isBotMentionOnly
6009
+ return stripMentionMarkup(trigger.text, adapter).trim() === ''
6010
+ }
6011
+
6012
+ // True when the engaged trigger is a bare ping AND a real (non-prefetch) message
6013
+ // was observed within the lookback window. Author-agnostic on purpose: in a group
6014
+ // one person can drop a message and a DIFFERENT teammate can ping the bot to loop
6015
+ // it in, so the recent message need not come from the pinger. The age must be
6016
+ // non-negative: a message that arrives DURING the mention's debounce window is
6017
+ // appended to contextBuffer after the ping, so `receivedAt - o.receivedAt` goes
6018
+ // negative — that message came AFTER the ping and is not what the user was
6019
+ // pointing back at, so it must not satisfy the "recent PRECEDING message" test.
6020
+ function isWakeRequest(observed: readonly ObservedInbound[], trigger: QueuedInbound, adapter: AdapterId): boolean {
6021
+ if (!isThinMention(trigger, adapter)) return false
6022
+ return observed.some((o) => {
6023
+ if (o.source !== 'observed') return false
6024
+ const age = trigger.receivedAt - o.receivedAt
6025
+ return age >= 0 && age <= WAKE_REQUEST_LOOKBACK_MS
6026
+ })
6027
+ }
6028
+
5970
6029
  function composeTurnPrompt(
5971
6030
  observed: readonly ObservedInbound[],
5972
6031
  batch: readonly QueuedInbound[],
@@ -6084,6 +6143,45 @@ function composeTurnPrompt(
6084
6143
  '',
6085
6144
  )
6086
6145
  }
6146
+ // Wake-request nudge: same SYSTEM MESSAGE convention as the loop guard and
6147
+ // group nudge. The trigger is a bare ping (mention with no text of its own),
6148
+ // which the model would otherwise answer with "what do you need?" while the
6149
+ // real request sits under "Recent context (not addressed to you)". This
6150
+ // re-licenses the model to act on that recent conversation. Placed
6151
+ // immediately BEFORE the Recent context block, and the nudge text points at
6152
+ // that section BY NAME ("the Recent context section below") rather than by
6153
+ // position, so the reference is unambiguous regardless of render order.
6154
+ // Cache-neutral (user-turn suffix), and skipped when the loop guard already
6155
+ // fired to avoid stacking two notices in one turn.
6156
+ if (batch.length === 1 && !state.loopGuardActive && isWakeRequest(observed, batch[0]!, adapter)) {
6157
+ parts.push(
6158
+ '---',
6159
+ '**[SYSTEM MESSAGE — not from a human]**',
6160
+ '',
6161
+ 'You were just @-mentioned with little or no text — effectively a "wake up',
6162
+ 'and look" ping, not a question in itself. This is an automated signal from',
6163
+ 'the channel router, not a message from anyone in the chat. **Do not',
6164
+ 'acknowledge or reply to this notice.**',
6165
+ '',
6166
+ 'A bare ping like this almost always means: "respond to what was just',
6167
+ 'said." Look at the "Recent context" section below (it shows who sent each',
6168
+ 'message):',
6169
+ '- If a recent message clearly wants a response and is relevant to you —',
6170
+ ' whether the person who pinged you sent it, or someone else did and the',
6171
+ ' pinger is looping you in — treat THAT message as the real request and',
6172
+ ' answer it directly. Do not ask "what do you need?" when the answer is',
6173
+ ' already in that recent context.',
6174
+ '- If several recent messages are relevant, address the substantive one(s).',
6175
+ '- If nothing in that recent context actually needs you (the ping was a',
6176
+ ' mistake, or the conversation moved on), a brief "what\'s up?" is fine.',
6177
+ '',
6178
+ 'When in doubt, prefer answering the most recent substantive message over',
6179
+ 'asking what they meant.',
6180
+ '',
6181
+ '---',
6182
+ '',
6183
+ )
6184
+ }
6087
6185
  if (observed.length > 0) {
6088
6186
  parts.push('## Recent context (not addressed to you, for awareness only)')
6089
6187
  for (const o of observed) {
@@ -80,6 +80,13 @@ export type InboundMessage = {
80
80
  // bounded loop guard so two or more bots cannot ping-pong forever.
81
81
  authorIsBot: boolean
82
82
  isBotMention: boolean
83
+ // Adapter-authoritative "this inbound is a bare ping — the mention IS the whole
84
+ // message" signal. Set only by adapters whose visible `text` cannot reveal it:
85
+ // Telegram renders a `text_mention` as the target's display NAME (not `<@id>`),
86
+ // so the router's markup-stripping cannot tell a bare ping from real text. When
87
+ // present the wake-request detector trusts it; when absent (Slack/Discord) the
88
+ // router falls back to stripping the platform's mention markup from `text`.
89
+ isBotMentionOnly?: boolean
83
90
  // When true, engagement treats this inbound as explicit-only: it skips
84
91
  // content-blind sticky credit AND plain-text alias matching, leaving only
85
92
  // structural DM / @mention / reply triggers. Used for GitHub PR review-thread
@@ -16,6 +16,7 @@ export type BuiltinCommandName =
16
16
  | 'stop'
17
17
  | 'restart'
18
18
  | 'status'
19
+ | 'stats'
19
20
  | 'reload'
20
21
  | 'logs'
21
22
  | 'inspect'
@@ -50,6 +51,7 @@ export const BUILTIN_COMMANDS: readonly BuiltinCommandMeta[] = [
50
51
  { name: 'stop', description: 'stop the agent container (host stage)' },
51
52
  { name: 'restart', description: 'stop and relaunch the agent container (host stage)' },
52
53
  { name: 'status', description: 'show the agent container and host daemon status (host stage)' },
54
+ { name: 'stats', description: 'show the agent container resource usage: cpu, memory, pids (host stage)' },
53
55
  { name: 'reload', description: "reload the running agent's reloadable subsystems (cron, ...)" },
54
56
  { name: 'logs', description: 'show the agent container logs (host stage)' },
55
57
  { name: 'inspect', description: 'session viewer: a session, the live TUI, or container logs' },
@@ -0,0 +1,103 @@
1
+ import { styleText } from 'node:util'
2
+
3
+ import type { AgentStatsState, ComposeStatsResult } from '@/compose'
4
+
5
+ export type FormatComposeStatsOptions = { useColor?: boolean }
6
+
7
+ type ColorFn = (s: string) => string
8
+ type Palette = {
9
+ bold: ColorFn
10
+ dim: ColorFn
11
+ green: ColorFn
12
+ yellow: ColorFn
13
+ cyan: ColorFn
14
+ }
15
+
16
+ const identity: ColorFn = (s) => s
17
+ const NO_PALETTE: Palette = {
18
+ bold: identity,
19
+ dim: identity,
20
+ green: identity,
21
+ yellow: identity,
22
+ cyan: identity,
23
+ }
24
+
25
+ const COLOR_PALETTE: Palette = {
26
+ bold: (s) => styleText('bold', s),
27
+ dim: (s) => styleText('dim', s),
28
+ green: (s) => styleText('green', s),
29
+ yellow: (s) => styleText('yellow', s),
30
+ cyan: (s) => styleText('cyan', s),
31
+ }
32
+
33
+ const STATE_LABELS: Record<AgentStatsState, string> = {
34
+ running: 'running',
35
+ stopped: 'stopped',
36
+ absent: 'not started',
37
+ }
38
+
39
+ const STATE_LABEL_WIDTH = Math.max(...Object.values(STATE_LABELS).map((l) => l.length))
40
+
41
+ export function formatComposeStats(result: ComposeStatsResult, opts: FormatComposeStatsOptions = {}): string {
42
+ const useColor = opts.useColor ?? false
43
+ const p: Palette = useColor ? COLOR_PALETTE : NO_PALETTE
44
+
45
+ if (result.entries.length === 0) {
46
+ return p.dim(`No typeclaw agents in ${result.rootCwd}.`)
47
+ }
48
+
49
+ const nameWidth = result.entries.reduce((w, e) => Math.max(w, e.name.length), 0)
50
+ const cpuWidth = result.entries.reduce((w, e) => Math.max(w, (e.cpuPercent ?? '').length), 'cpu'.length)
51
+ const memWidth = result.entries.reduce((w, e) => Math.max(w, (e.memUsage ?? '').length), 'memory'.length)
52
+
53
+ const header = p.dim(
54
+ `${result.entries.length} ${result.entries.length === 1 ? 'agent' : 'agents'} in ${result.rootCwd}`,
55
+ )
56
+
57
+ const lines = [header, '']
58
+ for (const entry of result.entries) {
59
+ lines.push(renderRow(entry, { nameWidth, cpuWidth, memWidth }, p))
60
+ }
61
+ return lines.join('\n')
62
+ }
63
+
64
+ type Widths = { nameWidth: number; cpuWidth: number; memWidth: number }
65
+
66
+ function renderRow(entry: ComposeStatsResult['entries'][number], w: Widths, p: Palette): string {
67
+ const glyph = renderGlyph(entry.state, p)
68
+ const name = p.bold(entry.name.padEnd(w.nameWidth))
69
+ const state = renderState(entry.state, p)
70
+
71
+ if (entry.state !== 'running') {
72
+ return ` ${glyph} ${name} ${state}`
73
+ }
74
+
75
+ const cpu = p.cyan((entry.cpuPercent ?? '-').padStart(w.cpuWidth))
76
+ const mem = p.cyan((entry.memUsage ?? '-').padEnd(w.memWidth))
77
+ const memPct = p.dim(`(${entry.memPercent ?? '-'})`)
78
+ const pids = p.dim(`${entry.pids ?? '-'} pids`)
79
+ return ` ${glyph} ${name} ${state} ${cpu} ${mem} ${memPct} ${pids}`
80
+ }
81
+
82
+ function renderGlyph(state: AgentStatsState, p: Palette): string {
83
+ switch (state) {
84
+ case 'running':
85
+ return p.green('●')
86
+ case 'stopped':
87
+ return p.yellow('○')
88
+ case 'absent':
89
+ return p.dim('·')
90
+ }
91
+ }
92
+
93
+ function renderState(state: AgentStatsState, p: Palette): string {
94
+ const label = STATE_LABELS[state].padEnd(STATE_LABEL_WIDTH)
95
+ switch (state) {
96
+ case 'running':
97
+ return p.green(label)
98
+ case 'stopped':
99
+ return p.yellow(label)
100
+ case 'absent':
101
+ return p.dim(label)
102
+ }
103
+ }
@@ -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),
@@ -150,6 +150,19 @@ export async function runInspectViewer(opts: RunInspectViewerOptions): Promise<n
150
150
  }
151
151
 
152
152
  const interactive = Boolean(process.stdin.isTTY)
153
+
154
+ // Without a TTY, clack's picker keypress loop busy-spins kevent64 at 100% CPU
155
+ // forever instead of resolving (e.g. `typeclaw inspect | head`, a daemon
156
+ // spawn). A resolved session arg auto-opens without the picker, so only the
157
+ // picker-mandatory case is refused — mirroring --json's explicit-id rule.
158
+ if (!interactive && preselectKey === undefined) {
159
+ process.stderr.write(`${errorLine('typeclaw inspect needs an interactive terminal to pick a session.')}\n`)
160
+ process.stderr.write(
161
+ 'Pass an explicit session id (`typeclaw inspect <id>`) or use `--json <id>` for a scriptable stream.\n',
162
+ )
163
+ return 2
164
+ }
165
+
153
166
  const liveHint = interactive ? escHintLine(color) : undefined
154
167
  const inspectUrl = containerRunning ? await resolveInspectUrl(cwd) : undefined
155
168
  const liveSource = inspectUrl !== undefined ? buildLiveSource(inspectUrl) : undefined
@@ -181,6 +194,9 @@ export async function runInspectViewer(opts: RunInspectViewerOptions): Promise<n
181
194
  const listOpts: Parameters<typeof listViewerItems>[0] = {
182
195
  sessionsDir,
183
196
  containerRunning,
197
+ // listViewerItems also gates writable promotion on `interactive`, so a
198
+ // non-TTY explicit id can't auto-open a TUI it cannot drive.
199
+ interactive,
184
200
  // Compose the CLI-level permission (false on tui detach handoff) with
185
201
  // the loop-level one (false after returning to the picker from a viewer).
186
202
  allowWritable: cliAllowWritable && loopAllowWritable,
@@ -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
+ }