typeclaw 0.39.7 → 0.40.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 (58) hide show
  1. package/package.json +1 -1
  2. package/scripts/dump-system-prompt.ts +4 -50
  3. package/src/agent/auth-reloadable.ts +24 -0
  4. package/src/agent/auth.ts +12 -0
  5. package/src/agent/index.ts +18 -58
  6. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +0 -2
  7. package/src/bundled-plugins/guard/policy.ts +0 -5
  8. package/src/bundled-plugins/memory/README.md +26 -37
  9. package/src/bundled-plugins/memory/index.ts +30 -144
  10. package/src/bundled-plugins/memory/load-memory.ts +7 -121
  11. package/src/bundled-plugins/memory/memory-logger.ts +8 -2
  12. package/src/bundled-plugins/memory/search-command.ts +2 -11
  13. package/src/bundled-plugins/memory/vector/doctor.ts +1 -1
  14. package/src/bundled-plugins/memory/vector/embedder.ts +4 -5
  15. package/src/bundled-plugins/memory/vector/hybrid.ts +47 -5
  16. package/src/bundled-plugins/memory/vector/relevance-gate.ts +11 -7
  17. package/src/bundled-plugins/memory/vector/script.ts +87 -0
  18. package/src/channels/adapters/describe-error.ts +40 -0
  19. package/src/channels/adapters/discord.ts +9 -12
  20. package/src/channels/adapters/kakaotalk.ts +14 -17
  21. package/src/channels/adapters/line.ts +11 -14
  22. package/src/channels/adapters/slack-bot.ts +15 -18
  23. package/src/channels/adapters/slack.ts +45 -21
  24. package/src/channels/adapters/telegram-bot.ts +15 -18
  25. package/src/channels/adapters/webex-bot.ts +13 -14
  26. package/src/channels/adapters/webex.ts +14 -15
  27. package/src/cli/compose.ts +20 -0
  28. package/src/cli/docker-preflight.ts +42 -0
  29. package/src/cli/hostd.ts +12 -3
  30. package/src/cli/init.ts +24 -22
  31. package/src/cli/logs.ts +7 -0
  32. package/src/cli/provider.ts +8 -1
  33. package/src/cli/reload.ts +6 -0
  34. package/src/cli/restart.ts +7 -0
  35. package/src/cli/shell.ts +7 -0
  36. package/src/cli/start.ts +7 -0
  37. package/src/cli/status.ts +9 -0
  38. package/src/cli/stop.ts +7 -0
  39. package/src/cli/tui.ts +6 -0
  40. package/src/config/config.ts +31 -8
  41. package/src/container/docker-app.ts +253 -0
  42. package/src/container/index.ts +11 -0
  43. package/src/container/start.ts +85 -41
  44. package/src/hostd/current-host-daemon.ts +21 -0
  45. package/src/hostd/daemon.ts +27 -3
  46. package/src/hostd/supervisor.ts +18 -3
  47. package/src/plugin/hooks.ts +3 -4
  48. package/src/plugin/types.ts +1 -1
  49. package/src/run/channel-session-factory.ts +3 -5
  50. package/src/run/index.ts +17 -16
  51. package/src/server/command-runner.ts +2 -11
  52. package/src/skills/typeclaw-memory/SKILL.md +2 -2
  53. package/src/skills/typeclaw-plugins/SKILL.md +1 -1
  54. package/typeclaw.schema.json +1 -23
  55. package/src/bundled-plugins/guard/policies/memory-retrieval-cache-write.ts +0 -43
  56. package/src/bundled-plugins/memory/memory-retrieval.ts +0 -111
  57. package/src/bundled-plugins/memory/vector/cache-write.ts +0 -19
  58. package/src/bundled-plugins/memory/vector/config.ts +0 -28
@@ -29,6 +29,7 @@ import type {
29
29
  SendResult,
30
30
  } from '@/channels/types'
31
31
 
32
+ import { describeError } from './describe-error'
32
33
  import { createWebexChannelNameResolver } from './webex-bot-channel-resolver'
33
34
  import { classifyInbound, type InboundDropReason, type WebexInboundMessage } from './webex-bot-classify'
34
35
  import { enrichWebexMessageReference } from './webex-bot-reference'
@@ -129,7 +130,7 @@ export function createOutboundCallback(deps: {
129
130
  logger.info(`[webex-bot] sent id=${sent.ref} ${tag}`)
130
131
  return { ok: true, messageId: sent.ref, messageIds: [sent.ref] }
131
132
  } catch (err) {
132
- const message = describe(err)
133
+ const message = describeError(err)
133
134
  logger.error(`[webex-bot] outbound failed: ${message}`)
134
135
  return { ok: false, error: message }
135
136
  }
@@ -168,7 +169,7 @@ export function createWebexHistoryCallback(deps: {
168
169
  }
169
170
  return toHistory(outcome.value)
170
171
  } catch (err) {
171
- const message = describe(err)
172
+ const message = describeError(err)
172
173
  if (args.prefetch === true && isWebexRateLimitError(err)) {
173
174
  deps.logger.info(`[webex-bot] history prefetch skipped: rate limited (${message})`)
174
175
  return { ok: false, error: message, skipReason: 'rate-limited' }
@@ -215,7 +216,9 @@ export function createWebexMembershipResolver(deps: {
215
216
  }
216
217
  return { humans: humanMemberIds.length, bots, fetchedAt: now(), truncated, humanMemberIds }
217
218
  } catch (err) {
218
- deps.logger.warn(`[webex-bot] membership room=${key.chat} failed: ${describe(err)}; deriving from recent history`)
219
+ deps.logger.warn(
220
+ `[webex-bot] membership room=${key.chat} failed: ${describeError(err)}; deriving from recent history`,
221
+ )
219
222
  return await deriveMembershipFromHistory({
220
223
  fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit, prefetch: true }),
221
224
  now,
@@ -267,7 +270,7 @@ export function createFetchAttachmentCallback(deps: {
267
270
  size: buffer.length,
268
271
  }
269
272
  } catch (err) {
270
- const message = describe(err)
273
+ const message = describeError(err)
271
274
  deps.logger.error(`[webex-bot] fetchAttachment failed for ${url.toString()}: ${message}`)
272
275
  return { ok: false, error: message }
273
276
  }
@@ -340,7 +343,7 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
340
343
  )
341
344
  await options.router.route(payload)
342
345
  } catch (err) {
343
- logger.error(`[webex-bot] handleInbound failed: ${describe(err)}`)
346
+ logger.error(`[webex-bot] handleInbound failed: ${describeError(err)}`)
344
347
  } finally {
345
348
  inflightInbounds--
346
349
  if (inflightInbounds === 0 && stopWaiters.length > 0) {
@@ -362,7 +365,7 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
362
365
  } catch (err) {
363
366
  started = false
364
367
  botPerson = null
365
- logger.error(`[webex-bot] login failed: ${describe(err)}`)
368
+ logger.error(`[webex-bot] login failed: ${describeError(err)}`)
366
369
  throw err
367
370
  }
368
371
 
@@ -378,9 +381,9 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
378
381
  logger.warn(`[webex-bot] disconnected: ${reason}`)
379
382
  })
380
383
  listener.on('error', (err) => {
381
- const error = err instanceof Error ? err : new Error(String(err))
384
+ const error = err instanceof Error ? err : new Error(describeError(err))
382
385
  if (!listenerConnected && listenerStartupError === null) listenerStartupError = error
383
- logger.error(`[webex-bot] listener error: ${describe(error)}`)
386
+ logger.error(`[webex-bot] listener error: ${describeError(err)}`)
384
387
  })
385
388
  listener.on('message_created', (event: WebexBotListenerEventMap['message_created'][0]) => {
386
389
  void handleMessage(event)
@@ -405,14 +408,14 @@ export function createWebexBotAdapter(options: WebexBotAdapterOptions): WebexBot
405
408
  botPerson = null
406
409
  connected = false
407
410
  started = false
408
- logger.error(`[webex-bot] ${reason}: ${describe(cause)}`)
411
+ logger.error(`[webex-bot] ${reason}: ${describeError(cause)}`)
409
412
  throw cause
410
413
  }
411
414
 
412
415
  try {
413
416
  await listener.start()
414
417
  } catch (err) {
415
- rollbackStart('listener start threw', err instanceof Error ? err : new Error(String(err)))
418
+ rollbackStart('listener start threw', err instanceof Error ? err : new Error(describeError(err)))
416
419
  }
417
420
  if (!listenerConnected) {
418
421
  rollbackStart(
@@ -474,10 +477,6 @@ function clampLimit(requested: number, max: number): number {
474
477
  return Math.min(Math.floor(requested), max)
475
478
  }
476
479
 
477
- function describe(err: unknown): string {
478
- return err instanceof Error ? err.message : String(err)
479
- }
480
-
481
480
  function dropHint(reason: InboundDropReason): string {
482
481
  switch (reason) {
483
482
  case 'empty_content':
@@ -34,6 +34,7 @@ import type {
34
34
  } from '@/channels/types'
35
35
  import type { WebexAccountRecord } from '@/secrets/schema'
36
36
 
37
+ import { describeError } from './describe-error'
37
38
  import { createWebexChannelNameResolver } from './webex-channel-resolver'
38
39
  import { classifyInbound, type InboundDropReason, type WebexInboundMessage } from './webex-classify'
39
40
  import { resolveWebexBodyText } from './webex-format'
@@ -136,7 +137,7 @@ export function createOutboundCallback(deps: {
136
137
  logger.info(`[webex] sent id=${sent.ref} ${tag}`)
137
138
  return { ok: true, messageId: sent.ref, messageIds: [sent.ref] }
138
139
  } catch (err) {
139
- const message = describe(err)
140
+ const message = describeError(err)
140
141
  logger.error(`[webex] outbound failed: ${message}`)
141
142
  return { ok: false, error: message }
142
143
  }
@@ -178,7 +179,7 @@ export function createTypingCallback(deps: {
178
179
  .then(() => client.setTyping(target.chat, typing))
179
180
  .catch(async (err: unknown) => {
180
181
  const tag = formatChannelTag ? await formatChannelTag(target.chat) : `room=${target.chat}`
181
- logger.warn(`[webex] typing ${tag} phase=${target.phase} failed: ${describe(err)}`)
182
+ logger.warn(`[webex] typing ${tag} phase=${target.phase} failed: ${describeError(err)}`)
182
183
  })
183
184
  queues.set(target.chat, next)
184
185
  void next.finally(() => {
@@ -217,7 +218,7 @@ export function createWebexHistoryCallback(deps: {
217
218
  }
218
219
  return toHistory(outcome.value)
219
220
  } catch (err) {
220
- const message = describe(err)
221
+ const message = describeError(err)
221
222
  if (args.prefetch === true && isWebexRateLimitError(err)) {
222
223
  deps.logger.info(`[webex] history prefetch skipped: rate limited (${message})`)
223
224
  return { ok: false, error: message, skipReason: 'rate-limited' }
@@ -264,7 +265,9 @@ export function createWebexMembershipResolver(deps: {
264
265
  }
265
266
  return { humans: humanMemberIds.length, bots, fetchedAt: now(), truncated, humanMemberIds }
266
267
  } catch (err) {
267
- deps.logger.warn(`[webex] membership room=${key.chat} failed: ${describe(err)}; deriving from recent history`)
268
+ deps.logger.warn(
269
+ `[webex] membership room=${key.chat} failed: ${describeError(err)}; deriving from recent history`,
270
+ )
268
271
  return await deriveMembershipFromHistory({
269
272
  fetchHistory: (limit) => deps.historyCallback({ chat: key.chat, thread: key.thread, limit, prefetch: true }),
270
273
  now,
@@ -318,7 +321,7 @@ export function createFetchAttachmentCallback(deps: {
318
321
  size: buffer.length,
319
322
  }
320
323
  } catch (err) {
321
- const message = describe(err)
324
+ const message = describeError(err)
322
325
  deps.logger.error(`[webex] fetchAttachment failed for ${url.toString()}: ${message}`)
323
326
  return { ok: false, error: message }
324
327
  }
@@ -391,7 +394,7 @@ export function createWebexAdapter(options: WebexAdapterOptions): WebexAdapter {
391
394
  )
392
395
  await options.router.route(payload)
393
396
  } catch (err) {
394
- logger.error(`[webex] handleInbound failed: ${describe(err)}`)
397
+ logger.error(`[webex] handleInbound failed: ${describeError(err)}`)
395
398
  } finally {
396
399
  inflightInbounds--
397
400
  if (inflightInbounds === 0 && stopWaiters.length > 0) {
@@ -419,7 +422,7 @@ export function createWebexAdapter(options: WebexAdapterOptions): WebexAdapter {
419
422
  started = false
420
423
  currentToken = null
421
424
  botPerson = null
422
- logger.error(`[webex] login failed: ${describe(err)}`)
425
+ logger.error(`[webex] login failed: ${describeError(err)}`)
423
426
  throw err
424
427
  }
425
428
 
@@ -438,9 +441,9 @@ export function createWebexAdapter(options: WebexAdapterOptions): WebexAdapter {
438
441
  logger.warn(`[webex] disconnected: ${reason}`)
439
442
  })
440
443
  listener.on('error', (err: unknown) => {
441
- const error = err instanceof Error ? err : new Error(String(err))
444
+ const error = err instanceof Error ? err : new Error(describeError(err))
442
445
  if (!listenerConnected && listenerStartupError === null) listenerStartupError = error
443
- logger.error(`[webex] listener error: ${describe(error)}`)
446
+ logger.error(`[webex] listener error: ${describeError(err)}`)
444
447
  })
445
448
  listener.on('message_created', (event: WebexListenerEventMap['message_created'][0]) => {
446
449
  void handleMessage(event)
@@ -470,14 +473,14 @@ export function createWebexAdapter(options: WebexAdapterOptions): WebexAdapter {
470
473
  currentToken = null
471
474
  connected = false
472
475
  started = false
473
- logger.error(`[webex] ${reason}: ${describe(cause)}`)
476
+ logger.error(`[webex] ${reason}: ${describeError(cause)}`)
474
477
  throw cause
475
478
  }
476
479
 
477
480
  try {
478
481
  await listener.start()
479
482
  } catch (err) {
480
- rollbackStart('listener start threw', err instanceof Error ? err : new Error(String(err)))
483
+ rollbackStart('listener start threw', err instanceof Error ? err : new Error(describeError(err)))
481
484
  }
482
485
  if (!listenerConnected) {
483
486
  rollbackStart(
@@ -554,10 +557,6 @@ function clampLimit(requested: number, max: number): number {
554
557
  return Math.min(Math.floor(requested), max)
555
558
  }
556
559
 
557
- function describe(err: unknown): string {
558
- return err instanceof Error ? err.message : String(err)
559
- }
560
-
561
560
  function dropHint(reason: InboundDropReason): string {
562
561
  switch (reason) {
563
562
  case 'empty_content':
@@ -17,9 +17,23 @@ import { formatJson, formatReport } from '@/doctor'
17
17
 
18
18
  import { formatComposeStatus } from './compose-status'
19
19
  import { formatComposeUsage, formatComposeUsageJson } from './compose-usage'
20
+ import { preflightDocker, printDockerGuidance } from './docker-preflight'
20
21
  import { c, errorLine, spinner } from './ui'
21
22
  import { parseSince, parseUntil } from './usage-args'
22
23
 
24
+ // Compose fans a docker command out across every agent folder. A down daemon
25
+ // would otherwise surface as N identical raw-stderr rows (one per agent) instead
26
+ // of one actionable message, so gate the whole fleet operation on a single
27
+ // preflight up front. usage reads only local session files and never touches
28
+ // docker, so it is intentionally not gated.
29
+ async function requireDockerOrExit(): Promise<void> {
30
+ const preflight = await preflightDocker()
31
+ if (!preflight.ok) {
32
+ printDockerGuidance(preflight)
33
+ process.exit(1)
34
+ }
35
+ }
36
+
23
37
  const startSub = defineCommand({
24
38
  meta: { name: 'start', description: 'start every agent in immediate subdirectories of cwd' },
25
39
  args: {
@@ -35,6 +49,7 @@ const startSub = defineCommand({
35
49
  },
36
50
  },
37
51
  async run({ args }) {
52
+ await requireDockerOrExit()
38
53
  const board = makeBoard('Starting agents')
39
54
  const s = spinner()
40
55
  const { agents, results } = await composeStart({
@@ -63,6 +78,7 @@ const startSub = defineCommand({
63
78
  const stopSub = defineCommand({
64
79
  meta: { name: 'stop', description: 'stop every agent in immediate subdirectories of cwd' },
65
80
  async run() {
81
+ await requireDockerOrExit()
66
82
  const board = makeBoard('Stopping agents')
67
83
  const s = spinner()
68
84
  const { agents, results } = await composeStop({
@@ -100,6 +116,7 @@ const restartSub = defineCommand({
100
116
  },
101
117
  },
102
118
  async run({ args }) {
119
+ await requireDockerOrExit()
103
120
  const board = makeBoard('Restarting agents')
104
121
  const s = spinner()
105
122
  const { agents, results } = await composeRestart({
@@ -130,6 +147,7 @@ const restartSub = defineCommand({
130
147
  const statusSub = defineCommand({
131
148
  meta: { name: 'status', description: 'show status of every agent in immediate subdirectories of cwd' },
132
149
  async run() {
150
+ await requireDockerOrExit()
133
151
  const result = await composeStatus(process.cwd())
134
152
  const useColor = Boolean(process.stdout.isTTY) && process.env.NO_COLOR === undefined
135
153
  process.stdout.write(`${formatComposeStatus(result, { useColor })}\n`)
@@ -162,6 +180,8 @@ const logsSub = defineCommand({
162
180
  tail = parsed.value
163
181
  }
164
182
 
183
+ await requireDockerOrExit()
184
+
165
185
  const controller = new AbortController()
166
186
  const onSig = (): void => controller.abort()
167
187
  process.once('SIGINT', onSig)
@@ -0,0 +1,42 @@
1
+ import {
2
+ checkDockerAvailable,
3
+ detectInstalledDockerApps,
4
+ pickRuntimeToNudge,
5
+ renderDockerUnavailableGuidance,
6
+ type DockerExec,
7
+ } from '@/container'
8
+
9
+ import { c, errorLine } from './ui'
10
+
11
+ export type DockerPreflightResult = { ok: true } | { ok: false; summary: string; guidance: string[] }
12
+
13
+ // Single host-side gate every Docker-dependent CLI command calls before it
14
+ // spawns docker. Without it the raw daemon-down stderr (an unactionable socket
15
+ // path) leaks straight to the user. This probes once via checkDockerAvailable,
16
+ // then hands the friendly, runtime-specific guidance back to the caller so each
17
+ // command renders it in its own style (spinner vs console) — no process.exit
18
+ // here, that belongs to the command.
19
+ export async function preflightDocker(exec?: DockerExec): Promise<DockerPreflightResult> {
20
+ const availability = exec ? await checkDockerAvailable(exec) : await checkDockerAvailable()
21
+ if (availability.ok) return { ok: true }
22
+
23
+ const detail = availability.reason === 'daemon-down' ? availability.detail : undefined
24
+ const installed = detectInstalledDockerApps()
25
+ const nudge = pickRuntimeToNudge(process.env, detail, installed)
26
+ const { summary, lines } = renderDockerUnavailableGuidance(availability, {
27
+ platform: process.platform,
28
+ nudge,
29
+ installed,
30
+ })
31
+ return { ok: false, summary, guidance: lines }
32
+ }
33
+
34
+ // Prints the friendly guidance to stderr in the standard CLI error style
35
+ // (red ✖ summary, then dimmed guidance lines). Shared by every command's
36
+ // non-spinner failure path so the look is identical everywhere.
37
+ export function printDockerGuidance(failure: Extract<DockerPreflightResult, { ok: false }>): void {
38
+ console.error(errorLine(failure.summary))
39
+ for (const line of failure.guidance) {
40
+ console.error(line === '' ? '' : c.dim(line))
41
+ }
42
+ }
package/src/cli/hostd.ts CHANGED
@@ -2,6 +2,7 @@ import { defineCommand } from 'citty'
2
2
 
3
3
  import { loadConfigSync, validateConfig, type Config, type ValidateConfigResult } from '@/config'
4
4
  import { start, stop, type StartOptions, type StartResult, type StopResult } from '@/container'
5
+ import { createCurrentHostDaemonHolder } from '@/hostd/current-host-daemon'
5
6
  import { startDaemon, type DaemonLogEvent, type RestartPreflight } from '@/hostd/daemon'
6
7
  import { createKakaoRenewalManager } from '@/hostd/kakao-renewal-manager'
7
8
  import { createPortbrokerManager } from '@/hostd/portbroker-manager'
@@ -26,6 +27,10 @@ export const hostdCommand = defineCommand({
26
27
  })
27
28
 
28
29
  const hostdRestart = buildHostdRestart(cliEntry, defaultRestartDeps, version)
30
+ // Renewal restarts call hostdRestart directly (not via the restart RPC), so
31
+ // they must thread currentHostDaemon themselves to get the in-process
32
+ // registration path. The daemon populates this holder once booted.
33
+ const currentHostDaemonHolder = createCurrentHostDaemonHolder()
29
34
  const kakaoRenewal = createKakaoRenewalManager({
30
35
  onLog: (event) => writeLogLine(formatLog(event)),
31
36
  onRenewalOk: async ({ containerName, cwd }) => {
@@ -33,7 +38,8 @@ export const hostdCommand = defineCommand({
33
38
  // up the renewed tokens from secrets.json. Without this, the cron
34
39
  // would write fresh tokens but the running adapter would keep using
35
40
  // the old token in its closure and still 401 at the ~7-day wall.
36
- const result = await hostdRestart({ containerName, cwd })
41
+ const currentHostDaemon = await currentHostDaemonHolder.ready()
42
+ const result = await hostdRestart({ containerName, cwd, currentHostDaemon })
37
43
  if (!result.ok) throw new Error(result.reason)
38
44
  },
39
45
  shouldRenew: ({ cwd }) => kakaoChannelConfigured(cwd),
@@ -45,7 +51,8 @@ export const hostdCommand = defineCommand({
45
51
  // secrets.json. Without this, the cron writes a fresh token but the
46
52
  // running adapter keeps the old token in its getToken closure and still
47
53
  // 401s on every outbound REST call + KMS key fetch.
48
- const result = await hostdRestart({ containerName, cwd })
54
+ const currentHostDaemon = await currentHostDaemonHolder.ready()
55
+ const result = await hostdRestart({ containerName, cwd, currentHostDaemon })
49
56
  if (!result.ok) throw new Error(result.reason)
50
57
  },
51
58
  shouldRenew: ({ cwd }) => webexChannelConfigured(cwd),
@@ -58,6 +65,7 @@ export const hostdCommand = defineCommand({
58
65
  portbroker,
59
66
  kakaoRenewal,
60
67
  webexRenewal,
68
+ currentHostDaemonHolder,
61
69
  restartPreflight: buildHostdRestartPreflight(cliEntry, version, defaultPreflightDeps),
62
70
  restart: hostdRestart,
63
71
  })
@@ -96,7 +104,7 @@ export function buildHostdRestart(
96
104
  deps: HostdRestartDeps = defaultRestartDeps,
97
105
  daemonVersion?: string,
98
106
  ): SupervisorRestart {
99
- return async ({ containerName, cwd, build = false }) => {
107
+ return async ({ containerName, cwd, build = false, currentHostDaemon }) => {
100
108
  const drift = await detectSourceDrift(cliEntry, daemonVersion)
101
109
  if (drift) return { ok: false, reason: drift }
102
110
 
@@ -114,6 +122,7 @@ export function buildHostdRestart(
114
122
  forceBuild: build,
115
123
  cliEntry,
116
124
  reuseCurrentHostDaemon: true,
125
+ ...(currentHostDaemon ? { currentHostDaemon } : {}),
117
126
  })
118
127
  if (!startResult.ok) return { ok: false, reason: `start failed: ${startResult.reason}` }
119
128
  return { ok: true }
package/src/cli/init.ts CHANGED
@@ -30,7 +30,13 @@ import {
30
30
  type KnownProviderId,
31
31
  type KnownProviderVendorId,
32
32
  } from '@/config/providers'
33
- import { checkDockerAvailable, type DockerAvailability } from '@/container'
33
+ import {
34
+ checkDockerAvailable,
35
+ detectInstalledDockerApps,
36
+ pickRuntimeToNudge,
37
+ renderDockerUnavailableGuidance,
38
+ type DockerAvailability,
39
+ } from '@/container'
34
40
  import {
35
41
  appendOrReplaceEnvKey,
36
42
  findAgentDir,
@@ -1928,31 +1934,27 @@ function reportProgress(
1928
1934
  }
1929
1935
  }
1930
1936
 
1937
+ function renderPreflightFailure(result: Extract<DockerAvailability, { ok: false }>): {
1938
+ summary: string
1939
+ lines: string[]
1940
+ } {
1941
+ const detail = result.reason === 'daemon-down' ? result.detail : undefined
1942
+ const installed = detectInstalledDockerApps()
1943
+ const nudge = pickRuntimeToNudge(process.env, detail, installed)
1944
+ return renderDockerUnavailableGuidance(result, {
1945
+ platform: process.platform,
1946
+ nudge,
1947
+ installed,
1948
+ retryHint: 'Then re-run `typeclaw init`.',
1949
+ })
1950
+ }
1951
+
1931
1952
  function preflightFailureSummary(result: Extract<DockerAvailability, { ok: false }>): string {
1932
- if (result.reason === 'binary-missing') return 'Docker is not installed.'
1933
- return 'Docker is installed but the daemon is not reachable.'
1953
+ return renderPreflightFailure(result).summary
1934
1954
  }
1935
1955
 
1936
1956
  function preflightFailureGuidance(result: Extract<DockerAvailability, { ok: false }>): string[] {
1937
- if (result.reason === 'binary-missing') {
1938
- return [
1939
- 'TypeClaw runs every agent inside its own Docker container, so Docker is required.',
1940
- '',
1941
- 'Install one of:',
1942
- ' • Docker Desktop — https://docs.docker.com/get-docker/',
1943
- ' • OrbStack (macOS, lighter) — https://orbstack.dev',
1944
- '',
1945
- 'Then re-run `typeclaw init`.',
1946
- ]
1947
- }
1948
- return [
1949
- 'The docker CLI is on $PATH, but the daemon refused the connection:',
1950
- '',
1951
- ` ${result.detail}`,
1952
- '',
1953
- 'Start Docker Desktop / OrbStack (or `sudo systemctl start docker` on Linux),',
1954
- 'then re-run `typeclaw init`.',
1955
- ]
1957
+ return renderPreflightFailure(result).lines
1956
1958
  }
1957
1959
 
1958
1960
  function reportKakaotalkAuth(result: KakaotalkAuthResult): string {
package/src/cli/logs.ts CHANGED
@@ -2,6 +2,7 @@ import { defineCommand } from 'citty'
2
2
 
3
3
  import { logs, parseTailValue } from '@/container'
4
4
 
5
+ import { preflightDocker, printDockerGuidance } from './docker-preflight'
5
6
  import { runInspectViewer } from './inspect'
6
7
  import { requireAgentDir } from './require-agent-dir'
7
8
  import { c, errorLine } from './ui'
@@ -51,6 +52,12 @@ export const logsCommand = defineCommand({
51
52
  process.exit(exitCode)
52
53
  }
53
54
 
55
+ const preflight = await preflightDocker()
56
+ if (!preflight.ok) {
57
+ printDockerGuidance(preflight)
58
+ process.exit(1)
59
+ }
60
+
54
61
  if (args.follow) {
55
62
  console.log(c.cyan('Streaming container logs...'))
56
63
  } else {
@@ -438,5 +438,12 @@ function describeSource(source: CredentialSource): string {
438
438
 
439
439
  function nextStepHints(opts: { credentialChanged: boolean }): { label: string; command: string }[] {
440
440
  if (!opts.credentialChanged) return []
441
- return [{ label: 'If the agent is running:', command: 'typeclaw reload' }]
441
+ // secrets.json is bind-mounted live, so `typeclaw reload` clears the provider
442
+ // auth cache and the next call re-reads this file. Editing a key's value in
443
+ // .env instead still needs a restart — container env is fixed at `docker run`
444
+ // — so surface both paths to the user, not just reload.
445
+ return [
446
+ { label: 'Apply the secrets.json change:', command: 'typeclaw reload' },
447
+ { label: 'If you changed a key in .env:', command: 'typeclaw restart' },
448
+ ]
442
449
  }
package/src/cli/reload.ts CHANGED
@@ -4,6 +4,7 @@ import { requireContainerRunning, resolveHostPort, resolveTuiToken } from '@/con
4
4
  import { findAgentDir } from '@/init'
5
5
  import { requestReloadWithFallback, type ReloadResult } from '@/reload'
6
6
 
7
+ import { preflightDocker, printDockerGuidance } from './docker-preflight'
7
8
  import { c, errorLine, spinner } from './ui'
8
9
 
9
10
  export const reload = defineCommand({
@@ -84,6 +85,11 @@ export function printReloadRecoveryHint(recoveredHostError: string | undefined):
84
85
 
85
86
  async function defaultTarget(): Promise<{ url: string; cwd: string; token: string | null }> {
86
87
  const cwd = findAgentDir(process.cwd()) ?? process.cwd()
88
+ const preflight = await preflightDocker()
89
+ if (!preflight.ok) {
90
+ printDockerGuidance(preflight)
91
+ process.exit(1)
92
+ }
87
93
  const precheck = await requireContainerRunning({ cwd })
88
94
  if (!precheck.ok) {
89
95
  console.error(errorLine(precheck.reason))
@@ -5,6 +5,7 @@ import { config, validateConfig } from '@/config'
5
5
  import { start, stop } from '@/container'
6
6
  import { findAgentDir, isInitialized } from '@/init'
7
7
 
8
+ import { preflightDocker, printDockerGuidance } from './docker-preflight'
8
9
  import { guardIncompleteInit } from './incomplete-init'
9
10
  import { c, errorLine, renderStartSuccess, reportConfigWarnings, spinner } from './ui'
10
11
 
@@ -63,6 +64,12 @@ export const restartCommand = defineCommand({
63
64
  }
64
65
  reportConfigWarnings(validated.warnings)
65
66
 
67
+ const preflight = await preflightDocker()
68
+ if (!preflight.ok) {
69
+ printDockerGuidance(preflight)
70
+ process.exit(1)
71
+ }
72
+
66
73
  const stopSpin = spinner()
67
74
  stopSpin.start('Stopping container...')
68
75
  const stopped = await stop({ cwd })
package/src/cli/shell.ts CHANGED
@@ -2,6 +2,7 @@ import { defineCommand } from 'citty'
2
2
 
3
3
  import { shell } from '@/container'
4
4
 
5
+ import { preflightDocker, printDockerGuidance } from './docker-preflight'
5
6
  import { requireAgentDir } from './require-agent-dir'
6
7
  import { c, errorLine } from './ui'
7
8
 
@@ -20,6 +21,12 @@ export const shellCommand = defineCommand({
20
21
  async run({ args }) {
21
22
  const cwd = requireAgentDir()
22
23
 
24
+ const preflight = await preflightDocker()
25
+ if (!preflight.ok) {
26
+ printDockerGuidance(preflight)
27
+ process.exit(1)
28
+ }
29
+
23
30
  console.log(c.cyan(`Attaching ${args.shell} inside the container...`))
24
31
 
25
32
  const result = await shell({ cwd, shell: args.shell })
package/src/cli/start.ts CHANGED
@@ -5,6 +5,7 @@ import { config, validateConfig } from '@/config'
5
5
  import { start } from '@/container'
6
6
  import { findAgentDir, isInitialized } from '@/init'
7
7
 
8
+ import { preflightDocker, printDockerGuidance } from './docker-preflight'
8
9
  import { guardIncompleteInit } from './incomplete-init'
9
10
  import { errorLine, renderStartSuccess, reportConfigWarnings, spinner } from './ui'
10
11
 
@@ -63,6 +64,12 @@ export const startCommand = defineCommand({
63
64
  }
64
65
  reportConfigWarnings(validated.warnings)
65
66
 
67
+ const preflight = await preflightDocker()
68
+ if (!preflight.ok) {
69
+ printDockerGuidance(preflight)
70
+ process.exit(1)
71
+ }
72
+
66
73
  const s = spinner()
67
74
  s.start('Starting container...')
68
75
  const result = await start({
package/src/cli/status.ts CHANGED
@@ -7,6 +7,8 @@ import { isDaemonReachable, send } from '@/hostd'
7
7
  import type { StatusResult } from '@/hostd'
8
8
  import { findAgentDir } from '@/init'
9
9
 
10
+ import { preflightDocker, printDockerGuidance } from './docker-preflight'
11
+
10
12
  export type HostdStatus =
11
13
  | { kind: 'unreachable' }
12
14
  | { kind: 'not-registered'; reason: string }
@@ -25,6 +27,13 @@ export const statusCommand = defineCommand({
25
27
  },
26
28
  async run() {
27
29
  const cwd = findAgentDir(process.cwd()) ?? process.cwd()
30
+
31
+ const preflight = await preflightDocker()
32
+ if (!preflight.ok) {
33
+ printDockerGuidance(preflight)
34
+ process.exit(1)
35
+ }
36
+
28
37
  const container = await containerStatus({ cwd })
29
38
  const hostd = await fetchHostdStatus(container.containerName)
30
39
 
package/src/cli/stop.ts CHANGED
@@ -2,6 +2,7 @@ import { defineCommand } from 'citty'
2
2
 
3
3
  import { stop } from '@/container'
4
4
 
5
+ import { preflightDocker, printDockerGuidance } from './docker-preflight'
5
6
  import { requireAgentDir } from './require-agent-dir'
6
7
  import { c, spinner } from './ui'
7
8
 
@@ -13,6 +14,12 @@ export const stopCommand = defineCommand({
13
14
  async run() {
14
15
  const cwd = requireAgentDir()
15
16
 
17
+ const preflight = await preflightDocker()
18
+ if (!preflight.ok) {
19
+ printDockerGuidance(preflight)
20
+ process.exit(1)
21
+ }
22
+
16
23
  const s = spinner()
17
24
  s.start('Stopping container...')
18
25
  const result = await stop({ cwd })
package/src/cli/tui.ts CHANGED
@@ -5,6 +5,7 @@ import { CLI_VERSION } from '@/init/cli-version'
5
5
  import { runTuiViewer } from '@/inspect'
6
6
  import { formatVersionMismatchWarning } from '@/tui'
7
7
 
8
+ import { preflightDocker, printDockerGuidance } from './docker-preflight'
8
9
  import { runInspectViewer } from './inspect'
9
10
  import { requireAgentDir } from './require-agent-dir'
10
11
  import { errorLine } from './ui'
@@ -75,6 +76,11 @@ export const tui = defineCommand({
75
76
  })
76
77
 
77
78
  async function defaultUrl(cwd: string): Promise<string> {
79
+ const preflight = await preflightDocker()
80
+ if (!preflight.ok) {
81
+ printDockerGuidance(preflight)
82
+ process.exit(1)
83
+ }
78
84
  const precheck = await requireContainerRunning({ cwd })
79
85
  if (!precheck.ok) throw new Error(precheck.reason)
80
86
  const port = await resolveHostPort({ cwd })