typeclaw 0.39.1 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "typeclaw",
3
- "version": "0.39.1",
3
+ "version": "0.39.2",
4
4
  "homepage": "https://github.com/typeclaw/typeclaw#readme",
5
5
  "bugs": {
6
6
  "url": "https://github.com/typeclaw/typeclaw/issues"
@@ -1179,6 +1179,10 @@ export type CreateChannelRouterOptions = {
1179
1179
  // resumes on the next boot; when absent (cold channel / native slash with no
1180
1180
  // session) it should just bounce the container with no handoff.
1181
1181
  onRestart?: (ctx?: RestartCommandContext) => Promise<string>
1182
+ // Test seam: override the sessions.json writer. Defaults to the disk-backed
1183
+ // saveChannelSessions (which swallows its own I/O errors). Tests inject a
1184
+ // throwing impl to exercise the persist-failure unwind in ensureLive.
1185
+ saveChannelSessions?: (agentDir: string, sessions: readonly ChannelSessionRecord[]) => Promise<void>
1182
1186
  }
1183
1187
 
1184
1188
  export type RestartCommandContext = {
@@ -1356,13 +1360,18 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1356
1360
  await loadOnce
1357
1361
  }
1358
1362
 
1363
+ const saveSessions = options.saveChannelSessions
1364
+ ? options.saveChannelSessions
1365
+ : (agentDir: string, sessions: readonly ChannelSessionRecord[]): Promise<void> =>
1366
+ saveChannelSessions(agentDir, sessions, logger)
1367
+
1359
1368
  const persist = async (): Promise<void> => {
1360
1369
  if (mappings === null || closing) return
1361
1370
  // Caller awaits `next` un-caught to observe write errors; the chain holds the
1362
1371
  // caught version so one rejection can't poison it or escape as unhandled.
1363
1372
  const next = persistChain.then(async () => {
1364
1373
  if (mappings === null) return
1365
- await saveChannelSessions(options.agentDir, mappings, logger)
1374
+ await saveSessions(options.agentDir, mappings)
1366
1375
  })
1367
1376
  persistChain = next.catch(() => {})
1368
1377
  await next
@@ -1608,10 +1617,12 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1608
1617
  logger.info(`[channels] ${keyId}: ensureLive begin (${phase})`)
1609
1618
  const participants = (resolvedRecord?.participants ?? []) as ChannelParticipant[]
1610
1619
  const membershipFetch = warmMembership(key)
1611
- const resolvedNames = await resolveChannelNames(key)
1612
- logger.info(`[channels] ${keyId}: ensureLive resolved-names`)
1613
- const membership = await membershipForPrompt(key, membershipFetch)
1614
- logger.info(`[channels] ${keyId}: ensureLive resolved-membership`)
1620
+ // Independent platform lookups — overlap so the chain pays max(), not sum().
1621
+ const [resolvedNames, membership] = await Promise.all([
1622
+ resolveChannelNames(key),
1623
+ membershipForPrompt(key, membershipFetch),
1624
+ ])
1625
+ logger.info(`[channels] ${keyId}: ensureLive resolved-names-and-membership`)
1615
1626
  // The session-creation origin is what the resource loader sees when it
1616
1627
  // renders the role/permissions block into the system prompt. It must
1617
1628
  // include the triggering author so author-scoped roles
@@ -1674,7 +1685,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1674
1685
  } else {
1675
1686
  mappings = [persistedRecord]
1676
1687
  }
1677
- await persist()
1688
+ // Kick off the mapping write now but don't block on it — the disk write is
1689
+ // independent of the synchronous `live` build below and the cold-start
1690
+ // network prefetch, so we overlap it. Every exit path below MUST settle
1691
+ // `persistPromise` (the immediate .catch is only an unhandled-rejection
1692
+ // guard; write errors are still surfaced by awaiting it later).
1693
+ const persistPromise = persist()
1694
+ void persistPromise.catch(() => {})
1678
1695
 
1679
1696
  const live: LiveSession = {
1680
1697
  key,
@@ -1791,16 +1808,38 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
1791
1808
  `[channels] ${keyId}: discarding session created across a teardown (gen ${generation} → ${liveGeneration})`,
1792
1809
  )
1793
1810
  await tearDownLive(live)
1811
+ // Settle the in-flight mapping write before bailing — preserves the
1812
+ // pre-overlap contract that a persist failure fails ensureLive.
1813
+ await persistPromise
1794
1814
  throw new StaleLiveSessionError(keyId)
1795
1815
  }
1796
- liveSessions.set(keyId, live)
1797
-
1798
1816
  if (isColdStart) {
1817
+ // Install before the slow prefetch so a concurrent teardown/shutdown can
1818
+ // see and dispose this session during the network fetch.
1819
+ liveSessions.set(keyId, live)
1799
1820
  const adapterConfig = options.configForAdapter(key.adapter)
1800
- if (adapterConfig) {
1801
- await prefetchChannelContext(live, adapterConfig, triggeringMessageId)
1802
- logger.info(`[channels] ${keyId}: ensureLive prefetched-context`)
1821
+ // Overlap the disk mapping-write with the network history prefetch —
1822
+ // they are independent. allSettled lets a persist failure take priority
1823
+ // (and unwind the install) even if prefetch also rejects.
1824
+ const prefetchPromise = adapterConfig
1825
+ ? prefetchChannelContext(live, adapterConfig, triggeringMessageId)
1826
+ : Promise.resolve()
1827
+ const [persistResult, prefetchResult] = await Promise.allSettled([persistPromise, prefetchPromise])
1828
+ if (persistResult.status === 'rejected') {
1829
+ await unwindInstalledLive(keyId, live)
1830
+ throw persistResult.reason
1831
+ }
1832
+ if (prefetchResult.status === 'rejected') {
1833
+ await unwindInstalledLive(keyId, live)
1834
+ throw prefetchResult.reason
1803
1835
  }
1836
+ if (adapterConfig) logger.info(`[channels] ${keyId}: ensureLive prefetched-context`)
1837
+ } else {
1838
+ // Rehydrate has no prefetch to overlap, so settle the mapping write
1839
+ // before installing — a failed persist must fail ensureLive without
1840
+ // leaving a warm session behind for later inbounds to reuse.
1841
+ await persistPromise
1842
+ liveSessions.set(keyId, live)
1804
1843
  }
1805
1844
 
1806
1845
  // Snapshot the rendered base context size now, after prefetch and before
@@ -4051,6 +4090,13 @@ export function createChannelRouter(options: CreateChannelRouterOptions): Channe
4051
4090
  }
4052
4091
  }
4053
4092
 
4093
+ // Roll back an install when a post-install step (persist/prefetch) fails, so a
4094
+ // rejected ensureLive never leaves a warm session behind for later inbounds.
4095
+ const unwindInstalledLive = async (keyId: string, live: LiveSession): Promise<void> => {
4096
+ if (liveSessions.get(keyId) === live) liveSessions.delete(keyId)
4097
+ if (!live.destroyed) await tearDownLive(live)
4098
+ }
4099
+
4054
4100
  const runIdleGc = async (): Promise<void> => {
4055
4101
  const t = now()
4056
4102
  const victims: LiveSession[] = []
@@ -1,7 +1,7 @@
1
1
  import { buildDockerLogsCmd, containerExists } from '@/container'
2
2
  import { supportsColor } from '@/container/log-colors'
3
3
  import { makeLogTimestampReformatter, type TimestampReformatter } from '@/container/log-timestamps'
4
- import { getBun } from '@/container/shared'
4
+ import { getBun, resolveDockerBinary } from '@/container/shared'
5
5
 
6
6
  import { discoverAgents, type AgentEntry } from './discover'
7
7
 
@@ -74,6 +74,17 @@ export async function composeLogs({
74
74
  }: ComposeLogsOptions): Promise<ComposeLogsResult> {
75
75
  const agents = discoverAgents(rootCwd)
76
76
 
77
+ // Resolve docker BEFORE probing containers: containerExists collapses a
78
+ // missing docker binary into `false`, so every agent would be classified
79
+ // "container not running" and the empty-attached early return would exit 0 —
80
+ // masking the real "docker not on PATH" cause (the stale-Windows-PATH case
81
+ // #1007 covers for start/init). Resolving first surfaces it correctly.
82
+ const dockerBinary = resolveDockerBinary()
83
+ if (dockerBinary === null) {
84
+ err.write('compose: docker not found on PATH\n')
85
+ return { agents, attached: [], missing: agents, exitCode: 1 }
86
+ }
87
+
77
88
  const liveness = await Promise.all(
78
89
  agents.map(async (a) => ({ agent: a, exists: await containerExists(a.containerName) })),
79
90
  )
@@ -95,11 +106,14 @@ export async function composeLogs({
95
106
  const useColor = supportsColor(out)
96
107
 
97
108
  const procs = attached.map((agent) => {
98
- const cmd = buildDockerLogsCmd({
99
- containerName: agent.containerName,
100
- follow,
101
- ...(tail !== undefined ? { tail } : {}),
102
- })
109
+ const cmd = buildDockerLogsCmd(
110
+ {
111
+ containerName: agent.containerName,
112
+ follow,
113
+ ...(tail !== undefined ? { tail } : {}),
114
+ },
115
+ dockerBinary,
116
+ )
103
117
  const proc = bun.spawn({ cmd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' })
104
118
  return { agent, proc }
105
119
  })
@@ -1,6 +1,6 @@
1
1
  import { supportsColor } from './log-colors'
2
2
  import { makeLogTimestampReformatter, type TimestampReformatter } from './log-timestamps'
3
- import { containerExists, containerNameFromCwd, getBun } from './shared'
3
+ import { containerExists, containerNameFromCwd, getBun, resolveDockerBinary } from './shared'
4
4
 
5
5
  export type LogsPlan = {
6
6
  containerName: string
@@ -39,6 +39,17 @@ export async function logs({
39
39
 
40
40
  const plan = planLogs(cwd, { follow, tail })
41
41
 
42
+ // Resolve docker before inspecting: containerExists collapses a missing
43
+ // docker binary into `false`, so deferring this would surface the misleading
44
+ // "Container … not found" instead of the real "Docker is not installed" on a
45
+ // host where docker isn't on PATH (cf. shell.ts). resolveDockerBinary also
46
+ // recovers the stale-Windows-PATH case where Bun.which misses (#1007).
47
+ const dockerBinary = resolveDockerBinary()
48
+ if (dockerBinary === null) {
49
+ return { ok: false, reason: 'Docker is not installed (docker not found on PATH).' }
50
+ }
51
+ const cmd = buildDockerLogsCmd(plan, dockerBinary)
52
+
42
53
  try {
43
54
  if (!(await containerExists(plan.containerName))) {
44
55
  return { ok: false, reason: `Container ${plan.containerName} not found. Run \`typeclaw start\` first.` }
@@ -47,7 +58,7 @@ export async function logs({
47
58
  // stdin:'ignore' — `docker logs` never reads stdin, and letting the child
48
59
  // hold the TTY breaks the viewer's raw-mode keypress listener (esc/q/ctrl-c
49
60
  // stop reaching it, freezing the logs view with no way out).
50
- const proc = bun.spawn({ cmd: buildDockerLogsCmd(plan), cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' })
61
+ const proc = bun.spawn({ cmd, cwd, stdin: 'ignore', stdout: 'pipe', stderr: 'pipe' })
51
62
 
52
63
  // `docker logs -f` never exits on its own; aborting the signal must kill it
53
64
  // so the pumps' stream readers end. Escalate to SIGKILL if SIGTERM is
@@ -112,8 +123,12 @@ export function parseTailValue(raw: string): { ok: true; value: string } | { ok:
112
123
  }
113
124
 
114
125
  // Exported so `compose/logs.ts` builds the exact same `docker logs` argv shape.
115
- export function buildDockerLogsCmd(plan: LogsPlan): string[] {
116
- const cmd = ['docker', 'logs', '--timestamps']
126
+ // Takes the already-resolved docker binary path (from resolveDockerBinary) as
127
+ // the argv head so a stale Windows PATH still spawns — passing a bare 'docker'
128
+ // throws ENOENT on the #1007 case. Callers resolve the binary and handle the
129
+ // missing-docker error before getting here.
130
+ export function buildDockerLogsCmd(plan: LogsPlan, dockerBinary: string): string[] {
131
+ const cmd = [dockerBinary, 'logs', '--timestamps']
117
132
  if (plan.tail !== undefined) cmd.push('--tail', plan.tail)
118
133
  if (plan.follow) cmd.push('-f')
119
134
  cmd.push(plan.containerName)
@@ -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,6 +1,7 @@
1
1
  import { randomBytes } from 'node:crypto'
2
2
  import { existsSync } from 'node:fs'
3
- import { readFile, writeFile } from 'node:fs/promises'
3
+ import { cp, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
4
5
  import { isAbsolute, join, resolve } from 'node:path'
5
6
 
6
7
  import { agentUsesVector } from '@/bundled-plugins/memory/vector/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, 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) {
@@ -733,6 +789,16 @@ export async function refreshDockerfile(
733
789
  // `docker build`. The user sees one successful `typeclaw start` instead of a
734
790
  // buildx-specific dead end. A genuine Dockerfile error fails both paths, so the
735
791
  // retry costs at most one extra attempt before the real error surfaces.
792
+ //
793
+ // Layered on top is a credential-helper recovery: typeclaw only pulls PUBLIC
794
+ // images (the BuildKit syntax frontend + the typeclaw-base FROM), but a broken
795
+ // `credsStore`/`credHelpers` in ~/.docker/config.json makes docker abort the
796
+ // pull trying to exec a helper binary that isn't on PATH (the canonical Windows
797
+ // Docker Desktop failure). When a build fails with exactly that signature we
798
+ // retry the SAME build under a sanitized DOCKER_CONFIG that strips only the
799
+ // broken helper hooks — anonymous pulls then succeed and the user's real config
800
+ // is left untouched. This is checked BEFORE the buildx->legacy strip so a
801
+ // cred-helper failure doesn't get misdiagnosed as a buildx problem.
736
802
  async function runImageBuild(args: {
737
803
  exec: DockerExec
738
804
  cwd: string
@@ -741,19 +807,93 @@ async function runImageBuild(args: {
741
807
  hasBuildx: boolean
742
808
  }): Promise<boolean> {
743
809
  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 })
810
+ const buildArgv = (frontend: 'buildx' | 'legacy'): string[] =>
811
+ frontend === 'buildx'
812
+ ? ['buildx', 'build', '--load', '-t', imageTag, buildContext]
813
+ : ['build', '-t', imageTag, buildContext]
814
+
815
+ let sanitizedConfig: SanitizedDockerConfig | null = null
816
+ const attempt = async (frontend: 'buildx' | 'legacy'): Promise<DockerExecResult> =>
817
+ exec(buildArgv(frontend), { cwd, inheritStdio: true, captureStderr: true, env: sanitizedConfig?.env })
818
+
819
+ try {
820
+ let frontend: 'buildx' | 'legacy' = hasBuildx ? 'buildx' : 'legacy'
821
+ let result = await attempt(frontend)
822
+ if (result.exitCode === 0) return true
823
+
824
+ // Same-frontend retry: a broken credential helper aborts the pull before
825
+ // the builder ever matters, so strip it and retry the identical build.
826
+ if (sanitizedConfig === null && isMissingDockerCredentialHelper(result.stderr)) {
827
+ sanitizedConfig = await createSanitizedDockerConfig()
828
+ if (sanitizedConfig) {
829
+ result = await attempt(frontend)
830
+ if (result.exitCode === 0) return true
831
+ }
832
+ }
833
+
834
+ if (frontend === 'buildx') {
835
+ // buildx failed for a non-cred reason — fall back to the legacy builder
836
+ // against a stripped Dockerfile so a misconfigured-buildx host still ends
837
+ // up with an image. The sanitized config (if any) carries into the retry.
838
+ await refreshDockerfile(cwd, { buildKit: false })
839
+ frontend = 'legacy'
840
+ result = await attempt(frontend)
841
+ if (result.exitCode === 0) return true
842
+ if (sanitizedConfig === null && isMissingDockerCredentialHelper(result.stderr)) {
843
+ sanitizedConfig = await createSanitizedDockerConfig()
844
+ if (sanitizedConfig) {
845
+ result = await attempt(frontend)
846
+ if (result.exitCode === 0) return true
847
+ }
848
+ }
849
+ }
850
+
851
+ if (sanitizedConfig !== null) {
852
+ process.stderr.write(
853
+ 'typeclaw: docker build still failed after retrying public image pulls without the configured ' +
854
+ 'credential helper. Your ~/.docker/config.json credsStore/credHelpers may be broken.\n',
855
+ )
856
+ }
857
+ return false
858
+ } finally {
859
+ await sanitizedConfig?.cleanup()
860
+ }
861
+ }
862
+
863
+ type SanitizedDockerConfig = { env: { DOCKER_CONFIG: string }; cleanup: () => Promise<void> }
864
+
865
+ // Materializes a temp DOCKER_CONFIG dir that is a full DEEP COPY of the user's
866
+ // ~/.docker tree with only the broken credential-helper hooks stripped from the
867
+ // copied config.json. Returns null when there's nothing to strip (no creds
868
+ // hooks present), so the caller skips a pointless retry. Cleanup removes the dir
869
+ // on every build outcome.
870
+ //
871
+ // DOCKER_CONFIG is not just credentials: `contexts/` maps the current docker
872
+ // context (e.g. Docker Desktop's `desktop-linux`) to the daemon endpoint, and
873
+ // `buildx/` holds builder instance state. A relocated config missing those
874
+ // makes `docker buildx build` (and `docker build`, which Docker Desktop forwards
875
+ // to `buildx build --builder <currentContext>`) fail with `no builder
876
+ // "desktop-linux" found` — the exact second failure this replaces. The earlier
877
+ // approach symlinked those subdirs, but Windows `fs.symlink` throws EPERM
878
+ // without Developer Mode/admin, so the catch silently produced a config dir with
879
+ // the context/builder state ABSENT. A recursive copy is portable and preserves
880
+ // the full topology; only config.json is overwritten with the sanitized form.
881
+ async function createSanitizedDockerConfig(): Promise<SanitizedDockerConfig | null> {
882
+ const srcDir = dockerConfigDir()
883
+ const raw = await readFile(join(srcDir, 'config.json'), 'utf8').catch(() => null)
884
+ const sanitized = sanitizeDockerConfigJson(raw)
885
+ if (sanitized === null) return null
886
+
887
+ const dir = await mkdtemp(join(tmpdir(), 'typeclaw-dockercfg-'))
888
+ const cleanup = (): Promise<void> => rm(dir, { recursive: true, force: true })
889
+ try {
890
+ if (existsSync(srcDir)) await cp(srcDir, dir, { recursive: true, dereference: false })
891
+ await writeFile(join(dir, 'config.json'), sanitized)
892
+ } catch {
893
+ await cleanup()
894
+ return null
754
895
  }
755
- const legacy = await exec(['build', '-t', imageTag, buildContext], { cwd, inheritStdio: true })
756
- return legacy.exitCode === 0
896
+ return { env: { DOCKER_CONFIG: dir }, cleanup }
757
897
  }
758
898
 
759
899
  export async function refreshGitignore(cwd: string): Promise<void> {
@@ -907,7 +1047,12 @@ async function detectDevSource(cwd: string): Promise<string | null> {
907
1047
  const raw = await readFile(join(cwd, PACKAGE_FILE), 'utf8')
908
1048
  const pkg = JSON.parse(raw) as { dependencies?: Record<string, string> }
909
1049
  const spec = pkg.dependencies?.typeclaw
910
- if (!spec || !spec.startsWith('file:')) return null
1050
+ if (typeof spec !== 'string') return null
1051
+ // Windows dev-mode declares `link:typeclaw` (a `bun link` registration);
1052
+ // the checkout path isn't in the spec, so resolve it from bun's global
1053
+ // link target. POSIX dev-mode declares `file:<rel>` and encodes the path.
1054
+ if (spec.startsWith('link:')) return resolveBunLinkedPackage(TYPECLAW_PACKAGE)
1055
+ if (!spec.startsWith('file:')) return null
911
1056
  const target = spec.slice('file:'.length)
912
1057
  return isAbsolute(target) ? resolve(target) : resolve(cwd, target)
913
1058
  } catch {
@@ -915,16 +1060,15 @@ async function detectDevSource(cwd: string): Promise<string | null> {
915
1060
  }
916
1061
  }
917
1062
 
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
1063
+ // POSIX dev mode: node_modules/typeclaw is a symlink to an absolute host path
1064
+ // outside /agent. The mirror mount bind-mounts that path at the SAME path inside
1065
+ // the (Linux) container so the symlink resolves. That only works when the host
1066
+ // path is itself a valid Linux container path — true on POSIX, false on native
922
1067
  // 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.
1068
+ // cannot be a same-path container mount `dst`). Native Windows takes the
1069
+ // `shouldMountWindowsDevSource` branch instead (mount the checkout directly over
1070
+ // the in-container node_modules path). End users install typeclaw from npm (a
1071
+ // registry spec, not file:), so they never hit either dev path.
928
1072
  export function shouldMirrorDevSource(
929
1073
  devSourcePath: string | null,
930
1074
  cwd: string,
@@ -933,6 +1077,19 @@ export function shouldMirrorDevSource(
933
1077
  return devSourcePath !== null && !devSourcePath.startsWith(cwd) && !isWindows(platform)
934
1078
  }
935
1079
 
1080
+ // Native-Windows dev mode (#899): the host's `C:\...` checkout cannot be
1081
+ // same-path mirror-mounted into a Linux container. Instead, bind-mount the
1082
+ // checkout directly over the standard resolution path `/agent/node_modules/
1083
+ // typeclaw` inside the container, so Node/Bun resolve typeclaw from source
1084
+ // regardless of how the host materialized node_modules/typeclaw (a junction,
1085
+ // per prepareWindowsDevJunction).
1086
+ export function shouldMountWindowsDevSource(
1087
+ devSourcePath: string | null,
1088
+ platform: NodeJS.Platform = process.platform,
1089
+ ): devSourcePath is string {
1090
+ return devSourcePath !== null && isWindows(platform)
1091
+ }
1092
+
936
1093
  // True when the agent's package.json declares typeclaw via `file:` or
937
1094
  // `link:` — i.e. a developer is iterating on the typeclaw source via a
938
1095
  // locally-linked checkout. `bun install` keys its file-dep cache on
@@ -942,14 +1099,18 @@ export function shouldMirrorDevSource(
942
1099
  // users (`^X.Y.Z`, `~X.Y.Z`, exact pins) pay nothing because their
943
1100
  // install path is already cache-correct.
944
1101
  async function hasLocallyLinkedTypeclawDep(cwd: string): Promise<boolean> {
1102
+ const spec = await readTypeclawDepSpec(cwd)
1103
+ return spec !== null && (spec.startsWith('file:') || spec.startsWith('link:'))
1104
+ }
1105
+
1106
+ async function readTypeclawDepSpec(cwd: string): Promise<string | null> {
945
1107
  try {
946
1108
  const raw = await readFile(join(cwd, PACKAGE_FILE), 'utf8')
947
1109
  const pkg = JSON.parse(raw) as { dependencies?: Record<string, string> }
948
1110
  const spec = pkg.dependencies?.typeclaw
949
- if (typeof spec !== 'string') return false
950
- return spec.startsWith('file:') || spec.startsWith('link:')
1111
+ return typeof spec === 'string' ? spec : null
951
1112
  } catch {
952
- return false
1113
+ return null
953
1114
  }
954
1115
  }
955
1116
 
@@ -30,21 +30,21 @@ export type AutoUpgradeOutcome =
30
30
  | { kind: 'exact-pin-respected'; declared: string; cliVersion: string }
31
31
  | { kind: 'spec-rewritten'; from: string; to: string; cliVersion: string }
32
32
  | { kind: 'reinstall-needed'; from: string; to: string }
33
+ | { kind: 'relinked-to-local'; from: string; to: string }
33
34
 
34
35
  export type AutoUpgradeOptions = {
35
36
  cwd: string
36
37
  // Test seam: lets tests simulate dev-mode (null) and arbitrary release
37
38
  // versions without depending on the test runner's actual CLI version.
38
39
  scaffoldVersion?: string | null
40
+ // Test seam: the local spec to relink to in dev-mode, so tests don't depend
41
+ // on the test runner's actual checkout path.
42
+ localSpec?: string
39
43
  }
40
44
 
41
45
  export async function autoUpgradeTypeclawDep(options: AutoUpgradeOptions): Promise<AutoUpgradeOutcome> {
42
46
  const { cwd } = options
43
47
  const scaffold = options.scaffoldVersion !== undefined ? options.scaffoldVersion : resolveScaffoldVersion()
44
- if (scaffold === null) return { kind: 'skipped-dev-mode' }
45
-
46
- const cliVersion = stripCaret(scaffold)
47
- if (cliVersion === null) return { kind: 'skipped-dev-mode' }
48
48
 
49
49
  const pkg = await readAgentPackageJson(cwd)
50
50
  if (pkg === null) return { kind: 'skipped-no-dep' }
@@ -52,8 +52,32 @@ export async function autoUpgradeTypeclawDep(options: AutoUpgradeOptions): Promi
52
52
  const declared = pkg.parsed.dependencies?.[TYPECLAW]
53
53
  if (typeof declared !== 'string') return { kind: 'skipped-no-dep' }
54
54
 
55
+ // The CLI runs from a source checkout (scaffold === null): the agent should
56
+ // track that checkout, not a published version. Relink any registry-range
57
+ // spec to the local spec (`file:`/`link:`); leave an exact pin (explicit user
58
+ // override) and an already-local spec alone.
59
+ if (scaffold === null) {
60
+ const localSpec = options.localSpec ?? null
61
+ if (localSpec === null || declared.startsWith('file:') || declared.startsWith('link:')) {
62
+ return { kind: 'skipped-dev-mode' }
63
+ }
64
+ if (classifyDepSpec(declared).kind === 'exact') return { kind: 'skipped-dev-mode' }
65
+ await writeDepSpec(cwd, pkg.raw, pkg.parsed, localSpec)
66
+ return { kind: 'relinked-to-local', from: declared, to: localSpec }
67
+ }
68
+
69
+ const cliVersion = stripCaret(scaffold)
70
+ if (cliVersion === null) return { kind: 'skipped-dev-mode' }
71
+
55
72
  const declaredKind = classifyDepSpec(declared)
56
73
  if (declaredKind.kind === 'non-release') {
74
+ // An installed CLI against a local (`file:`/`link:`) spec: the agent was on
75
+ // a dev checkout but is now run by an npm CLI — restore the registry range.
76
+ if (declared.startsWith('file:') || declared.startsWith('link:')) {
77
+ const newSpec = `^${cliVersion}`
78
+ await writeDepSpec(cwd, pkg.raw, pkg.parsed, newSpec)
79
+ return { kind: 'spec-rewritten', from: declared, to: newSpec, cliVersion }
80
+ }
57
81
  return { kind: 'skipped-non-release-spec', declared }
58
82
  }
59
83
 
@@ -113,6 +137,14 @@ export function outcomeForcesInstall(outcome: AutoUpgradeOutcome): boolean {
113
137
  return outcome.kind === 'spec-rewritten' || outcome.kind === 'reinstall-needed'
114
138
  }
115
139
 
140
+ // A relink to a local `file:`/`link:` spec installs via a forced `bun install`
141
+ // (file deps don't "update"), NOT the `bun update --latest` path above — and it
142
+ // skips version verification, since a local install's version is whatever the
143
+ // checkout declares. start.ts ORs this into its ensureDeps force flag.
144
+ export function outcomeRequiresForceInstall(outcome: AutoUpgradeOutcome): boolean {
145
+ return outcome.kind === 'relinked-to-local'
146
+ }
147
+
116
148
  // The version we expect to find in node_modules/typeclaw after the
117
149
  // auto-upgrade-triggered install completes. Callers use this to verify
118
150
  // the install actually moved the on-disk version (not just resolved the
@@ -130,6 +162,8 @@ export function describeAutoUpgrade(outcome: AutoUpgradeOutcome): string {
130
162
  return `Upgrading agent typeclaw ${outcome.from} → ${outcome.to} to match CLI`
131
163
  case 'reinstall-needed':
132
164
  return `Upgrading agent typeclaw ${outcome.from} → ${outcome.to} to match CLI`
165
+ case 'relinked-to-local':
166
+ return `Linking agent typeclaw to local checkout (${outcome.to})`
133
167
  case 'exact-pin-respected':
134
168
  return `Agent typeclaw is exact-pinned to ${outcome.declared}; CLI is ${outcome.cliVersion}. Not upgrading (remove the exact pin to allow auto-upgrade).`
135
169
  default:
@@ -1,5 +1,7 @@
1
1
  import { readFileSync } from 'node:fs'
2
- import { join } from 'node:path'
2
+ import { dirname, join, relative } from 'node:path'
3
+
4
+ import { isWindows } from '@/shared/platform'
3
5
 
4
6
  // Single source of truth for "what version of typeclaw is this agent on,
5
7
  // and where does that mean we should pin the base image / write the dep
@@ -34,6 +36,33 @@ export function resolveScaffoldVersion(): string | null {
34
36
  return `^${CLI_VERSION}`
35
37
  }
36
38
 
39
+ const TYPECLAW_PACKAGE = 'typeclaw'
40
+
41
+ // The local typeclaw source checkout this CLI runs from (the dir holding the
42
+ // CLI's own package.json), or null when the CLI is an installed package.
43
+ export function typeclawCheckoutRoot(): string | null {
44
+ return isInstalledCli() ? null : dirname(CLI_PACKAGE_JSON_PATH)
45
+ }
46
+
47
+ // The `dependencies.typeclaw` spec a fresh/reconciled agent should declare to
48
+ // track the running CLI: `^X.Y.Z` when the CLI is an installed package, else the
49
+ // local checkout — `link:typeclaw` on native Windows (a `bun link` registration
50
+ // bun symlinks instead of copying; `file:` would copy the whole checkout incl
51
+ // `.git/` and EPERM, the #899 path) and `file:<rel>` on POSIX.
52
+ export function resolveTypeclawSpec(agentRoot: string, platform: NodeJS.Platform = process.platform): string {
53
+ const scaffoldVersion = resolveScaffoldVersion()
54
+ if (scaffoldVersion !== null) return scaffoldVersion
55
+ if (isWindows(platform)) return `link:${TYPECLAW_PACKAGE}`
56
+ const checkout = typeclawCheckoutRoot()
57
+ return checkout ? `file:${toFileSpec(relative(agentRoot, checkout))}` : 'file:../typeclaw'
58
+ }
59
+
60
+ function toFileSpec(rel: string): string {
61
+ if (rel === '') return '.'
62
+ // bun/npm accept POSIX-style paths in file: specifiers; normalize separators.
63
+ return rel.split(/[\\/]/).join('/')
64
+ }
65
+
37
66
  // The version of typeclaw the AGENT will actually run inside the container.
38
67
  // Prefers `<agent>/node_modules/typeclaw/package.json#version` because that
39
68
  // is what the bind-mount exposes to the container at /agent/node_modules,
@@ -125,6 +125,18 @@ export const CLOUDFLARED_RELEASE_URL_BASE = 'https://github.com/cloudflare/cloud
125
125
 
126
126
  export const TYPECLAW_ENTRYPOINT_PATH = '/usr/local/bin/typeclaw-entrypoint'
127
127
 
128
+ // The installed TypeClaw CLI entry, executed directly by the container
129
+ // entrypoint. `package.json#bin.typeclaw` points at `src/cli/index.ts` and the
130
+ // package ships `src`, so this path exists for both the registry install and a
131
+ // `file:`/linked dev install (where node_modules/typeclaw is the repo). Running
132
+ // it directly bypasses `bun run typeclaw`'s script/`.bin` resolution — which
133
+ // breaks when the agent folder was installed on a Windows host: the hoisted
134
+ // linker writes Windows-native `.bin/typeclaw` shims that aren't valid Linux
135
+ // executables once the folder is bind-mounted into the container, so
136
+ // `bun run typeclaw` finds no usable bin, falls back to treating `typeclaw` as
137
+ // a path, and resolves `/agent/typeclaw.json` (`Cannot run json files`).
138
+ export const TYPECLAW_CLI_ENTRY = '/agent/node_modules/typeclaw/src/cli/index.ts'
139
+
128
140
  // IPv4 networks the container is forbidden to egress to when
129
141
  // `network.blockInternal` is true. Loopback (127/8) is NOT here — loopback
130
142
  // traffic uses the `lo` interface, which the shim's first ACCEPT rule
@@ -157,9 +169,10 @@ export const NETWORK_BLOCK_IPV6_NETS = ['fc00::/7', 'fe80::/10', 'ff00::/8', '::
157
169
  // modes, picked at boot time from `$TYPECLAW_NETWORK_BLOCK_INTERNAL`:
158
170
  //
159
171
  // off (env unset or != "1"): no rules installed, no setpriv. Just exec
160
- // `bun run typeclaw "$@"`. Identical observable behavior to a container
161
- // without this feature. This is the opt-out path for users who set
162
- // `network.blockInternal: false` in their `typeclaw.json`.
172
+ // the TypeClaw CLI entry directly (see TYPECLAW_CLI_ENTRY). Identical
173
+ // observable behavior to a container without this feature. This is the
174
+ // opt-out path for users who set `network.blockInternal: false` in their
175
+ // `typeclaw.json`.
163
176
  //
164
177
  // on (default, env = "1" via `network.blockInternal: true`): walks IPv4 +
165
178
  // IPv6 block lists and installs
@@ -515,7 +528,7 @@ if [ "\${TYPECLAW_NETWORK_BLOCK_INTERNAL:-0}" != "1" ]; then
515
528
  link_persistent_home_files
516
529
  link_configured_symlinks
517
530
  start_xvfb
518
- exec bun run typeclaw "$@"
531
+ exec bun run ${TYPECLAW_CLI_ENTRY} "$@"
519
532
  fi
520
533
 
521
534
  iptables -A OUTPUT -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
@@ -562,7 +575,7 @@ ${ipv6Rules.join('\n')}
562
575
  link_persistent_home_files
563
576
  link_configured_symlinks
564
577
  start_xvfb
565
- exec setpriv --bounding-set -net_admin --inh-caps -net_admin --ambient-caps -net_admin -- bun run typeclaw "$@"
578
+ exec setpriv --bounding-set -net_admin --inh-caps -net_admin --ambient-caps -net_admin -- bun run ${TYPECLAW_CLI_ENTRY} "$@"
566
579
  `
567
580
  }
568
581
 
package/src/init/index.ts CHANGED
@@ -1,7 +1,6 @@
1
- import { existsSync, readdirSync, readFileSync } from 'node:fs'
1
+ import { existsSync, readdirSync } from 'node:fs'
2
2
  import { mkdir, readFile, writeFile } from 'node:fs/promises'
3
- import { basename, dirname, join, relative, resolve } from 'node:path'
4
- import { fileURLToPath } from 'node:url'
3
+ import { basename, join, resolve } from 'node:path'
5
4
 
6
5
  import {
7
6
  config,
@@ -31,9 +30,10 @@ import {
31
30
  import { commitSystemFile } from '@/git/system-commit'
32
31
  import { createSecretsStoreForAgent, type Channels, type Secret, SecretsBackend } from '@/secrets'
33
32
  import { hostLocaleIsCjk } from '@/shared/host-locale'
33
+ import { isWindows } from '@/shared/platform'
34
34
  import { createTui } from '@/tui'
35
35
 
36
- import { resolveBaseImageVersion, resolveScaffoldVersion } from './cli-version'
36
+ import { resolveBaseImageVersion, resolveTypeclawSpec, typeclawCheckoutRoot } from './cli-version'
37
37
  import { buildDockerfile, DOCKERFILE } from './dockerfile'
38
38
  import { CONFIG_FILE, findAgentDir, isInitialized } from './find-agent-dir'
39
39
  import { installGithubWebhooksEagerly, type EagerGithubWebhookInstallResult } from './github-webhook-install'
@@ -42,6 +42,7 @@ import { buildHatchingPrompt } from './hatching'
42
42
  import type { OAuthLoginRunner, OAuthLoginResult } from './oauth-login'
43
43
  import { GITKEEP_FILE, PACKAGES_DIR, PUBLIC_DIR } from './paths'
44
44
  import { type InstallResult, type InstallRunner, runBunInstall } from './run-bun-install'
45
+ import { linkWindowsDevTypeclaw, type RunBunLink } from './windows-dev-link'
45
46
 
46
47
  export { type InstallResult, type InstallRunner, runBunInstall } from './run-bun-install'
47
48
 
@@ -231,6 +232,11 @@ export type InitOptions = {
231
232
  runHatching?: HatchRunner
232
233
  runBunInstall?: InstallRunner
233
234
  dockerExec?: DockerExec
235
+ // Test seams for the native-Windows dev-mode `bun link` flow. `platform`
236
+ // defaults to `process.platform`; `runBunLink` defaults to spawning
237
+ // `bun link` in the typeclaw checkout.
238
+ platform?: NodeJS.Platform
239
+ runBunLink?: RunBunLink
234
240
  // Production CLI callers (src/cli/init.ts) pass `process.argv[1]` so the
235
241
  // hatching step's `start()` call spawns the host daemon and registers the
236
242
  // freshly-hatched container — same path `typeclaw start` takes. Tests omit
@@ -269,6 +275,8 @@ export async function runInit({
269
275
  runBunInstall: installRunner = runBunInstall,
270
276
  dockerExec,
271
277
  cliEntry,
278
+ platform = process.platform,
279
+ runBunLink,
272
280
  }: InitOptions): Promise<void> {
273
281
  const emit = onProgress ?? (() => {})
274
282
 
@@ -340,6 +348,7 @@ export async function runInit({
340
348
  withWebex: wantsWebex,
341
349
  withWebexUser,
342
350
  withKakaotalk,
351
+ platform,
343
352
  })
344
353
  // Only write the LLM API key on the api-key path. OAuth providers persist
345
354
  // their credentials to secrets.json (via the OAuth login step above); writing
@@ -407,6 +416,12 @@ export async function runInit({
407
416
  }
408
417
 
409
418
  emit({ step: 'install', phase: 'start' })
419
+ // Native-Windows dev-mode emits `link:typeclaw` (see resolveTypeclawSpec);
420
+ // register the checkout with `bun link` first so the subsequent install
421
+ // resolves it to a symlink bun SKIPS copying, instead of `file:` copying the
422
+ // checkout (incl `.git/`) and EPERMing — the #899 path. Registry deps still
423
+ // install normally. No-op on POSIX / registry installs.
424
+ await maybeLinkWindowsDevTypeclaw(platform, runBunLink)
410
425
  const install = await installRunner(cwd)
411
426
  emit({ step: 'install', phase: 'done', result: install })
412
427
  if (!install.ok) throw new Error(`Dependency install failed: ${install.reason}`)
@@ -481,7 +496,7 @@ export async function defaultRunHatching({
481
496
  // the preferred port, otherwise we'd connect to the wrong service.
482
497
  const hostPort = launch.hostPort
483
498
 
484
- await waitForAgentFn(`http://127.0.0.1:${hostPort}`, { timeoutMs: 30_000 })
499
+ await waitForAgentFn(`http://127.0.0.1:${hostPort}`, { timeoutMs: hatchingReadinessTimeoutMs() })
485
500
 
486
501
  if (configuredChannels !== undefined && configuredChannels.length > 0) {
487
502
  const url = buildTuiUrl(hostPort, launch.tuiToken)
@@ -527,6 +542,20 @@ function buildTuiUrl(hostPort: number, token: string | null): string {
527
542
  return url.toString()
528
543
  }
529
544
 
545
+ // Cold-boot readiness budget for the first `typeclaw init`. The image was just
546
+ // unpacked and the agent folder (incl. a large node_modules) is bind-mounted
547
+ // into the container, so the very first server boot is markedly slower than
548
+ // subsequent `typeclaw start`s — plugin loading reads hundreds of files off a
549
+ // cold mount before Bun.serve() binds the port. On Windows Docker Desktop that
550
+ // mount crosses into the WSL2 VM and is slower still; during the warmup window
551
+ // Docker Desktop's port proxy may accept then immediately reset connections
552
+ // ("socket connection was closed unexpectedly"), which is why a too-short budget
553
+ // fails the first run even though an immediate retry (warm caches) succeeds.
554
+ // Give Windows a generous budget; keep other platforms tighter.
555
+ export function hatchingReadinessTimeoutMs(platform: NodeJS.Platform = process.platform): number {
556
+ return isWindows(platform) ? 120_000 : 60_000
557
+ }
558
+
530
559
  // Probe the server's plain HTTP fallback (non-upgrade requests get a 200 with
531
560
  // body "typeclaw agent") instead of opening a WebSocket. Opening a WS here
532
561
  // would trigger createSession on the server and burn an LLM session just to
@@ -582,6 +611,9 @@ export type ScaffoldOptions = {
582
611
  withWebex?: boolean
583
612
  withWebexUser?: boolean
584
613
  withKakaotalk?: boolean
614
+ // Defaults to `process.platform`; controls the dev-mode typeclaw spec
615
+ // (`link:` on Windows, `file:` on POSIX). Tests inject it.
616
+ platform?: NodeJS.Platform
585
617
  }
586
618
 
587
619
  export async function scaffold(root: string, options: ScaffoldOptions = {}): Promise<void> {
@@ -630,7 +662,7 @@ export async function scaffold(root: string, options: ScaffoldOptions = {}): Pro
630
662
  }
631
663
  await writeFile(join(root, CRON_FILE), `${JSON.stringify(cron, null, 2)}\n`, { flag: 'wx' }).catch(ignoreExists)
632
664
 
633
- const pkg = buildPackageJson(root, basename(root))
665
+ const pkg = buildPackageJson(root, basename(root), options.platform ?? process.platform)
634
666
  await writeFile(join(root, PACKAGE_FILE), `${JSON.stringify(pkg, null, 2)}\n`, { flag: 'wx' }).catch(ignoreExists)
635
667
 
636
668
  await Promise.all(MARKDOWN_FILES.map((file) => writeFile(join(root, file), '', { flag: 'wx' }).catch(ignoreExists)))
@@ -664,14 +696,14 @@ function addCustomModel(
664
696
  // two installs of the same CLI and a skew is silent. Enforced by a guard test
665
697
  // in packagejson.test.ts.
666
698
  export const AGENT_BROWSER_VERSION = '^0.27.0'
667
- function buildPackageJson(root: string, name: string): Record<string, unknown> {
699
+ function buildPackageJson(root: string, name: string, platform: NodeJS.Platform): Record<string, unknown> {
668
700
  return {
669
701
  name,
670
702
  private: true,
671
703
  type: 'module',
672
704
  workspaces: [`${PACKAGES_DIR}/*`],
673
705
  dependencies: {
674
- typeclaw: resolveTypeclawSpec(root),
706
+ typeclaw: resolveTypeclawSpec(root, platform),
675
707
  'agent-browser': AGENT_BROWSER_VERSION,
676
708
  [GWS_MULTI_ACCOUNT_PLUGIN_PACKAGE]: GWS_MULTI_ACCOUNT_PLUGIN_VERSION,
677
709
  },
@@ -683,37 +715,13 @@ function buildPackageJson(root: string, name: string): Record<string, unknown> {
683
715
  }
684
716
  }
685
717
 
686
- // Prefer the registry-style range (`^X.Y.Z`) when typeclaw is itself an
687
- // installed package — that's what lets `bun install` in the agent resolve
688
- // typeclaw from npm. Fall back to `file:` against the local checkout for
689
- // dev contributors running `bun run src/cli/index.ts init` from the repo.
690
- function resolveTypeclawSpec(agentRoot: string): string {
691
- const scaffoldVersion = resolveScaffoldVersion()
692
- if (scaffoldVersion !== null) return scaffoldVersion
693
- const typeclawRoot = findTypeclawRoot()
694
- return typeclawRoot ? `file:${toFileSpec(relative(agentRoot, typeclawRoot))}` : 'file:../typeclaw'
695
- }
696
-
697
- function toFileSpec(rel: string): string {
698
- if (rel === '') return '.'
699
- // bun/npm accept POSIX-style paths in file: specifiers; normalize separators.
700
- return rel.split(/[\\/]/).join('/')
701
- }
702
-
703
- function findTypeclawRoot(): string | null {
704
- try {
705
- let dir = dirname(fileURLToPath(import.meta.url))
706
- const root = resolve('/')
707
- while (dir !== root) {
708
- const pkgPath = join(dir, 'package.json')
709
- if (existsSync(pkgPath)) {
710
- const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { name?: string }
711
- if (pkg.name === 'typeclaw') return dir
712
- }
713
- dir = dirname(dir)
714
- }
715
- } catch {}
716
- return null
718
+ async function maybeLinkWindowsDevTypeclaw(
719
+ platform: NodeJS.Platform,
720
+ runBunLink: RunBunLink | undefined,
721
+ ): Promise<void> {
722
+ const typeclawRoot = typeclawCheckoutRoot()
723
+ if (typeclawRoot === null) return
724
+ await linkWindowsDevTypeclaw(typeclawRoot, { platform, ...(runBunLink !== undefined ? { runBunLink } : {}) })
717
725
  }
718
726
 
719
727
  export async function writeDockerAssets(root: string): Promise<DockerAssetsResult> {
@@ -0,0 +1,64 @@
1
+ import { realpathSync } from 'node:fs'
2
+ import { homedir } from 'node:os'
3
+ import { join } from 'node:path'
4
+
5
+ import { isWindows } from '@/shared/platform'
6
+
7
+ const NODE_MODULES = 'node_modules'
8
+ const TYPECLAW_DEP = 'typeclaw'
9
+
10
+ export type RunBunLink = (cwd: string) => Promise<void>
11
+
12
+ export type LinkWindowsDevTypeclawOptions = {
13
+ platform?: NodeJS.Platform
14
+ runBunLink?: RunBunLink
15
+ env?: NodeJS.ProcessEnv
16
+ }
17
+
18
+ // Mirrors Bun's `openGlobalDir` env-var precedence (BUN_INSTALL_GLOBAL_DIR >
19
+ // BUN_INSTALL/install/global > XDG_CACHE_HOME/bun/install/global >
20
+ // homedir/.bun/install/global) so we resolve the same global-link location Bun
21
+ // writes to. The node_modules/<name> entry is a junction (Windows) or symlink
22
+ // (POSIX) whose target is the checkout absolute path; realpathSync resolves both.
23
+ export function resolveBunLinkedPackage(packageName: string, env: NodeJS.ProcessEnv = process.env): string | null {
24
+ const globalDir =
25
+ env.BUN_INSTALL_GLOBAL_DIR ??
26
+ (env.BUN_INSTALL ? join(env.BUN_INSTALL, 'install', 'global') : null) ??
27
+ (env.XDG_CACHE_HOME ? join(env.XDG_CACHE_HOME, 'bun', 'install', 'global') : null) ??
28
+ join(homedir(), '.bun', 'install', 'global')
29
+ try {
30
+ return realpathSync(join(globalDir, NODE_MODULES, packageName))
31
+ } catch {
32
+ return null
33
+ }
34
+ }
35
+
36
+ // Native-Windows dev-mode only: register the typeclaw checkout via `bun link` so
37
+ // the agent can depend on it as `link:typeclaw`. `link:` resolves to a
38
+ // symlink/junction that bun's installer SKIPS entirely (no `.folder` verify,
39
+ // no uninstall-before-install, no source-tree copy) — unlike `file:`, which
40
+ // copies the whole checkout incl `.git/` and EPERMs on locked git files (the
41
+ // #899 path). Returns the linked target path (for the container bind-mount) or
42
+ // null when not Windows. POSIX keeps `file:` (registry users use a version spec
43
+ // and never reach here).
44
+ export async function linkWindowsDevTypeclaw(
45
+ typeclawRoot: string,
46
+ options: LinkWindowsDevTypeclawOptions = {},
47
+ ): Promise<string | null> {
48
+ const platform = options.platform ?? process.platform
49
+ if (!isWindows(platform)) return null
50
+ const runLink = options.runBunLink ?? defaultRunBunLink
51
+ await runLink(typeclawRoot)
52
+ return resolveBunLinkedPackage(TYPECLAW_DEP, options.env ?? process.env) ?? typeclawRoot
53
+ }
54
+
55
+ async function defaultRunBunLink(cwd: string): Promise<void> {
56
+ const bun = (globalThis as { Bun?: { spawn: typeof Bun.spawn } }).Bun
57
+ if (!bun) throw new Error('bun runtime not available to run `bun link`')
58
+ const proc = bun.spawn({ cmd: ['bun', 'link'], cwd, stdout: 'pipe', stderr: 'pipe' })
59
+ const code = await proc.exited
60
+ if (code !== 0) {
61
+ const stderr = await new Response(proc.stderr).text()
62
+ throw new Error(`bun link failed in ${cwd}: ${stderr.trim() || `exited with code ${code}`}`)
63
+ }
64
+ }