typeclaw 0.39.0 → 0.39.2

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 (43) hide show
  1. package/README.md +1 -0
  2. package/package.json +2 -2
  3. package/src/agent/attention-escalation.ts +154 -4
  4. package/src/agent/git-nudge.ts +7 -7
  5. package/src/agent/session-origin.ts +21 -0
  6. package/src/bundled-plugins/backup/index.ts +5 -2
  7. package/src/bundled-plugins/backup/runner.ts +55 -23
  8. package/src/bundled-plugins/guard/policies/uncommitted-changes.ts +7 -8
  9. package/src/bundled-plugins/memory/dreaming.ts +37 -24
  10. package/src/channels/adapters/kakaotalk-membership.ts +67 -0
  11. package/src/channels/adapters/kakaotalk.ts +8 -0
  12. package/src/channels/adapters/line-token.ts +55 -0
  13. package/src/channels/adapters/line.ts +74 -0
  14. package/src/channels/adapters/webex-bot-classify.ts +14 -1
  15. package/src/channels/adapters/webex-bot.ts +24 -1
  16. package/src/channels/adapters/webex-classify.ts +16 -1
  17. package/src/channels/adapters/webex.ts +27 -1
  18. package/src/channels/router.ts +112 -13
  19. package/src/cli/hostd.ts +40 -0
  20. package/src/compose/logs.ts +20 -6
  21. package/src/config/config.ts +7 -5
  22. package/src/container/logs.ts +19 -4
  23. package/src/container/shared.ts +222 -18
  24. package/src/container/shell.ts +12 -2
  25. package/src/container/start.ts +191 -30
  26. package/src/doctor/commit.ts +10 -10
  27. package/src/dreams/git.ts +20 -7
  28. package/src/dreams/index.ts +22 -7
  29. package/src/git/reconcile-ignored.ts +56 -27
  30. package/src/git/resolve-agent-git.ts +12 -0
  31. package/src/git/system-commit.ts +16 -10
  32. package/src/hostd/daemon.ts +16 -0
  33. package/src/hostd/webex-renewal-manager.ts +216 -0
  34. package/src/init/auto-upgrade.ts +38 -4
  35. package/src/init/cli-version.ts +30 -1
  36. package/src/init/dockerfile.ts +31 -9
  37. package/src/init/gitignore.ts +4 -2
  38. package/src/init/index.ts +47 -39
  39. package/src/init/windows-dev-link.ts +64 -0
  40. package/src/secrets/schema.ts +1 -0
  41. package/src/secrets/webex-renewal.ts +215 -0
  42. package/src/server/index.ts +25 -3
  43. package/typeclaw.schema.json +6 -1
@@ -1,30 +1,60 @@
1
1
  import { createHash } from 'node:crypto'
2
- import { basename, resolve } from 'node:path'
2
+ import { existsSync } from 'node:fs'
3
+ import { homedir } from 'node:os'
4
+ import { basename, join as joinPath, resolve, win32 } from 'node:path'
5
+
6
+ import { isWindows } from '@/shared'
3
7
 
4
8
  export type DockerExecResult = { exitCode: number; stdout: string; stderr: string }
5
9
 
6
- export type DockerExec = (
7
- args: string[],
8
- options?: { cwd?: string; inheritStdio?: boolean; signal?: AbortSignal },
9
- ) => Promise<DockerExecResult>
10
+ export type DockerExecOptions = {
11
+ cwd?: string
12
+ inheritStdio?: boolean
13
+ signal?: AbortSignal
14
+ // Extra environment for the docker child, merged over process.env. Used to
15
+ // thread DOCKER_CONFIG when retrying a build under a sanitized config that
16
+ // strips a broken credential helper (see runImageBuild).
17
+ env?: Record<string, string | undefined>
18
+ // Only meaningful with inheritStdio: mirror the child's stderr to the parent
19
+ // terminal AND capture it into the returned `stderr`. Lets a streamed build
20
+ // stay visible to the user while start() still inspects stderr to detect the
21
+ // missing-credential-helper failure and decide whether to retry.
22
+ captureStderr?: boolean
23
+ }
24
+
25
+ export type DockerExec = (args: string[], options?: DockerExecOptions) => Promise<DockerExecResult>
10
26
 
11
27
  export const defaultDockerExec: DockerExec = async (args, options) => {
12
28
  const bun = getBun()
13
29
  if (!bun) return { exitCode: -1, stdout: '', stderr: 'bun runtime not available' }
14
- // Bun.spawn throws synchronously with code 'ENOENT' when docker isn't on
15
- // $PATH (rather than returning a non-zero exit). Two overloads (pipe vs
16
- // inherit) so each spawn call site has the literal stdout/stderr type
17
- // attached — that's what lets `new Response(proc.stdout)` typecheck on
18
- // the piped path. `signal` is forwarded to Bun.spawn so callers can bound
19
- // long-running docker subcommands (e.g. `docker logs` on a stuck daemon).
30
+ // Resolve `docker` to an absolute path before spawning. Bun.spawn() resolves
31
+ // a bare command name through Bun.which() internally, but Windows PATH/PATHEXT
32
+ // resolution has a string of historical bugs (oven-sh/bun#16070, #11182,
33
+ // #29636) that make `cmd: ['docker', …]` throw ENOENT even when Docker
34
+ // Desktop is installed and docker.exe is on %PATH% — surfacing as the
35
+ // misleading "Docker is not installed." on a machine that has Docker.
36
+ // dockerCmd() goes through Bun.which(), which reliably honors PATHEXT and
37
+ // returns the full docker.exe path; it returns null only when docker is
38
+ // genuinely absent from PATH, which maps to the binary-missing sentinel.
39
+ const cmd = dockerCmd(args)
40
+ if (cmd === null) return { exitCode: -1, stdout: '', stderr: DOCKER_NOT_FOUND_STDERR }
41
+ // Two overloads (pipe vs inherit) so each spawn call site has the literal
42
+ // stdout/stderr type attached — that's what lets `new Response(proc.stdout)`
43
+ // typecheck on the piped path. `signal` is forwarded to Bun.spawn so callers
44
+ // can bound long-running docker subcommands (e.g. `docker logs` on a stuck
45
+ // daemon). The ENOENT catch stays as a safety net for the race where the
46
+ // binary disappears between resolution and spawn.
47
+ const env = options?.env ? { ...process.env, ...options.env } : undefined
20
48
  if (options?.inheritStdio) {
21
49
  try {
50
+ if (options.captureStderr) return await spawnInheritTeeStderr(bun, cmd, options.cwd, options.signal, env)
22
51
  const proc = bun.spawn({
23
- cmd: ['docker', ...args],
52
+ cmd,
24
53
  cwd: options.cwd,
25
54
  stdout: 'inherit',
26
55
  stderr: 'inherit',
27
56
  signal: options.signal,
57
+ env,
28
58
  })
29
59
  return { exitCode: await proc.exited, stdout: '', stderr: '' }
30
60
  } catch (error) {
@@ -36,11 +66,12 @@ export const defaultDockerExec: DockerExec = async (args, options) => {
36
66
  }
37
67
  try {
38
68
  const proc = bun.spawn({
39
- cmd: ['docker', ...args],
69
+ cmd,
40
70
  cwd: options?.cwd,
41
71
  stdout: 'pipe',
42
72
  stderr: 'pipe',
43
73
  signal: options?.signal,
74
+ env,
44
75
  })
45
76
  const exitCode = await proc.exited
46
77
  const stdout = await new Response(proc.stdout).text()
@@ -54,11 +85,121 @@ export const defaultDockerExec: DockerExec = async (args, options) => {
54
85
  }
55
86
  }
56
87
 
57
- // Sentinel stderr from defaultDockerExec when Bun.spawn throws ENOENT.
88
+ // Streams a docker child's stdout straight to the parent terminal while teeing
89
+ // stderr to BOTH the terminal and a buffer. A plain `stderr: 'inherit'` would
90
+ // keep the build output live but leave start() blind to the failure reason;
91
+ // piping stderr alone would swallow the user-visible progress. The build path
92
+ // needs both: the user watches the build, and start() inspects the captured
93
+ // stderr to detect a missing credential helper and retry under a sanitized
94
+ // DOCKER_CONFIG.
95
+ async function spawnInheritTeeStderr(
96
+ bun: NonNullable<ReturnType<typeof getBun>>,
97
+ cmd: string[],
98
+ cwd: string | undefined,
99
+ signal: AbortSignal | undefined,
100
+ env: NodeJS.ProcessEnv | undefined,
101
+ ): Promise<DockerExecResult> {
102
+ const proc = bun.spawn({ cmd, cwd, stdout: 'inherit', stderr: 'pipe', signal, env })
103
+ const chunks: Uint8Array[] = []
104
+ const reader = proc.stderr.getReader()
105
+ for (;;) {
106
+ const { done, value } = await reader.read()
107
+ if (done) break
108
+ process.stderr.write(value)
109
+ chunks.push(value)
110
+ }
111
+ const exitCode = await proc.exited
112
+ return { exitCode, stdout: '', stderr: Buffer.concat(chunks).toString('utf8') }
113
+ }
114
+
115
+ // Sentinel stderr from defaultDockerExec when docker can't be resolved/spawned.
58
116
  // checkDockerAvailable matches on this exact string to distinguish
59
117
  // "binary missing" from "daemon down".
60
118
  export const DOCKER_NOT_FOUND_STDERR = 'docker: command not found in $PATH'
61
119
 
120
+ export type DockerBinaryProbes = {
121
+ which?: (command: string) => string | null
122
+ platform?: NodeJS.Platform
123
+ env?: NodeJS.ProcessEnv
124
+ exists?: (path: string) => boolean
125
+ }
126
+
127
+ // Resolves the `docker` binary to an absolute path. First via Bun.which(),
128
+ // which — unlike a bare `cmd: ['docker']` handed to Bun.spawn() — reliably
129
+ // honors Windows PATHEXT and returns e.g. C:\…\docker.exe. On POSIX the
130
+ // resolved path equals what the bare name would have found.
131
+ //
132
+ // When Bun.which() finds nothing on Windows we fall back to Docker Desktop's
133
+ // known install locations: its installer registers docker.exe on the SYSTEM
134
+ // PATH, so a shell/process started before the install (or with a customized
135
+ // PATH) inherits a stale PATH where Bun.which can't see docker even though the
136
+ // binary exists and the engine is running — the real-world "Docker is not
137
+ // installed" report on a machine with a working Docker. Probing these paths
138
+ // fixes detection without a reinstall or PATH edit. The MS-Store packaged
139
+ // build is deliberately NOT probed: its binary lives in ACL-locked
140
+ // WindowsApps and can't be executed by a child process anyway.
141
+ //
142
+ // Returns null when docker is genuinely absent, which callers translate into
143
+ // the binary-missing sentinel. Probes are injectable so tests stay
144
+ // deterministic without depending on a real docker install or host platform.
145
+ export function resolveDockerBinary(probes: DockerBinaryProbes = {}): string | null {
146
+ const which = probes.which ?? ((command: string) => getBun()?.which(command) ?? null)
147
+ const fromPath = which('docker')
148
+ if (fromPath !== null) return fromPath
149
+
150
+ const platform = probes.platform ?? process.platform
151
+ if (!isWindows(platform)) return null
152
+
153
+ const exists = probes.exists ?? existsSync
154
+ for (const candidate of windowsDockerCandidates(probes.env ?? process.env)) {
155
+ if (exists(candidate)) return candidate
156
+ }
157
+ return null
158
+ }
159
+
160
+ // Real, child-process-executable docker.exe locations across the common
161
+ // Windows install methods, most-canonical first. All are confirmed real
162
+ // binaries or executable shims (not ACL-locked WindowsApps Store stubs).
163
+ // Probe order prefers Docker Desktop, then package-manager Docker, then the
164
+ // standalone CLI, then the Rancher Desktop alternative runtime. An
165
+ // arbitrary `--installation-dir` install can't be enumerated and is left to
166
+ // Bun.which/PATH.
167
+ function windowsDockerCandidates(env: NodeJS.ProcessEnv): string[] {
168
+ const candidates: string[] = []
169
+ // win32.join (not the host-default join) so the probe builds backslash paths
170
+ // regardless of the host the resolver runs/tests on.
171
+ const add = (root: string | undefined, ...segments: string[]): void => {
172
+ if (root) candidates.push(win32.join(root, ...segments))
173
+ }
174
+ // ProgramW6432 covers a 32-bit Bun seeing the WOW64-redirected ProgramFiles.
175
+ const programFiles = env.ProgramW6432 ?? env.ProgramFiles ?? 'C:\\Program Files'
176
+ const programData = env.ProgramData ?? 'C:\\ProgramData'
177
+
178
+ // Docker Desktop: all-users, per-user, and the installer symlink dir.
179
+ add(programFiles, 'Docker', 'Docker', 'resources', 'bin', 'docker.exe')
180
+ add(env.LOCALAPPDATA, 'Programs', 'DockerDesktop', 'resources', 'bin', 'docker.exe')
181
+ add(programData, 'DockerDesktop', 'version-bin', 'docker.exe')
182
+ // Docker Desktop pre-3.3.1 layout (resources\docker.exe, no \bin).
183
+ add(programFiles, 'Docker', 'Docker', 'resources', 'docker.exe')
184
+ // Chocolatey and Scoop shims (executable redirectors, on PATH after install).
185
+ add(programData, 'chocolatey', 'bin', 'docker.exe')
186
+ add(env.USERPROFILE, 'scoop', 'shims', 'docker.exe')
187
+ // Standalone Docker CLI binary (Windows Server / manual `Expand-Archive`).
188
+ add(programFiles, 'Docker', 'docker.exe')
189
+ // Rancher Desktop's bundled Moby docker CLI (note the doubled `resources`).
190
+ add(programFiles, 'Rancher Desktop', 'resources', 'resources', 'win32', 'bin', 'docker.exe')
191
+ return candidates
192
+ }
193
+
194
+ // Builds the argv for a docker invocation with the binary resolved to an
195
+ // absolute path (see resolveDockerBinary). Returns null when docker is absent
196
+ // from PATH. The resolver is injectable so callers and tests stay deterministic
197
+ // without depending on a real docker install.
198
+ export function dockerCmd(args: string[], resolveBinary: () => string | null = resolveDockerBinary): string[] | null {
199
+ const binary = resolveBinary()
200
+ return binary === null ? null : [binary, ...args]
201
+ }
202
+
62
203
  // Collapse a multi-line `docker` CLI stderr into a single readable clause
63
204
  // suitable for inline `reason:` strings. The motivating case is `compose
64
205
  // restart`, which prints one row per agent — raw stderr from a failed
@@ -108,6 +249,65 @@ export async function buildxAvailable(exec: DockerExec = defaultDockerExec): Pro
108
249
  return (await exec(['buildx', 'version'])).exitCode === 0
109
250
  }
110
251
 
252
+ // Detects the specific failure where Docker's configured credential helper
253
+ // binary (`docker-credential-<name>`, from `credsStore`/`credHelpers` in
254
+ // ~/.docker/config.json) is not on PATH, so docker aborts EVERY registry
255
+ // interaction — including anonymous pulls of the PUBLIC images typeclaw builds
256
+ // from. The canonical Windows case is a broken Docker Desktop install:
257
+ // error getting credentials - err: exec: "docker-credential-desktop":
258
+ // executable file not found in %PATH%
259
+ //
260
+ // Kept deliberately narrow (helper token + "credentials" + a not-found phrase)
261
+ // so a genuine private-registry auth failure is NOT mistaken for this and
262
+ // silently retried anonymously. Docker/BuildKit emit these as English Go/CLI
263
+ // runtime strings (not localized user text), so English matching is correct;
264
+ // the not-found phrasings cover Linux (`executable file not found`), Windows
265
+ // (`not recognized` / `cannot find the file`), and generic (`no such file`).
266
+ export function isMissingDockerCredentialHelper(stderr: string): boolean {
267
+ const text = stderr.toLowerCase()
268
+ const namesHelper = /docker-credential-[\w.-]+/i.test(stderr)
269
+ const aboutCredentials = text.includes('getting credentials') || text.includes('credential')
270
+ const notFound =
271
+ text.includes('executable file not found') ||
272
+ text.includes('no such file') ||
273
+ text.includes('cannot find the file') ||
274
+ text.includes('not recognized') ||
275
+ text.includes('not found in %path%') ||
276
+ text.includes('not found in $path')
277
+ return namesHelper && aboutCredentials && notFound
278
+ }
279
+
280
+ type DockerConfigJson = Record<string, unknown> & { credsStore?: unknown; credHelpers?: unknown }
281
+
282
+ // Resolves the effective Docker config dir the same way the docker CLI does:
283
+ // $DOCKER_CONFIG wins, else ~/.docker.
284
+ export function dockerConfigDir(env: NodeJS.ProcessEnv = process.env, home: string = homedir()): string {
285
+ return env.DOCKER_CONFIG ?? joinPath(home, '.docker')
286
+ }
287
+
288
+ // Produces the JSON for a sanitized Docker config that drops ONLY the broken
289
+ // credential-helper hooks while preserving everything operationally relevant —
290
+ // inline `auths` (base64 creds for private mirrors), `proxies`, `currentContext`,
291
+ // `HttpHeaders`, plugin/feature flags. An empty `{}` would lose the user's
292
+ // context and proxy setup; copy-and-strip is the safe middle ground. The
293
+ // `contexts/` and `buildx/` subdirs are NOT copied here (they're referenced by
294
+ // path from the sanitized dir via the caller, which symlinks them) — this
295
+ // function only owns config.json's contents. Returns null when there is nothing
296
+ // to strip, signalling the caller to skip the retry entirely.
297
+ export function sanitizeDockerConfigJson(raw: string | null): string | null {
298
+ let parsed: DockerConfigJson = {}
299
+ if (raw !== null && raw.trim() !== '') {
300
+ try {
301
+ parsed = JSON.parse(raw) as DockerConfigJson
302
+ } catch {
303
+ parsed = {}
304
+ }
305
+ }
306
+ if (parsed.credsStore === undefined && parsed.credHelpers === undefined) return null
307
+ const { credsStore: _credsStore, credHelpers: _credHelpers, ...rest } = parsed
308
+ return JSON.stringify(rest, null, 2)
309
+ }
310
+
111
311
  export type BindMountSpec = { src: string; dst: string; readonly?: boolean }
112
312
 
113
313
  // Emits `--mount type=bind,...` argv for a host->container bind mount, used in
@@ -299,8 +499,10 @@ function sanitizeContainerName(name: string): string {
299
499
  export async function imageExists(tag: string): Promise<boolean> {
300
500
  const bun = getBun()
301
501
  if (!bun) return false
502
+ const cmd = dockerCmd(['image', 'inspect', tag])
503
+ if (cmd === null) return false
302
504
  const proc = bun.spawn({
303
- cmd: ['docker', 'image', 'inspect', tag],
505
+ cmd,
304
506
  stdout: 'pipe',
305
507
  stderr: 'pipe',
306
508
  })
@@ -323,8 +525,10 @@ export type ContainerState = { exists: false } | { exists: true; running: boolea
323
525
  export async function inspectContainer(name: string): Promise<ContainerState> {
324
526
  const bun = getBun()
325
527
  if (!bun) return { exists: false }
528
+ const cmd = dockerCmd(['inspect', '--format', '{{.State.Running}}', name])
529
+ if (cmd === null) return { exists: false }
326
530
  const proc = bun.spawn({
327
- cmd: ['docker', 'inspect', '--format', '{{.State.Running}}', name],
531
+ cmd,
328
532
  stdout: 'pipe',
329
533
  stderr: 'pipe',
330
534
  })
@@ -333,6 +537,6 @@ export async function inspectContainer(name: string): Promise<ContainerState> {
333
537
  return { exists: true, running: out === 'true' }
334
538
  }
335
539
 
336
- export function getBun(): { spawn: typeof Bun.spawn } | undefined {
337
- return (globalThis as { Bun?: { spawn: typeof Bun.spawn } }).Bun
540
+ export function getBun(): { spawn: typeof Bun.spawn; which: typeof Bun.which } | undefined {
541
+ return (globalThis as { Bun?: { spawn: typeof Bun.spawn; which: typeof Bun.which } }).Bun
338
542
  }
@@ -1,4 +1,4 @@
1
- import { containerNameFromCwd, getBun, inspectContainer, type ContainerState } from './shared'
1
+ import { containerNameFromCwd, dockerCmd, getBun, inspectContainer, type ContainerState } from './shared'
2
2
 
3
3
  export type ShellPlan = {
4
4
  containerName: string
@@ -10,6 +10,7 @@ export type ShellResult = { ok: true; containerName: string; exitCode: number }
10
10
  type ShellDeps = {
11
11
  inspect?: (name: string) => Promise<ContainerState>
12
12
  spawn?: InteractiveSpawn
13
+ resolveDocker?: () => string | null
13
14
  }
14
15
 
15
16
  type InteractiveSpawn = (options: {
@@ -30,6 +31,15 @@ export async function shell(
30
31
 
31
32
  const { containerName, shell: plannedShell } = planShell(cwd, { shell: shellPath })
32
33
 
34
+ // Resolve docker before inspecting: inspectContainer collapses a missing
35
+ // docker binary into { exists: false }, so deferring this check would
36
+ // surface the misleading "Container … not found" instead of the real
37
+ // "Docker is not installed" on a host without docker on PATH.
38
+ const cmd = dockerCmd(['exec', '-it', containerName, plannedShell], deps.resolveDocker)
39
+ if (cmd === null) {
40
+ return { ok: false, reason: 'Docker is not installed (docker not found on PATH).' }
41
+ }
42
+
33
43
  try {
34
44
  const state = await (deps.inspect ?? inspectContainer)(containerName)
35
45
  if (!state.exists) {
@@ -40,7 +50,7 @@ export async function shell(
40
50
  }
41
51
 
42
52
  const proc = spawn({
43
- cmd: ['docker', 'exec', '-it', containerName, plannedShell],
53
+ cmd,
44
54
  cwd,
45
55
  stdin: 'inherit',
46
56
  stdout: 'inherit',