typeclaw 0.39.1 → 0.39.3

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 (79) hide show
  1. package/auth.schema.json +110 -0
  2. package/package.json +2 -2
  3. package/secrets.schema.json +110 -0
  4. package/src/agent/index.ts +44 -19
  5. package/src/agent/plugin-tools.ts +12 -12
  6. package/src/agent/session-origin.ts +2 -0
  7. package/src/agent/todo/store.ts +21 -1
  8. package/src/agent/tools/channel-reply.ts +18 -5
  9. package/src/agent/tools/channel-send.ts +13 -2
  10. package/src/bundled-plugins/doc-render/render.ts +2 -2
  11. package/src/bundled-plugins/github-cli-auth/approve-idempotency.ts +40 -18
  12. package/src/channels/adapters/discord-author-resolver.ts +52 -0
  13. package/src/channels/adapters/discord-bot.ts +1 -1
  14. package/src/channels/adapters/discord-channel-resolver.ts +44 -0
  15. package/src/channels/adapters/discord-classify.ts +121 -0
  16. package/src/channels/adapters/discord-reactions.ts +138 -0
  17. package/src/channels/adapters/discord.ts +416 -0
  18. package/src/channels/adapters/github/outbound.ts +23 -4
  19. package/src/channels/adapters/kakaotalk.ts +8 -1
  20. package/src/channels/adapters/line.ts +1 -1
  21. package/src/channels/adapters/slack-author-resolver.ts +54 -0
  22. package/src/channels/adapters/slack-bot.ts +3 -1
  23. package/src/channels/adapters/slack-channel-resolver.ts +49 -0
  24. package/src/channels/adapters/slack-classify.ts +83 -0
  25. package/src/channels/adapters/slack-reactions.ts +126 -0
  26. package/src/channels/adapters/slack.ts +416 -0
  27. package/src/channels/adapters/telegram-bot.ts +2 -1
  28. package/src/channels/adapters/webex-bot.ts +5 -2
  29. package/src/channels/adapters/webex.ts +55 -2
  30. package/src/channels/github-review-turn-ledger.ts +32 -0
  31. package/src/channels/github-verdict-activity.ts +60 -0
  32. package/src/channels/index.ts +6 -0
  33. package/src/channels/manager.ts +130 -6
  34. package/src/channels/pr-verdict-activity-bridge.ts +43 -0
  35. package/src/channels/router.ts +218 -20
  36. package/src/channels/schema.ts +4 -0
  37. package/src/channels/types.ts +17 -1
  38. package/src/cli/builtins.ts +1 -0
  39. package/src/cli/channel.ts +170 -18
  40. package/src/cli/index.ts +11 -0
  41. package/src/cli/init.ts +2 -0
  42. package/src/cli/update-check.ts +14 -0
  43. package/src/cli/update-notify.ts +91 -0
  44. package/src/cli/update-suppression.ts +19 -0
  45. package/src/compose/logs.ts +20 -6
  46. package/src/config/channels-mutation.ts +3 -1
  47. package/src/config/config.ts +51 -0
  48. package/src/config/index.ts +1 -0
  49. package/src/container/logs.ts +19 -4
  50. package/src/container/shared.ts +108 -5
  51. package/src/container/start.ts +218 -33
  52. package/src/doctor/channel-checks.ts +57 -3
  53. package/src/hostd/daemon.ts +22 -5
  54. package/src/hostd/index.ts +11 -1
  55. package/src/hostd/paths.ts +4 -0
  56. package/src/hostd/protocol.ts +15 -2
  57. package/src/init/auto-upgrade.ts +38 -4
  58. package/src/init/cli-version.ts +31 -2
  59. package/src/init/discord-auth.ts +50 -0
  60. package/src/init/dockerfile.ts +18 -5
  61. package/src/init/index.ts +140 -42
  62. package/src/init/reconcile-plugin-deps.ts +30 -5
  63. package/src/init/run-owner-claim.ts +2 -0
  64. package/src/init/slack-auth.ts +51 -0
  65. package/src/init/windows-dev-link.ts +64 -0
  66. package/src/mcp/manager.ts +94 -7
  67. package/src/mcp/tools.ts +7 -4
  68. package/src/permissions/resolve.ts +2 -0
  69. package/src/role-claim/match-rule.ts +2 -0
  70. package/src/run/index.ts +74 -29
  71. package/src/secrets/discord-store.ts +96 -0
  72. package/src/secrets/schema.ts +34 -0
  73. package/src/secrets/slack-store.ts +96 -0
  74. package/src/server/command-runner.ts +21 -0
  75. package/src/skills/typeclaw-cron/SKILL.md +13 -2
  76. package/src/tui/format.ts +0 -19
  77. package/src/tui/index.ts +2 -8
  78. package/src/update/check.ts +192 -0
  79. package/typeclaw.schema.json +332 -0
@@ -1,15 +1,28 @@
1
1
  import { createHash } from 'node:crypto'
2
2
  import { existsSync } from 'node:fs'
3
- import { basename, resolve, win32 } from 'node:path'
3
+ import { homedir } from 'node:os'
4
+ import { basename, join as joinPath, resolve, win32 } from 'node:path'
4
5
 
5
6
  import { isWindows } from '@/shared'
6
7
 
7
8
  export type DockerExecResult = { exitCode: number; stdout: string; stderr: string }
8
9
 
9
- export type DockerExec = (
10
- args: string[],
11
- options?: { cwd?: string; inheritStdio?: boolean; signal?: AbortSignal },
12
- ) => 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>
13
26
 
14
27
  export const defaultDockerExec: DockerExec = async (args, options) => {
15
28
  const bun = getBun()
@@ -31,14 +44,17 @@ export const defaultDockerExec: DockerExec = async (args, options) => {
31
44
  // can bound long-running docker subcommands (e.g. `docker logs` on a stuck
32
45
  // daemon). The ENOENT catch stays as a safety net for the race where the
33
46
  // binary disappears between resolution and spawn.
47
+ const env = options?.env ? { ...process.env, ...options.env } : undefined
34
48
  if (options?.inheritStdio) {
35
49
  try {
50
+ if (options.captureStderr) return await spawnInheritTeeStderr(bun, cmd, options.cwd, options.signal, env)
36
51
  const proc = bun.spawn({
37
52
  cmd,
38
53
  cwd: options.cwd,
39
54
  stdout: 'inherit',
40
55
  stderr: 'inherit',
41
56
  signal: options.signal,
57
+ env,
42
58
  })
43
59
  return { exitCode: await proc.exited, stdout: '', stderr: '' }
44
60
  } catch (error) {
@@ -55,6 +71,7 @@ export const defaultDockerExec: DockerExec = async (args, options) => {
55
71
  stdout: 'pipe',
56
72
  stderr: 'pipe',
57
73
  signal: options?.signal,
74
+ env,
58
75
  })
59
76
  const exitCode = await proc.exited
60
77
  const stdout = await new Response(proc.stdout).text()
@@ -68,6 +85,33 @@ export const defaultDockerExec: DockerExec = async (args, options) => {
68
85
  }
69
86
  }
70
87
 
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
+
71
115
  // Sentinel stderr from defaultDockerExec when docker can't be resolved/spawned.
72
116
  // checkDockerAvailable matches on this exact string to distinguish
73
117
  // "binary missing" from "daemon down".
@@ -205,6 +249,65 @@ export async function buildxAvailable(exec: DockerExec = defaultDockerExec): Pro
205
249
  return (await exec(['buildx', 'version'])).exitCode === 0
206
250
  }
207
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
+
208
311
  export type BindMountSpec = { src: string; dst: string; readonly?: boolean }
209
312
 
210
313
  // Emits `--mount type=bind,...` argv for a host->container bind mount, used in
@@ -1,7 +1,8 @@
1
1
  import { randomBytes } from 'node:crypto'
2
2
  import { existsSync } from 'node:fs'
3
- import { readFile, writeFile } from 'node:fs/promises'
4
- import { isAbsolute, join, resolve } from 'node:path'
3
+ import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import { isAbsolute, join, relative, resolve } from 'node:path'
5
6
 
6
7
  import { agentUsesVector } from '@/bundled-plugins/memory/vector/config'
7
8
  import { expandMountPath, loadConfigSync, withDefaultPlugins, type Config } from '@/config'
@@ -17,15 +18,17 @@ import {
17
18
  type AutoUpgradeOutcome,
18
19
  expectedInstalledAfterUpgrade,
19
20
  outcomeForcesInstall,
21
+ outcomeRequiresForceInstall,
20
22
  readInstalledTypeclawVersionFromAgent,
21
23
  } from '@/init/auto-upgrade'
22
- import { resolveBaseImageVersion } from '@/init/cli-version'
24
+ import { resolveBaseImageVersion, resolveTypeclawSpec, typeclawCheckoutRoot } from '@/init/cli-version'
23
25
  import { buildDockerfile, classifyDockerfileAppend, DOCKERFILE } from '@/init/dockerfile'
24
26
  import { ensureDepsInstalled, type EnsureDepsResult } from '@/init/ensure-deps'
25
27
  import { buildGitignore, GITIGNORE_FILE } from '@/init/gitignore'
26
28
  import { refreshPackageJson } from '@/init/packagejson'
27
29
  import { reconcilePluginDeps } from '@/init/reconcile-plugin-deps'
28
30
  import { runBunUpdate, type UpdateRunner } from '@/init/run-bun-install'
31
+ import { linkWindowsDevTypeclaw, resolveBunLinkedPackage, type RunBunLink } from '@/init/windows-dev-link'
29
32
  import { isWindows } from '@/shared'
30
33
  import { hostLocaleIsCjk } from '@/shared/host-locale'
31
34
 
@@ -39,14 +42,19 @@ import {
39
42
  type DockerExec,
40
43
  type DockerExecResult,
41
44
  dockerBindMount,
45
+ dockerConfigDir,
42
46
  imageTagFromCwd,
43
47
  isContainerNameConflict,
48
+ isMissingDockerCredentialHelper,
49
+ sanitizeDockerConfigJson,
44
50
  sanitizeDockerStderr,
45
51
  waitForRemoval,
46
52
  } from './shared'
47
53
  import { buildCrashReason, createVerifyRunning, type VerifyRunningFn } from './verify-running'
48
54
 
49
55
  const PACKAGE_FILE = 'package.json'
56
+ const TYPECLAW_PACKAGE = 'typeclaw'
57
+ const DEV_SOURCE_CONTAINER_PATH = '/agent/node_modules/typeclaw'
50
58
  const BUN_LOCK_FILE = 'bun.lock'
51
59
  const DEPENDENCY_FILES = [PACKAGE_FILE, BUN_LOCK_FILE] as const
52
60
  const ENV_FILE = '.env'
@@ -75,6 +83,9 @@ export type PlanStartOptions = {
75
83
  hostdControl?: HostDaemonControl
76
84
  publishHost?: string
77
85
  tuiToken?: string | null
86
+ // Defaults to `process.platform`; tests inject it to exercise the native-
87
+ // Windows dev-source mount branch without running on a Windows host.
88
+ platform?: NodeJS.Platform
78
89
  }
79
90
 
80
91
  export type HostDaemonControl = {
@@ -123,6 +134,13 @@ export type StartOptions = {
123
134
  // function to override the wait window or to bypass verification entirely
124
135
  // (e.g. a no-op `async () => ({ ok: true })` for unit tests that don't care).
125
136
  verifyRunning?: VerifyRunningFn
137
+ // Test seam for the native-Windows dev-link step run before ensureDeps when a
138
+ // local-checkout reconcile emits `link:typeclaw`. Defaults to `bun link` in
139
+ // the checkout. Mirrors init's `runBunLink` seam.
140
+ runBunLink?: RunBunLink
141
+ // Defaults to `process.platform`; tests inject it to exercise the
142
+ // native-Windows dev-link reconcile path off a non-Windows runner.
143
+ platform?: NodeJS.Platform
126
144
  }
127
145
 
128
146
  export type HostDaemonStatus =
@@ -166,10 +184,12 @@ export async function start({
166
184
  cliEntry,
167
185
  reuseCurrentHostDaemon = false,
168
186
  ensureDeps = (dir, opts) => ensureDepsInstalled({ cwd: dir, ...opts }),
169
- autoUpgrade = (dir) => autoUpgradeTypeclawDep({ cwd: dir }),
187
+ autoUpgrade = (dir) => autoUpgradeTypeclawDep({ cwd: dir, localSpec: resolveTypeclawSpec(dir) }),
170
188
  forceBunUpdate = runBunUpdate,
171
189
  readInstalledVersion = readInstalledTypeclawVersionFromAgent,
172
190
  verifyRunning = createVerifyRunning({ exec }),
191
+ runBunLink,
192
+ platform = process.platform,
173
193
  }: StartOptions): Promise<StartResult> {
174
194
  try {
175
195
  const containerName = containerNameFromCwd(cwd)
@@ -234,6 +254,32 @@ export async function start({
234
254
  // image to a fresh container build.
235
255
  const upgrade = await autoUpgrade(cwd)
236
256
  const upgradeCommitMessage = commitMessageForAutoUpgrade(upgrade)
257
+ // Any agent on a `link:typeclaw` spec (native-Windows dev) needs the
258
+ // checkout registered with `bun link` BEFORE ensureDeps, exactly as init's
259
+ // maybeLinkWindowsDevTypeclaw does — otherwise bun can't resolve the link:
260
+ // spec. We gate on the EFFECTIVE on-disk spec, not the transition outcome:
261
+ // a prior start that wrote `link:` but failed/interrupted before
262
+ // registering would otherwise leave the next start (which sees the spec
263
+ // already local → skipped-dev-mode) reaching ensureDeps unregistered.
264
+ // `bun link` is idempotent, so re-running it on every link: start is safe
265
+ // and self-heals that gap. No-op off Windows (linkWindowsDevTypeclaw → null).
266
+ // True when this is a native-Windows agent on a `link:typeclaw` spec, after
267
+ // (re)registering its checkout. Forces ensureDeps below: ensureDeps' drift
268
+ // detector only looks for MISSING dep names, so a stale npm-installed
269
+ // node_modules/typeclaw left by an interrupted relink would make it skip the
270
+ // install and leave the agent on the old runtime. Forcing materializes the
271
+ // link. Off Windows / non-link specs this stays false.
272
+ let registeredWindowsLink = false
273
+ if ((await readTypeclawDepSpec(cwd))?.startsWith('link:') === true) {
274
+ const checkout = typeclawCheckoutRoot()
275
+ if (checkout !== null) {
276
+ const linked = await linkWindowsDevTypeclaw(checkout, {
277
+ platform,
278
+ ...(runBunLink !== undefined ? { runBunLink } : {}),
279
+ })
280
+ registeredWindowsLink = linked !== null
281
+ }
282
+ }
237
283
  if (outcomeForcesInstall(upgrade)) {
238
284
  const forced = await forceBunUpdate(cwd, 'typeclaw')
239
285
  if (!forced.ok) {
@@ -284,7 +330,11 @@ export async function start({
284
330
  // version bump (dir already present) or a removal (stale dir left behind)
285
331
  // would otherwise leave bun.lock/node_modules out of sync with the
286
332
  // reconciled package.json.
287
- const forceDepsReinstall = (forceBuild && (await hasLocallyLinkedTypeclawDep(cwd))) || pluginReconcile.changed
333
+ const forceDepsReinstall =
334
+ (forceBuild && (await hasLocallyLinkedTypeclawDep(cwd))) ||
335
+ pluginReconcile.changed ||
336
+ outcomeRequiresForceInstall(upgrade) ||
337
+ registeredWindowsLink
288
338
  const deps = await ensureDeps(cwd, { force: forceDepsReinstall })
289
339
  if (!deps.ok) {
290
340
  return { ok: false, reason: `dependency install failed: ${deps.reason}` }
@@ -388,6 +438,7 @@ export async function start({
388
438
  hostdControl,
389
439
  publishHost,
390
440
  tuiToken,
441
+ platform,
391
442
  })
392
443
 
393
444
  let built = false
@@ -463,6 +514,7 @@ export async function start({
463
514
  hostdControl,
464
515
  publishHost,
465
516
  tuiToken,
517
+ platform,
466
518
  })
467
519
  run = await execRunWithConflictRetry(exec, plan.runArgs, cwd, containerName)
468
520
  }
@@ -501,6 +553,7 @@ export async function start({
501
553
  function commitMessageForAutoUpgrade(outcome: AutoUpgradeOutcome): string | null {
502
554
  if (outcome.kind === 'spec-rewritten') return `Upgrade typeclaw to ${outcome.to}`
503
555
  if (outcome.kind === 'reinstall-needed') return `Upgrade typeclaw to ${outcome.to}`
556
+ if (outcome.kind === 'relinked-to-local') return `Link typeclaw to local checkout (${outcome.to})`
504
557
  return null
505
558
  }
506
559
 
@@ -524,6 +577,7 @@ export async function planStart({
524
577
  hostdControl,
525
578
  publishHost = '127.0.0.1',
526
579
  tuiToken = null,
580
+ platform = process.platform,
527
581
  }: PlanStartOptions): Promise<StartPlan> {
528
582
  const containerName = containerNameFromCwd(cwd)
529
583
  const imageTag = imageTagFromCwd(cwd)
@@ -660,8 +714,10 @@ export async function planStart({
660
714
 
661
715
  runArgs.push(...dockerBindMount({ src: cwd, dst: '/agent' }))
662
716
 
663
- if (shouldMirrorDevSource(devSourcePath, cwd)) {
717
+ if (shouldMirrorDevSource(devSourcePath, cwd, platform)) {
664
718
  runArgs.push(...dockerBindMount({ src: devSourcePath, dst: devSourcePath, readonly: true }))
719
+ } else if (shouldMountWindowsDevSource(devSourcePath, cwd, platform)) {
720
+ runArgs.push(...dockerBindMount({ src: devSourcePath, dst: DEV_SOURCE_CONTAINER_PATH, readonly: true }))
665
721
  }
666
722
 
667
723
  for (const mount of mounts) {
@@ -711,8 +767,16 @@ export async function refreshDockerfile(
711
767
  opts: { buildKit?: boolean } = {},
712
768
  ): Promise<{ changed: boolean; warnings: string[] }> {
713
769
  const cfg = await loadTypeclawConfig(cwd)
770
+ // A local-spec (`file:`/`link:`) dev install must inline the heavy stack: its
771
+ // unreleased version has no published `typeclaw-base` tag, and
772
+ // resolveBaseImageVersion prefers node_modules/typeclaw/package.json#version —
773
+ // which `ensureDeps` has already materialized by the time start() calls this —
774
+ // so without the gate a release-shaped dev version pins a nonexistent
775
+ // `FROM ghcr.io/...:<version>`. `null` selects the inline `oven/bun:1-slim`
776
+ // path. Mirrors the same gate in writeDockerAssets (src/init/index.ts).
777
+ const devMode = await hasLocallyLinkedTypeclawDep(cwd)
714
778
  const next = buildDockerfile(cfg.docker.file, {
715
- baseImageVersion: resolveBaseImageVersion(cwd),
779
+ baseImageVersion: devMode ? null : resolveBaseImageVersion(cwd),
716
780
  cjkFontsAuto: hostLocaleIsCjk(),
717
781
  buildKit: opts.buildKit,
718
782
  })
@@ -733,6 +797,16 @@ export async function refreshDockerfile(
733
797
  // `docker build`. The user sees one successful `typeclaw start` instead of a
734
798
  // buildx-specific dead end. A genuine Dockerfile error fails both paths, so the
735
799
  // retry costs at most one extra attempt before the real error surfaces.
800
+ //
801
+ // Layered on top is a credential-helper recovery: typeclaw only pulls PUBLIC
802
+ // images (the BuildKit syntax frontend + the typeclaw-base FROM), but a broken
803
+ // `credsStore`/`credHelpers` in ~/.docker/config.json makes docker abort the
804
+ // pull trying to exec a helper binary that isn't on PATH (the canonical Windows
805
+ // Docker Desktop failure). When a build fails with exactly that signature we
806
+ // retry the SAME build under a sanitized DOCKER_CONFIG that strips only the
807
+ // broken helper hooks — anonymous pulls then succeed and the user's real config
808
+ // is left untouched. This is checked BEFORE the buildx->legacy strip so a
809
+ // cred-helper failure doesn't get misdiagnosed as a buildx problem.
736
810
  async function runImageBuild(args: {
737
811
  exec: DockerExec
738
812
  cwd: string
@@ -741,19 +815,93 @@ async function runImageBuild(args: {
741
815
  hasBuildx: boolean
742
816
  }): Promise<boolean> {
743
817
  const { exec, cwd, imageTag, buildContext, hasBuildx } = args
744
- if (hasBuildx) {
745
- // `--load` puts the image in the local store so the subsequent `docker run`
746
- // finds it. Non-default buildx drivers (docker-container, etc.) export to
747
- // the build cache ONLY without it; on the default `docker` driver --load is
748
- // already implied, so passing it unconditionally is a safe no-op there.
749
- const buildx = await exec(['buildx', 'build', '--load', '-t', imageTag, buildContext], { cwd, inheritStdio: true })
750
- if (buildx.exitCode === 0) return true
751
- // buildx failed — fall back to the legacy builder against a stripped
752
- // Dockerfile so a misconfigured-buildx host still ends up with an image.
753
- await refreshDockerfile(cwd, { buildKit: false })
818
+ const buildArgv = (frontend: 'buildx' | 'legacy'): string[] =>
819
+ frontend === 'buildx'
820
+ ? ['buildx', 'build', '--load', '-t', imageTag, buildContext]
821
+ : ['build', '-t', imageTag, buildContext]
822
+
823
+ let sanitizedConfig: SanitizedDockerConfig | null = null
824
+ const attempt = async (frontend: 'buildx' | 'legacy'): Promise<DockerExecResult> =>
825
+ exec(buildArgv(frontend), { cwd, inheritStdio: true, captureStderr: true, env: sanitizedConfig?.env })
826
+
827
+ try {
828
+ let frontend: 'buildx' | 'legacy' = hasBuildx ? 'buildx' : 'legacy'
829
+ let result = await attempt(frontend)
830
+ if (result.exitCode === 0) return true
831
+
832
+ // Same-frontend retry: a broken credential helper aborts the pull before
833
+ // the builder ever matters, so strip it and retry the identical build.
834
+ if (sanitizedConfig === null && isMissingDockerCredentialHelper(result.stderr)) {
835
+ sanitizedConfig = await createSanitizedDockerConfig()
836
+ if (sanitizedConfig) {
837
+ result = await attempt(frontend)
838
+ if (result.exitCode === 0) return true
839
+ }
840
+ }
841
+
842
+ if (frontend === 'buildx') {
843
+ // buildx failed for a non-cred reason — fall back to the legacy builder
844
+ // against a stripped Dockerfile so a misconfigured-buildx host still ends
845
+ // up with an image. The sanitized config (if any) carries into the retry.
846
+ await refreshDockerfile(cwd, { buildKit: false })
847
+ frontend = 'legacy'
848
+ result = await attempt(frontend)
849
+ if (result.exitCode === 0) return true
850
+ if (sanitizedConfig === null && isMissingDockerCredentialHelper(result.stderr)) {
851
+ sanitizedConfig = await createSanitizedDockerConfig()
852
+ if (sanitizedConfig) {
853
+ result = await attempt(frontend)
854
+ if (result.exitCode === 0) return true
855
+ }
856
+ }
857
+ }
858
+
859
+ if (sanitizedConfig !== null) {
860
+ process.stderr.write(
861
+ 'typeclaw: docker build still failed after retrying public image pulls without the configured ' +
862
+ 'credential helper. Your ~/.docker/config.json credsStore/credHelpers may be broken.\n',
863
+ )
864
+ }
865
+ return false
866
+ } finally {
867
+ await sanitizedConfig?.cleanup()
754
868
  }
755
- const legacy = await exec(['build', '-t', imageTag, buildContext], { cwd, inheritStdio: true })
756
- return legacy.exitCode === 0
869
+ }
870
+
871
+ type SanitizedDockerConfig = { env: { DOCKER_CONFIG: string }; cleanup: () => Promise<void> }
872
+
873
+ // Materializes a temp DOCKER_CONFIG dir that is a full DEEP COPY of the user's
874
+ // ~/.docker tree with only the broken credential-helper hooks stripped from the
875
+ // copied config.json. Returns null when there's nothing to strip (no creds
876
+ // hooks present), so the caller skips a pointless retry. Cleanup removes the dir
877
+ // on every build outcome.
878
+ //
879
+ // DOCKER_CONFIG is not just credentials: `contexts/` maps the current docker
880
+ // context (e.g. Docker Desktop's `desktop-linux`) to the daemon endpoint, and
881
+ // `buildx/` holds builder instance state. A relocated config missing those
882
+ // makes `docker buildx build` (and `docker build`, which Docker Desktop forwards
883
+ // to `buildx build --builder <currentContext>`) fail with `no builder
884
+ // "desktop-linux" found` — the exact second failure this replaces. The earlier
885
+ // approach symlinked those subdirs, but Windows `fs.symlink` throws EPERM
886
+ // without Developer Mode/admin, so the catch silently produced a config dir with
887
+ // the context/builder state ABSENT. A recursive copy is portable and preserves
888
+ // the full topology; only config.json is overwritten with the sanitized form.
889
+ async function createSanitizedDockerConfig(): Promise<SanitizedDockerConfig | null> {
890
+ const srcDir = dockerConfigDir()
891
+ const raw = await readFile(join(srcDir, 'config.json'), 'utf8').catch(() => null)
892
+ const sanitized = sanitizeDockerConfigJson(raw)
893
+ if (sanitized === null) return null
894
+
895
+ const dir = await mkdtemp(join(tmpdir(), 'typeclaw-dockercfg-'))
896
+ const cleanup = (): Promise<void> => rm(dir, { recursive: true, force: true })
897
+ try {
898
+ if (existsSync(srcDir)) await cp(srcDir, dir, { recursive: true, dereference: false })
899
+ await writeFile(join(dir, 'config.json'), sanitized)
900
+ } catch {
901
+ await cleanup()
902
+ return null
903
+ }
904
+ return { env: { DOCKER_CONFIG: dir }, cleanup }
757
905
  }
758
906
 
759
907
  export async function refreshGitignore(cwd: string): Promise<void> {
@@ -907,7 +1055,12 @@ async function detectDevSource(cwd: string): Promise<string | null> {
907
1055
  const raw = await readFile(join(cwd, PACKAGE_FILE), 'utf8')
908
1056
  const pkg = JSON.parse(raw) as { dependencies?: Record<string, string> }
909
1057
  const spec = pkg.dependencies?.typeclaw
910
- if (!spec || !spec.startsWith('file:')) return null
1058
+ if (typeof spec !== 'string') return null
1059
+ // Windows dev-mode declares `link:typeclaw` (a `bun link` registration);
1060
+ // the checkout path isn't in the spec, so resolve it from bun's global
1061
+ // link target. POSIX dev-mode declares `file:<rel>` and encodes the path.
1062
+ if (spec.startsWith('link:')) return resolveBunLinkedPackage(TYPECLAW_PACKAGE)
1063
+ if (!spec.startsWith('file:')) return null
911
1064
  const target = spec.slice('file:'.length)
912
1065
  return isAbsolute(target) ? resolve(target) : resolve(cwd, target)
913
1066
  } catch {
@@ -915,22 +1068,50 @@ async function detectDevSource(cwd: string): Promise<string | null> {
915
1068
  }
916
1069
  }
917
1070
 
918
- // Dev mode: node_modules/typeclaw is a symlink to an absolute host path outside
919
- // /agent. The mirror mount bind-mounts that path at the SAME path inside the
920
- // (Linux) container so the symlink resolves. That only works when the host path
921
- // is itself a valid Linux container path — true on POSIX, false on native
1071
+ // True when `child` is `parent` itself or nested beneath it. Lexical, not
1072
+ // realpath-aware — callers pass already-resolved absolute paths. Preferred over
1073
+ // `child.startsWith(parent)`, which mis-fires on sibling-prefix collisions
1074
+ // (`C:\foo` vs `C:\foobar`), trailing-separator skew, and would treat
1075
+ // `/srv/agentX` as inside `/srv/agent`. A dev source already inside the agent
1076
+ // folder is reachable through the `/agent` bind mount, so neither dev-source
1077
+ // branch should add a second mount for it.
1078
+ export function isPathInsideOrEqual(child: string, parent: string): boolean {
1079
+ const rel = relative(parent, child)
1080
+ return rel === '' || (!rel.startsWith('..') && !isAbsolute(rel))
1081
+ }
1082
+
1083
+ // POSIX dev mode: node_modules/typeclaw is a symlink to an absolute host path
1084
+ // outside /agent. The mirror mount bind-mounts that path at the SAME path inside
1085
+ // the (Linux) container so the symlink resolves. That only works when the host
1086
+ // path is itself a valid Linux container path — true on POSIX, false on native
922
1087
  // Windows where devSourcePath is `C:\...` (not an absolute Linux path, so it
923
- // cannot be a container mount `dst`, and the in-container symlink would point at
924
- // a Windows path regardless). Native-Windows dev-mode (file:/link: typeclaw dep)
925
- // needs the deferred symlink/junction translation in #899; until then we skip
926
- // the mirror mount rather than emit an invalid `dst`. End users install typeclaw
927
- // from npm (a registry spec, not file:), so they never hit this path.
1088
+ // cannot be a same-path container mount `dst`). Native Windows takes the
1089
+ // `shouldMountWindowsDevSource` branch instead (mount the checkout directly over
1090
+ // the in-container node_modules path). End users install typeclaw from npm (a
1091
+ // registry spec, not file:), so they never hit either dev path.
928
1092
  export function shouldMirrorDevSource(
929
1093
  devSourcePath: string | null,
930
1094
  cwd: string,
931
1095
  platform: NodeJS.Platform = process.platform,
932
1096
  ): devSourcePath is string {
933
- return devSourcePath !== null && !devSourcePath.startsWith(cwd) && !isWindows(platform)
1097
+ return devSourcePath !== null && !isPathInsideOrEqual(devSourcePath, cwd) && !isWindows(platform)
1098
+ }
1099
+
1100
+ // Native-Windows dev mode (#899): the host's `C:\...` checkout cannot be
1101
+ // same-path mirror-mounted into a Linux container. Instead, bind-mount the
1102
+ // checkout directly over the standard resolution path `/agent/node_modules/
1103
+ // typeclaw` inside the container, so Node/Bun resolve typeclaw from source
1104
+ // regardless of how the host materialized node_modules/typeclaw (a junction,
1105
+ // per prepareWindowsDevJunction). Like the POSIX branch, skip when the dev
1106
+ // source lives inside the agent folder: a `file:./vendor/typeclaw` checkout is
1107
+ // already exposed via the `/agent` mount, so a second mount is wrong. A
1108
+ // bun-linked (`link:`) checkout legitimately lives outside cwd and still mounts.
1109
+ export function shouldMountWindowsDevSource(
1110
+ devSourcePath: string | null,
1111
+ cwd: string,
1112
+ platform: NodeJS.Platform = process.platform,
1113
+ ): devSourcePath is string {
1114
+ return devSourcePath !== null && !isPathInsideOrEqual(devSourcePath, cwd) && isWindows(platform)
934
1115
  }
935
1116
 
936
1117
  // True when the agent's package.json declares typeclaw via `file:` or
@@ -942,14 +1123,18 @@ export function shouldMirrorDevSource(
942
1123
  // users (`^X.Y.Z`, `~X.Y.Z`, exact pins) pay nothing because their
943
1124
  // install path is already cache-correct.
944
1125
  async function hasLocallyLinkedTypeclawDep(cwd: string): Promise<boolean> {
1126
+ const spec = await readTypeclawDepSpec(cwd)
1127
+ return spec !== null && (spec.startsWith('file:') || spec.startsWith('link:'))
1128
+ }
1129
+
1130
+ async function readTypeclawDepSpec(cwd: string): Promise<string | null> {
945
1131
  try {
946
1132
  const raw = await readFile(join(cwd, PACKAGE_FILE), 'utf8')
947
1133
  const pkg = JSON.parse(raw) as { dependencies?: Record<string, string> }
948
1134
  const spec = pkg.dependencies?.typeclaw
949
- if (typeof spec !== 'string') return false
950
- return spec.startsWith('file:') || spec.startsWith('link:')
1135
+ return typeof spec === 'string' ? spec : null
951
1136
  } catch {
952
- return false
1137
+ return null
953
1138
  }
954
1139
  }
955
1140