typeclaw 0.39.7 → 0.41.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 (72) 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/agent/multimodal/look-at.ts +87 -0
  7. package/src/bundled-plugins/guard/policies/non-workspace-write.ts +0 -2
  8. package/src/bundled-plugins/guard/policy.ts +0 -5
  9. package/src/bundled-plugins/memory/README.md +26 -37
  10. package/src/bundled-plugins/memory/index.ts +32 -147
  11. package/src/bundled-plugins/memory/load-memory.ts +7 -121
  12. package/src/bundled-plugins/memory/memory-logger.ts +8 -2
  13. package/src/bundled-plugins/memory/search-command.ts +2 -11
  14. package/src/bundled-plugins/memory/vector/doctor.ts +1 -1
  15. package/src/bundled-plugins/memory/vector/embedder.ts +4 -5
  16. package/src/bundled-plugins/memory/vector/hybrid.ts +47 -5
  17. package/src/bundled-plugins/memory/vector/index-on-write.ts +25 -20
  18. package/src/bundled-plugins/memory/vector/reference-index-on-write.ts +28 -23
  19. package/src/bundled-plugins/memory/vector/relevance-gate.ts +11 -7
  20. package/src/bundled-plugins/memory/vector/script.ts +87 -0
  21. package/src/bundled-plugins/memory/vector/store.ts +2 -0
  22. package/src/bundled-plugins/planner/planner.ts +4 -2
  23. package/src/bundled-plugins/reviewer/reviewer.ts +9 -1
  24. package/src/channels/adapters/describe-error.ts +40 -0
  25. package/src/channels/adapters/discord.ts +9 -12
  26. package/src/channels/adapters/kakaotalk-classify.ts +31 -6
  27. package/src/channels/adapters/kakaotalk.ts +15 -18
  28. package/src/channels/adapters/line.ts +11 -14
  29. package/src/channels/adapters/slack-bot.ts +15 -18
  30. package/src/channels/adapters/slack.ts +45 -21
  31. package/src/channels/adapters/telegram-bot.ts +15 -18
  32. package/src/channels/adapters/webex-bot.ts +13 -14
  33. package/src/channels/adapters/webex.ts +14 -15
  34. package/src/cli/compose.ts +20 -0
  35. package/src/cli/docker-preflight.ts +42 -0
  36. package/src/cli/hostd.ts +12 -3
  37. package/src/cli/init.ts +24 -22
  38. package/src/cli/logs.ts +7 -0
  39. package/src/cli/provider.ts +8 -1
  40. package/src/cli/reload.ts +6 -0
  41. package/src/cli/restart.ts +7 -0
  42. package/src/cli/shell.ts +7 -0
  43. package/src/cli/start.ts +7 -0
  44. package/src/cli/status.ts +9 -0
  45. package/src/cli/stop.ts +7 -0
  46. package/src/cli/tui.ts +6 -0
  47. package/src/config/config.ts +31 -8
  48. package/src/container/docker-app.ts +253 -0
  49. package/src/container/index.ts +11 -0
  50. package/src/container/start.ts +85 -41
  51. package/src/hostd/current-host-daemon.ts +21 -0
  52. package/src/hostd/daemon.ts +75 -15
  53. package/src/hostd/kakao-renewal-manager.ts +35 -10
  54. package/src/hostd/supervisor.ts +18 -3
  55. package/src/hostd/tailscale.ts +41 -5
  56. package/src/hostd/webex-renewal-manager.ts +13 -4
  57. package/src/plugin/hooks.ts +3 -4
  58. package/src/plugin/index.ts +1 -0
  59. package/src/plugin/manager.ts +14 -0
  60. package/src/plugin/registry.ts +12 -0
  61. package/src/plugin/types.ts +5 -1
  62. package/src/run/channel-session-factory.ts +3 -5
  63. package/src/run/index.ts +63 -36
  64. package/src/server/command-runner.ts +2 -11
  65. package/src/skills/typeclaw-memory/SKILL.md +2 -2
  66. package/src/skills/typeclaw-plugins/SKILL.md +1 -1
  67. package/src/test-helpers/rm-temp-dir.ts +24 -0
  68. package/typeclaw.schema.json +1 -23
  69. package/src/bundled-plugins/guard/policies/memory-retrieval-cache-write.ts +0 -43
  70. package/src/bundled-plugins/memory/memory-retrieval.ts +0 -111
  71. package/src/bundled-plugins/memory/vector/cache-write.ts +0 -19
  72. package/src/bundled-plugins/memory/vector/config.ts +0 -28
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 })
@@ -1197,7 +1197,7 @@ export function loadConfigBundleSync(cwd: string): { config: Config; pluginConfi
1197
1197
  // `changed` is the boolean equivalent of `applied.length > 0` and is preserved
1198
1198
  // for back-compat with the many call sites that only care whether ANY rewrite
1199
1199
  // happened.
1200
- export type MigrationStep = { kind: 'drop-github-seeded-event-allowlist' }
1200
+ export type MigrationStep = { kind: 'drop-github-seeded-event-allowlist' } | { kind: 'drop-memory-vector-config' }
1201
1201
 
1202
1202
  export type MigrationResult = { json: unknown; changed: boolean; applied: MigrationStep[] }
1203
1203
 
@@ -1207,18 +1207,20 @@ export function migrateLegacyConfigShape(json: unknown): MigrationResult {
1207
1207
  }
1208
1208
 
1209
1209
  const obj = json as Record<string, unknown>
1210
- const hasSeededGithubEventAllowlist = isSeededGithubEventAllowlist(obj)
1211
- if (!hasSeededGithubEventAllowlist) {
1212
- return { json, changed: false, applied: [] }
1213
- }
1214
-
1215
1210
  const applied: MigrationStep[] = []
1216
1211
  const next: Record<string, unknown> = { ...obj }
1217
- if (hasSeededGithubEventAllowlist) {
1212
+
1213
+ if (isSeededGithubEventAllowlist(obj)) {
1218
1214
  dropSeededGithubEventAllowlist(next)
1219
1215
  applied.push({ kind: 'drop-github-seeded-event-allowlist' })
1220
1216
  }
1221
- return { json: next, changed: true, applied }
1217
+
1218
+ if (hasLegacyMemoryVectorConfig(obj)) {
1219
+ dropMemoryVectorConfig(next)
1220
+ applied.push({ kind: 'drop-memory-vector-config' })
1221
+ }
1222
+
1223
+ return { json: applied.length > 0 ? next : json, changed: applied.length > 0, applied }
1222
1224
  }
1223
1225
 
1224
1226
  // True when channels.github.eventAllowlist deep-equals an allowlist that
@@ -1243,6 +1245,23 @@ function dropSeededGithubEventAllowlist(next: Record<string, unknown>): void {
1243
1245
  next.channels = { ...channels, github: rest }
1244
1246
  }
1245
1247
 
1248
+ function hasLegacyMemoryVectorConfig(obj: Record<string, unknown>): boolean {
1249
+ const memory = obj.memory
1250
+ return isPlainObject(memory) && Object.prototype.hasOwnProperty.call(memory, 'vector')
1251
+ }
1252
+
1253
+ function dropMemoryVectorConfig(next: Record<string, unknown>): void {
1254
+ const memory = next.memory
1255
+ if (!isPlainObject(memory)) return
1256
+ const clone = { ...memory }
1257
+ delete clone.vector
1258
+ if (Object.keys(clone).length === 0) {
1259
+ delete next.memory
1260
+ return
1261
+ }
1262
+ next.memory = clone
1263
+ }
1264
+
1246
1265
  function arraysEqual(a: readonly unknown[], b: readonly unknown[]): boolean {
1247
1266
  if (a.length !== b.length) return false
1248
1267
  for (let i = 0; i < a.length; i++) {
@@ -1267,6 +1286,8 @@ function shortStepLabel(step: MigrationStep): string {
1267
1286
  switch (step.kind) {
1268
1287
  case 'drop-github-seeded-event-allowlist':
1269
1288
  return 'drop seeded channels.github.eventAllowlist'
1289
+ case 'drop-memory-vector-config':
1290
+ return 'drop memory.vector config'
1270
1291
  }
1271
1292
  }
1272
1293
 
@@ -1274,6 +1295,8 @@ function describeStep(step: MigrationStep): string {
1274
1295
  switch (step.kind) {
1275
1296
  case 'drop-github-seeded-event-allowlist':
1276
1297
  return 'drop seeded channels.github.eventAllowlist so it re-tracks the shipped default'
1298
+ case 'drop-memory-vector-config':
1299
+ return 'drop memory.vector config; vector memory is always on'
1277
1300
  }
1278
1301
  }
1279
1302
 
@@ -0,0 +1,253 @@
1
+ import { existsSync } from 'node:fs'
2
+
3
+ import { getBun } from './shared'
4
+ import type { DockerAvailability } from './shared'
5
+
6
+ // Detection + friendly guidance for "Docker is not reachable".
7
+ //
8
+ // `checkDockerAvailable` (in ./shared) already tells us WHETHER docker works and
9
+ // discriminates `binary-missing` (no `docker` on PATH) from `daemon-down` (CLI
10
+ // present, daemon refused the connection — the common "Docker Desktop / OrbStack
11
+ // installed but not started" case on macOS). What it does NOT do is tell the
12
+ // user WHICH runtime to nudge. This module fills that gap: it classifies the
13
+ // likely runtime and renders a short, copy-pasteable instruction instead of
14
+ // leaking the raw daemon error (which on OrbStack embeds a per-user socket path
15
+ // under the user's home dir — noise the user can't act on).
16
+ //
17
+ // Classification priority (most → least authoritative):
18
+ // 1. The configured socket: `DOCKER_HOST` or the socket path inside the raw
19
+ // daemon-down `detail`. An `orbstack` / `docker-desktop` / `colima` /
20
+ // `podman` marker in that path is a high-confidence signal of the runtime
21
+ // the CLI is actually configured to talk to — sharper than guessing from
22
+ // what's installed on disk.
23
+ // 2. Installed-app probes (filesystem / PATH). A fallback used only when the
24
+ // socket gives no hint.
25
+ // 3. Platform default (generic "start your Docker daemon").
26
+
27
+ export type DockerApp = 'docker-desktop' | 'orbstack' | 'colima' | 'podman'
28
+
29
+ export type DockerAppProbes = {
30
+ platform?: NodeJS.Platform
31
+ exists?: (path: string) => boolean
32
+ which?: (command: string) => string | null
33
+ env?: NodeJS.ProcessEnv
34
+ }
35
+
36
+ const APP_LABELS: Record<DockerApp, string> = {
37
+ 'docker-desktop': 'Docker Desktop',
38
+ orbstack: 'OrbStack',
39
+ colima: 'Colima',
40
+ podman: 'Podman',
41
+ }
42
+
43
+ export function dockerAppLabel(app: DockerApp): string {
44
+ return APP_LABELS[app]
45
+ }
46
+
47
+ function defaultWhich(command: string): string | null {
48
+ return getBun()?.which(command) ?? null
49
+ }
50
+
51
+ function resolveProbes(probes: DockerAppProbes): Required<DockerAppProbes> {
52
+ return {
53
+ platform: probes.platform ?? process.platform,
54
+ exists: probes.exists ?? existsSync,
55
+ which: probes.which ?? defaultWhich,
56
+ env: probes.env ?? process.env,
57
+ }
58
+ }
59
+
60
+ // Reads the socket the docker CLI is configured to use and classifies the
61
+ // runtime from its path. `DOCKER_HOST` wins (it overrides the default socket);
62
+ // otherwise we fall back to the socket path docker printed inside its own
63
+ // connection-refused error. Both are matched case-insensitively on the vendor's
64
+ // own directory/socket naming, which is ASCII by the tools' own conventions —
65
+ // these are protocol/path tokens, not human language, so English matching is
66
+ // correct here.
67
+ export function classifyConfiguredRuntime(env: NodeJS.ProcessEnv, detail: string | undefined): DockerApp | null {
68
+ // DOCKER_HOST is the runtime the CLI is actually configured to talk to, so it
69
+ // must win outright: classify it alone first and only consult the daemon error
70
+ // detail when DOCKER_HOST names no recognized runtime. Folding both into one
71
+ // haystack would let a stale marker in the error text override an explicit
72
+ // DOCKER_HOST (e.g. DOCKER_HOST=…/.colima/… but the error mentions orbstack).
73
+ return classifyRuntimeMarker(env.DOCKER_HOST) ?? classifyRuntimeMarker(detail)
74
+ }
75
+
76
+ function classifyRuntimeMarker(text: string | undefined): DockerApp | null {
77
+ if (!text) return null
78
+ const lower = text.toLowerCase()
79
+ if (lower.includes('orbstack')) return 'orbstack'
80
+ if (lower.includes('colima')) return 'colima'
81
+ if (lower.includes('podman')) return 'podman'
82
+ // Docker Desktop's user socket lives under `~/.docker/<context>/docker.sock`;
83
+ // the only stable runtime marker in that path is the `desktop`/`desktop-linux`
84
+ // context dir. Checked last so a colima/orbstack context that also sits under
85
+ // `~/.docker` is classified by its own sharper marker first.
86
+ if (lower.includes('desktop')) return 'docker-desktop'
87
+ return null
88
+ }
89
+
90
+ // Probes which Docker runtimes are installed on disk / PATH, most-canonical
91
+ // first. macOS app bundles for the GUI runtimes; PATH binaries for the CLI-first
92
+ // runtimes (Colima/Podman). The list is deliberately conservative — a false
93
+ // "installed" only downgrades the message from runtime-specific to generic, it
94
+ // never blocks anything.
95
+ export function detectInstalledDockerApps(probes: DockerAppProbes = {}): DockerApp[] {
96
+ const { platform, exists, which, env } = resolveProbes(probes)
97
+ const found: DockerApp[] = []
98
+
99
+ if (platform === 'darwin') {
100
+ if (exists('/Applications/Docker.app')) found.push('docker-desktop')
101
+ if (exists('/Applications/OrbStack.app')) found.push('orbstack')
102
+ }
103
+
104
+ if (platform === 'win32') {
105
+ if (windowsDockerDesktopInstalled(env, exists)) found.push('docker-desktop')
106
+ if (windowsPodmanInstalled(env, exists)) found.push('podman')
107
+ }
108
+
109
+ // Colima and OrbStack are macOS/Linux only, so probing them on win32 would be
110
+ // dead weight; Podman ships a `podman.exe` that also lands on PATH, caught by
111
+ // the install-path probe above. Off Windows, the PATH binaries are the
112
+ // canonical signal for the CLI-first runtimes.
113
+ if (platform !== 'win32') {
114
+ if (which('colima') !== null) found.push('colima')
115
+ if (which('podman') !== null) found.push('podman')
116
+ }
117
+
118
+ return found
119
+ }
120
+
121
+ // Docker Desktop's GUI launcher (`Docker Desktop.exe`) across the MSI, 32-bit,
122
+ // and per-user install layouts confirmed by the Docker Desktop installer and
123
+ // PowerShell's own probing scripts. Probing the exe (not just `docker` on PATH)
124
+ // is what lets us say "Docker Desktop is installed but not started" when the
125
+ // daemon is down — a stale PATH can hide the CLI even when Desktop is present.
126
+ function windowsDockerDesktopInstalled(env: NodeJS.ProcessEnv, exists: (path: string) => boolean): boolean {
127
+ const programFiles = env.ProgramW6432 ?? env.ProgramFiles ?? 'C:\\Program Files'
128
+ const programFilesX86 = env['ProgramFiles(x86)'] ?? 'C:\\Program Files (x86)'
129
+ const candidates = [
130
+ `${programFiles}\\Docker\\Docker\\Docker Desktop.exe`,
131
+ `${programFilesX86}\\Docker\\Docker\\Docker Desktop.exe`,
132
+ ]
133
+ if (env.LOCALAPPDATA) {
134
+ candidates.push(`${env.LOCALAPPDATA}\\Programs\\Docker\\Docker\\Docker Desktop.exe`)
135
+ }
136
+ return candidates.some(exists)
137
+ }
138
+
139
+ // Podman's Windows install layouts: per-machine (current + legacy RedHat path)
140
+ // and per-user, from the official podman win-installer test script.
141
+ function windowsPodmanInstalled(env: NodeJS.ProcessEnv, exists: (path: string) => boolean): boolean {
142
+ const programFiles = env.ProgramW6432 ?? env.ProgramFiles ?? 'C:\\Program Files'
143
+ const candidates = [`${programFiles}\\Podman\\podman.exe`, `${programFiles}\\RedHat\\Podman\\podman.exe`]
144
+ if (env.LOCALAPPDATA) {
145
+ candidates.push(`${env.LOCALAPPDATA}\\Programs\\Podman\\podman.exe`)
146
+ }
147
+ return candidates.some(exists)
148
+ }
149
+
150
+ // The runtime we should nudge the user to start: configured-socket hint first,
151
+ // then the single installed app (if unambiguous), else null (caller emits the
152
+ // generic message). When multiple apps are installed and the socket gives no
153
+ // hint we deliberately return null rather than guess wrong — the
154
+ // "don't claim OrbStack just because the bundle exists" guardrail.
155
+ export function pickRuntimeToNudge(
156
+ env: NodeJS.ProcessEnv,
157
+ detail: string | undefined,
158
+ installed: DockerApp[],
159
+ ): DockerApp | null {
160
+ const configured = classifyConfiguredRuntime(env, detail)
161
+ if (configured !== null) return configured
162
+ if (installed.length === 1) return installed[0] ?? null
163
+ return null
164
+ }
165
+
166
+ function startInstructions(app: DockerApp, platform: NodeJS.Platform): string[] {
167
+ switch (app) {
168
+ case 'orbstack':
169
+ return platform === 'darwin'
170
+ ? ['Open OrbStack (from Applications or Spotlight), then retry.', 'Or from a terminal: `orb start`']
171
+ : ['Start OrbStack, then retry. (`orb start`)']
172
+ case 'docker-desktop':
173
+ if (platform === 'darwin') {
174
+ return [
175
+ 'Open Docker Desktop (from Applications or Spotlight), then retry.',
176
+ 'Or from a terminal: `open -a Docker`',
177
+ ]
178
+ }
179
+ if (platform === 'win32') {
180
+ return ['Start Docker Desktop from the Start menu, then retry.']
181
+ }
182
+ return ['Start Docker Desktop, then retry.']
183
+ case 'colima':
184
+ return ['Start Colima, then retry: `colima start`']
185
+ case 'podman':
186
+ return ['Start the Podman machine, then retry: `podman machine start`']
187
+ }
188
+ }
189
+
190
+ // Generic "start your daemon" guidance when we can't name the runtime. On Linux
191
+ // the daemon is usually systemd-managed; elsewhere it's a GUI app.
192
+ function genericStartInstructions(platform: NodeJS.Platform): string[] {
193
+ if (platform === 'linux') {
194
+ return ['Start the Docker daemon, then retry.', 'On most distros: `sudo systemctl start docker`']
195
+ }
196
+ if (platform === 'darwin') {
197
+ return ['Start your Docker runtime (Docker Desktop or OrbStack), then retry.']
198
+ }
199
+ return ['Start your Docker runtime, then retry.']
200
+ }
201
+
202
+ const INSTALL_LINES = [
203
+ 'TypeClaw runs every agent inside its own Docker container, so Docker is required.',
204
+ '',
205
+ 'Install one of:',
206
+ ' • Docker Desktop — https://docs.docker.com/get-docker/',
207
+ ' • OrbStack (macOS, lighter) — https://orbstack.dev',
208
+ ]
209
+
210
+ // Builds the friendly, multi-line guidance shown when Docker is unavailable.
211
+ // Pure (no I/O): callers pass the availability result plus pre-probed detection
212
+ // facts so this stays trivially testable and reusable by both the CLI preflight
213
+ // and `typeclaw init`. `retryHint` lets each caller append its own next step
214
+ // (e.g. "re-run `typeclaw init`" vs "retry `typeclaw start`").
215
+ export function renderDockerUnavailableGuidance(
216
+ availability: Extract<DockerAvailability, { ok: false }>,
217
+ options: {
218
+ platform: NodeJS.Platform
219
+ nudge: DockerApp | null
220
+ installed: DockerApp[]
221
+ retryHint?: string
222
+ },
223
+ ): { summary: string; lines: string[] } {
224
+ const { platform, nudge, installed, retryHint } = options
225
+
226
+ if (availability.reason === 'binary-missing') {
227
+ const lines = [...INSTALL_LINES]
228
+ if (retryHint) {
229
+ lines.push('', retryHint)
230
+ }
231
+ return { summary: 'Docker is not installed.', lines }
232
+ }
233
+
234
+ // daemon-down
235
+ const lines: string[] = []
236
+ let summary: string
237
+ if (nudge !== null) {
238
+ summary = `Docker is not running. ${dockerAppLabel(nudge)} is installed but not started.`
239
+ lines.push(...startInstructions(nudge, platform))
240
+ } else if (installed.length > 1) {
241
+ const names = installed.map(dockerAppLabel).join(', ')
242
+ summary = 'Docker is not running.'
243
+ lines.push(`Detected: ${names}. Start whichever one you use, then retry.`)
244
+ } else {
245
+ summary = 'Docker is installed but the daemon is not reachable.'
246
+ lines.push(...genericStartInstructions(platform))
247
+ }
248
+
249
+ if (retryHint) {
250
+ lines.push('', retryHint)
251
+ }
252
+ return { summary, lines }
253
+ }
@@ -1,3 +1,12 @@
1
+ export {
2
+ classifyConfiguredRuntime,
3
+ detectInstalledDockerApps,
4
+ dockerAppLabel,
5
+ pickRuntimeToNudge,
6
+ renderDockerUnavailableGuidance,
7
+ type DockerApp,
8
+ type DockerAppProbes,
9
+ } from './docker-app'
1
10
  export { buildDockerLogsCmd, logs, parseTailValue, planLogs, type LogsPlan, type LogsResult } from './logs'
2
11
  export { CONTAINER_PORT, TUI_TOKEN_LABEL, findFreePort, resolveHostPort, resolveTuiToken } from './port'
3
12
  export {
@@ -26,6 +35,8 @@ export {
26
35
  refreshDockerfile,
27
36
  refreshGitignore,
28
37
  start,
38
+ type CurrentHostDaemon,
39
+ type HostDaemonRegisterPayload,
29
40
  type HostDaemonStatus,
30
41
  type PlanStartOptions,
31
42
  type StartOptions,