typeclaw 0.48.10 → 0.48.12

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 (68) hide show
  1. package/package.json +2 -2
  2. package/scripts/apparmor/typeclaw-bwrap +43 -0
  3. package/scripts/verify-apparmor-signals.sh +161 -0
  4. package/scripts/verify-mask-fd-sandbox.sh +86 -16
  5. package/src/agent/index.ts +11 -1
  6. package/src/agent/live-subagents.ts +98 -0
  7. package/src/agent/session-origin.ts +5 -1
  8. package/src/agent/tools/channel-reply.ts +30 -2
  9. package/src/agent/tools/channel-send.ts +19 -2
  10. package/src/agent/tools/spawn-subagent.ts +37 -1
  11. package/src/bundled-plugins/github-cli-auth/gh-command.ts +7 -1
  12. package/src/bundled-plugins/github-cli-auth/index.ts +2 -1
  13. package/src/bundled-plugins/github-cli-auth/review-checkout.ts +9 -1
  14. package/src/bundled-plugins/memory/dreaming.ts +21 -6
  15. package/src/channels/adapters/github/inbound.ts +195 -25
  16. package/src/channels/adapters/github/index.ts +16 -18
  17. package/src/channels/adapters/github/reconcile-cooldown-store.ts +15 -1
  18. package/src/channels/adapters/github/recover-failed-deliveries.ts +7 -2
  19. package/src/channels/adapters/github/review-submitter.ts +28 -0
  20. package/src/channels/adapters/kakaotalk-channel-resolver.ts +86 -16
  21. package/src/channels/adapters/kakaotalk.ts +7 -8
  22. package/src/channels/adapters/teams-classify.ts +21 -0
  23. package/src/channels/adapters/teams-edit.ts +2 -1
  24. package/src/channels/adapters/teams-format.ts +16 -0
  25. package/src/channels/adapters/teams.ts +12 -5
  26. package/src/channels/github-repo.ts +11 -0
  27. package/src/channels/github-review-verdict-coordinator.ts +179 -29
  28. package/src/channels/github-verdict-activity.ts +10 -6
  29. package/src/channels/manager.ts +9 -0
  30. package/src/channels/persistence.ts +28 -2
  31. package/src/channels/router.ts +284 -61
  32. package/src/channels/schema.ts +18 -0
  33. package/src/channels/types.ts +1 -0
  34. package/src/cli/compose.ts +3 -3
  35. package/src/cli/docker-preflight.ts +8 -4
  36. package/src/cli/restart.ts +89 -23
  37. package/src/cli/start.ts +68 -16
  38. package/src/cli/status.ts +38 -6
  39. package/src/cli/stop.ts +5 -2
  40. package/src/compose/stop.ts +5 -4
  41. package/src/config/config.ts +9 -1
  42. package/src/container/build-cache.ts +807 -0
  43. package/src/container/compose-project.ts +4 -0
  44. package/src/container/docker-app.ts +74 -0
  45. package/src/container/log-archive.ts +33 -5
  46. package/src/container/memory-limit.ts +80 -0
  47. package/src/container/memory-oversubscription.ts +125 -0
  48. package/src/container/restart.ts +6 -1
  49. package/src/container/shared.ts +43 -16
  50. package/src/container/start.ts +313 -77
  51. package/src/container/stop.ts +19 -13
  52. package/src/container/verify-running.ts +12 -0
  53. package/src/cron/scheduler.ts +12 -4
  54. package/src/doctor/apparmor.ts +101 -0
  55. package/src/doctor/bounded-exec.ts +14 -0
  56. package/src/doctor/checks.ts +42 -15
  57. package/src/doctor/index.ts +14 -2
  58. package/src/doctor/plugin-bridge.ts +15 -3
  59. package/src/hostd/paths.ts +4 -0
  60. package/src/init/dockerfile.ts +7 -6
  61. package/src/init/windows-dev-link.ts +34 -2
  62. package/src/run/index.ts +17 -0
  63. package/src/run/resource-sample.ts +171 -0
  64. package/src/sandbox/availability.ts +7 -5
  65. package/src/sandbox/index.ts +8 -1
  66. package/src/sandbox/session-tmp.ts +26 -1
  67. package/src/skills/typeclaw-channel-github/SKILL.md +4 -2
  68. package/typeclaw.schema.json +7 -0
@@ -2,7 +2,7 @@ import { DEFAULT_LOG_RETENTION_DAYS, loadConfigSync } from '@/config'
2
2
  import { isDaemonReachable, send as sendToDaemon } from '@/hostd/client'
3
3
 
4
4
  import { type AgentOperationLease, type WithAgentOperationLock, withAgentOperationLock } from './agent-operation-lock'
5
- import { archiveContainerLogs, type DockerLogArchiver } from './log-archive'
5
+ import { archiveContainerLogs, dockerLogsUnavailableWarning, type DockerLogArchiver } from './log-archive'
6
6
  import {
7
7
  classifyRmStderr,
8
8
  containerNameFromCwd,
@@ -13,6 +13,7 @@ import {
13
13
  sanitizeDockerStderr,
14
14
  waitForRemoval,
15
15
  } from './shared'
16
+ import { describeUnremovableContainer } from './verify-running'
16
17
 
17
18
  export type StopPlan = {
18
19
  containerName: string
@@ -26,6 +27,7 @@ export type StopOptions = {
26
27
  archiveLogs?: DockerLogArchiver
27
28
  operationLock?: WithAgentOperationLock
28
29
  operationLease?: AgentOperationLease
30
+ onWarning?: (warning: string) => void
29
31
  }
30
32
 
31
33
  export async function stop(options: StopOptions): Promise<StopResult> {
@@ -45,6 +47,7 @@ async function runStop({
45
47
  cwd,
46
48
  exec = defaultDockerExec,
47
49
  archiveLogs = archiveContainerLogs,
50
+ onWarning,
48
51
  }: StopOptions): Promise<StopResult> {
49
52
  const { containerName } = planStop(cwd)
50
53
 
@@ -89,10 +92,13 @@ async function runStop({
89
92
 
90
93
  const archive = await archiveLogs({ agentDir: cwd, containerId, retentionDays })
91
94
  if (!archive.ok) {
92
- return {
93
- ok: false,
94
- reason: `Could not archive logs for container ${containerId}: ${archive.reason}. Preserving the Docker container as the source of truth.`,
95
+ if (archive.kind === 'failed') {
96
+ return {
97
+ ok: false,
98
+ reason: `Could not archive logs for container ${containerId}: ${archive.reason}. Preserving the Docker container as the source of truth.`,
99
+ }
95
100
  }
101
+ onWarning?.(dockerLogsUnavailableWarning(containerId))
96
102
  }
97
103
 
98
104
  // Containers run without `--rm`, so `docker stop` only stops them. Remove
@@ -123,19 +129,19 @@ async function runStop({
123
129
  }
124
130
  const kind = classifyRmStderr(rmResult.stderr)
125
131
  if (kind === null) {
126
- return { ok: false, reason: `docker rm failed: ${sanitizeDockerStderr(rmResult.stderr) || 'no stderr'}` }
132
+ const reason = `docker rm failed: ${sanitizeDockerStderr(rmResult.stderr) || 'no stderr'}`
133
+ const diagnosis = await describeUnremovableContainer(exec, containerId)
134
+ return { ok: false, reason: diagnosis === null ? reason : `${reason} ${diagnosis}` }
127
135
  }
128
136
  if (kind === 'in-progress' && !(await waitForRemoval(exec, containerName))) {
129
- return {
130
- ok: false,
131
- reason: `Container ${containerName} is still being removed by docker after 10s.`,
132
- }
137
+ const reason = `Container ${containerName} is still being removed by docker after 10s.`
138
+ const diagnosis = await describeUnremovableContainer(exec, containerId)
139
+ return { ok: false, reason: diagnosis === null ? reason : `${reason} ${diagnosis}` }
133
140
  }
134
141
  } else if (!(await waitForRemoval(exec, containerName))) {
135
- return {
136
- ok: false,
137
- reason: `Container ${containerName} is still being removed by docker after 10s.`,
138
- }
142
+ const reason = `Container ${containerName} is still being removed by docker after 10s.`
143
+ const diagnosis = await describeUnremovableContainer(exec, containerId)
144
+ return { ok: false, reason: diagnosis === null ? reason : `${reason} ${diagnosis}` }
139
145
  }
140
146
 
141
147
  return { ok: true, containerName, running }
@@ -101,6 +101,18 @@ export async function probeContainer(exec: DockerExec, name: string): Promise<Co
101
101
  return { kind: 'daemon-error', detail }
102
102
  }
103
103
 
104
+ export async function describeUnremovableContainer(exec: DockerExec, containerRef: string): Promise<string | null> {
105
+ const probe = await probeContainer(exec, containerRef)
106
+ if (probe.kind !== 'status') return null
107
+ if (probe.status === 'removing') {
108
+ return 'Docker is still removing this container, but the removal is not draining. docker rm, including --force, cannot re-enter an in-flight removal. Restart Docker or OrbStack; Docker will restore the container as dead, and TypeClaw can remove it on the next start or restart.'
109
+ }
110
+ if (probe.status === 'dead') {
111
+ return 'Docker marked this container dead because it could not remove its filesystem. Resolve the busy mount or restart Docker, then retry.'
112
+ }
113
+ return null
114
+ }
115
+
104
116
  function isLifeStatus(value: string): value is ContainerLifeStatus {
105
117
  return (
106
118
  value === 'running' ||
@@ -58,9 +58,17 @@ const consoleLogger: SchedulerLogger = {
58
58
  error: (m) => console.error(m),
59
59
  }
60
60
 
61
- // Node clamps delays greater than this to 1ms. Re-arm long waits instead of
62
- // allowing an early callback to dispatch a future occurrence.
63
- const maxTimeoutMs = 2 ** 31 - 1
61
+ // Timers count down against a monotonic clock, while cron occurrences are wall-clock
62
+ // instants. A machine or VM suspension advances the latter but not the former, so a
63
+ // single day-long timer would resume still holding almost its full delay and fire late
64
+ // by the suspension. There is no portable in-process resume callback to correct that;
65
+ // periodically re-checking the wall clock is the only reliable mechanism.
66
+ //
67
+ // One minute bounds resumed-host convergence while keeping the idle cost modest: each
68
+ // enabled job wakes once per minute (30 jobs are 30 wake-ups/minute, or 43,200/day).
69
+ // An intermediate wake-up only re-arms the immutable occurrence below; it never fires
70
+ // early, because the callback dispatches only after the wall clock reaches nextFire.
71
+ const maxArmMs = 60 * 1000
64
72
 
65
73
  export function createScheduler({
66
74
  jobs,
@@ -119,7 +127,7 @@ export function createScheduler({
119
127
  fire(live)
120
128
  scheduleNext(id)
121
129
  },
122
- Math.min(delay, maxTimeoutMs),
130
+ Math.min(delay, maxArmMs),
123
131
  )
124
132
  handles.set(id, handle)
125
133
  }
@@ -0,0 +1,101 @@
1
+ import { readFile } from 'node:fs/promises'
2
+
3
+ import { loadConfigSync } from '@/config'
4
+
5
+ import type { CheckResult, DoctorCheck } from './types'
6
+
7
+ const APPARMOR_ENABLED_PATH = '/sys/module/apparmor/parameters/enabled'
8
+ const RESTRICT_UNPRIVILEGED_USERNS_PATH = '/proc/sys/kernel/apparmor_restrict_unprivileged_userns'
9
+
10
+ const SHIPPED_PROFILE = 'typeclaw-bwrap'
11
+ const DOCKER_DEFAULT_PROFILE = 'docker-default'
12
+
13
+ const INSTALL_SHIPPED_PROFILE_FIX =
14
+ 'Install the shipped scripts/apparmor/typeclaw-bwrap profile as /etc/apparmor.d/typeclaw-bwrap, run `sudo apparmor_parser -r -W /etc/apparmor.d/typeclaw-bwrap`, set `sandbox.apparmorProfile` to `typeclaw-bwrap`, then run `typeclaw restart`.'
15
+
16
+ export type ApparmorSandboxDeps = {
17
+ readHostFile?: (path: string) => Promise<string | null>
18
+ loadApparmorProfile?: (cwd: string) => string
19
+ }
20
+
21
+ export function apparmorSandbox(deps: ApparmorSandboxDeps = {}): DoctorCheck {
22
+ const readHostFile = deps.readHostFile ?? safeReadHostFile
23
+ const loadApparmorProfile = deps.loadApparmorProfile ?? ((cwd) => loadConfigSync(cwd).sandbox.apparmorProfile)
24
+
25
+ return {
26
+ name: 'container.apparmor-bwrap',
27
+ category: 'container',
28
+ description: 'host AppArmor permits the per-tool bwrap sandbox',
29
+ applies: (ctx) => ctx.hasAgentFolder,
30
+ async run(ctx) {
31
+ const [enabled, restricted] = await Promise.all([
32
+ readHostFile(APPARMOR_ENABLED_PATH),
33
+ readHostFile(RESTRICT_UNPRIVILEGED_USERNS_PATH),
34
+ ])
35
+ if (enabled?.trim() !== 'Y') {
36
+ return { status: 'ok', message: 'host AppArmor is not enabled; no container profile applies' }
37
+ }
38
+
39
+ let profile: string
40
+ try {
41
+ profile = loadApparmorProfile(ctx.cwd)
42
+ } catch {
43
+ return { status: 'ok', message: 'AppArmor profile check deferred until typeclaw.json is valid' }
44
+ }
45
+ return classifyProfile(profile, restricted?.trim() === '1')
46
+ },
47
+ }
48
+ }
49
+
50
+ // Profile FIRST, host sysctl second. docker-default's `deny mount,` rejects
51
+ // bwrap's opening mount(NULL, "/", MS_SLAVE|MS_REC) on any AppArmor-enabled
52
+ // host, so gating that verdict on kernel.apparmor_restrict_unprivileged_userns
53
+ // would report a dead bash surface as healthy. Only the `unconfined` verdict
54
+ // actually depends on the sysctl.
55
+ function classifyProfile(profile: string, restrictedUserns: boolean): CheckResult {
56
+ if (profile === SHIPPED_PROFILE) {
57
+ return { status: 'ok', message: `sandbox uses the shipped ${SHIPPED_PROFILE} AppArmor profile` }
58
+ }
59
+
60
+ // `error`, not `warning`: an unavailable sandbox makes every model bash call
61
+ // throw SandboxUnavailableError (src/sandbox/availability.ts) — the surface is
62
+ // dead, not degraded.
63
+ if (profile === DOCKER_DEFAULT_PROFILE) {
64
+ return {
65
+ status: 'error',
66
+ message: `AppArmor profile ${DOCKER_DEFAULT_PROFILE} denies the mount that sandboxed bash needs, so every bash call fails`,
67
+ fix: { description: INSTALL_SHIPPED_PROFILE_FIX },
68
+ }
69
+ }
70
+
71
+ if (profile === 'unconfined') {
72
+ if (!restrictedUserns) {
73
+ return { status: 'ok', message: 'host AppArmor does not require a custom bwrap profile' }
74
+ }
75
+ return {
76
+ status: 'error',
77
+ message:
78
+ 'stock Ubuntu AppArmor blocks the user namespace required by sandboxed bash when sandbox.apparmorProfile is unconfined',
79
+ fix: { description: INSTALL_SHIPPED_PROFILE_FIX },
80
+ }
81
+ }
82
+
83
+ // A deliberate operator-authored profile. Doctor cannot read
84
+ // /sys/kernel/security/apparmor/profiles unprivileged, so it can neither
85
+ // confirm nor refute this one — say so rather than assert it works.
86
+ return {
87
+ status: 'info',
88
+ message: `sandbox uses custom AppArmor profile ${profile}; typeclaw cannot verify it permits userns, mount, and signal delivery`,
89
+ details: [
90
+ `Compare it against the shipped ${SHIPPED_PROFILE} profile, and run scripts/verify-apparmor-signals.sh against this host to confirm cancellation and container stop/restart still work.`,
91
+ ],
92
+ }
93
+ }
94
+
95
+ async function safeReadHostFile(path: string): Promise<string | null> {
96
+ try {
97
+ return await readFile(path, 'utf8')
98
+ } catch {
99
+ return null
100
+ }
101
+ }
@@ -0,0 +1,14 @@
1
+ import { defaultDockerExec, type DockerExec } from '@/container'
2
+
3
+ // Every Docker call reachable from `doctor` must carry a deadline.
4
+ //
5
+ // The bounded availability probe only proves the daemon answered ONCE; it can
6
+ // wedge immediately afterward, so gating on it is necessary but not sufficient.
7
+ // This is the whole point of the command: an operator runs `doctor` precisely
8
+ // when the host is sick, and a diagnostic that blocks forever on the thing it
9
+ // is diagnosing is worse than useless.
10
+ export const DOCTOR_DOCKER_TIMEOUT_MS = 5_000
11
+
12
+ export function boundedExec(exec: DockerExec = defaultDockerExec, timeoutMs = DOCTOR_DOCKER_TIMEOUT_MS): DockerExec {
13
+ return (args, options) => exec(args, { ...options, signal: options?.signal ?? AbortSignal.timeout(timeoutMs) })
14
+ }
@@ -13,6 +13,7 @@ import {
13
13
  refreshDockerfile,
14
14
  refreshGitignore,
15
15
  resolveHostPort,
16
+ type DockerAvailability,
16
17
  type DockerExec,
17
18
  } from '@/container'
18
19
  import { homeRoot, isDaemonReachable, send } from '@/hostd'
@@ -22,6 +23,8 @@ import { detectMissingDeps } from '@/init/ensure-deps'
22
23
  import { buildGitignore, GITIGNORE_FILE } from '@/init/gitignore'
23
24
  import { detectWsl, isWindows, isWindowsDriveMount, type WslInfo } from '@/shared'
24
25
 
26
+ import { apparmorSandbox } from './apparmor'
27
+ import { boundedExec } from './bounded-exec'
25
28
  import { buildChannelChecks } from './channel-checks'
26
29
  import { agentFileOwnership, type FileOwnershipDeps } from './file-ownership'
27
30
  import { buildOperationalIncidentChecks } from './operational-incidents'
@@ -31,7 +34,7 @@ export function buildStaticChecks(opts: { dockerExec?: DockerExec } & FileOwners
31
34
  const dockerExec = opts.dockerExec ?? defaultDockerExec
32
35
 
33
36
  return [
34
- dockerDaemon(dockerExec),
37
+ dockerDaemon(boundedExec(dockerExec)),
35
38
  bunRuntime(),
36
39
  agentFolderInitialized(),
37
40
  agentFolderDockerfileTemplate(),
@@ -40,14 +43,15 @@ export function buildStaticChecks(opts: { dockerExec?: DockerExec } & FileOwners
40
43
  agentFolderGitRepo(),
41
44
  agentFileOwnership(opts),
42
45
  configValid(),
46
+ apparmorSandbox(),
43
47
  hostdHomeWritable(),
44
48
  wslDriveMount(),
45
49
  windowsSecretPerms(),
46
50
  hostdReachable(),
47
51
  hostdRegistration(),
48
52
  windowsBindMount(),
49
- containerState(dockerExec),
50
- containerHostPort(),
53
+ containerState(boundedExec(dockerExec)),
54
+ containerHostPort(dockerExec),
51
55
  ...buildOperationalIncidentChecks(),
52
56
  ...buildChannelChecks(),
53
57
  ]
@@ -63,20 +67,38 @@ function dockerDaemon(exec: DockerExec): DoctorCheck {
63
67
  if (result.ok) return { status: 'ok', message: 'docker info responded' }
64
68
  return {
65
69
  status: 'error',
66
- message: result.reason === 'binary-missing' ? 'docker binary missing on $PATH' : 'docker daemon not reachable',
70
+ message: dockerDaemonMessage(result.reason),
67
71
  details: [result.detail],
68
- fix:
69
- result.reason === 'binary-missing'
70
- ? { description: 'Install Docker (Docker Desktop, OrbStack, or docker-ce).' }
71
- : {
72
- description:
73
- 'Start the Docker runtime (Docker Desktop, OrbStack, or `systemctl start docker`). If it is already running, check `docker context ls`, `DOCKER_CONTEXT`, and `DOCKER_HOST`.',
74
- },
72
+ fix: { description: dockerDaemonFix(result.reason) },
75
73
  }
76
74
  },
77
75
  }
78
76
  }
79
77
 
78
+ type DockerUnavailableReason = Extract<DockerAvailability, { ok: false }>['reason']
79
+
80
+ function dockerDaemonMessage(reason: DockerUnavailableReason): string {
81
+ switch (reason) {
82
+ case 'binary-missing':
83
+ return 'docker binary missing on $PATH'
84
+ case 'unresponsive':
85
+ return 'docker daemon accepted the request but never responded'
86
+ case 'daemon-down':
87
+ return 'docker daemon not reachable'
88
+ }
89
+ }
90
+
91
+ function dockerDaemonFix(reason: DockerUnavailableReason): string {
92
+ switch (reason) {
93
+ case 'binary-missing':
94
+ return 'Install Docker (Docker Desktop, OrbStack, or docker-ce), or if it is already installed, add its bin directory to PATH — a non-interactive or SSH shell often misses it.'
95
+ case 'unresponsive':
96
+ return 'Restart the Docker runtime (`orb stop` then reopen OrbStack, restart Docker Desktop, or `systemctl restart docker`). A daemon that answers nothing is usually host or VM memory exhaustion, so check memory pressure or it will recur.'
97
+ case 'daemon-down':
98
+ return 'Start the Docker runtime (Docker Desktop, OrbStack, or `systemctl start docker`). If it is already running, check `docker context ls`, `DOCKER_CONTEXT`, and `DOCKER_HOST`.'
99
+ }
100
+ }
101
+
80
102
  function bunRuntime(): DoctorCheck {
81
103
  return {
82
104
  name: 'runtime.bun-available',
@@ -449,7 +471,7 @@ function containerState(exec: DockerExec): DoctorCheck {
449
471
  return { status: 'skipped', message: 'docker unavailable (covered by docker.daemon-reachable)' }
450
472
  }
451
473
  const name = containerNameFromCwd(ctx.cwd)
452
- const state = await inspectContainer(name)
474
+ const state = await inspectContainer(name, { exec })
453
475
  if (!state.exists) {
454
476
  return {
455
477
  status: 'info',
@@ -467,20 +489,25 @@ function containerState(exec: DockerExec): DoctorCheck {
467
489
  }
468
490
  }
469
491
 
470
- function containerHostPort(): DoctorCheck {
492
+ function containerHostPort(exec: DockerExec): DoctorCheck {
471
493
  return {
472
494
  name: 'container.host-port-resolves',
473
495
  category: 'container',
474
496
  description: 'running container exposes its host port',
475
497
  applies: (ctx) => ctx.hasAgentFolder,
476
498
  async run(ctx) {
499
+ const bounded = boundedExec(exec)
500
+ const available = await checkDockerAvailable(bounded)
501
+ if (!available.ok) {
502
+ return { status: 'skipped', message: 'docker unavailable (covered by docker.daemon-reachable)' }
503
+ }
477
504
  const name = containerNameFromCwd(ctx.cwd)
478
- const state = await inspectContainer(name)
505
+ const state = await inspectContainer(name, { exec: bounded })
479
506
  if (!state.exists || !state.running) {
480
507
  return { status: 'skipped', message: 'container not running' }
481
508
  }
482
509
  try {
483
- const port = await resolveHostPort({ cwd: ctx.cwd })
510
+ const port = await resolveHostPort({ cwd: ctx.cwd, exec: bounded })
484
511
  return { status: 'ok', message: `host port ${port} -> container` }
485
512
  } catch (err) {
486
513
  return {
@@ -1,3 +1,4 @@
1
+ import type { DockerExec } from '@/container'
1
2
  import { findAgentDir } from '@/init'
2
3
  import type { DoctorCheckPayload } from '@/shared'
3
4
 
@@ -38,6 +39,10 @@ export type RunDoctorOptions = {
38
39
  cwd?: string
39
40
  only?: string[]
40
41
  fix?: boolean
42
+ // Docker executor used by BOTH the static checks and plugin discovery, so a
43
+ // test can drive the whole command against one wedged daemon and prove the
44
+ // real sequencing terminates — not just each half in isolation.
45
+ dockerExec?: DockerExec
41
46
  staticChecks?: DoctorCheck[]
42
47
  fetchPluginChecks?: PluginBridgeFetchChecks
43
48
  fetchPluginFix?: PluginBridgeFetchFix
@@ -49,10 +54,17 @@ export async function runDoctor(opts: RunDoctorOptions = {}): Promise<DoctorRunR
49
54
  const hasAgentFolder = findAgentDir(cwd) === cwd
50
55
  const ctx: CheckContext = { cwd, hasAgentFolder }
51
56
 
52
- const staticChecks = (opts.staticChecks ?? buildStaticChecks()).filter((c) => isAllowed(c, opts.only, c.category))
57
+ const staticChecks = (
58
+ opts.staticChecks ?? buildStaticChecks(opts.dockerExec === undefined ? {} : { dockerExec: opts.dockerExec })
59
+ ).filter((c) => isAllowed(c, opts.only, c.category))
53
60
  const staticResults = await runStaticChecks(staticChecks, ctx)
54
61
 
55
- const fetchPluginChecks = opts.fetchPluginChecks ?? defaultFetchPluginDoctorChecks
62
+ const fetchPluginChecks =
63
+ opts.fetchPluginChecks ??
64
+ ((bridgeOpts) =>
65
+ defaultFetchPluginDoctorChecks(
66
+ opts.dockerExec === undefined ? bridgeOpts : { ...bridgeOpts, exec: opts.dockerExec },
67
+ ))
56
68
  const pluginResults = await collectPluginChecks(fetchPluginChecks, ctx, opts.only)
57
69
 
58
70
  const initial = buildReport(ctx, staticResults, pluginResults)
@@ -1,10 +1,15 @@
1
- import { resolveHostPort, resolveTuiToken } from '@/container'
1
+ import { resolveHostPort, resolveTuiToken, type DockerExec } from '@/container'
2
2
  import type { ClientMessage, DoctorCheckPayload, DoctorFixPayload, ServerMessage } from '@/shared'
3
3
 
4
+ import { boundedExec } from './bounded-exec'
5
+
4
6
  export type PluginBridgeOptions = {
5
7
  cwd: string
6
8
  url?: string
7
9
  timeoutMs?: number
10
+ // Injectable so a regression test can prove the late discovery path is
11
+ // bounded too, not just the static checks.
12
+ exec?: DockerExec
8
13
  }
9
14
 
10
15
  export type PluginBridgeFetchChecks = (opts: PluginBridgeOptions) => Promise<PluginBridgeChecksResult>
@@ -79,8 +84,15 @@ async function dial(opts: PluginBridgeOptions): Promise<DialResult> {
79
84
  let url = opts.url
80
85
  if (url === undefined) {
81
86
  try {
82
- const port = await resolveHostPort({ cwd: opts.cwd })
83
- const token = await resolveTuiToken({ cwd: opts.cwd })
87
+ // Plugin discovery runs AFTER the static checks, so it is the last place
88
+ // a wedged daemon can still hang the command: `docker port` and
89
+ // `docker inspect` here would otherwise block with no deadline of their
90
+ // own, long after the earlier `docker info` probes succeeded.
91
+ // Wrap unconditionally rather than only defaulting: an injected exec is
92
+ // no safer than the default one, and the deadline is the invariant here.
93
+ const exec = boundedExec(opts.exec)
94
+ const port = await resolveHostPort({ cwd: opts.cwd, exec })
95
+ const token = await resolveTuiToken({ cwd: opts.cwd, exec })
84
96
  url = buildBridgeUrl(port, token)
85
97
  } catch (err) {
86
98
  return { kind: 'unreachable', reason: err instanceof Error ? err.message : String(err) }
@@ -87,6 +87,10 @@ export function modelsDir(): string {
87
87
  return join(homeRoot(), 'models')
88
88
  }
89
89
 
90
+ export function buildCacheDir(): string {
91
+ return join(homeRoot(), 'build-cache')
92
+ }
93
+
90
94
  export function versionCachePath(): string {
91
95
  return join(homeRoot(), 'version-cache.json')
92
96
  }
@@ -56,12 +56,13 @@ export type BuildDockerfileOptions = {
56
56
  // agent author. See `src/sandbox/` for the bwrap command builder, and
57
57
  // `docs/internals/sandbox.mdx` for why bwrap is the right
58
58
  // shape for per-call isolation inside an already-containerized agent. The
59
- // outer container's `--security-opt seccomp=unconfined` (added in the same
60
- // commit as this line; see `src/container/start.ts:planStart`) is what lets
61
- // bwrap create user/pid/mount namespaces from inside Docker. Without that
62
- // flag the seccomp default profile blocks `unshare(CLONE_NEWUSER)` and bwrap
63
- // fails at startup. The two changes are load-bearing together — do not drop
64
- // one without the other.
59
+ // outer container's `seccomp=unconfined` plus configured AppArmor profile
60
+ // (see `src/container/start.ts:planStart`) let bwrap create user/pid/mount
61
+ // namespaces from inside Docker. Docker's seccomp default blocks userns and
62
+ // docker-default AppArmor explicitly denies mount; on stock Ubuntu 23.10+ the
63
+ // operator must load the shipped typeclaw-bwrap profile because the host's
64
+ // unprivileged_userns catch-all also denies uid_map writes to unconfined
65
+ // processes. The package, options, and host profile are load-bearing together.
65
66
  //
66
67
  // `jq` is in baseline (not behind a toggle) so it is available to the
67
68
  // per-tool bwrap sandbox that wraps agent bash calls. The sandbox only
@@ -47,9 +47,41 @@ export async function linkWindowsDevTypeclaw(
47
47
  ): Promise<string | null> {
48
48
  const platform = options.platform ?? process.platform
49
49
  if (!isWindows(platform)) return null
50
+ const env = options.env ?? process.env
50
51
  const runLink = options.runBunLink ?? defaultRunBunLink
51
- await runLink(typeclawRoot)
52
- return resolveBunLinkedPackage(TYPECLAW_DEP, options.env ?? process.env) ?? typeclawRoot
52
+ try {
53
+ await runLink(typeclawRoot)
54
+ } catch (error) {
55
+ // `bun link` is not idempotent on Windows. It deletes any existing
56
+ // <globalDir>/node_modules/<name> entry and then creates the junction, but
57
+ // the delete is best-effort (its error is discarded) and the pair is not
58
+ // atomic — so a junction that resists deletion, or a second `bun link`
59
+ // racing the first, dies on EEXIST. Re-running `typeclaw init` from a dev
60
+ // checkout then aborts on a step that had nothing left to do. Swallow the
61
+ // failure ONLY when the end state we wanted is already true: the global
62
+ // entry resolves to THIS checkout. An entry pointing at a different
63
+ // checkout, or no entry at all, still propagates, so a link that genuinely
64
+ // failed is never mistaken for a success.
65
+ if (!isLinkedTo(typeclawRoot, env)) throw error
66
+ }
67
+ return resolveBunLinkedPackage(TYPECLAW_DEP, env) ?? typeclawRoot
68
+ }
69
+
70
+ function isLinkedTo(typeclawRoot: string, env: NodeJS.ProcessEnv): boolean {
71
+ const linked = resolveBunLinkedPackage(TYPECLAW_DEP, env)
72
+ if (linked === null) return false
73
+ // Both sides are realpath'd so a junction target compares equal to the
74
+ // checkout path we were handed, and case-folded because Windows paths are
75
+ // case-insensitive while the two resolutions need not agree on casing.
76
+ return linked.toLowerCase() === canonicalize(typeclawRoot).toLowerCase()
77
+ }
78
+
79
+ function canonicalize(path: string): string {
80
+ try {
81
+ return realpathSync(path)
82
+ } catch {
83
+ return path
84
+ }
53
85
  }
54
86
 
55
87
  async function defaultRunBunLink(cwd: string): Promise<void> {
package/src/run/index.ts CHANGED
@@ -92,6 +92,7 @@ import { installFatalGuard } from './fatal-guard'
92
92
  import { installLlmFetchObserver } from './llm-fetch-observer'
93
93
  import { createPluginRuntime, type PluginRuntime, type PluginSubagentEntry } from './plugin-runtime'
94
94
  import { logResourceReport } from './resource-report'
95
+ import { startResourceSampler } from './resource-sample'
95
96
  import { acquireSubagentCoalesceLease } from './subagent-coalescing'
96
97
 
97
98
  type BunServer = ReturnType<Server['start']>
@@ -136,6 +137,9 @@ export type StartAgentOptions = {
136
137
  // a refresh that holds the real secrets lock on a gate, proving the boot
137
138
  // barrier settles this before any session-producing consumer starts.
138
139
  refreshProviderOAuth?: (options: { agentDir: string; log: (message: string) => void }) => Promise<unknown>
140
+ // Injectable so a test can prove the sampler's disposer is wired into BOTH
141
+ // teardown paths without waiting out a real sampling interval.
142
+ startResourceSampler?: () => () => void
139
143
  }
140
144
 
141
145
  export type StartAgentResult = {
@@ -200,6 +204,7 @@ async function startAgentRuntime(
200
204
  exportClaudeCredentialsFile = exportClaudeCredentialsFileForAgent,
201
205
  exportGithubCliStore = exportGithubCliStoreForAgent,
202
206
  refreshProviderOAuth = refreshProviderOAuthForAgent,
207
+ startResourceSampler: startResourceSamplerFor = startResourceSampler,
203
208
  }: StartAgentOptions,
204
209
  registerBootCleanup: (cleanup: () => void | Promise<void>) => void,
205
210
  ): Promise<StartAgentResult> {
@@ -322,6 +327,16 @@ async function startAgentRuntime(
322
327
  // startup index build is itself an OOM path; if it kills the process, this
323
328
  // line must already be in the log so the ceiling is still recorded.
324
329
  logResourceReport(cwd)
330
+ // The boot line names the ceiling; this names the climb toward it. Without a
331
+ // series there is no way to tell a leak from a spike after the fact, which is
332
+ // exactly the question an OOM post-mortem opens with.
333
+ //
334
+ // Registered for boot-failure cleanup the instant it exists, and torn down by
335
+ // stop() on the normal path. `unref()` only keeps it from holding the process
336
+ // open; without an explicit clear, repeated start/stop cycles accumulate
337
+ // intervals that scan /proc and log after their runtime is gone.
338
+ const stopResourceSampler = startResourceSamplerFor()
339
+ registerBootCleanup(() => stopResourceSampler())
325
340
  const vectorStartupPromise = runVectorStartup(cwd)
326
341
  let pluginsLoaded: LoadPluginsResult
327
342
  try {
@@ -504,6 +519,7 @@ async function startAgentRuntime(
504
519
  .list({ parentSessionId: sessionId })
505
520
  .filter((child) => child.status === 'running' && child.background === true)
506
521
  .map((child) => child.subagentName),
522
+ cancelRunningSubagentsByWorkKey: (workKey, reason) => liveSubagentRegistry.cancelRunningByWorkKey(workKey, reason),
507
523
  onReload: async () => {
508
524
  const { results } = await reloadAllNonDestructive()
509
525
  return formatChannelReloadSummary(results)
@@ -1081,6 +1097,7 @@ async function startAgentRuntime(
1081
1097
  // rejection cannot strand process-global listeners or plugin-owned handles
1082
1098
  // into the next `startAgent`.
1083
1099
  try {
1100
+ stopResourceSampler()
1084
1101
  scheduler?.stop()
1085
1102
  cronConsumer.stop()
1086
1103
  subagentConsumer.stop()